diff --git a/.github/workflows/release-preflight.yml b/.github/workflows/release-preflight.yml index 005ac2f..0a2b01c 100644 --- a/.github/workflows/release-preflight.yml +++ b/.github/workflows/release-preflight.yml @@ -35,6 +35,7 @@ name: release-preflight on: pull_request: branches: [master] + types: [opened, synchronize, reopened, closed] permissions: contents: read @@ -45,6 +46,7 @@ concurrency: jobs: preflight: + if: github.event.action != 'closed' runs-on: ubuntu-latest steps: # `lfs: true` is load-bearing, not a nicety. The default (false) leaves every @@ -53,28 +55,33 @@ jobs: # FETCHABLE from the remote — the exact failure that hit uiservice, where the # working tree held stubs while the published 1.2.1 had real content. - name: Check out the package - uses: actions/checkout@v4 + uses: actions/checkout@v7 with: fetch-depth: 0 lfs: true persist-credentials: false # The gate logic is shared rather than vendored into six repos, so there is - # one source of truth. `ref` is explicit: actions/checkout defaults to the - # target repo's DEFAULT branch (master), where the tooling does not exist - # yet — omitting it fails with "No such file or directory". Retarget this to - # master once the skill is merged there. + # one source of truth. Pinning its full commit keeps an unchanged package PR + # reproducible when Frameworks/develop advances; the installer performs + # intentional snapshot updates across all package repositories. - name: Check out the release tooling - uses: actions/checkout@v4 + uses: actions/checkout@v7 with: repository: CoderGamester/Frameworks - ref: develop + # Immutable tooling snapshot. Update intentionally through + # `release.py install-preflight`, never by following a moving branch. + ref: be8c147f3d12d94a4055d556ffdc0a26e077e5ec path: .release-tooling sparse-checkout: .claude/skills/unity-package-release/scripts persist-credentials: false + - name: Assert the release tooling checkout + run: | + test -f .release-tooling/.claude/skills/unity-package-release/scripts/release.py + - name: Set up Python - uses: actions/setup-python@v5 + uses: actions/setup-python@v7 with: python-version: "3.12" @@ -82,3 +89,42 @@ jobs: run: | python3 .release-tooling/.claude/skills/unity-package-release/scripts/release.py \ preflight-pr --path . --base "origin/${{ github.base_ref }}" + + # GITHUB_TOKEN cannot dispatch into another repository. Add a fine-grained + # FRAMEWORKS_DISPATCH_TOKEN secret (Contents: read/write on Frameworks) to each + # package repository to activate this hand-off. A missing token is reported as + # a warning rather than turning an already-merged release PR red. + notify-release: + if: github.event.action == 'closed' && github.event.pull_request.merged == true + runs-on: ubuntu-latest + steps: + - name: Notify the host release workflow + env: + DISPATCH_TOKEN: ${{ secrets.FRAMEWORKS_DISPATCH_TOKEN }} + PACKAGE_REPOSITORY: ${{ github.event.repository.name }} + run: | + if [ -z "$DISPATCH_TOKEN" ]; then + echo "::warning::FRAMEWORKS_DISPATCH_TOKEN is not configured; skipping host release notification." + exit 0 + fi + + case "$PACKAGE_REPOSITORY" in + Unity-GameData) package=gamedata ;; + Unity-GoogleSheet-Importer) package=googlesheetimporter ;; + Unity-MobileServices) package=mobileservices ;; + Unity-Services) package=services ;; + Statechart-HFSM) package=statechart ;; + Unity-UiService) package=uiservice ;; + *) + echo "::error::Unknown package repository: $PACKAGE_REPOSITORY" + exit 1 + ;; + esac + + payload=$(printf '{"event_type":"upm-release","client_payload":{"package":"%s","phase":"status"}}' "$package") + curl --fail-with-body --location --request POST \ + --url https://api.github.com/repos/CoderGamester/Frameworks/dispatches \ + --header "Accept: application/vnd.github+json" \ + --header "Authorization: Bearer $DISPATCH_TOKEN" \ + --header "X-GitHub-Api-Version: 2022-11-28" \ + --data "$payload" diff --git a/AGENTS.md b/AGENTS.md index 2c00760..25e7e2c 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1,90 +1,55 @@ -# GameLovers.Statechart - AI Agent Guide - -> **Companion files**: `CLAUDE.md` wraps this file for Claude Code — edit `AGENTS.md`, not `CLAUDE.md`. `README.md` is the user-facing entry point. - -## 1. Package Overview -- **Package**: `com.gamelovers.statechart` -- **Unity**: 2022.3+ (the only package in the family with a floor below 6000.0 — verify before assuming 6000.0-only APIs are safe here) -- **Dependencies** (see `package.json`) - - `com.cysharp.unitask` (2.5.10): `ITaskWaitState.WaitingFor(Func)` overload - -Hierarchical State Machine (HFSM / Statechart, per the [UML spec](http://www.omg.org/spec/UML) and [statecharts.github.io](https://statecharts.github.io/what-is-a-statechart.html)) — states can nest, split into parallel regions, and run async waits, all defined once in a constructor setup closure with no further runtime mutation. Smallest package in the family: no `Editor/` assembly, no `Samples~/`, single `Runtime/` assembly. - -## 2. Runtime Architecture (high level) - -### The chart itself -- **`Statechart`** (`Runtime/Statechart.cs`, implements `IStatechart : IStateMachineDebug`) is the entry point. Construct with `new Statechart(Action setup)` — the setup closure runs immediately and defines every state and transition; there is no API to add states after construction. Throws `MissingMemberException` if the setup never calls `factory.Initial(...)`. - - `Run()` — starts/resumes execution from wherever the chart is anchored. No-op if already running. - - `Trigger(IStatechartEvent trigger)` — processes an event with run-to-completion semantics. **No-op if the chart isn't running** (`Pause()`d or never `Run()` called) — a common "my event did nothing" cause. - - `Pause()` — stops processing; `Run()` resumes from the same point. - - `Reset()` — jumps back to the initial state. Does **not** implicitly pause or resume; if the chart was waiting on an event, it needs a fresh `Run()` to continue after reset. - - `LogsEnabled` (from `IStateMachineDebug`) — per-chart debug logging toggle; `IState.LogsEnabled` is the same toggle per-state. - - `CurrentState` (string name) is exposed **only under `#if UNITY_EDITOR`** — do not reference it from a runtime code path that also needs to compile for a player build. - - In `#if UNITY_EDITOR || DEBUG`, every state's `Validate()` runs once at construction — this is where the "missing transition target" / "transition loop" exceptions below come from. -- **`IStateFactory`** (`Runtime/IStateFactory.cs`) is passed into the setup closure — one factory instance per region (top-level chart, and one more per `Nest`/`Split` sub-region). Each factory method takes a `name` string (debug-only identity) and returns the state's own narrow interface: - - | Factory method | Returns | Purpose | - |---|---|---| - | `Initial(name)` | `IInitialState` | Entry point of the region. Exactly one per region. | - | `Final(name)` | `IFinalState` | Marks the region complete. | - | `State(name)` | `ISimpleState` | Blocks until an `Event(...)` transition fires. | - | `Transition(name)` | `ITransitionState` | Non-blocking; falls through to its target immediately. | - | `Nest(name)` | `INestState` | Opens one new nested (sequential) region. | - | `Choice(name)` | `IChoiceState` | Non-blocking; picks among `Transition().Condition(...)` branches. | - | `Wait(name)` | `IWaitState` | Blocks on `IWaitActivity` completion (and/or an event). | - | `TaskWait(name)` | `ITaskWaitState` | Blocks on a `Task`/`UniTask`; cannot process events while waiting. | - | `Split(name)` | `ISplitState` | Opens two-or-more new nested **parallel** regions. | - | `Leave(name)` | `ILeaveState` | Like `Final`, but its transition targets a state in an **ancestor** region, jumping out of the current `Nest`/`Split` by exactly one layer. | - -### State capability interfaces (`Runtime/IState.cs`) -Every concrete state interface above is composed from these narrower capability interfaces — check which ones a state implements to know what it can do: -- `IStateEnter.OnEnter(Action)` / `IStateExit.OnExit(Action)` — lifecycle callbacks. -- `IStateTransition.Transition()` → `ITransition` — unconditional transition (used by `Initial`/`Transition`/`Leave` states). -- `IStateEvent.Event(IStatechartEvent)` → `ITransition` — event-triggered transition (used by `State`/`Nest`/`Wait`/`Split` states). -- `ITransition.OnTransition(Action)` (chainable) + `.Target(IState)` (terminal — every transition must call this or `Statechart`'s validation throws). -- `ITransitionCondition : ITransition` adds `.Condition(Func)` — used exclusively by `IChoiceState.Transition()`; a choice with a failing condition does not transition (evaluate carefully — a choice state with no satisfied condition stalls the chart there). - -### Nesting and parallelism -- **`INestState.Nest(Action | NestedStateData)`** opens a new sequential sub-region; its returned `ITransition` fires once that sub-region reaches its `Final`. The `NestedStateData` overload (`Setup` + `ExecuteExit` + `ExecuteFinal` bools) controls whether the *parent* nest state's own `OnExit` and the *sub-region's* `IFinalState.OnEnter` actually run when leaving via a `Leave` state from inside vs. via normal completion — the plain `Action` overload defaults both to `true`. -- **`ISplitState.Split(params Action[] | NestedStateData[])`** opens N parallel sub-regions simultaneously; its `ITransition` fires only once **all** sub-regions reach their own `Final`. -- **`ILeaveState`** exits a `Nest`/`Split` region early, targeting a state in the parent region directly — bypasses the nest/split's own completion transition. Can only jump one region layer (an inner `Leave` inside a doubly-nested region still only reaches its immediate parent, not the top level). - -### Waiting states -- **`IWaitState.WaitingFor(Action)`** — the action receives an `IWaitActivity` (`Runtime/IWaitActivity.cs`); call `.Complete()` when the awaited work finishes, or `.Split()` first to fan out into multiple sub-activities whose *own* `.Complete()` calls all must return true before the parent completes. A `Wait` state also still processes `Event(...)` transitions (checked after `WaitingFor` since concurrency needs `WaitingFor` resolved first) — the doc comment on `IWaitState` explicitly notes this ordering. If a wait state is the active state when an ancestor `Nest`/`Split` exits, it force-completes itself and all inner activities rather than leaving them dangling. -- **`ITaskWaitState.WaitingFor(Func | Func)`** — blocks on true async work. Unlike `IWaitState`, **cannot process `Event(...)` transitions while waiting** (no `IStateEvent` in its interface composition) — if an ancestor region exits mid-wait, the exit itself is paused and any events that arrive during the wait are queued rather than dropped, to avoid a concurrency bottleneck. - -### Events -- **`IStatechartEvent`** (`Runtime/StatechartEvent.cs`) — equality is by an auto-incrementing `uint Id` assigned at construction, **not** by `Name`. Two `new StatechartEvent("Jump")` instances are never equal to each other; keep one instance per logical event and reuse it across every `.Event(theSameInstance)` call site that should respond to it. - -## 3. Key Directories / Files -- **Public interfaces** (root of `Runtime/`): `IState.cs` (all state-capability + concrete-state interfaces + `NestedStateData`), `ITransition.cs`, `IStateFactory.cs`, `IWaitActivity.cs`, `Statechart.cs` (+ `IStatechart`/`IStateMachineDebug`), `StatechartEvent.cs` (+ `IStatechartEvent`). -- **`Runtime/Internal/*`** — concrete state implementations (`InitialState`, `FinalState`, `SimpleState`, `TransitionState`, `NestState`, `SplitState`, `ChoiceState`, `WaitState`, `TaskWaitState`, `LeaveState`), `StateFactory`, `Transition`, `InnerStateData`, `StatechartUtils`. All `internal` — not part of the public surface; consumers only ever see the interfaces above. -- **Tests**: `Tests/Editor/*` (one asmdef, `GameLovers.Statechart.Editor.Tests`) — `StatechartTest.cs` (core lifecycle + validation-exception coverage), `StatechartStateTest.cs`, `StatechartTransitionTest.cs`, `StatechartChoiceTest.cs`, `StatechartNestTest.cs`, `StatechartSplitTest.cs`, `StatechartWaitTest.cs`, `StatechartTaskWaitTest.cs`, `StatechartLeaveTest.cs`, `StatechartNestSplit_IntegrationTest.cs`, `IMockCaler.cs` (mocked-callback interface used across the suite via NSubstitute). Before reading, editing, or creating any file in `Tests/`, you **MUST** read [`Tests/AGENTS.md`](Tests/AGENTS.md) first. -- **No `Editor/` assembly, no `Samples~/`, no `docs/`** — this package's entire surface is the interfaces above; there is no editor tooling and nothing to import as a sample. - -## 4. Important Behaviors / Gotchas -- **Setup-time validation, not always-on**: the exceptions below (`MissingMemberException`, `InvalidOperationException`) only fire from the `#if UNITY_EDITOR || DEBUG` validation pass in the `Statechart` constructor — a malformed chart in a release build without `DEBUG` defined will not be caught the same way. Always validate in-editor / in tests before shipping a chart's setup. -- **`Trigger` is a no-op unless running**: calling `Trigger(...)` before the first `Run()`, or after `Pause()`, silently does nothing — it does not queue the event for later. -- **Event identity is per-instance, not per-name**: see `IStatechartEvent` above — a fresh `new StatechartEvent("X")` never equals a previously created `"X"` event. Store event instances as fields/constants, not locals recreated per call. -- **`ITaskWaitState` cannot receive events while waiting**; `IWaitState` can, but only after its `WaitingFor` activities resolve first in a concurrent scenario. Picking the wrong one of these two for a state that needs to react to an event mid-wait is a common design mistake. -- **`ILeaveState` only jumps one region layer** — from inside a doubly-nested region, a `Leave` still only reaches the immediate parent, not further up. -- **`CurrentState` is Editor/DEBUG-only surface** on `Statechart` — don't wire game logic to it. - -## 5. Coding Standards (Unity 6 / C# 9.0) -- **C#**: C# 9.0 syntax; explicit namespaces (`GameLovers.StatechartMachine` for Runtime, `GameLoversEditor.StatechartMachine.Tests` for Tests); no global usings. -- **Assemblies**: `Runtime/GameLovers.Statechart.asmdef` has no Editor/UnityEditor reference — this package has no Editor assembly at all. Keep everything under `Runtime/Internal/` truly `internal`; the public surface is exactly the interfaces in section 2/3. -- **Async**: `Cysharp.Threading.Tasks` (UniTask) only appears in `ITaskWaitState.WaitingFor(Func)` — the plain-`Task` overload exists for consumers who don't want the UniTask dependency in their own state-setup code (the package dependency itself is unconditional either way). - -## 6. External Package Sources (for API lookups) -- UniTask: `Library/PackageCache/com.cysharp.unitask/` - -## 7. Common change workflows -- **Add a new state type**: define its public capability-composed interface in `Runtime/IState.cs`, add the corresponding `internal` implementation under `Runtime/Internal/`, and add the factory method to `IStateFactory` + `Runtime/Internal/StateFactory.cs`. Add test coverage under `Tests/Editor/` following the existing `StatechartTest.cs` naming. -- **Change validation behavior**: the per-state `Validate()` calls happen in `Statechart`'s constructor under `#if UNITY_EDITOR || DEBUG` — keep new validation failures as exceptions thrown from state `Validate()` implementations under `Runtime/Internal/`, matching the existing `MissingMemberException`/`InvalidOperationException` pattern. - -## 8. Update Policy -Update this file when: -- Public API changes (`IStatechart`, any state-capability interface in `IState.cs`, `IStateFactory`, `ITransition`, `IWaitActivity`, `IStatechartEvent`) -- Validation/exception behavior changes in the `Statechart` constructor's setup pass -- Nesting/splitting/leaving semantics change (region completion rules, `NestedStateData` flag behavior) -- Dependencies in `package.json` change (cross-check this file and `README.md` for stale references) +# GameLovers Statechart — Agent Guide + +This guide adds package-specific rules to the host repository guide. Consumer usage belongs in `README.md`. + +## Scope + +- Package: `com.gamelovers.statechart`; minimum Unity version and dependencies are authoritative in `package.json`. Supported streams are 6000.0, 6000.3 and 6000.6. +- `GameLovers.Statechart` (runtime) implements hierarchical statecharts with nested and parallel regions, events, choices, callback waits, Task/UniTask waits, and the read-only topology, active-state and trace API. +- `GameLovers.Statechart.Editor` holds the Statechart Debugger. +- `Samples~/GameFlow` is the single package sample. This package is render-pipeline-neutral. +- Public contracts live at `Runtime/`; implementations under `Runtime/Internal/` remain internal. `Runtime/AssemblyInfo.cs` grants internals to the Editor and Editor test assemblies only. + +## Statechart invariants + +- A `Statechart` is fully defined by its constructor setup closure. Runtime mutation of the state graph is unsupported, and every region requires exactly one initial state. The read-only view (`IRegionNode`, `IStateNode`, `ITransitionEdge`) is implemented by the live `StateFactory`, states and `Transition` objects; do not reintroduce a parallel node graph. Each state records its edges through `StateInternal.CreateTransition`. +- `Trigger` is a no-op until `Run()` and while paused. `Pause()` preserves the active position and stops a chain of automatic transitions mid-way when called from a callback. +- Events are processed run to completion: an event triggered while `MoveNext` is processing is queued and drained after the current step. Do not reintroduce re-entrant processing. +- `Reset()` returns to the initial state without exit callbacks or a run/pause change. It drops queued events and cancels the chart token, then starts a new one. Waits and tasks capture the token when they start and ignore their completion once it is cancelled; it is the only stale-completion guard. `Dispose()` cancels the same way and stops the chart for good. +- Statechart events compare by generated instance id, not by name. Reuse one event instance for one logical event. +- Event transitions on simple, wait, nest and split states may omit a target to run an action only; such an event leaves inner waits running. Initial, transition, choice, leave and completion transitions need a target. A choice with no satisfied condition remains in the choice state. +- `Nest` completes one sequential child region. `Split` completes only after all parallel child regions finish. +- `NestedStateData` separately controls whether leaving a nested region executes the parent nest state's exit callback and the child final state's enter callback. The plain setup-closure overload enables both; preserve the distinction when changing leave/completion behavior. +- `Leave` exits exactly one region layer and bypasses the current nest/split completion transition. +- `IWaitState` may process events and uses `IWaitActivity` completion. `ITaskWaitState` cannot process events while awaiting its task; ancestor exit waits for it and queues intervening events. +- A faulted task completes its `TaskWait` state after the fault is reported. Task completions resume on the main thread, and a `Task` completing on the main thread resumes inline; keep `AwaitTask` rather than `AsUniTask`, which posts to a later frame. +- When an active callback wait is abandoned by an ancestor region exit, complete its outstanding inner activities rather than leaving them dangling. Task waits instead delay the exit until the task completes. +- Every observable step goes through `StateInternal.Trace` / `Statechart.Emit`. `LogsEnabled` formats those traces; do not add separate `Debug.Log` paths. With no `Traced` subscriber and logs off, nothing is formatted. +- The runtime's only debugger hook is the Editor-only `Statechart.Created` event. `StatechartRegistry` and `StatechartExport` live in the Editor assembly; the registry holds charts weakly, records history as ids and text, and drops a chart on its `Disposed` trace. +- Validation runs only under `UNITY_EDITOR || DEBUG`. Do not treat release-build absence of validation as a supported malformed graph. + +## Change placement + +- A new state type requires a public capability-composed interface, an internal implementation with a `StateKind` value that creates its transitions with `CreateTransition`, a factory method on `IStateFactory`, and the matching `StateFactory` implementation. Update `Editor/StatechartExport` and the debugger views if the kind needs special drawing. +- Keep the public surface expressed through narrow capability interfaces in `Runtime/IState.cs`; consumers should not depend on internal concrete states. +- Preserve the existing Task and UniTask overloads, with and without a `CancellationToken`, when changing async waiting. +- Tools read the chart only through `RootRegion`, `GetActiveStates`, `IsActive` and `Traced`, and discover it through `Statechart.Created`. Do not add view-specific hooks to the runtime. +- Sample code stays in `Samples~/GameFlow` with its own asmdef; package assemblies never reference it. After changing `Samples~`, refresh and validate the imported copy as the host guide requires. +- Before changing anything under `Tests/`, read `Tests/AGENTS.md`. + +## Statechart Debugger + +- `StatechartDebuggerWindow` is a UI Toolkit `EditorWindow` under `Tools/GameLovers/Statechart Debugger`. Its toolbar acts on the selected live chart (Run, Pause, Reset); it never builds a throwaway chart. +- `LiveChartView` and `TreeTraceView` read the same three sources: `IStatechart.RootRegion`, `GetActiveStates`, and `StatechartRegistry.Entry.History`. A view must not need its own runtime data. Toolbar toggles named after each view turn it on or off. +- `StatechartRegistry` subscribes to `Statechart.Created`. History records keep state ids and paths, never `IStateNode` references: a node is a live state, so holding one keeps its chart alive. +- The window refreshes on a 100 ms schedule and repaints views only when `StatechartRegistry.Version` changes. Keep per-refresh work proportional to the chart size and free of allocations beyond the active list. +- Styles live in `StatechartDebugger.uss`, loaded by package path. Use colors that read in both Editor themes. +- A Graph Toolkit view was tried and removed: on 6000.6 its flat graph hid nest and split hierarchy, and the API has no read-only or container node. Do not reintroduce it without those capabilities. + +## Verification and documentation + +- Test lifecycle, run-to-completion ordering, transition target validation, nested/split completion, leave depth, waiting/event ordering, and trace order when those areas change. +- Validation tests must run with Editor or DEBUG behavior enabled and must not imply equivalent release-build enforcement. +- Debugger and sample changes need a fresh Play-mode capture with the sample running and the affected view visible; green tests do not prove the views. +- Prefer the local UniTask package source under `Library/PackageCache/` for external API questions. +- Update `README.md` for public statechart semantics and this guide only for durable invariants or test conventions. diff --git a/CHANGELOG.md b/CHANGELOG.md index a234b42..a54775c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,42 @@ All notable changes to this package will be documented in this file. The format is based on [Keep a Changelog](http://keepachangelog.com/en/1.0.0/) and this project adheres to [Semantic Versioning](http://semver.org/spec/v2.0.0.html). +## [1.0.0] - 2026-11-17 + +**New**: +- **Statechart Debugger**: *Tools > GameLovers > Statechart Debugger* shows any running chart live, with Run, Pause and Reset controls and two views that can each be turned on or off: a live chart of nested boxes with parallel regions as lanes, and a state tree with the latest 256 trace steps. The **Copy** menu exports a Mermaid diagram, the active state paths or the trace. +- **Chart view**: `IStatechart.RootRegion` exposes the chart's structure through `IRegionNode`, `IStateNode` and `ITransitionEdge`, and `GetActiveStates` and the allocation-free `IsActive` report which states are active. The view is the live chart itself, so it costs nothing to build. +- **Trace**: `IStatechart.Traced` publishes every event, exit, transition, enter, fault and lifecycle step in execution order as a `StatechartTrace`; nothing is allocated while no one listens. +- **Lifecycle**: a `Statechart(string name, Action setup)` constructor, `Name` and `IsRunning`, and `IDisposable` support. `Dispose()` stops the chart for good, cancels token-aware tasks and removes it from the debugger; `Run()` after it throws `ObjectDisposedException`. +- **Cancellable task waits**: `ITaskWaitState.WaitingFor` overloads receive a `CancellationToken` that `Reset()` and `Dispose()` cancel. +- **Game Flow sample**: one statechart drives a small game loop that uses every state kind, with on-screen controls, meant to be watched in the Statechart Debugger. + +**Changed**: +- The minimum Unity version is now 6000.0 (was 2022.3); 6000.0.x, 6000.3.x and 6000.6.x are the supported streams. +- Requires UniTask 2.5.11 (was 2.5.10), the first version whose Editor code compiles on Unity 6000.6, and the built-in UIElements module used by the debugger and the sample. +- Events triggered while another event is being processed, for example from an enter callback, are now queued and processed right after it (run to completion) instead of running against the previous state. +- `Reset()` now drops queued events and abandons pending waits and tasks, so their late completion no longer moves the chart. +- `LogsEnabled` now writes one trace line per step, such as `[Statechart 'Player'] Idle -> Jumping on 'Jump'`. +- Null arguments now throw `ArgumentNullException`, and a setup without an initial state throws `InvalidOperationException` instead of `MissingMemberException`. + +**Removed**: +- The Editor-only `Statechart.CurrentState`. + +**Migration**: +- Replace `CurrentState` with `GetActiveStates`, `IsActive` or the Statechart Debugger. +- Custom `IStatechart` implementations must add the new members: `Name`, `IsRunning`, `RootRegion`, `Traced`, `GetActiveStates`, `IsActive` and `Dispose`. +- Catch `InvalidOperationException` instead of `MissingMemberException` for a setup without an initial state. + +**Fixed**: +- A `TaskWait` state whose task throws no longer blocks the chart and its parent splits forever; the fault is logged and the state completes. +- `TaskWait` states now resume the chart on the main thread, and a `Task` completing on the main thread resumes it in the same frame. +- Pausing or resetting the chart from a callback now stops a chain of automatic transitions. +- An action-only event on a nest or split state no longer force-completes the waits inside it. +- Creation stack traces in error logs now start at the code that declared the failing state, and enter-callback errors no longer report themselves as exit errors. + +**Docs**: +- Rewrote the README with state kinds, runtime semantics, the observe API, the debugger and the sample. + ## [0.9.5] - 2026-08-04 **Changed**: diff --git a/CLAUDE.md b/CLAUDE.md index f642129..43c994c 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -1,12 +1 @@ -# Claude Code Guide — Statechart - -This package's contributor/agent guide lives in `AGENTS.md`. -Claude Code will automatically import it below. - @AGENTS.md - -## Claude-Specific Notes - -- Treat `AGENTS.md` as the source of truth. -- If anything in this file appears to conflict with `AGENTS.md`, prefer `AGENTS.md`. -- For user-facing usage, see `README.md`. diff --git a/Editor.meta b/Editor.meta new file mode 100644 index 0000000..8e5b539 --- /dev/null +++ b/Editor.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 3377c39247f77450990dc4ac28d425e5 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Editor/AssemblyInfo.cs b/Editor/AssemblyInfo.cs new file mode 100644 index 0000000..ba898f4 --- /dev/null +++ b/Editor/AssemblyInfo.cs @@ -0,0 +1,3 @@ +using System.Runtime.CompilerServices; + +[assembly: InternalsVisibleTo("GameLovers.Statechart.Editor.Tests")] diff --git a/Editor/AssemblyInfo.cs.meta b/Editor/AssemblyInfo.cs.meta new file mode 100644 index 0000000..1ce21dd --- /dev/null +++ b/Editor/AssemblyInfo.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 825824ca165c841a099cf52dc1cae66c \ No newline at end of file diff --git a/Editor/GameLovers.Statechart.Editor.asmdef b/Editor/GameLovers.Statechart.Editor.asmdef new file mode 100644 index 0000000..b17d3a2 --- /dev/null +++ b/Editor/GameLovers.Statechart.Editor.asmdef @@ -0,0 +1,18 @@ +{ + "name": "GameLovers.Statechart.Editor", + "rootNamespace": "", + "references": [ + "GameLovers.Statechart" + ], + "includePlatforms": [ + "Editor" + ], + "excludePlatforms": [], + "allowUnsafeCode": false, + "overrideReferences": false, + "precompiledReferences": [], + "autoReferenced": true, + "defineConstraints": [], + "versionDefines": [], + "noEngineReferences": false +} diff --git a/Editor/GameLovers.Statechart.Editor.asmdef.meta b/Editor/GameLovers.Statechart.Editor.asmdef.meta new file mode 100644 index 0000000..4822ee2 --- /dev/null +++ b/Editor/GameLovers.Statechart.Editor.asmdef.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: e2c76c534fbf148a287d5c3443b4c5f2 +AssemblyDefinitionImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Editor/LiveChartView.cs b/Editor/LiveChartView.cs new file mode 100644 index 0000000..fc91c74 --- /dev/null +++ b/Editor/LiveChartView.cs @@ -0,0 +1,158 @@ +using System.Collections.Generic; +using UnityEngine; +using UnityEngine.UIElements; + +// ReSharper disable CheckNamespace + +namespace GameLovers.StatechartMachine.Editor +{ + /// + /// The chart drawn as nested boxes. Nest and split states contain their regions, split regions sit side + /// by side as dashed lanes, and every active state is highlighted. + /// + internal sealed class LiveChartView : VisualElement + { + private const double RecentSeconds = 0.8; + + private readonly Dictionary _elements = new Dictionary(); + private readonly ScrollView _scroll; + + internal LiveChartView() + { + AddToClassList("sc-pane"); + AddToClassList("sc-pane-live"); + + var header = new Label("Live chart"); + header.AddToClassList("sc-pane-header"); + Add(header); + + // Vertical only: a bounded width lets each region's boxes wrap onto new rows. + _scroll = new ScrollView(ScrollViewMode.Vertical); + _scroll.AddToClassList("sc-pane-content"); + Add(_scroll); + } + + /// Rebuilds the boxes for , or clears them when null. + internal void SetChart(IStatechart chart) + { + _elements.Clear(); + _scroll.Clear(); + + if (chart != null) + { + _scroll.Add(BuildRegion(chart.RootRegion, false)); + } + } + + /// Highlights states and briefly flashes recently entered ones. + internal void UpdateActive(List active, IReadOnlyCollection history) + { + var recent = new HashSet(); + var now = Time.realtimeSinceStartupAsDouble; + + foreach (var record in history) + { + if (record.Kind == StatechartTraceKind.StateEntered && now - record.Time < RecentSeconds) + { + recent.Add(record.StateId); + } + } + + foreach (var pair in _elements) + { + pair.Value.EnableInClassList("sc-active", active.Contains(pair.Key)); + pair.Value.EnableInClassList("sc-recent", recent.Contains(pair.Key.Id)); + } + } + + private VisualElement BuildRegion(IRegionNode region, bool isLane) + { + var container = new VisualElement(); + + container.AddToClassList("sc-region"); + container.EnableInClassList("sc-lane", isLane); + + foreach (var state in region.States) + { + container.Add(BuildState(state)); + } + + return container; + } + + private VisualElement BuildState(IStateNode state) + { + var box = new VisualElement { tooltip = $"{state.Path}\n{state.Kind}" }; + + box.AddToClassList("sc-state"); + box.AddToClassList($"sc-kind-{state.Kind.ToString().ToLowerInvariant()}"); + _elements[state] = box; + + if (state.Kind == StateKind.Initial || state.Kind == StateKind.Final) + { + box.AddToClassList("sc-pseudo"); + box.Add(new Label(state.Kind == StateKind.Initial ? "●" : "◉")); + return box; + } + + var title = new VisualElement(); + title.AddToClassList("sc-state-title"); + title.Add(new Label(state.Name) { name = "name" }); + + if (state.Kind != StateKind.Simple) + { + var badge = new Label(state.Kind.ToString()); + badge.AddToClassList("sc-badge"); + title.Add(badge); + } + + box.Add(title); + + if (state.Regions.Count > 0) + { + var regions = new VisualElement(); + + regions.AddToClassList("sc-regions"); + regions.EnableInClassList("sc-regions-split", state.Kind == StateKind.Split); + + foreach (var region in state.Regions) + { + regions.Add(BuildRegion(region, state.Kind == StateKind.Split)); + } + + box.Add(regions); + } + + foreach (var edge in state.Transitions) + { + if (edge.Kind == TransitionKind.Automatic && edge.Target != null) + { + continue; + } + + var chip = new Label($"{EdgeLabel(edge)} → {edge.Target?.Name ?? "action"}"); + chip.AddToClassList("sc-edge"); + box.Add(chip); + } + + return box; + } + + private static string EdgeLabel(ITransitionEdge edge) + { + switch (edge.Kind) + { + case TransitionKind.Event: + return edge.Event.Name; + case TransitionKind.Choice: + return edge.HasCondition ? "if" : "else"; + case TransitionKind.Completion: + return "done"; + case TransitionKind.Leave: + return "leave"; + default: + return "auto"; + } + } + } +} diff --git a/Editor/LiveChartView.cs.meta b/Editor/LiveChartView.cs.meta new file mode 100644 index 0000000..116ddba --- /dev/null +++ b/Editor/LiveChartView.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: d5eb4c35f6a2f429686f0f5d376897dd \ No newline at end of file diff --git a/Editor/StatechartDebugger.uss b/Editor/StatechartDebugger.uss new file mode 100644 index 0000000..e2c21d5 --- /dev/null +++ b/Editor/StatechartDebugger.uss @@ -0,0 +1,167 @@ +.sc-root { + flex-grow: 1; +} + +.sc-chart-menu { + min-width: 160px; +} + +.sc-status { + -unity-text-align: middle-left; + padding: 0 8px; + color: rgb(230, 160, 60); +} + +.sc-status-running { + color: rgb(80, 190, 110); +} + +.sc-empty { + margin: 24px; + white-space: normal; + color: rgba(128, 128, 128, 1); +} + +.sc-body { + flex-grow: 1; + flex-direction: row; +} + +.sc-pane { + flex-grow: 1; + flex-basis: 0; + border-right-width: 1px; + border-right-color: rgba(0, 0, 0, 0.3); +} + +.sc-pane-live { + flex-grow: 2; +} + +.sc-pane-header { + -unity-font-style: bold; + padding: 4px 8px; + background-color: rgba(128, 128, 128, 0.15); +} + +.sc-pane-content { + flex-grow: 1; + padding: 8px; +} + +.sc-region { + flex-direction: row; + flex-wrap: wrap; + align-items: flex-start; +} + +.sc-regions { + flex-direction: column; + margin-top: 4px; +} + +.sc-regions-split { + flex-direction: row; +} + +.sc-lane { + flex-grow: 1; + border-width: 1px; + border-color: rgba(128, 128, 128, 0.6); + border-radius: 4px; + padding: 4px; + margin: 2px; +} + +.sc-state { + border-width: 1px; + border-color: rgba(128, 128, 128, 0.7); + border-radius: 6px; + padding: 4px 6px; + margin: 3px; + min-width: 70px; + background-color: rgba(128, 128, 128, 0.08); +} + +.sc-state-title { + flex-direction: row; + align-items: center; +} + +.sc-state-title > #name { + -unity-font-style: bold; +} + +.sc-badge { + font-size: 9px; + margin-left: 4px; + padding: 0 4px; + border-radius: 3px; + background-color: rgba(128, 128, 128, 0.25); +} + +.sc-edge { + font-size: 10px; + color: rgba(128, 128, 128, 1); +} + +.sc-pseudo { + min-width: 0; + border-radius: 10px; + padding: 0 4px; + align-self: center; +} + +.sc-state.sc-active { + border-width: 2px; + border-color: rgb(60, 180, 95); + background-color: rgba(60, 180, 95, 0.18); +} + +.sc-state.sc-recent { + border-color: rgb(255, 200, 60); +} + +.sc-tree { + flex-grow: 1; + flex-basis: 0; + padding: 4px 0; +} + +.sc-tree-row { + color: rgba(128, 128, 128, 1); +} + +.sc-tree-row.sc-active { + color: rgb(60, 180, 95); + -unity-font-style: bold; +} + +.sc-tree-lane { + font-size: 9px; + color: rgba(128, 128, 128, 0.8); + -unity-font-style: italic; +} + +.sc-trace { + flex-grow: 1; + flex-basis: 0; +} + +.sc-trace-row { + font-size: 11px; + padding-left: 6px; + -unity-text-align: middle-left; +} + +.sc-trace-event { + color: rgb(255, 200, 60); +} + +.sc-trace-enter { + color: rgb(60, 180, 95); +} + +.sc-trace-fault { + color: rgb(230, 80, 80); +} diff --git a/Editor/StatechartDebugger.uss.meta b/Editor/StatechartDebugger.uss.meta new file mode 100644 index 0000000..09c006e --- /dev/null +++ b/Editor/StatechartDebugger.uss.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 5ae4d79bb23a74f1398d278a1219f301 +ScriptedImporter: + internalIDToNameTable: [] + externalObjects: {} + serializedVersion: 2 + userData: + assetBundleName: + assetBundleVariant: + script: {fileID: 12385, guid: 0000000000000000e000000000000000, type: 0} + disableValidation: 0 + unsupportedSelectorAction: 0 diff --git a/Editor/StatechartDebuggerWindow.cs b/Editor/StatechartDebuggerWindow.cs new file mode 100644 index 0000000..215b754 --- /dev/null +++ b/Editor/StatechartDebuggerWindow.cs @@ -0,0 +1,264 @@ +using System; +using System.Collections.Generic; +using UnityEditor; +using UnityEditor.UIElements; +using UnityEngine; +using UnityEngine.UIElements; + +// ReSharper disable CheckNamespace + +namespace GameLovers.StatechartMachine.Editor +{ + /// + /// Live debugger for every running . Shows the selected chart as a live chart of nested + /// boxes and as a state tree with its trace log; the toolbar toggles turn each view on or off. + /// + public class StatechartDebuggerWindow : EditorWindow + { + private const string StyleSheetPath = "Packages/com.gamelovers.statechart/Editor/StatechartDebugger.uss"; + private const long RefreshIntervalMs = 100; + + [SerializeField] private string _selectedChartName; + [SerializeField] private bool _showLiveChart = true; + [SerializeField] private bool _showTreeTrace = true; + + private readonly List _activeStates = new List(); + + private StatechartRegistry.Entry _selected; + private IStatechart _selectedChart; + private int _renderedVersion = -1; + private ToolbarMenu _chartMenu; + private Label _statusLabel; + private VisualElement _body; + private Label _emptyLabel; + private LiveChartView _liveChartView; + private TreeTraceView _treeTraceView; + + [MenuItem("Tools/GameLovers/Statechart Debugger", priority = 100)] + private static void Open() + { + var window = GetWindow(); + + window.titleContent = new GUIContent("Statechart Debugger"); + window.minSize = new Vector2(480, 320); + window.Show(); + } + + private void CreateGUI() + { + var styleSheet = AssetDatabase.LoadAssetAtPath(StyleSheetPath); + + if (styleSheet != null) + { + rootVisualElement.styleSheets.Add(styleSheet); + } + + rootVisualElement.AddToClassList("sc-root"); + rootVisualElement.Add(BuildToolbar()); + + _emptyLabel = new Label("No live statecharts. Enter Play mode, or create a Statechart from code."); + _emptyLabel.AddToClassList("sc-empty"); + rootVisualElement.Add(_emptyLabel); + + _body = new VisualElement(); + _body.AddToClassList("sc-body"); + rootVisualElement.Add(_body); + + _liveChartView = new LiveChartView(); + _treeTraceView = new TreeTraceView(); + _body.Add(_liveChartView); + _body.Add(_treeTraceView); + + StatechartRegistry.Changed += OnRegistryChanged; + rootVisualElement.RegisterCallback(_ => StatechartRegistry.Changed -= OnRegistryChanged); + rootVisualElement.schedule.Execute(Refresh).Every(RefreshIntervalMs); + + ApplyViewVisibility(); + SelectChart(null); + } + + private Toolbar BuildToolbar() + { + var toolbar = new Toolbar(); + + _chartMenu = new ToolbarMenu { text = "Select chart" }; + _chartMenu.AddToClassList("sc-chart-menu"); + _chartMenu.RegisterCallback(_ => PopulateChartMenu(), TrickleDown.TrickleDown); + toolbar.Add(_chartMenu); + + _statusLabel = new Label(); + _statusLabel.AddToClassList("sc-status"); + toolbar.Add(_statusLabel); + + toolbar.Add(new ToolbarButton(() => _selectedChart?.Run()) { text = "Run", tooltip = "Run or resume the chart" }); + toolbar.Add(new ToolbarButton(() => _selectedChart?.Pause()) { text = "Pause" }); + toolbar.Add(new ToolbarButton(() => _selectedChart?.Reset()) { text = "Reset", tooltip = "Reset to the initial state" }); + toolbar.Add(new ToolbarSpacer { flex = true }); + + toolbar.Add(CreateViewToggle("Live chart", _showLiveChart, value => _showLiveChart = value)); + toolbar.Add(CreateViewToggle("Tree + trace", _showTreeTrace, value => _showTreeTrace = value)); + + var copyMenu = new ToolbarMenu { text = "Copy" }; + copyMenu.menu.AppendAction("Mermaid diagram", _ => Copy(StatechartExport.ToMermaid), + _ => _selectedChart != null ? DropdownMenuAction.Status.Normal : DropdownMenuAction.Status.Disabled); + copyMenu.menu.AppendAction("Active state paths", _ => Copy(StatechartExport.ToActivePaths), + _ => _selectedChart != null ? DropdownMenuAction.Status.Normal : DropdownMenuAction.Status.Disabled); + copyMenu.menu.AppendAction("Trace history", _ => CopyTrace(), + _ => _selected != null ? DropdownMenuAction.Status.Normal : DropdownMenuAction.Status.Disabled); + toolbar.Add(copyMenu); + + return toolbar; + } + + private ToolbarToggle CreateViewToggle(string label, bool initial, Action setter) + { + var toggle = new ToolbarToggle { text = label, value = initial }; + + toggle.RegisterValueChangedCallback(evt => + { + setter(evt.newValue); + ApplyViewVisibility(); + }); + + return toggle; + } + + private void ApplyViewVisibility() + { + _liveChartView.style.display = _showLiveChart ? DisplayStyle.Flex : DisplayStyle.None; + _treeTraceView.style.display = _showTreeTrace ? DisplayStyle.Flex : DisplayStyle.None; + } + + private void PopulateChartMenu() + { + var menu = _chartMenu.menu; + + menu.ClearItems(); + + foreach (var entry in StatechartRegistry.GetEntries()) + { + var captured = entry; + + menu.AppendAction(entry.Name, _ => SelectChart(captured), + _ => captured == _selected ? DropdownMenuAction.Status.Checked : DropdownMenuAction.Status.Normal); + } + + if (StatechartRegistry.GetEntries().Count == 0) + { + menu.AppendAction("No live statecharts", null, DropdownMenuAction.Status.Disabled); + } + } + + private void OnRegistryChanged() + { + if (_selected == null || !_selected.TryGetChart(out _) || !Contains(StatechartRegistry.GetEntries(), _selected)) + { + SelectChart(null); + } + } + + private void SelectChart(StatechartRegistry.Entry entry) + { + var entries = StatechartRegistry.GetEntries(); + + if (entry == null) + { + // Prefer the last selected name so the window survives domain reloads and play mode restarts. + foreach (var candidate in entries) + { + if (candidate.Name == _selectedChartName) + { + entry = candidate; + break; + } + } + + entry ??= entries.Count > 0 ? entries[entries.Count - 1] : null; + } + + _selected = entry; + _selectedChart = null; + entry?.TryGetChart(out _selectedChart); + _selectedChartName = entry?.Name ?? _selectedChartName; + _renderedVersion = -1; + + _chartMenu.text = entry?.Name ?? "Select chart"; + _emptyLabel.style.display = _selectedChart == null ? DisplayStyle.Flex : DisplayStyle.None; + _body.style.display = _selectedChart == null ? DisplayStyle.None : DisplayStyle.Flex; + + _liveChartView.SetChart(_selectedChart); + _treeTraceView.SetChart(_selectedChart); + Refresh(); + } + + private void Refresh() + { + if (_selected != null && !_selected.TryGetChart(out _)) + { + SelectChart(null); + return; + } + + if (_selectedChart == null) + { + if (StatechartRegistry.GetEntries().Count > 0) + { + SelectChart(null); + } + + return; + } + + _statusLabel.text = _selectedChart.IsRunning ? "Running" : "Paused"; + _statusLabel.EnableInClassList("sc-status-running", _selectedChart.IsRunning); + + if (_renderedVersion == StatechartRegistry.Version) + { + return; + } + + _renderedVersion = StatechartRegistry.Version; + _selectedChart.GetActiveStates(_activeStates); + _liveChartView.UpdateActive(_activeStates, _selected.History); + _treeTraceView.UpdateActive(_activeStates, _selected.History); + } + + private void Copy(Func export) + { + if (_selectedChart != null) + { + EditorGUIUtility.systemCopyBuffer = export(_selectedChart); + } + } + + private void CopyTrace() + { + if (_selected == null) + { + return; + } + + var lines = new List(); + + foreach (var record in _selected.History) + { + lines.Add($"#{record.Frame} {record.Message}"); + } + + EditorGUIUtility.systemCopyBuffer = string.Join("\n", lines); + } + + private static bool Contains(IReadOnlyList entries, StatechartRegistry.Entry entry) + { + for (var i = 0; i < entries.Count; i++) + { + if (entries[i] == entry) + { + return true; + } + } + + return false; + } + } +} diff --git a/Editor/StatechartDebuggerWindow.cs.meta b/Editor/StatechartDebuggerWindow.cs.meta new file mode 100644 index 0000000..b6d4c2e --- /dev/null +++ b/Editor/StatechartDebuggerWindow.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 83401716ef65c444e8089150d477da78 \ No newline at end of file diff --git a/Editor/StatechartExport.cs b/Editor/StatechartExport.cs new file mode 100644 index 0000000..3de4cbd --- /dev/null +++ b/Editor/StatechartExport.cs @@ -0,0 +1,162 @@ +using System; +using System.Collections.Generic; +using System.Text; + +// ReSharper disable CheckNamespace + +namespace GameLovers.StatechartMachine.Editor +{ + /// + /// Text exports of a statechart's topology and active states, for the Statechart Debugger's Copy menu. + /// + internal static class StatechartExport + { + /// + /// Returns a Mermaid stateDiagram-v2 of the chart with its active states classed active. + /// + internal static string ToMermaid(IStatechart statechart) + { + if (statechart == null) + { + throw new ArgumentNullException(nameof(statechart)); + } + + var builder = new StringBuilder(); + var active = new List(); + + statechart.GetActiveStates(active); + builder.AppendLine("stateDiagram-v2"); + AppendRegion(builder, statechart.RootRegion, 1, new List()); + builder.AppendLine(" classDef active fill:#9be7b0,stroke:#1d7a3d,stroke-width:2px"); + + var activeIds = new List(); + + foreach (var state in active) + { + if (state.Kind != StateKind.Initial && state.Kind != StateKind.Final) + { + activeIds.Add(Id(state)); + } + } + + if (activeIds.Count > 0) + { + builder.Append(" class ").Append(string.Join(",", activeIds)).AppendLine(" active"); + } + + return builder.ToString(); + } + + /// Returns the active state paths of the chart, one per line, parents before children. + internal static string ToActivePaths(IStatechart statechart) + { + if (statechart == null) + { + throw new ArgumentNullException(nameof(statechart)); + } + + var active = new List(); + var builder = new StringBuilder(); + + statechart.GetActiveStates(active); + + foreach (var state in active) + { + builder.AppendLine(state.Path); + } + + return builder.ToString(); + } + + private static void AppendRegion(StringBuilder builder, IRegionNode region, int depth, + List leaveEdges) + { + var indent = new string(' ', depth * 2); + + foreach (var state in region.States) + { + if (state.Kind == StateKind.Initial || state.Kind == StateKind.Final) + { + continue; + } + + if (state.Regions.Count == 0) + { + builder.Append(indent).Append(Id(state)).Append(" : ").AppendLine(Label(state)); + continue; + } + + builder.Append(indent).Append("state \"").Append(Label(state)).Append("\" as ").Append(Id(state)) + .AppendLine(" {"); + + var innerLeaves = new List(); + + for (var i = 0; i < state.Regions.Count; i++) + { + if (i > 0) + { + builder.Append(indent).AppendLine(" --"); + } + + AppendRegion(builder, state.Regions[i], depth + 1, innerLeaves); + } + + builder.Append(indent).AppendLine("}"); + + // Mermaid cannot draw an edge out of a composite from inside it, so a leave is drawn from its owner. + foreach (var leave in innerLeaves) + { + builder.Append(indent).Append(Id(state)).Append(" --> ").Append(Endpoint(leave.Target)) + .Append(" : leave ").AppendLine(leave.Source.Name.Replace(":", " ")); + } + } + + foreach (var state in region.States) + { + foreach (var edge in state.Transitions) + { + if (edge.Target == null) + { + continue; + } + + if (edge.Kind == TransitionKind.Leave) + { + leaveEdges.Add(edge); + continue; + } + + var label = edge.Event?.Name ?? (edge.HasCondition ? "[condition]" : null); + + builder.Append(indent).Append(Endpoint(edge.Source)).Append(" --> ").Append(Endpoint(edge.Target)); + + if (label != null) + { + builder.Append(" : ").Append(label.Replace(":", " ")); + } + + builder.AppendLine(); + } + } + } + + private static string Endpoint(IStateNode state) + { + return state.Kind == StateKind.Initial || state.Kind == StateKind.Final ? "[*]" : Id(state); + } + + private static string Id(IStateNode state) + { + return $"s{state.Id}"; + } + + private static string Label(IStateNode state) + { + var name = state.Name.Replace("\"", "'").Replace(":", " "); + + return state.Kind == StateKind.Simple || state.Kind == StateKind.Nest || state.Kind == StateKind.Split + ? name + : $"{name} ({state.Kind})"; + } + } +} diff --git a/Editor/StatechartExport.cs.meta b/Editor/StatechartExport.cs.meta new file mode 100644 index 0000000..cd1bcb0 --- /dev/null +++ b/Editor/StatechartExport.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 58160ead0971451abe547f2f3e680129 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Editor/StatechartRegistry.cs b/Editor/StatechartRegistry.cs new file mode 100644 index 0000000..1d2b3e7 --- /dev/null +++ b/Editor/StatechartRegistry.cs @@ -0,0 +1,140 @@ +using System; +using System.Collections.Generic; +using UnityEditor; +using UnityEngine; + +// ReSharper disable CheckNamespace + +namespace GameLovers.StatechartMachine.Editor +{ + /// + /// A trace step copied as ids and text, so recorded history never keeps a chart or its states alive. + /// + internal readonly struct StatechartTraceRecord + { + public readonly double Time; + public readonly int Frame; + public readonly StatechartTraceKind Kind; + public readonly uint StateId; + public readonly uint TargetId; + public readonly string StatePath; + public readonly string TargetPath; + public readonly string EventName; + public readonly string Message; + + public StatechartTraceRecord(in StatechartTrace trace, double time, int frame) + { + Time = time; + Frame = frame; + Kind = trace.Kind; + StateId = trace.State?.Id ?? 0; + TargetId = trace.Target?.Id ?? 0; + StatePath = trace.State?.Path; + TargetPath = trace.Target?.Path; + EventName = trace.Event?.Name; + Message = trace.ToString(); + } + } + + /// + /// List of live statecharts and their recent trace history, read by the Statechart Debugger. + /// Charts are held weakly, so a chart that is never disposed still disappears once it is collected. + /// + [InitializeOnLoad] + internal static class StatechartRegistry + { + internal const int HistoryCapacity = 256; + + private static readonly List _entries = new List(); + + /// Raised on the main thread after a chart is added or removed. + internal static event Action Changed; + + /// Increments on every recorded trace of any chart, so views can repaint only on change. + internal static int Version { get; private set; } + + /// + /// One registered chart and its recent trace history, oldest first. + /// + internal sealed class Entry + { + private readonly WeakReference _chart; + private readonly Queue _history = new Queue(); + + /// The chart name captured at registration. + internal string Name { get; } + /// The recent trace steps, oldest first, capped at . + internal IReadOnlyCollection History => _history; + + internal Entry(IStatechart chart) + { + _chart = new WeakReference(chart); + Name = chart.Name; + } + + /// Returns the chart while it is still alive. + internal bool TryGetChart(out IStatechart chart) + { + return _chart.TryGetTarget(out chart); + } + + /// Records ; a Disposed trace also leaves the registry. + internal void Record(StatechartTrace trace) + { + if (_history.Count == HistoryCapacity) + { + _history.Dequeue(); + } + + _history.Enqueue(new StatechartTraceRecord(trace, Time.realtimeSinceStartupAsDouble, Time.frameCount)); + Version++; + + if (trace.Kind == StatechartTraceKind.Disposed && _entries.Remove(this)) + { + Changed?.Invoke(); + } + } + } + + static StatechartRegistry() + { + Statechart.Created += Register; + EditorApplication.playModeStateChanged += OnPlayModeChanged; + } + + /// + /// Returns the live entries, dropping charts that were collected. + /// + internal static IReadOnlyList GetEntries() + { + if (_entries.RemoveAll(entry => !entry.TryGetChart(out _)) > 0) + { + Changed?.Invoke(); + } + + return _entries; + } + + private static void Register(Statechart chart) + { + var entry = new Entry(chart); + + chart.Traced += entry.Record; + _entries.RemoveAll(e => !e.TryGetChart(out _)); + _entries.Add(entry); + Changed?.Invoke(); + } + + private static void OnPlayModeChanged(PlayModeStateChange change) + { + if (change != PlayModeStateChange.ExitingEditMode) + { + return; + } + + // Keeps charts from a previous play session out when domain reload is disabled. + _entries.Clear(); + Changed?.Invoke(); + } + } +} diff --git a/Editor/StatechartRegistry.cs.meta b/Editor/StatechartRegistry.cs.meta new file mode 100644 index 0000000..9018a00 --- /dev/null +++ b/Editor/StatechartRegistry.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 10c96eacee9943a18ed8f36477030720 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Editor/TreeTraceView.cs b/Editor/TreeTraceView.cs new file mode 100644 index 0000000..6ab0b44 --- /dev/null +++ b/Editor/TreeTraceView.cs @@ -0,0 +1,143 @@ +using System.Collections.Generic; +using UnityEngine.UIElements; + +// ReSharper disable CheckNamespace + +namespace GameLovers.StatechartMachine.Editor +{ + /// + /// An indented tree of every state with the active ones marked, above a scrolling trace log. + /// + internal sealed class TreeTraceView : VisualElement + { + private readonly Dictionary _rows = new Dictionary(); + private readonly List _records = new List(); + private readonly ScrollView _tree; + private readonly ListView _trace; + + internal TreeTraceView() + { + AddToClassList("sc-pane"); + AddToClassList("sc-pane-tree"); + + var treeHeader = new Label("State tree"); + treeHeader.AddToClassList("sc-pane-header"); + Add(treeHeader); + + _tree = new ScrollView(); + _tree.AddToClassList("sc-tree"); + Add(_tree); + + var traceHeader = new Label("Trace (newest last)"); + traceHeader.AddToClassList("sc-pane-header"); + Add(traceHeader); + + _trace = new ListView(_records, 18, MakeTraceRow, BindTraceRow) + { + selectionType = SelectionType.None + }; + _trace.AddToClassList("sc-trace"); + Add(_trace); + } + + /// Rebuilds the tree for , or clears it when null. + internal void SetChart(IStatechart chart) + { + _rows.Clear(); + _tree.Clear(); + _records.Clear(); + _trace.RefreshItems(); + + if (chart != null) + { + AddRegion(chart.RootRegion); + } + } + + /// Marks states and shows the latest . + internal void UpdateActive(List active, IReadOnlyCollection history) + { + foreach (var pair in _rows) + { + var isActive = active.Contains(pair.Key); + + pair.Value.text = $"{(isActive ? "●" : "○")} {pair.Key.Name}"; + pair.Value.EnableInClassList("sc-active", isActive); + } + + _records.Clear(); + _records.AddRange(history); + _trace.RefreshItems(); + + if (_records.Count > 0) + { + _trace.ScrollToItem(_records.Count - 1); + } + } + + private void AddRegion(IRegionNode region) + { + if (region.Owner != null && region.Owner.Kind == StateKind.Split) + { + var lane = new Label($"region {region.Index + 1}"); + lane.AddToClassList("sc-tree-lane"); + lane.style.paddingLeft = region.Depth * 14; + _tree.Add(lane); + } + + foreach (var state in region.States) + { + var row = new Label { tooltip = $"{state.Path} ({state.Kind})" }; + + row.AddToClassList("sc-tree-row"); + row.style.paddingLeft = region.Depth * 14 + 4; + _rows[state] = row; + _tree.Add(row); + + foreach (var child in state.Regions) + { + AddRegion(child); + } + } + } + + private static VisualElement MakeTraceRow() + { + var label = new Label(); + + label.AddToClassList("sc-trace-row"); + + return label; + } + + private void BindTraceRow(VisualElement element, int index) + { + var record = _records[index]; + var label = (Label) element; + + label.text = $"#{record.Frame} {Describe(record)}"; + label.EnableInClassList("sc-trace-event", record.Kind == StatechartTraceKind.EventTriggered); + label.EnableInClassList("sc-trace-fault", record.Kind == StatechartTraceKind.Faulted); + label.EnableInClassList("sc-trace-enter", record.Kind == StatechartTraceKind.StateEntered); + } + + private static string Describe(StatechartTraceRecord record) + { + switch (record.Kind) + { + case StatechartTraceKind.EventTriggered: + return $"⚡ {record.EventName}"; + case StatechartTraceKind.StateEntered: + return $"→ enter {record.StatePath}"; + case StatechartTraceKind.StateExited: + return $"← exit {record.StatePath}"; + case StatechartTraceKind.Transition: + return $" {record.StatePath} ⟶ {record.TargetPath ?? "(action)"}"; + case StatechartTraceKind.Faulted: + return $"✖ fault in {record.StatePath}"; + default: + return record.Kind.ToString(); + } + } + } +} diff --git a/Editor/TreeTraceView.cs.meta b/Editor/TreeTraceView.cs.meta new file mode 100644 index 0000000..d144a60 --- /dev/null +++ b/Editor/TreeTraceView.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: f0c5c27682ea24eea9d881b58f5e8ba8 \ No newline at end of file diff --git a/README.md b/README.md index cf3de76..d3f4090 100644 --- a/README.md +++ b/README.md @@ -1,103 +1,147 @@ # GameLovers Statechart -[![Unity Version](https://img.shields.io/badge/Unity-2022.3%2B-blue.svg)](https://unity3d.com/get-unity/download) -[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](LICENSE.md) - -A Hierarchical Finite State Machine (Statechart / HFSM) for Unity — states can nest into sub-regions, split into parallel regions, and block on async waits, all defined once in a single setup closure with no runtime mutation of the chart's shape. - -## Why Use This Package? - -Plain FSMs get unwieldy once a game state has sub-states of its own (a "Playing" state that is itself "Loading" → "Countdown" → "InProgress"), or needs two things happening at once (an animation playing while input is disabled). A Statechart — per the [UML spec](http://www.omg.org/spec/UML) and the broader [statecharts model](https://statecharts.github.io/what-is-a-statechart.html) — solves both by letting a state open its own nested region (`Nest`) or two parallel regions (`Split`), instead of flattening everything into one state graph. - -### Key Features -- **10 state types** covering the common Statechart vocabulary: `Initial`, `Final`, `State` (event-blocking), `Transition` (pass-through), `Choice` (conditional branch), `Wait` (activity-blocking), `TaskWait` (async-blocking), `Nest` (sequential sub-region), `Split` (parallel sub-regions), `Leave` (early exit to a parent region). -- **Fluent setup** — one constructor closure defines the entire chart; no separate registration step. -- **Async-aware waiting** — `TaskWait` states block on a `Task` or `UniTask` directly. -- **Editor-time validation** — malformed setups (missing initial state, transition with no target, transition loops) throw immediately at construction in the Editor / Debug builds. +Hierarchical statecharts for Unity 6 with nested and parallel regions, event transitions, choices, async waits, a live debugger, and a playable sample. -## System Requirements +[![Unity](https://img.shields.io/badge/Unity-6000.0%20%7C%206000.3%20%7C%206000.6-blue.svg)](https://unity.com/download) +[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](LICENSE.md) -- **[Unity](https://unity.com/download)** (v2022.3+) — the only package in the GameLovers family that doesn't require Unity 6 -- **[UniTask](https://github.com/Cysharp/UniTask)** (v2.5.10+) — for the `ITaskWaitState.WaitingFor(Func)` overload +## When to use it -Dependencies are automatically resolved when installing via Unity Package Manager. +Use Statechart when a flat FSM cannot express hierarchical behavior, concurrent regions, or controlled async waits clearly. The package is pipeline-neutral and requires UniTask for its `UniTask` wait overloads. -## Installation +## Unity compatibility -### Via Unity Package Manager (Recommended) +| Item | Current policy | +| --- | --- | +| Minimum Unity version | `6000.0` | +| Supported streams | `6000.0.x`, `6000.3.x`, `6000.6.x` (LTS) | +| Statechart Debugger | All supported streams | +| Render pipeline | Pipeline-neutral | -1. Open Unity Package Manager (`Window` → `Package Manager`) -2. Click `+` → `Add package from git URL` -3. Enter: `https://github.com/CoderGamester/Statechart-HFSM.git` +## Install -### Via manifest.json +Add UniTask explicitly when installing from Git. Use UniTask 2.5.11 or newer: 2.5.10's Editor code does not compile on Unity 6000.6. ```json { "dependencies": { - "com.gamelovers.statechart": "https://github.com/CoderGamester/Statechart-HFSM.git" + "com.cysharp.unitask": "https://github.com/Cysharp/UniTask.git?path=src/UniTask/Assets/Plugins/UniTask#2.5.11", + "com.gamelovers.statechart": "https://github.com/CoderGamester/Statechart-HFSM.git#1.0.0" } } ``` -## Key Components - -| Type | Purpose | -|---|---| -| `Statechart` | The chart itself — `Run()` / `Pause()` / `Trigger(event)` / `Reset()` | -| `IStateFactory` | Passed into the setup closure; one factory method per state type (`Initial`, `Final`, `State`, `Transition`, `Choice`, `Wait`, `TaskWait`, `Nest`, `Split`, `Leave`) | -| `ITransition` / `ITransitionCondition` | `.OnTransition(action).Target(state)`; `Choice` transitions add `.Condition(() => bool)` | -| `IStatechartEvent` / `StatechartEvent` | Event identity is per-instance — keep one instance per logical event | -| `IWaitActivity` | Passed into a `Wait` state's `WaitingFor(...)`; call `.Complete()` to unblock, or `.Split()` to fan out | +## First success -## Quick Start +Keep events as fields: statechart event identity is by object instance, not by its display name. Give the chart a name so logs and the debugger can tell charts apart, and dispose it with its owner. ```csharp using GameLovers.StatechartMachine; using UnityEngine; -var jumpEvent = new StatechartEvent("Jump"); - -var statechart = new Statechart(factory => +public sealed class PlayerStatechart : MonoBehaviour { - var initial = factory.Initial("Initial"); - var idle = factory.State("Idle"); - var jumping = factory.State("Jumping"); - var final = factory.Final("Final"); + private readonly StatechartEvent _jump = new("Jump"); + private IStatechart _chart; + + private void Awake() + { + _chart = new Statechart("Player", factory => + { + var initial = factory.Initial("Initial"); + var idle = factory.State("Idle"); + var jumping = factory.State("Jumping"); + + initial.Transition().Target(idle); + idle.Event(_jump).Target(jumping); + jumping.Event(_jump).Target(idle); + }); + _chart.Run(); + } + + private void OnDestroy() => _chart.Dispose(); + + public void Jump() => _chart.Trigger(_jump); +} +``` + +```mermaid +stateDiagram-v2 + [*] --> Idle + Idle --> Jumping: jump event + Jumping --> Idle: jump event +``` - initial.Transition().Target(idle); +## State kinds + +| Factory method | Kind | Behavior | +| --- | --- | --- | +| `Initial` | Initial | Entry point of a region; exactly one per region | +| `Final` | Final | Completes its region | +| `State` | Simple | Waits for events; event transitions may omit a target to run an action only | +| `Transition` | Transition | Passes straight through to its target, running its callbacks | +| `Choice` | Choice | Takes the first transition whose condition is true, otherwise the one without a condition | +| `Wait` | Wait | Resumes when its `IWaitActivity` completes; still reacts to configured events | +| `TaskWait` | TaskWait | Awaits a `Task` or `UniTask`; ignores events while waiting | +| `Nest` | Nest | One nested region; completes when that region reaches its final state | +| `Split` | Split | Two or more parallel regions; completes when all of them finish | +| `Leave` | Leave | Leaves the enclosing nest or split from inside a region | + +## Runtime semantics + +| Topic | Behavior | +| --- | --- | +| `Trigger` | Ignored until `Run()` and while paused | +| Run to completion | An event triggered while another one is processed (for example from `OnEnter`) is queued and processed right after it | +| `Pause()` | Stops the chart, also mid-chain when called from a callback; `Run()` resumes from the same states | +| `Reset()` | Returns to the initial state without exit callbacks; drops queued events and abandons pending waits and tasks | +| `Dispose()` | Stops the chart for good, cancels token-aware tasks and removes it from the debugger; `Run()` then throws `ObjectDisposedException` | +| `TaskWait` faults | A task that throws is logged and still completes the state, so the chart and parent splits never wait forever | +| `TaskWait` threads | The chart always resumes on the main thread, even if the awaited task completes on a worker thread | +| Cancellation | `WaitingFor(Func)` and the `Task` variant receive a token cancelled by `Reset()` and `Dispose()` | +| Callback exceptions | Enter, exit and transition exceptions are logged with the stack trace of the code that declared the failing state, and the chart keeps going | + +The constructor rejects a setup without an initial state in every build. Other setup validation (missing targets, self loops, malformed choices, leave depth) runs only in the Editor and in `DEBUG` builds. + +## Observe a running chart + +Every chart exposes its structure and its live state, so tools, tests and logs read the same data: - idle.Event(jumpEvent).OnTransition(() => Debug.Log("Jumping!")).Target(jumping); - idle.OnEnter(() => Debug.Log("Entered Idle")); +```csharp +// Read-only view of the chart; it is the live chart itself, so it never goes stale. +foreach (var state in chart.RootRegion.States) +{ + Debug.Log($"{state.Path} ({state.Kind}) with {state.Transitions.Count} transitions"); +} - jumping.OnEnter(() => Debug.Log("Entered Jumping")); - jumping.Event(jumpEvent).Target(final); // second Jump ends the chart +// Active states, parents before children. +var active = new List(); +chart.GetActiveStates(active); - final.OnEnter(() => Debug.Log("Done")); -}); +// Is one state active right now? Allocation-free. +var isIdle = chart.IsActive(active[0]); -statechart.Run(); -statechart.Trigger(jumpEvent); // Idle -> Jumping -statechart.Trigger(jumpEvent); // Jumping -> Final +// Every step in execution order: events, exits, transitions, enters, faults, lifecycle. +chart.Traced += trace => Debug.Log(trace); ``` -Every state is created via the `factory` passed into the constructor closure — there is no separate registration call, and the chart's shape cannot be changed after construction. See [AGENTS.md](AGENTS.md) for nested regions (`Nest`), parallel regions (`Split`), async waits (`TaskWait`), and the full state-type reference. +Set `chart.LogsEnabled = true` (or `LogsEnabled` on a single state) to write the same trace lines to the console, for example `[Statechart 'Player'] Idle -> Jumping on 'Jump'`. Nothing is formatted or published while no one subscribes and logs are off. -## Related docs +## Statechart Debugger -| Document | Purpose | -|---|---| -| [AGENTS.md](AGENTS.md) | Contributor/agent guide — full state-type reference, architecture, gotchas | -| [CHANGELOG.md](CHANGELOG.md) | Version history | +Open **Tools > GameLovers > Statechart Debugger** in Play mode. Pick a chart from the toolbar; Run, Pause and Reset act on that chart. Two views read the same data; the **Live chart** and **Tree + trace** toolbar toggles turn each one on or off: -## Contributing +| View | What it shows | +| --- | --- | +| **Live chart** | Nested boxes: nest and split states contain their regions, split regions are dashed lanes, active states are green and newly entered ones flash | +| **Tree + trace** | An indented tree with the active states marked, and the latest 256 trace steps | -Contributions are welcome! See [AGENTS.md](AGENTS.md) for architecture details, coding standards, and common workflows. +The **Copy** menu puts the Mermaid diagram, the active state paths or the trace history on the clipboard. -## Support +## Samples -- **Issues**: [Report bugs or request features](https://github.com/CoderGamester/Statechart-HFSM/issues) +Import **Game Flow** from the Package Manager's Samples tab. One statechart runs a small game loop that uses every state kind: a nested boot sequence with cancellable task waits, a menu, a split gameplay state (a player region and a waves region), a choice, leave states and results. It has on-screen buttons and an activity log, and is meant to be watched with the Statechart Debugger open. See the sample's `README.md`. -## License +## Support -MIT — see [LICENSE.md](LICENSE.md). +See [CHANGELOG.md](CHANGELOG.md) and file an [issue](https://github.com/CoderGamester/Statechart-HFSM/issues). `AGENTS.md` is contributor guidance, not end-user API documentation. diff --git a/Runtime/AssemblyInfo.cs b/Runtime/AssemblyInfo.cs new file mode 100644 index 0000000..004f244 --- /dev/null +++ b/Runtime/AssemblyInfo.cs @@ -0,0 +1,4 @@ +using System.Runtime.CompilerServices; + +[assembly: InternalsVisibleTo("GameLovers.Statechart.Editor")] +[assembly: InternalsVisibleTo("GameLovers.Statechart.Editor.Tests")] diff --git a/Runtime/AssemblyInfo.cs.meta b/Runtime/AssemblyInfo.cs.meta new file mode 100644 index 0000000..5848ea0 --- /dev/null +++ b/Runtime/AssemblyInfo.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 5f40afdb30bd4a39a76d3f6c22775184 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/IState.cs b/Runtime/IState.cs index 61d6e23..5830fd5 100644 --- a/Runtime/IState.cs +++ b/Runtime/IState.cs @@ -1,5 +1,6 @@ using Cysharp.Threading.Tasks; using System; +using System.Threading; using System.Threading.Tasks; // ReSharper disable CheckNamespace @@ -159,12 +160,29 @@ public interface ITaskWaitState : IStateEnter, IStateExit { /// /// Blocks the state behaviour until the given async is completed. - /// It will return the created that will triggered as soon as the state is unblocked + /// It will return the created that will triggered as soon as the state is unblocked. + /// A task that throws is logged and still completes the state, so the chart never waits forever; handle + /// errors inside the task when a failure needs a different path. The chart resumes on the main thread. /// + /// The async work to await each time the state is entered. + /// The transition taken when the task completes. + /// Thrown when is null. ITransition WaitingFor(Func taskAwaitAction); - /// + /// ITransition WaitingFor(Func taskAwaitAction); + + /// + /// Same as , but passes a token that is cancelled when the statechart is + /// reset or disposed, so long-running work can stop with the chart. + /// + /// The async work to await each time the state is entered. + /// The transition taken when the task completes. + /// Thrown when is null. + ITransition WaitingFor(Func taskAwaitAction); + + /// + ITransition WaitingFor(Func taskAwaitAction); } /// diff --git a/Runtime/Internal/ChoiceState.cs b/Runtime/Internal/ChoiceState.cs index 59db0a1..a111a9b 100644 --- a/Runtime/Internal/ChoiceState.cs +++ b/Runtime/Internal/ChoiceState.cs @@ -16,6 +16,9 @@ public ChoiceState(string name, IStateFactoryInternal factory) : base(name, fact { } + /// + public override StateKind Kind => StateKind.Choice; + /// public override void Enter() { @@ -77,7 +80,7 @@ public override void Validate() if (noTransitionConditionCount > 1) { UnityEngine.Debug.LogWarning($"Choice state {Name} has multiple transition without a condition defined." + - "This will lead to improper behaviour and will pick a random transition"); + "Only the last one declared is used as the fallback"); } #endif } @@ -87,7 +90,7 @@ public void OnEnter(Action action) { if (action == null) { - throw new NullReferenceException($"The state {Name} cannot have a null OnEnter action"); + throw new ArgumentNullException(nameof(action), $"The state {Name} cannot have a null OnEnter action"); } _onEnter.Add(action); @@ -98,7 +101,7 @@ public void OnExit(Action action) { if (action == null) { - throw new NullReferenceException($"The state {Name} cannot have a null OnExit action"); + throw new ArgumentNullException(nameof(action), $"The state {Name} cannot have a null OnExit action"); } _onExit.Add(action); @@ -107,7 +110,7 @@ public void OnExit(Action action) /// public ITransitionCondition Transition() { - var transition = new Transition(); + var transition = CreateTransition(TransitionKind.Choice); _transitions.Add(transition); diff --git a/Runtime/Internal/FinalState.cs b/Runtime/Internal/FinalState.cs index f43ca53..61e8d37 100644 --- a/Runtime/Internal/FinalState.cs +++ b/Runtime/Internal/FinalState.cs @@ -14,6 +14,9 @@ public FinalState(string name, IStateFactoryInternal factory) : base(name, facto { } + /// + public override StateKind Kind => StateKind.Final; + /// public override void Enter() { @@ -46,7 +49,7 @@ public void OnEnter(Action action) { if (action == null) { - throw new NullReferenceException($"The state {Name} cannot have a null OnEnter action"); + throw new ArgumentNullException(nameof(action), $"The state {Name} cannot have a null OnEnter action"); } _onEnter.Add(action); diff --git a/Runtime/Internal/InitialState.cs b/Runtime/Internal/InitialState.cs index 9238939..ba37d6c 100644 --- a/Runtime/Internal/InitialState.cs +++ b/Runtime/Internal/InitialState.cs @@ -16,6 +16,9 @@ public InitialState(string name, IStateFactoryInternal factory) : base(name, fac { } + /// + public override StateKind Kind => StateKind.Initial; + /// public override void Enter() { @@ -37,7 +40,7 @@ public override void Validate() #if UNITY_EDITOR || DEBUG if (_transition?.TargetState == null) { - throw new MissingMemberException($"Initial state {Name} doesn't have a transition defined, so nothing will happen"); + throw new InvalidOperationException($"Initial state {Name} doesn't have a transition defined, so nothing will happen"); } if (_transition.TargetState.Id == Id) @@ -55,7 +58,7 @@ public ITransition Transition() throw new InvalidOperationException($"State {Name} already has a transition defined"); } - _transition = new Transition(); + _transition = CreateTransition(TransitionKind.Automatic); return _transition; } @@ -65,7 +68,7 @@ public void OnExit(Action action) { if (action == null) { - throw new NullReferenceException($"The state {Name} cannot have a null OnExit action"); + throw new ArgumentNullException(nameof(action), $"The state {Name} cannot have a null OnExit action"); } _onExit.Add(action); diff --git a/Runtime/Internal/LeaveState.cs b/Runtime/Internal/LeaveState.cs index 8d3e467..83ad316 100644 --- a/Runtime/Internal/LeaveState.cs +++ b/Runtime/Internal/LeaveState.cs @@ -10,13 +10,18 @@ internal class LeaveState : StateInternal, ILeaveState { private readonly IList _onEnter = new List(); - /// The transition this leave state hands back to the parent region, set when the state is configured. + /// + /// The transition this leave state hands back to the parent region, set when the state is configured. + /// internal ITransitionInternal LeaveTransition { get; private set; } public LeaveState(string name, IStateFactoryInternal factory) : base(name, factory) { } + /// + public override StateKind Kind => StateKind.Leave; + /// public override void Enter() { @@ -59,7 +64,7 @@ public void OnEnter(Action action) { if (action == null) { - throw new NullReferenceException($"The state {Name} cannot have a null OnEnter action"); + throw new ArgumentNullException(nameof(action), $"The state {Name} cannot have a null OnEnter action"); } _onEnter.Add(action); @@ -73,7 +78,7 @@ public ITransition Transition() throw new InvalidOperationException($"State {Name} already has a transition defined"); } - LeaveTransition = new Transition(); + LeaveTransition = CreateTransition(TransitionKind.Leave); return LeaveTransition; } diff --git a/Runtime/Internal/NestState.cs b/Runtime/Internal/NestState.cs index 12509e6..e41f01e 100644 --- a/Runtime/Internal/NestState.cs +++ b/Runtime/Internal/NestState.cs @@ -12,6 +12,9 @@ public NestState(string name, IStateFactoryInternal factory) : base(name, factor { } + /// + public override StateKind Kind => StateKind.Nest; + /// public override void Validate() { diff --git a/Runtime/Internal/SimpleState.cs b/Runtime/Internal/SimpleState.cs index d45a1fa..6dfaf7e 100644 --- a/Runtime/Internal/SimpleState.cs +++ b/Runtime/Internal/SimpleState.cs @@ -16,6 +16,9 @@ public SimpleState(string name, IStateFactoryInternal factory) : base(name, fact { } + /// + public override StateKind Kind => StateKind.Simple; + /// public override void Enter() { @@ -53,7 +56,7 @@ public void OnEnter(Action action) { if (action == null) { - throw new NullReferenceException($"The state {Name} cannot have a null OnEnter action"); + throw new ArgumentNullException(nameof(action), $"The state {Name} cannot have a null OnEnter action"); } _onEnter.Add(action); @@ -64,7 +67,7 @@ public void OnExit(Action action) { if (action == null) { - throw new NullReferenceException($"The state {Name} cannot have a null OnExit action"); + throw new ArgumentNullException(nameof(action), $"The state {Name} cannot have a null OnExit action"); } _onExit.Add(action); @@ -75,10 +78,10 @@ public ITransition Event(IStatechartEvent statechartEvent) { if (statechartEvent == null) { - throw new NullReferenceException($"The state {Name} cannot have a null event"); + throw new ArgumentNullException(nameof(statechartEvent), $"The state {Name} cannot have a null event"); } - var transition = new Transition(); + var transition = CreateTransition(TransitionKind.Event, statechartEvent); _events.Add(statechartEvent, transition); diff --git a/Runtime/Internal/SplitState.cs b/Runtime/Internal/SplitState.cs index 62a22d8..4d9b180 100644 --- a/Runtime/Internal/SplitState.cs +++ b/Runtime/Internal/SplitState.cs @@ -13,13 +13,23 @@ internal class SplitState : StateInternal, ISplitState protected readonly IDictionary _events = new Dictionary(); protected readonly IList _innerStatesData = new List(); + private readonly List _regions = new List(); + private bool _isPaused; private ITransitionInternal _transition; + /// The nested regions of this state and their current inner state. + internal IList InnerStates => _innerStatesData; + public SplitState(string name, IStateFactoryInternal factory) : base(name, factory) { } + /// + public override StateKind Kind => StateKind.Split; + /// + public override IReadOnlyList Regions => _regions; + /// public override void Enter() { @@ -51,12 +61,12 @@ public override void Exit() if (innerState.ExecuteExit) { - innerState.CurrenState.Exit(); + innerState.CurrenState.ExitSafely(null); } if (innerState.ExecuteFinal && !(innerState.CurrenState is FinalState) && !(innerState.CurrenState is LeaveState)) { - innerState.NestedFactory.FinalState?.Enter(); + innerState.NestedFactory.FinalState?.EnterSafely(null); } } @@ -118,7 +128,7 @@ public void OnEnter(Action action) { if (action == null) { - throw new NullReferenceException($"The state {Name} cannot have a null OnEnter action"); + throw new ArgumentNullException(nameof(action), $"The state {Name} cannot have a null OnEnter action"); } _onEnter.Add(action); @@ -129,7 +139,7 @@ public void OnExit(Action action) { if (action == null) { - throw new NullReferenceException($"The state {Name} cannot have a null OnExit action"); + throw new ArgumentNullException(nameof(action), $"The state {Name} cannot have a null OnExit action"); } _onExit.Add(action); @@ -140,10 +150,10 @@ public ITransition Event(IStatechartEvent statechartEvent) { if (statechartEvent == null) { - throw new NullReferenceException($"The state {Name} cannot have a null event"); + throw new ArgumentNullException(nameof(statechartEvent), $"The state {Name} cannot have a null event"); } - var transition = new Transition(); + var transition = CreateTransition(TransitionKind.Event, statechartEvent); _events.Add(statechartEvent, transition); @@ -173,11 +183,11 @@ public ITransition Split(params NestedStateData[] data) foreach (var stateData in data) { - var factory = new StateFactory(_stateFactory.RegionLayer + 1, _stateFactory.Data); + var factory = new StateFactory(this, _regions.Count, _stateFactory.RegionLayer + 1, _stateFactory.Data); stateData.Setup(factory); - _stateFactory.Add(factory.States); + _regions.Add(factory); _innerStatesData.Add(new InnerStateData { InitialState = factory.InitialState, @@ -188,7 +198,7 @@ public ITransition Split(params NestedStateData[] data) }); } - _transition = new Transition(); + _transition = CreateTransition(TransitionKind.Completion); return _transition; } @@ -206,6 +216,12 @@ protected override ITransitionInternal OnTrigger(IStatechartEvent statechartEven if (statechartEvent != null && _events.TryGetValue(statechartEvent, out var transition)) { + // An action-only event keeps this state active, so its inner waits must keep running. + if (transition.TargetState == null) + { + return transition; + } + // Delay the completion of this state while some tasks are running return !isUnpausing && DelayForceComplete(statechartEvent) ? null : transition; } diff --git a/Runtime/Internal/StateFactory.cs b/Runtime/Internal/StateFactory.cs index 296f324..8ce3476 100644 --- a/Runtime/Internal/StateFactory.cs +++ b/Runtime/Internal/StateFactory.cs @@ -11,11 +11,11 @@ namespace GameLovers.StatechartMachine.Internal internal struct StateFactoryData { public Action StateChartMoveNextCall; - public IStatechart Statechart; + public Statechart Statechart; } /// - internal interface IStateFactoryInternal : IStateFactory + internal interface IStateFactoryInternal : IStateFactory, IRegionNode { /// /// The Layer that this is building upon @@ -30,18 +30,13 @@ internal interface IStateFactoryInternal : IStateFactory /// FinalState FinalState { get; } /// - /// The current list of states that this is building upon + /// The states declared directly in this region, in declaration order /// - IList States { get; } + new IList States { get; } /// /// The that this is building upon /// StateFactoryData Data { get; } - - /// - /// Adds the given list of to this to building upon - /// - void Add(IList states); } /// @@ -57,28 +52,30 @@ internal class StateFactory : IStateFactoryInternal public IList States { get; private set; } /// public StateFactoryData Data { get; private set; } + /// + public IStateNode Owner { get; } + /// + public int Index { get; } + /// + public int Depth => (int) RegionLayer; + + IStateNode IRegionNode.Initial => InitialState; + IReadOnlyList IRegionNode.States => (List) States; private StateFactory() { } - public StateFactory(uint layer, StateFactoryData data) + public StateFactory(IStateNode owner, int index, uint layer, StateFactoryData data) { States = new List(); + Owner = owner; + Index = index; Data = data; RegionLayer = layer; } - /// - public void Add(IList states) - { - for (var i = 0; i < states.Count; i++) - { - States.Add(states[i]); - } - } - /// public IInitialState Initial(string name) { diff --git a/Runtime/Internal/StateInternal.cs b/Runtime/Internal/StateInternal.cs index 42410d1..74217e6 100644 --- a/Runtime/Internal/StateInternal.cs +++ b/Runtime/Internal/StateInternal.cs @@ -1,4 +1,5 @@ using System; +using System.Collections.Generic; using UnityEngine; // ReSharper disable CheckNamespace @@ -6,25 +7,21 @@ namespace GameLovers.StatechartMachine.Internal { /// - internal interface IStateInternal : IState, IEquatable + internal interface IStateInternal : IState, IStateNode, IEquatable { - /// - /// The unique value identifying this state - /// - uint Id { get; } - /// - /// The string representation identifying this state - /// - string Name { get; } /// /// The layer in the nested setup this state is in. If in the root then the value will be 0 /// uint RegionLayer { get; } /// + /// The factory that created this state, identifying its region + /// + IStateFactoryInternal Factory { get; } + /// /// The stack trace when this setup was created. Relevant for debugging purposes /// string CreationStackTrace { get; } - + /// /// Triggers the given as input to the and returns /// the processed as an output @@ -39,6 +36,14 @@ internal interface IStateInternal : IState, IEquatable /// void Exit(); /// + /// Traces and runs , reporting any exception instead of throwing it + /// + void EnterSafely(IStatechartEvent statechartEvent); + /// + /// Traces and runs , reporting any exception instead of throwing it + /// + void ExitSafely(IStatechartEvent statechartEvent); + /// /// Validates this state to any potential bad setup schemes. Relevant to debug purposes. /// It requires the to run at runtime. /// @@ -52,6 +57,9 @@ internal abstract class StateInternal : IStateInternal private static uint _idRef; + private readonly List _transitions = new List(); + private string _path; + /// public bool LogsEnabled { get; set; } /// @@ -59,12 +67,24 @@ internal abstract class StateInternal : IStateInternal /// public string Name { get; } /// + public abstract StateKind Kind { get; } + /// public uint RegionLayer => _stateFactory.RegionLayer; /// + public IStateFactoryInternal Factory => _stateFactory; + /// public string CreationStackTrace { get; } + /// + public IRegionNode Region => _stateFactory; + /// + public string Path => _path ??= Region.Owner == null ? Name : $"{Region.Owner.Path}/{Name}"; + /// + public virtual IReadOnlyList Regions => Array.Empty(); + /// + public IReadOnlyList Transitions => _transitions; - /// True when either this state or its owning statechart has logging switched on. - protected bool IsStateLogsEnabled => LogsEnabled || _stateFactory.Data.Statechart.LogsEnabled; + /// The statechart that owns this state. + protected Statechart Chart => _stateFactory.Data.Statechart; protected StateInternal(string name, IStateFactoryInternal stateFactory) { @@ -85,11 +105,6 @@ public IStateInternal Trigger(IStatechartEvent statechartEvent) if (transition == null) { - if (IsStateLogsEnabled) - { - Debug.Log($"({GetType().UnderlyingSystemType.Name}) - '{statechartEvent?.Name}' : ## STOP ## '{Name}'"); - } - return null; } @@ -97,29 +112,53 @@ public IStateInternal Trigger(IStatechartEvent statechartEvent) if (Equals(nextState)) { - if (IsStateLogsEnabled) - { - Debug.Log($"({GetType().UnderlyingSystemType.Name}) - '{statechartEvent?.Name}' : " + - $"'{Name}' -> '{Name}' because => {GetType().UnderlyingSystemType.Name}"); - } - return nextState; } if (nextState == null) { - TriggerTransition(transition, statechartEvent?.Name); + TriggerTransition(transition, statechartEvent); return null; } - TriggerExit(); - TriggerTransition(transition, statechartEvent?.Name); - TriggerEnter(nextState); + ExitSafely(statechartEvent); + TriggerTransition(transition, statechartEvent); + nextState.EnterSafely(statechartEvent); return nextState; } + /// + public void EnterSafely(IStatechartEvent statechartEvent) + { + Trace(StatechartTraceKind.StateEntered, null, statechartEvent); + + try + { + Enter(); + } + catch (Exception e) + { + ReportFault(e, $"Exception in the state '{Name}', OnEnter() actions.", CreationStackTrace); + } + } + + /// + public void ExitSafely(IStatechartEvent statechartEvent) + { + Trace(StatechartTraceKind.StateExited, null, statechartEvent); + + try + { + Exit(); + } + catch (Exception e) + { + ReportFault(e, $"Exception in the state '{Name}', OnExit() actions.", CreationStackTrace); + } + } + /// public bool Equals(IStateInternal stateInternal) { @@ -151,80 +190,65 @@ public override string ToString() /// public abstract void Validate(); + /// + /// Creates an outgoing transition of this state and records it in . + /// + protected Transition CreateTransition(TransitionKind kind, IStatechartEvent statechartEvent = null) + { + var transition = new Transition(this, kind, statechartEvent); + + _transitions.Add(transition); + + return transition; + } + /// /// Returns the transition this state takes for the given event, or null when it does not handle it. /// protected abstract ITransitionInternal OnTrigger(IStatechartEvent statechartEvent); - private void TriggerEnter(IStateInternal state) + /// + /// Publishes a trace about this state when the chart has a listener or this state's logs are enabled. + /// + protected void Trace(StatechartTraceKind kind, IStateNode target, IStatechartEvent statechartEvent, + Exception exception = null) { - try + var chart = Chart; + + if (!chart.HasTraceListeners && !LogsEnabled) { - if (IsStateLogsEnabled) - { - Debug.Log($"({state.GetType().UnderlyingSystemType.Name}) - Entering '{state.Name}'"); - } - state.Enter(); + return; } - catch (Exception e) - { - var finalMessage = ""; -#if UNITY_EDITOR || DEBUG - finalMessage = $"\nStackTrace log of '{state.Name}' state creation bellow.\n{CreationStackTrace}"; -#endif - Debug.LogError($"Exception in the state '{state.Name}', OnExit() actions.\n" + - $"-->> Check the exception log after this one for more details <<-- {finalMessage}"); - Debug.LogException(e); - } + chart.Emit(new StatechartTrace(chart, kind, this, target, statechartEvent, exception), LogsEnabled); } - private void TriggerExit() + /// + /// Logs a user-code exception with the setup stack trace that declared the failing element, and traces it. + /// + protected void ReportFault(Exception exception, string message, string creationStackTrace) { - try - { - if(IsStateLogsEnabled) - { - Debug.LogFormat($"({GetType().UnderlyingSystemType.Name}) - Exiting '{Name}'"); - } - Exit(); - } - catch(Exception e) - { - var finalMessage = ""; + var finalMessage = ""; #if UNITY_EDITOR || DEBUG - finalMessage = $"\nStackTrace log of '{Name}' state creation bellow.\n{CreationStackTrace}"; + finalMessage = $"\nStackTrace log of the failing element's creation below.\n{creationStackTrace}"; #endif - - Debug.LogError($"Exception in the state '{Name}', OnExit() actions.\n" + - $"-->> Check the exception log after this one for more details <<-- {finalMessage}"); - Debug.LogException(e); - } + Debug.LogError($"{message}\n-->> Check the exception log after this one for more details <<-- {finalMessage}"); + Debug.LogException(exception); + Trace(StatechartTraceKind.Faulted, null, null, exception); } - private void TriggerTransition(ITransitionInternal transition, string eventName) + private void TriggerTransition(ITransitionInternal transition, IStatechartEvent statechartEvent) { + Trace(StatechartTraceKind.Transition, transition.TargetState, statechartEvent); + try { - if (IsStateLogsEnabled) - { - var targetState = transition.TargetState?.Name ?? "only invokes OnTransition()"; - - Debug.Log($"({GetType().UnderlyingSystemType.Name}) - '{eventName}' : '{Name}' -> '{targetState}'"); - } - transition.TriggerTransition(); } catch (Exception e) { - var finalMessage = ""; -#if UNITY_EDITOR || DEBUG - finalMessage = $"\nStackTrace log of this transition creation bellow.\n{transition.CreationStackTrace}"; -#endif - - Debug.LogError($"Exception in the transition '{Name}' -> '{transition.TargetState?.Name}'" + - $"-->> Check the exception log after this one for more details <<-- {finalMessage}"); - Debug.LogException(e); + ReportFault(e, $"Exception in the transition '{Name}' -> '{transition.TargetState?.Name}'.", + transition.CreationStackTrace); } } } diff --git a/Runtime/Internal/StatechartUtils.cs b/Runtime/Internal/StatechartUtils.cs index 5669420..c45ec44 100644 --- a/Runtime/Internal/StatechartUtils.cs +++ b/Runtime/Internal/StatechartUtils.cs @@ -8,19 +8,27 @@ namespace GameLovers.StatechartMachine.Internal internal static class StatechartUtils { /// - /// Cleans ups the given of unnecessary string data + /// Removes the leading stack frames that belong to and to this package, so the + /// trace starts at the user code that declared the state or transition. /// public static string RemoveGarbageFromStackTrace(string stackTrace) { - var lineIdx = stackTrace.IndexOf('\n') + 1; - do + var lines = stackTrace.Split('\n'); + var first = 0; + + while (first < lines.Length && IsPackageFrame(lines[first])) { - stackTrace = stackTrace.Remove(0, lineIdx); - lineIdx = stackTrace.IndexOf('\n') + 1; + first++; } - while (stackTrace.Substring(0, lineIdx).Contains("StateMachine.Internal")); - return stackTrace + "\n"; + return string.Join("\n", lines, first, lines.Length - first) + "\n"; + } + + private static bool IsPackageFrame(string line) + { + return line.Contains("System.Environment") || + line.Contains("GameLovers.StatechartMachine.Internal.") || + line.Contains("GameLovers.StatechartMachine.Statechart"); } } } diff --git a/Runtime/Internal/TaskWaitState.cs b/Runtime/Internal/TaskWaitState.cs index 2d84a2a..c809283 100644 --- a/Runtime/Internal/TaskWaitState.cs +++ b/Runtime/Internal/TaskWaitState.cs @@ -1,8 +1,8 @@ using Cysharp.Threading.Tasks; using System; using System.Collections.Generic; +using System.Threading; using System.Threading.Tasks; -using UnityEngine; // ReSharper disable CheckNamespace @@ -12,9 +12,10 @@ namespace GameLovers.StatechartMachine.Internal internal class TaskWaitState : StateInternal, ITaskWaitState { private ITransitionInternal _transition; - private Func _taskAwaitAction; + private Func _taskAwaitAction; private IStatechartEvent _eventQueued; private bool _triggered; + private int _enterCount; private readonly IList _onEnter = new List(); private readonly IList _onExit = new List(); @@ -38,11 +39,15 @@ public void EnqueuEvent(IStatechartEvent statechartEvent) _eventQueued ??= statechartEvent; } + /// + public override StateKind Kind => StateKind.TaskWait; + /// public override void Enter() { _eventQueued = null; _triggered = false; + _enterCount++; Completed = false; for (int i = 0; i < _onEnter.Count; i++) @@ -88,7 +93,7 @@ public void OnEnter(Action action) { if (action == null) { - throw new NullReferenceException($"The state {Name} cannot have a null OnEnter action"); + throw new ArgumentNullException(nameof(action), $"The state {Name} cannot have a null OnEnter action"); } _onEnter.Add(action); @@ -99,7 +104,7 @@ public void OnExit(Action action) { if (action == null) { - throw new NullReferenceException($"The state {Name} cannot have a null OnExit action"); + throw new ArgumentNullException(nameof(action), $"The state {Name} cannot have a null OnExit action"); } _onExit.Add(action); @@ -108,24 +113,33 @@ public void OnExit(Action action) /// public ITransition WaitingFor(Func taskAwaitAction) { - if (taskAwaitAction == null) - { - throw new NullReferenceException($"The state {Name} cannot have a null wait action"); - } - - _taskAwaitAction = () => taskAwaitAction().AsUniTask(); - _transition = new Transition(); + ThrowIfNull(taskAwaitAction); - return _transition; + return SetAwaitAction(_ => AwaitTask(taskAwaitAction())); } /// public ITransition WaitingFor(Func taskAwaitAction) { - _taskAwaitAction = taskAwaitAction ?? throw new NullReferenceException($"The state {Name} cannot have a null wait action"); - _transition = new Transition(); + ThrowIfNull(taskAwaitAction); - return _transition; + return SetAwaitAction(_ => taskAwaitAction()); + } + + /// + public ITransition WaitingFor(Func taskAwaitAction) + { + ThrowIfNull(taskAwaitAction); + + return SetAwaitAction(token => AwaitTask(taskAwaitAction(token))); + } + + /// + public ITransition WaitingFor(Func taskAwaitAction) + { + ThrowIfNull(taskAwaitAction); + + return SetAwaitAction(taskAwaitAction); } /// @@ -134,40 +148,63 @@ protected override ITransitionInternal OnTrigger(IStatechartEvent statechartEven if (!_triggered) { _triggered = true; - _ = InnerTaskAwait(statechartEvent?.Name); + InnerTaskAwait(_enterCount, Chart.CancellationToken).Forget(); } return Completed ? _transition : null; } - private async UniTask InnerTaskAwait(string eventName) + private void ThrowIfNull(Delegate taskAwaitAction) { - try + if (taskAwaitAction == null) { - if (IsStateLogsEnabled) - { - Debug.Log($"TaskWait - '{eventName}' : '{_taskAwaitAction.Target}.{_taskAwaitAction.Method.Name}()' => '{Name}'"); - } + throw new ArgumentNullException(nameof(taskAwaitAction), $"The state {Name} cannot have a null wait action"); + } + } + + private ITransition SetAwaitAction(Func taskAwaitAction) + { + _taskAwaitAction = taskAwaitAction; + _transition = CreateTransition(TransitionKind.Completion); - //await Task.Yield(); - await _taskAwaitAction(); + return _transition; + } - Completed = true; + private static async UniTask AwaitTask(Task task) + { + // Awaiting the Task directly resumes inline when it completes on the main thread; AsUniTask would always + // post the continuation to a later frame. + await task; + } - _stateFactory.Data.StateChartMoveNextCall(_eventQueued); + private async UniTaskVoid InnerTaskAwait(int enterCount, CancellationToken token) + { + try + { + await _taskAwaitAction(token); + } + catch (OperationCanceledException) when (token.IsCancellationRequested) + { + // Cancelled by Reset or Dispose: the state was abandoned, so there is nothing left to complete. + return; } catch (Exception e) { - var finalMessage = ""; -#if UNITY_EDITOR || DEBUG - finalMessage = $"\nStackTrace log of '{Name}' state creation bellow.\n{CreationStackTrace}"; -#endif + // A faulted task still completes the state; otherwise the chart and any parent split would wait forever. + ReportFault(e, $"Exception in the state '{Name}', when awaiting the task wait action.", CreationStackTrace); + } - Debug.LogError($"Exception in the state '{Name}', when calling the task wait action" + - $"'{_taskAwaitAction.Target}.{_taskAwaitAction.Method.Name}()'.\n" + - $"-->> Check the exception log after this one for more details <<-- {finalMessage}"); - Debug.LogException(e); + // Task continuations may resume on a worker thread; the chart and its callbacks only run on the main thread. + await UniTask.SwitchToMainThread(); + + if (enterCount != _enterCount || token.IsCancellationRequested) + { + return; } + + Completed = true; + + _stateFactory.Data.StateChartMoveNextCall(_eventQueued); } } } diff --git a/Runtime/Internal/Transition.cs b/Runtime/Internal/Transition.cs index 4e2f00e..9e010af 100644 --- a/Runtime/Internal/Transition.cs +++ b/Runtime/Internal/Transition.cs @@ -6,17 +6,13 @@ namespace GameLovers.StatechartMachine.Internal { /// - internal interface ITransitionInternal : ITransitionCondition + internal interface ITransitionInternal : ITransitionCondition, ITransitionEdge { /// /// The current target state of this transition /// IStateInternal TargetState { get; } /// - /// True if this transition has a condition to check, false otherwise - /// - bool HasCondition { get; } - /// /// Debug stack trace string /// string CreationStackTrace { get; } @@ -44,6 +40,27 @@ internal class Transition : ITransitionInternal public string CreationStackTrace { get; private set; } /// public bool HasCondition => _condition.Count > 0; + /// + public IStateNode Source { get; } + /// + public IStatechartEvent Event { get; } + /// + public TransitionKind Kind { get; } + + IStateNode ITransitionEdge.Target => TargetState; + + public Transition(IStateNode source, TransitionKind kind, IStatechartEvent statechartEvent) + { + Source = source; + Kind = kind; + Event = statechartEvent; + } + + /// + public override string ToString() + { + return $"{Source.Name} -({Event?.Name ?? Kind.ToString()})-> {TargetState?.Name ?? "(action only)"}"; + } /// public bool CheckCondition() @@ -72,7 +89,7 @@ public ITransition Condition(Func condition) { if(condition == null) { - throw new NullReferenceException("The transition cannot have a null condition"); + throw new ArgumentNullException(nameof(condition), "The transition cannot have a null condition"); } #if UNITY_EDITOR || DEBUG @@ -89,7 +106,7 @@ public ITransition OnTransition(Action action) { if (action == null) { - throw new NullReferenceException("The transition cannot have a null OnTransition action"); + throw new ArgumentNullException(nameof(action), "The transition cannot have a null OnTransition action"); } #if UNITY_EDITOR || DEBUG @@ -106,7 +123,7 @@ public void Target(IState state) { if (state == null) { - throw new NullReferenceException("The transition cannot have a null target state"); + throw new ArgumentNullException(nameof(state), "The transition cannot have a null target state"); } TargetState = (IStateInternal) state; diff --git a/Runtime/Internal/TransitionState.cs b/Runtime/Internal/TransitionState.cs index fb0a81e..82aefa6 100644 --- a/Runtime/Internal/TransitionState.cs +++ b/Runtime/Internal/TransitionState.cs @@ -16,6 +16,9 @@ public TransitionState(string name, IStateFactoryInternal factory) : base(name, { } + /// + public override StateKind Kind => StateKind.Transition; + /// public override void Enter() { @@ -58,7 +61,7 @@ public ITransition Transition() throw new InvalidOperationException($"State {Name} already has a transition defined"); } - _transition = new Transition(); + _transition = CreateTransition(TransitionKind.Automatic); return _transition; } @@ -68,7 +71,7 @@ public void OnEnter(Action action) { if (action == null) { - throw new NullReferenceException($"The state {Name} cannot have a null OnEnter action"); + throw new ArgumentNullException(nameof(action), $"The state {Name} cannot have a null OnEnter action"); } _onEnter.Add(action); @@ -79,7 +82,7 @@ public void OnExit(Action action) { if (action == null) { - throw new NullReferenceException($"The state {Name} cannot have a null OnExit action"); + throw new ArgumentNullException(nameof(action), $"The state {Name} cannot have a null OnExit action"); } _onExit.Add(action); diff --git a/Runtime/Internal/WaitState.cs b/Runtime/Internal/WaitState.cs index 62331e9..d890dcb 100644 --- a/Runtime/Internal/WaitState.cs +++ b/Runtime/Internal/WaitState.cs @@ -1,6 +1,6 @@ using System; using System.Collections.Generic; -using UnityEngine; +using System.Threading; // ReSharper disable CheckNamespace @@ -13,6 +13,7 @@ internal class WaitState : StateInternal, IWaitState private IWaitActivityInternal _waitingActivity; private Action _waitAction; private bool _triggered; + private CancellationToken _token; private readonly IList _onEnter = new List(); private readonly IList _onExit = new List(); @@ -32,12 +33,16 @@ public void ForceComplete() _waitingActivity.ForceComplete(); } + /// + public override StateKind Kind => StateKind.Wait; + /// public override void Enter() { // It needs to create a new activity everytime on to make sure old activities don't override new ones _waitingActivity = new WaitActivity(OnActivityComplete); _triggered = false; + _token = Chart.CancellationToken; for (int i = 0; i < _onEnter.Count; i++) { @@ -89,7 +94,7 @@ public void OnEnter(Action action) { if (action == null) { - throw new NullReferenceException($"The state {Name} cannot have a null OnEnter action"); + throw new ArgumentNullException(nameof(action), $"The state {Name} cannot have a null OnEnter action"); } _onEnter.Add(action); @@ -100,7 +105,7 @@ public void OnExit(Action action) { if (action == null) { - throw new NullReferenceException($"The state {Name} cannot have a null OnExit action"); + throw new ArgumentNullException(nameof(action), $"The state {Name} cannot have a null OnExit action"); } _onExit.Add(action); @@ -111,10 +116,10 @@ public ITransition Event(IStatechartEvent statechartEvent) { if (statechartEvent == null) { - throw new NullReferenceException($"The state {Name} cannot have a null event"); + throw new ArgumentNullException(nameof(statechartEvent), $"The state {Name} cannot have a null event"); } - var transition = new Transition(); + var transition = CreateTransition(TransitionKind.Event, statechartEvent); _events.Add(statechartEvent, transition); @@ -124,15 +129,16 @@ public ITransition Event(IStatechartEvent statechartEvent) /// public ITransition WaitingFor(Action waitAction) { - _waitAction = waitAction ?? throw new NullReferenceException($"The state {Name} cannot have a null wait action"); - _transition = new Transition(); + _waitAction = waitAction ?? throw new ArgumentNullException(nameof(waitAction), $"The state {Name} cannot have a null wait action"); + _transition = CreateTransition(TransitionKind.Completion); return _transition; } private void OnActivityComplete(uint id) { - if (id == _waitingActivity.Id) + // A completion that arrives after the chart was reset or disposed belongs to an abandoned wait. + if (id == _waitingActivity.Id && !_token.IsCancellationRequested) { _stateFactory.Data.StateChartMoveNextCall(null); } @@ -154,34 +160,22 @@ protected override ITransitionInternal OnTrigger(IStatechartEvent statechartEven if (!_triggered) { _triggered = true; - InnerWait(statechartEvent?.Name); + InnerWait(); } return _waitingActivity.IsCompleted ? _transition : null; } - private void InnerWait(string eventName) + private void InnerWait() { try { - if (IsStateLogsEnabled) - { - Debug.Log($"'{eventName}' event triggers the wait method '{_waitAction.Method.Name}'" + - $"from the object {_waitAction.Target} in the state {Name}"); - } _waitAction(_waitingActivity); } catch (Exception e) { - var finalMessage = ""; -#if UNITY_EDITOR || DEBUG - finalMessage = $"\nStackTrace log of '{Name}' state creation bellow.\n{CreationStackTrace}"; -#endif - - Debug.LogError($"Exception in the state '{Name}', when calling the wait action {_waitAction.Method.Name}" + - $" from the object {_waitAction.Target}.\n" + - $"-->> Check the exception log after this one for more details <<-- {finalMessage}"); - Debug.LogException(e); + ReportFault(e, $"Exception in the state '{Name}', when calling the wait action " + + $"{_waitAction.Method.Name} from the object {_waitAction.Target}.", CreationStackTrace); } } } diff --git a/Runtime/Statechart.cs b/Runtime/Statechart.cs index 9bf451f..1440c1b 100644 --- a/Runtime/Statechart.cs +++ b/Runtime/Statechart.cs @@ -1,5 +1,8 @@ using System; +using System.Collections.Generic; +using System.Threading; using GameLovers.StatechartMachine.Internal; +using UnityEngine; // ReSharper disable CheckNamespace @@ -11,7 +14,7 @@ namespace GameLovers.StatechartMachine public interface IStateMachineDebug { /// - /// Allows to show logs in the console to help debugging possible errors in the states & transitions + /// Writes every of this chart to the Unity console. /// bool LogsEnabled { get; set; } } @@ -19,20 +22,42 @@ public interface IStateMachineDebug /// /// The main object which represents the State Chart and drives it forward. /// The State Chart schematics are defined in the constructor setup action and cannot be modified during runtime. - /// See for Semantics. + /// Events are processed with run-to-completion semantics: an event triggered while another one is being processed, + /// for example from an enter or transition callback, is queued and processed right after the current one. /// - public interface IStatechart : IStateMachineDebug + public interface IStatechart : IStateMachineDebug, IDisposable { /// - /// Processes the event for the State Chart with run-to-completion paradigm. - /// Triggers only work if the State Chart is not paused. + /// The name used by logs, traces and debugging tools. + /// + string Name { get; } + + /// + /// True after until or . + /// + bool IsRunning { get; } + + /// + /// The read-only topology of the chart, starting at its root region. + /// + IRegionNode RootRegion { get; } + + /// + /// Publishes every observable step of the chart in execution order. + /// No trace is allocated or published while nothing subscribes and logs are disabled. + /// + event Action Traced; + + /// + /// Processes the event for the State Chart with run-to-completion paradigm. + /// Triggers only work if the State Chart is running. /// void Trigger(IStatechartEvent trigger); /// /// Start/Resume the control of the State Chart from where is anchored. - /// Does nothing if already running. /// + /// Thrown when the chart was disposed. void Run(); /// @@ -42,34 +67,82 @@ public interface IStatechart : IStateMachineDebug void Pause(); /// - /// Resets the State Chart to it's initial starting point. - /// This call doesn't pause or resume the control of the State Chart. If the State Chart is in waiting - /// mode for an event or paused, it will require a call to resume it. + /// Resets the State Chart to it's initial starting point without running any exit callback. + /// Pending events are dropped and outstanding waits and tasks are abandoned: their completion no longer moves + /// the chart, and tasks awaited with a are cancelled. + /// This call doesn't pause or resume the control of the State Chart. /// void Reset(); + + /// + /// Fills with every active state, parents before their children. + /// Before the only active state is the root initial state. + /// + void GetActiveStates(List results); + + /// + /// Returns true when is currently active. + /// + bool IsActive(IStateNode state); } /// public class Statechart : IStatechart { - private bool _isRunning; + private enum Lifecycle + { + Paused, + Running, + Disposed + } + +#if UNITY_EDITOR + /// Raised after every chart is constructed, so the Statechart Debugger can discover it. + internal static event Action Created; +#endif + + private Lifecycle _lifecycle; + private bool _isProcessing; private IStateInternal _currentState; + private CancellationTokenSource _cancellation = new CancellationTokenSource(); private readonly IStateFactoryInternal _stateFactory; + private readonly Queue _pendingEvents = new Queue(); /// public bool LogsEnabled { get; set; } + /// + public string Name { get; } + /// + public bool IsRunning => _lifecycle == Lifecycle.Running; + /// + public IRegionNode RootRegion => _stateFactory; -#if UNITY_EDITOR - /// Name of the state currently active. Editor-only, for debugging. - public string CurrentState => _currentState.Name; -#endif + /// + public event Action Traced; - private Statechart() {} + /// + /// Cancelled on Reset/Dispose. Waits and tasks capture it when they start and ignore their completion once it + /// is cancelled, and token-aware task waits receive it. + /// + internal CancellationToken CancellationToken => _cancellation.Token; + /// True when a trace would reach a subscriber or the console. + internal bool HasTraceListeners => Traced != null || LogsEnabled; - public Statechart(Action setup) + public Statechart(Action setup) : this(null, setup) { - var stateFactory = new StateFactory(0, new StateFactoryData { Statechart = this, StateChartMoveNextCall = MoveNext }); + } + + public Statechart(string name, Action setup) + { + if (setup == null) + { + throw new ArgumentNullException(nameof(setup)); + } + + Name = string.IsNullOrEmpty(name) ? nameof(Statechart) : name; + + var stateFactory = new StateFactory(null, 0, 0, new StateFactoryData { Statechart = this, StateChartMoveNextCall = MoveNext }); setup(stateFactory); @@ -77,7 +150,7 @@ public Statechart(Action setup) if (_stateFactory.InitialState == null) { - throw new MissingMemberException("State chart doesn't have initial state"); + throw new InvalidOperationException($"State chart {Name} doesn't have initial state"); } _currentState = _stateFactory.InitialState; @@ -87,13 +160,16 @@ public Statechart(Action setup) { _stateFactory.States[i].Validate(); } +#endif +#if UNITY_EDITOR + Created?.Invoke(this); #endif } /// public void Trigger(IStatechartEvent trigger) { - if (!_isRunning) + if (!IsRunning) { return; } @@ -104,34 +180,213 @@ public void Trigger(IStatechartEvent trigger) /// public void Run() { - _isRunning = true; + if (_lifecycle == Lifecycle.Disposed) + { + throw new ObjectDisposedException(Name); + } + + _lifecycle = Lifecycle.Running; + Emit(new StatechartTrace(this, StatechartTraceKind.Started)); MoveNext(null); } /// public void Pause() { - _isRunning = false; + if (!IsRunning) + { + return; + } + + _lifecycle = Lifecycle.Paused; + + Emit(new StatechartTrace(this, StatechartTraceKind.Paused)); } /// public void Reset() { + if (_lifecycle == Lifecycle.Disposed) + { + return; + } + + AbandonPendingWork(); + _cancellation = new CancellationTokenSource(); _currentState = _stateFactory.InitialState; + + Emit(new StatechartTrace(this, StatechartTraceKind.Reset)); + } + + /// + /// Stops the chart for good: pauses it, abandons pending waits and tasks, cancels token-aware tasks and + /// unregisters it from debugging tools. Calling it again does nothing. + /// + public void Dispose() + { + if (_lifecycle == Lifecycle.Disposed) + { + return; + } + + _lifecycle = Lifecycle.Disposed; + + AbandonPendingWork(); + Emit(new StatechartTrace(this, StatechartTraceKind.Disposed)); + + Traced = null; + } + + /// + public void GetActiveStates(List results) + { + if (results == null) + { + throw new ArgumentNullException(nameof(results)); + } + + results.Clear(); + AddActive(_currentState, results); + } + + /// + public bool IsActive(IStateNode state) + { + return state != null && IsActiveWithin(_currentState, state); + } + + /// + public override string ToString() + { + return Name; + } + + /// Publishes to subscribers and, when logging is on, the console. + internal void Emit(in StatechartTrace trace, bool forceLog = false) + { + Traced?.Invoke(trace); + + if (trace.Kind == StatechartTraceKind.Faulted) + { + // Faults are always reported by the throwing site; repeating them here would double every error. + return; + } + + if (LogsEnabled || forceLog) + { + Debug.Log(trace.ToString()); + } + } + + private static void AddActive(IStateInternal state, List results) + { + results.Add(state); + + if (state is not SplitState split) + { + return; + } + + for (var i = 0; i < split.InnerStates.Count; i++) + { + var current = split.InnerStates[i].CurrenState; + + if (current != null) + { + AddActive(current, results); + } + } + } + + private static bool IsActiveWithin(IStateInternal current, IStateNode state) + { + if (ReferenceEquals(current, state)) + { + return true; + } + + if (current is not SplitState split) + { + return false; + } + + for (var i = 0; i < split.InnerStates.Count; i++) + { + var inner = split.InnerStates[i].CurrenState; + + if (inner != null && IsActiveWithin(inner, state)) + { + return true; + } + } + + return false; + } + + private void AbandonPendingWork() + { + _pendingEvents.Clear(); + // Not disposed: abandoned waits still read their captured token, and a timer-free source owns nothing. + _cancellation.Cancel(); } private void MoveNext(IStatechartEvent trigger) { - if (!_isRunning) + if (!IsRunning) + { + return; + } + + if (_isProcessing) { + // Several completions can request a re-evaluation in one step; one queued null trigger covers them all. + if (trigger != null || !_pendingEvents.Contains(null)) + { + _pendingEvents.Enqueue(trigger); + } + return; } + _isProcessing = true; + + try + { + Process(trigger); + + while (IsRunning && _pendingEvents.Count > 0) + { + Process(_pendingEvents.Dequeue()); + } + } + finally + { + _isProcessing = false; + } + } + + private void Process(IStatechartEvent trigger) + { + var token = _cancellation.Token; + + if (trigger != null) + { + Emit(new StatechartTrace(this, StatechartTraceKind.EventTriggered, _currentState, null, trigger)); + } + var nextState = _currentState.Trigger(trigger); - while (nextState != null) + + while (nextState != null && !token.IsCancellationRequested) { _currentState = nextState; + + if (!IsRunning) + { + // Paused from a callback: the entered state is processed again on the next Run(). + return; + } + nextState = _currentState.Trigger(null); } } diff --git a/Runtime/StatechartTopology.cs b/Runtime/StatechartTopology.cs new file mode 100644 index 0000000..04d3948 --- /dev/null +++ b/Runtime/StatechartTopology.cs @@ -0,0 +1,127 @@ +using System.Collections.Generic; + +// ReSharper disable CheckNamespace + +namespace GameLovers.StatechartMachine +{ + /// + /// The kind of state an describes, matching the method that + /// created it. + /// + public enum StateKind + { + Initial, // Created by IStateFactory.Initial + Final, // Created by IStateFactory.Final + Simple, // Created by IStateFactory.State + Transition, // Created by IStateFactory.Transition + Choice, // Created by IStateFactory.Choice + Wait, // Created by IStateFactory.Wait + TaskWait, // Created by IStateFactory.TaskWait + Nest, // Created by IStateFactory.Nest + Split, // Created by IStateFactory.Split + Leave // Created by IStateFactory.Leave + } + + /// + /// What causes an to be taken. + /// + public enum TransitionKind + { + Event, // Taken when its event is triggered + Automatic, // Taken as soon as the source state is processed (initial and transition states) + Choice, // A choice branch, conditional or the fallback + Completion, // Taken when the source's wait, task or nested regions complete + Leave // Leaves the enclosing region from a leave state + } + + /// + /// Read-only view of one state in a . + /// It is the live state itself, so the description never goes stale and costs nothing extra to build. + /// + public interface IStateNode + { + /// + /// Unique id of the state within the running application. + /// + uint Id { get; } + /// + /// The name given to the state in the setup. + /// + string Name { get; } + /// + /// The kind of state. + /// + StateKind Kind { get; } + /// + /// The region that contains this state. + /// + IRegionNode Region { get; } + /// + /// The slash-separated names from the root to this state, for example Gameplay/Idle. + /// + string Path { get; } + /// + /// The nested regions of a nest (one) or split (two or more) state; empty for every other kind. + /// + IReadOnlyList Regions { get; } + /// + /// The outgoing transitions of this state, in declaration order. + /// + IReadOnlyList Transitions { get; } + } + + /// + /// Read-only view of one region: a sequential group of states with a single initial state. + /// + public interface IRegionNode + { + /// + /// The nest or split state that owns this region, or null for the root region. + /// + IStateNode Owner { get; } + /// + /// The position of this region among its owner's regions. + /// + int Index { get; } + /// + /// The nesting depth of the states in this region; the root region has depth 0. + /// + int Depth { get; } + /// + /// The states declared in this region, in declaration order. + /// + IReadOnlyList States { get; } + /// + /// The initial state of this region. + /// + IStateNode Initial { get; } + } + + /// + /// Read-only view of one transition between two states. + /// + public interface ITransitionEdge + { + /// + /// The state that owns the transition. + /// + IStateNode Source { get; } + /// + /// The state the transition moves to, or null for an action-only event transition. + /// + IStateNode Target { get; } + /// + /// The event that triggers the transition, or null when is not + /// . + /// + IStatechartEvent Event { get; } + /// + /// What causes the transition. + /// + TransitionKind Kind { get; } + /// + /// True when the transition has at least one guard condition. + /// + bool HasCondition { get; } + } +} diff --git a/Runtime/StatechartTopology.cs.meta b/Runtime/StatechartTopology.cs.meta new file mode 100644 index 0000000..0580f1c --- /dev/null +++ b/Runtime/StatechartTopology.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 2bc40ac7ac4a46f18524cacc8c05d1b5 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/StatechartTrace.cs b/Runtime/StatechartTrace.cs new file mode 100644 index 0000000..968c76a --- /dev/null +++ b/Runtime/StatechartTrace.cs @@ -0,0 +1,90 @@ +using System; + +// ReSharper disable CheckNamespace + +namespace GameLovers.StatechartMachine +{ + /// + /// The kind of step a records. + /// + public enum StatechartTraceKind + { + Started, // Run() started or resumed the chart + Paused, // Pause() stopped the chart + Reset, // Reset() moved the chart back to its initial state + Disposed, // Dispose() released the chart + EventTriggered, // An event started processing + StateExited, // A state is about to run its exit callbacks + Transition, // A transition is about to run its transition callbacks + StateEntered, // A state is about to run its enter callbacks + Faulted // A user callback, wait action or awaited task threw + } + + /// + /// One observable step of a running , published through + /// in execution order. + /// + public readonly struct StatechartTrace + { + /// + /// The statechart that produced this step. + /// + public IStatechart Statechart { get; } + /// + /// What happened. + /// + public StatechartTraceKind Kind { get; } + /// + /// The state the step is about: the exited, entered or faulted state, or a transition's source. + /// + public IStateNode State { get; } + /// + /// The target of a ; null for action-only transitions and for + /// every other kind. + /// + public IStateNode Target { get; } + /// + /// The event being processed when the step happened, or null when the chart moved on its own. + /// + public IStatechartEvent Event { get; } + /// + /// The exception of a step; null otherwise. + /// + public Exception Exception { get; } + + internal StatechartTrace(IStatechart statechart, StatechartTraceKind kind, IStateNode state = null, + IStateNode target = null, IStatechartEvent statechartEvent = null, + Exception exception = null) + { + Statechart = statechart; + Kind = kind; + State = state; + Target = target; + Event = statechartEvent; + Exception = exception; + } + + /// + public override string ToString() + { + var prefix = $"[Statechart '{Statechart?.Name}']"; + var eventSuffix = Event == null ? "" : $" on '{Event.Name}'"; + + switch (Kind) + { + case StatechartTraceKind.EventTriggered: + return $"{prefix} event '{Event?.Name}'"; + case StatechartTraceKind.StateExited: + return $"{prefix} exit {State?.Path}"; + case StatechartTraceKind.StateEntered: + return $"{prefix} enter {State?.Path}"; + case StatechartTraceKind.Transition: + return $"{prefix} {State?.Path} -> {Target?.Path ?? "(action only)"}{eventSuffix}"; + case StatechartTraceKind.Faulted: + return $"{prefix} fault in {State?.Path}: {Exception?.GetType().Name} {Exception?.Message}"; + default: + return $"{prefix} {Kind}"; + } + } + } +} diff --git a/Runtime/StatechartTrace.cs.meta b/Runtime/StatechartTrace.cs.meta new file mode 100644 index 0000000..be024d1 --- /dev/null +++ b/Runtime/StatechartTrace.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 9e243932bbdd4fb6acaf8f9f2e3261ef +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Samples~/GameFlow.meta b/Samples~/GameFlow.meta new file mode 100644 index 0000000..16ca562 --- /dev/null +++ b/Samples~/GameFlow.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 0a5fbbf9d70c44caab4fdab7405b7b61 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Samples~/GameFlow/GameFlow.unity b/Samples~/GameFlow/GameFlow.unity new file mode 100644 index 0000000..6474702 --- /dev/null +++ b/Samples~/GameFlow/GameFlow.unity @@ -0,0 +1,279 @@ +%YAML 1.1 +%TAG !u! tag:unity3d.com,2011: +--- !u!29 &1 +OcclusionCullingSettings: + m_ObjectHideFlags: 0 + serializedVersion: 2 + m_OcclusionBakeSettings: + smallestOccluder: 5 + smallestHole: 0.25 + backfaceThreshold: 100 + m_SceneGUID: 00000000000000000000000000000000 + m_OcclusionCullingData: {fileID: 0} +--- !u!104 &2 +RenderSettings: + m_ObjectHideFlags: 0 + serializedVersion: 10 + m_Fog: 0 + m_FogColor: {r: 0.5, g: 0.5, b: 0.5, a: 1} + m_FogMode: 3 + m_FogDensity: 0.01 + m_LinearFogStart: 0 + m_LinearFogEnd: 300 + m_AmbientSkyColor: {r: 0.212, g: 0.227, b: 0.259, a: 1} + m_AmbientEquatorColor: {r: 0.114, g: 0.125, b: 0.133, a: 1} + m_AmbientGroundColor: {r: 0.047, g: 0.043, b: 0.035, a: 1} + m_AmbientIntensity: 1 + m_AmbientMode: 0 + m_SubtractiveShadowColor: {r: 0.42, g: 0.478, b: 0.627, a: 1} + m_SkyboxMaterial: {fileID: 10304, guid: 0000000000000000f000000000000000, type: 0} + m_HaloStrength: 0.5 + m_FlareStrength: 1 + m_FlareFadeSpeed: 3 + m_HaloTexture: {fileID: 0} + m_SpotCookie: {fileID: 10001, guid: 0000000000000000e000000000000000, type: 0} + m_DefaultReflectionMode: 0 + m_DefaultReflectionResolution: 128 + m_ReflectionBounces: 1 + m_ReflectionIntensity: 1 + m_CustomReflection: {fileID: 0} + m_Sun: {fileID: 0} + m_UseRadianceAmbientProbe: 0 +--- !u!157 &3 +LightmapSettings: + m_ObjectHideFlags: 0 + serializedVersion: 13 + m_BakeOnSceneLoad: 0 + m_GISettings: + serializedVersion: 2 + m_BounceScale: 1 + m_IndirectOutputScale: 1 + m_AlbedoBoost: 1 + m_EnvironmentLightingMode: 0 + m_EnableBakedLightmaps: 1 + m_EnableRealtimeLightmaps: 0 + m_LightmapEditorSettings: + serializedVersion: 12 + m_Resolution: 2 + m_BakeResolution: 40 + m_AtlasSize: 1024 + m_AO: 0 + m_AOMaxDistance: 1 + m_CompAOExponent: 1 + m_CompAOExponentDirect: 0 + m_ExtractAmbientOcclusion: 0 + m_Padding: 2 + m_LightmapParameters: {fileID: 0} + m_LightmapsBakeMode: 1 + m_TextureCompression: 1 + m_ReflectionCompression: 2 + m_MixedBakeMode: 2 + m_BakeBackend: 2 + m_PVRSampling: 1 + m_PVRDirectSampleCount: 32 + m_PVRSampleCount: 512 + m_PVRBounces: 2 + m_PVREnvironmentSampleCount: 256 + m_PVREnvironmentReferencePointCount: 2048 + m_PVRFilteringMode: 1 + m_PVRDenoiserTypeDirect: 2 + m_PVRDenoiserTypeIndirect: 2 + m_PVRDenoiserTypeAO: 2 + m_PVRFilterTypeDirect: 0 + m_PVRFilterTypeIndirect: 0 + m_PVRFilterTypeAO: 0 + m_PVREnvironmentMIS: 1 + m_PVRCulling: 1 + m_PVRFilteringGaussRadiusDirect: 1 + m_PVRFilteringGaussRadiusIndirect: 1 + m_PVRFilteringGaussRadiusAO: 1 + m_PVRFilteringAtrousPositionSigmaDirect: 0.5 + m_PVRFilteringAtrousPositionSigmaIndirect: 2 + m_PVRFilteringAtrousPositionSigmaAO: 1 + m_ExportTrainingData: 0 + m_TrainingDataDestination: TrainingData + m_LightProbeSampleCountMultiplier: 4 + m_LightingDataAsset: {fileID: 20201, guid: 0000000000000000f000000000000000, type: 0} + m_LightingSettings: {fileID: 0} +--- !u!196 &4 +NavMeshSettings: + serializedVersion: 2 + m_ObjectHideFlags: 0 + m_BuildSettings: + serializedVersion: 3 + agentTypeID: 0 + agentRadius: 0.5 + agentHeight: 2 + agentSlope: 45 + agentClimb: 0.4 + ledgeDropHeight: 0 + maxJumpAcrossDistance: 0 + minRegionArea: 2 + manualCellSize: 0 + cellSize: 0.16666667 + manualTileSize: 0 + tileSize: 256 + buildHeightMesh: 0 + maxJobWorkers: 0 + preserveTilesOutsideBounds: 0 + debug: + m_Flags: 0 + m_NavMeshData: {fileID: 0} +--- !u!1 &609648222 +GameObject: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + serializedVersion: 6 + m_Component: + - component: {fileID: 609648225} + - component: {fileID: 609648224} + - component: {fileID: 609648223} + m_Layer: 0 + m_Name: Game Flow + m_TagString: Untagged + m_Icon: {fileID: 0} + m_NavMeshLayer: 0 + m_StaticEditorFlags: 0 + m_IsActive: 1 +--- !u!114 &609648223 +MonoBehaviour: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 609648222} + m_Enabled: 1 + m_EditorHideFlags: 0 + m_Script: {fileID: 11500000, guid: c31eda84241be490c8ba644c62282f64, type: 3} + m_Name: + m_EditorClassIdentifier: GameLovers.Statechart.Samples.GameFlow::GameLovers.StatechartMachine.Samples.GameFlow.GameFlowSample + _document: {fileID: 609648224} +--- !u!114 &609648224 +MonoBehaviour: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 609648222} + m_Enabled: 1 + m_EditorHideFlags: 0 + m_Script: {fileID: 19102, guid: 0000000000000000e000000000000000, type: 0} + m_Name: + m_EditorClassIdentifier: UnityEngine.dll::UnityEngine.UIElements.UIDocument + m_PanelSettings: {fileID: 11400000, guid: 28ff431fcb6b34c878a226c193dfb62b, type: 2} + m_ParentUI: {fileID: 0} + sourceAsset: {fileID: 9197481963319205126, guid: e541c877dd86c4642abe51b8d4c03791, type: 3} + m_SortingOrder: 0 + m_Position: 0 + m_WorldSpaceSizeMode: 1 + m_WorldSpaceWidth: 1920 + m_WorldSpaceHeight: 1080 + m_PivotReferenceSize: 0 + m_Pivot: 0 + m_WorldSpaceCollider: {fileID: 0} +--- !u!4 &609648225 +Transform: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 609648222} + serializedVersion: 2 + m_LocalRotation: {x: 0, y: 0, z: 0, w: 1} + m_LocalPosition: {x: 0, y: 0, z: 0} + m_LocalScale: {x: 1, y: 1, z: 1} + m_ConstrainProportionsScale: 0 + m_Children: [] + m_Father: {fileID: 0} + m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} +--- !u!1 &1017260713 +GameObject: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + serializedVersion: 6 + m_Component: + - component: {fileID: 1017260715} + - component: {fileID: 1017260714} + m_Layer: 0 + m_Name: Main Camera + m_TagString: MainCamera + m_Icon: {fileID: 0} + m_NavMeshLayer: 0 + m_StaticEditorFlags: 0 + m_IsActive: 1 +--- !u!20 &1017260714 +Camera: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1017260713} + m_Enabled: 1 + serializedVersion: 2 + m_ClearFlags: 2 + m_BackGroundColor: {r: 0.11, g: 0.12, b: 0.15, a: 1} + m_projectionMatrixMode: 1 + m_GateFitMode: 2 + m_FOVAxisMode: 0 + m_Iso: 200 + m_ShutterSpeed: 0.005 + m_Aperture: 16 + m_FocusDistance: 10 + m_FocalLength: 50 + m_BladeCount: 5 + m_Curvature: {x: 2, y: 11} + m_BarrelClipping: 0.25 + m_Anamorphism: 0 + m_SensorSize: {x: 36, y: 24} + m_LensShift: {x: 0, y: 0} + m_NormalizedViewPortRect: + serializedVersion: 2 + x: 0 + y: 0 + width: 1 + height: 1 + near clip plane: 0.3 + far clip plane: 1000 + field of view: 60 + orthographic: 0 + orthographic size: 5 + m_Depth: 0 + m_CullingMask: + serializedVersion: 2 + m_Bits: 4294967295 + m_RenderingPath: -1 + m_TargetTexture: {fileID: 0} + m_TargetDisplay: 0 + m_TargetEye: 3 + m_HDR: 1 + m_AllowMSAA: 1 + m_AllowDynamicResolution: 0 + m_ForceIntoRT: 0 + m_OcclusionCulling: 1 + m_StereoConvergence: 10 + m_StereoSeparation: 0.022 +--- !u!4 &1017260715 +Transform: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1017260713} + serializedVersion: 2 + m_LocalRotation: {x: 0, y: 0, z: 0, w: 1} + m_LocalPosition: {x: 0, y: 0, z: 0} + m_LocalScale: {x: 1, y: 1, z: 1} + m_ConstrainProportionsScale: 0 + m_Children: [] + m_Father: {fileID: 0} + m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} +--- !u!1660057539 &9223372036854775807 +SceneRoots: + m_ObjectHideFlags: 0 + m_Roots: + - {fileID: 1017260715} + - {fileID: 609648225} diff --git a/Samples~/GameFlow/GameFlow.unity.meta b/Samples~/GameFlow/GameFlow.unity.meta new file mode 100644 index 0000000..cbbf47f --- /dev/null +++ b/Samples~/GameFlow/GameFlow.unity.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: d2aa569a0247b4dad98f3c417280a0dc +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Samples~/GameFlow/README.md b/Samples~/GameFlow/README.md new file mode 100644 index 0000000..9b2ea08 --- /dev/null +++ b/Samples~/GameFlow/README.md @@ -0,0 +1,26 @@ +# Game Flow sample + +One statechart drives a small game loop. Between them, its states use every state kind: + +| State | Kind | What it shows | +| --- | --- | --- | +| Boot | Nest | A sequential nested region that completes, then moves to Menu | +| Load Config, Warm Up | TaskWait | Token-aware `UniTask` work that is cancelled if the chart resets or is disposed | +| Menu, Idle, Results | Simple | Event transitions (Play, Jump, Hit, Retry) | +| Gameplay | Split | Two parallel regions: the player and the waves | +| Airborne, Spawning | Wait | Callback waits completed by a coroutine; Airborne still reacts to Hit | +| More Waves? | Choice | A guarded branch with a fallback | +| Next Wave, Reset Score | Transition | Pass-through states that run an action | +| Defeated, Victory | Leave | Leave the split from either region and go to Results | + +## Run it + +1. Open `GameFlow.unity` and enter Play mode. +2. Open **Tools > GameLovers > Statechart Debugger** and dock it next to the Game view. +3. Use the on-screen buttons. The debugger follows the chart live: + - **Live chart** shows nested boxes with the active states highlighted. + - **Tree + trace** shows the state tree and the latest trace steps. + + Turn either view on or off with its toolbar toggle. + +The Activity panel in the game lists the same events and state entries from `IStatechart.Traced`. diff --git a/Samples~/GameFlow/README.md.meta b/Samples~/GameFlow/README.md.meta new file mode 100644 index 0000000..6c0bfb9 --- /dev/null +++ b/Samples~/GameFlow/README.md.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: cb447aa762b214ff1976c77210739163 +TextScriptImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Samples~/GameFlow/Scripts.meta b/Samples~/GameFlow/Scripts.meta new file mode 100644 index 0000000..032056b --- /dev/null +++ b/Samples~/GameFlow/Scripts.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 26ac8dda7a47a4e2c969c4bea3151844 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Samples~/GameFlow/Scripts/GameFlowSample.cs b/Samples~/GameFlow/Scripts/GameFlowSample.cs new file mode 100644 index 0000000..fad94c0 --- /dev/null +++ b/Samples~/GameFlow/Scripts/GameFlowSample.cs @@ -0,0 +1,237 @@ +using System.Collections; +using System.Collections.Generic; +using System.Threading; +using Cysharp.Threading.Tasks; +using UnityEngine; +using UnityEngine.UIElements; + +// ReSharper disable CheckNamespace + +namespace GameLovers.StatechartMachine.Samples.GameFlow +{ + /// + /// A small game loop driven by one statechart that uses every state kind: a nested boot sequence with task waits, + /// a menu, a split gameplay state with a player region and a waves region, choices, leave states and results. + /// + public class GameFlowSample : MonoBehaviour + { + private const int WaveCount = 3; + private const int ActivityLines = 14; + + [SerializeField] private UIDocument _document; + + private readonly IStatechartEvent _play = new StatechartEvent("Play"); + private readonly IStatechartEvent _jump = new StatechartEvent("Jump"); + private readonly IStatechartEvent _hit = new StatechartEvent("Hit"); + private readonly IStatechartEvent _quit = new StatechartEvent("Quit"); + private readonly IStatechartEvent _retry = new StatechartEvent("Retry"); + private readonly Queue _activity = new Queue(); + private readonly List _active = new List(); + + private IStatechart _statechart; + private int _wave; + private bool _won; + private Label _phase; + private Label _detail; + private Label _waves; + private Label _activityLog; + private VisualElement _player; + private Button _playButton; + private Button _jumpButton; + private Button _hitButton; + private Button _quitButton; + private Button _retryButton; + + private void Awake() + { + var root = _document.rootVisualElement; + + _phase = root.Q