# Unreal Engine 5 reference

Use Unreal only if the user asks for it. `animstream-unreal-sdk.zip` contains:

| Folder | Contents |
|--------|----------|
| `AnimStreamOriginals/` | C++ plugin with Blueprint support (UE 5.3+, Win64 and Mac, Linux allowed): the complete protocol 1 client with the optional features (state, leaderboard with pictures, gift rules), Blueprint events, async nodes, an actor component and a Project Settings page |
| `CommunityCounter/` | complete C++ template project (no `.uasset` files): the plugin in `Plugins/`, lobby, rounds, pause menu, de/en, saved settings, audio, leaderboard with pictures, gift guide, portrait window; `manifest.example.json`, placeholder images in `media/actions/` and `tools/art/action-prompts.json` |
| `README.md`, `PROTOCOL.md`, `ANIMSTREAM-SDK.md`, `manifest.example.json`, `media/` | guide, protocol, publishing guide, shared manifest and images |

The template implements Originals checklist points 1–12 like the Godot
template. **Be honest with the user about verification:** the SDK's protocol
core (`Private/Core/`), its WebSocket codec and the template's game rules
(`CounterRules.*`) are plain C++ that AnimStream builds with g++ and tests
against the mock Studio; the Unreal wrapper (subsystem, Blueprint types, Slate
HUD) has not been compiled by AnimStream because no Unreal toolchain is
available there. The user builds it in their own Unreal installation; report
compile errors with the exact message.

An agent cannot install Unreal. Ask the user where Unreal Engine is installed
(Windows: `C:\Program Files\Epic Games\UE_5.x`, macOS:
`/Users/Shared/Epic Games/UE_5.x`) and that Visual Studio 2022 with "Game
development with C++" (Windows) or Xcode (macOS) is installed.

## Setup

New game from the template:

1. Extract the ZIP; copy `CommunityCounter/` to the project folder and rename
   it consistently: `CommunityCounter.uproject`, the module folder
   `Source/CommunityCounter`, `CommunityCounter.Build.cs`, both `*.Target.cs`
   files, the `COMMUNITYCOUNTER_API` macro and `/Script/CommunityCounter.` in
   `Config/*.ini`. Keeping the name `CommunityCounter` is fine while prototyping.
2. Rename `manifest.example.json` to `manifest.json`; `media/actions/` and
   `tools/art/action-prompts.json` stay next to it. Install the agent kit into
   the same folder (`install-skills.sh --project .`).
3. Build the editor target once:
   - Windows: `"<UE>\Engine\Build\BatchFiles\Build.bat" CommunityCounterEditor Win64 Development -Project="<abs>\CommunityCounter.uproject" -WaitMutex`
   - macOS: `"<UE>/Engine/Build/BatchFiles/Mac/Build.sh" CommunityCounterEditor Mac Development -Project="<abs>/CommunityCounter.uproject"`
   Or right-click the `.uproject` → Generate project files, then build in the IDE.
4. Open the project in the editor once (it uses the engine's empty Entry map and
   builds everything in C++, so there is nothing to import).

Existing project: copy `AnimStreamOriginals/` to `<Project>/Plugins/`, enable it,
add `"AnimStreamOriginals"` to `PublicDependencyModuleNames` in
`<Project>.Build.cs`, regenerate project files and rebuild. Then add the
checklist behavior following `CommunityCounter/Source/`.

## The template

| File | Contents |
|------|----------|
| `CounterRules.h/.cpp` | phases, carry-over of gifts, the four example actions, state reports, final score; plain C++ (no engine types) so the harness tests exactly this code; `grep -rn "GAME IDEA" Source` lists the places to change |
| `CommunityCounterGameMode.*` | connects the rules to the AnimStream subsystem: registers every action in `BeginPlay`, then `StartSession()`; leaderboard, pictures, gift guide, pause, window mode, settings |
| `SCommunityCounterView.*` | Slate HUD laid out for 1080×1180, scaled to the window: status, playfield, lobby, feed, leaderboard with pictures, gift guide, pause menu |
| `CommunityCounterPlayerController.*` | Esc pause, F11 borderless fullscreen, L language, Enter/Space start the round; never F7 |
| `CommunityCounterSave.*` | `USaveGame` slot `Settings`: language, music and effects volume, mute, fullscreen |
| `CommunityCounterAudio.*` | shuffled music playlist and effect cues from `Config/DefaultGame.ini`; ships none (silent) |
| `Config/DefaultEngine.ini` | Entry map, GameMode, `[Audio] UnfocusedVolumeMultiplier=1.0` (streamers keep Studio focused) |
| `Config/DefaultGame.ini` | `ProjectVersion` (read by `animstream-pack --all`), packaging without prerequisites installer, crash reporter and debug files, app-local C++ runtime, AnimStream settings |
| `Config/DefaultGameUserSettings.ini` | windowed 864×944 portrait window |

Behavior (identical to the Godot template): session gate ("Waiting for
AnimStream Studio"); lobby 15 s with `SetState(true, "lobby")`, actions kept and
applied when round 1 starts by itself (Enter/Space starts it at once); `playing`
60 s; `round-over` 10 s with `acceptingActions: false`, `SubmitScore`, then
`GetLeaderboard` with the own entry highlighted and pictures (initial as
fallback); pause menu on Esc with `SetState(false, "paused")`, controls,
language (automatic/de/en), music, effects, mute; the world pauses
(`SetGamePaused`), the subsystem keeps ticking (heartbeat). Language: saved
choice, else `GetLanguage()` (session), else the OS culture. The timed
`double-points` example has a 0.5 s warm-up that is dropped on cancellation.
Development switch for tests: `-LobbySeconds=2 -RoundSeconds=10 -BreakSeconds=2`
(Studio never passes arguments).

Change at the `GAME IDEA` markers (`CounterRules.*`, the GameMode's
`DefaultPawnClass`, the view, `Config/DefaultGame.ini` audio lists). Keep the
rules free of engine types if you want the Linux harness to keep testing them;
spawn actors from the GameMode (for example in `PlayCue` or a new host
callback).

## C++ API (`UAnimStreamGameSubsystem`, one per GameInstance)

```cpp
UAnimStreamGameSubsystem* Studio = UAnimStreamGameSubsystem::Get(this);
Studio->RegisterAction(TEXT("spawn-zombies"), [Weak = TWeakObjectPtr<AMyGameMode>(this)](const TSharedRef<FJsonObject>& Params, const FAnimStreamActionContext& Context, FAnimStreamCompletion Complete)
{
    AMyGameMode* Game = Weak.Get();
    if (!Game || Context.IsCancelled()) { Complete(false, TEXT("not_ready")); return; }
    const int32 Count = static_cast<int32>(Params->GetNumberField(TEXT("count"))); // stackable: Rose x99 -> 99
    Game->QueueZombies(Count);   // lobby or break: keep them for the next round
    Complete(true, FString());   // acknowledge once the effect has started
});
Studio->OnReady = [Weak](const TSharedRef<FJsonObject>&) { /* list bindings, load the leaderboard */ };
Studio->SetState(true, TEXT("lobby"), 0.0);   // kept until ready, sent once Studio announced "state"
Studio->StartFromEnvironment();               // after every RegisterAction
// Round end:
Studio->SetState(false, TEXT("round-over"), Score);
Studio->SubmitScore(Score, [](bool bOk, TSharedPtr<FJsonObject> Data, const FString& Error) { /* best, rank, improved */ });
Studio->GetLeaderboard(10, [](bool bOk, TSharedPtr<FJsonObject> Data, const FString& Error) {
    const FAnimStreamLeaderboard Board = UAnimStreamBlueprintLibrary::ParseLeaderboard(Data);
});
```

| API | Notes |
|-----|-------|
| `GetActionEffect(id)` | Manifest `effect` of an action: help, sabotage, neutral or unclassified (see below). |
| `RegisterAction(id, handler)` / `UnregisterAction(id)` | Before `StartFromEnvironment()`, game thread. The completion may be called later from any thread; repeated or late calls never send a second result. Dry runs never call it. |
| `Subscribe(code, handler)` → `FDelegateHandle` / `Unsubscribe` | Raw events from the manifest's `events`; display only. |
| `StartFromEnvironment()` / `StartSession()` | Reads the launch variables; without them `launch_required` (packaged game quits, PIE stays open). Retries only a failed first connection (6 s); never reconnects. |
| `StopSession(reason)`, `IsReady()`, `HasSessionEnded()`, `GetStopReason()` | |
| `HasFeature`, `GetFeatures`, `GetLanguage`, `GetStreamerHandle`, `GetManifestJson` | Empty on Studio 0.1.285 and older. |
| `SetState(accepting, phase, TOptional<double> score)` | Phase `^[a-z0-9][a-z0-9-]{0,31}$`, \|score\| ≤ 10¹⁵; buffered before ready, deduplicated, at most 10 per second; `false` if invalid or unsupported. |
| `SubmitScore`, `GetLeaderboard`, `ListBindings`, `Request(op, params, cb)` | Callbacks on the game thread, never inside the call. Local errors: `unsupported`, `not_ready`, `invalid`, `busy`, `timeout`, `stopped`, `invalid_response`; Studio errors: `rate_limited`, `unavailable`. `avatarUrl` is already validated (empty/null otherwise). |
| `LoadAvatar(url, cb)` | 5 s, ≤ 1 MiB, PNG ≤ 1024 px, cached by URL; `nullptr` on any failure. |
| `OnReady`, `OnStopped`, `OnBindingsChangedNative` (TFunction) and the Blueprint events | |
| `bQuitOnSessionEnd` | Keep `true` (Project Settings default). |

Context: `Id`, `ExpiresAt`, `Viewer` (`name`, `handle`), `Source` (`code`,
`giftId`, `giftName`, `giftCoins`, `giftCount`; empty object without feature
`source`), `IsCancelled()`. Copy the context and the completion when work
continues later; check `IsCancelled()` before every delayed effect; the
`OnActionCancelled` event names cancelled requests.

## Blueprint

Everything is available without C++ in your own project (the template itself
is C++). Two ways:

1. **AnimStream Actions component** on any actor (for example a `BP_GameManager`
   in the level): set `Actions` (the manifest IDs), keep `Auto Complete` on for
   instant effects, optionally `Event Codes` (`GIFT` for a ticker) and
   `Start Session` (if nothing else starts it), then implement its events.
2. **Get AnimStream Subsystem** (or `Get AnimStream`) → `Register Blueprint
   Action` for each ID → bind `On Action` → `Start AnimStream Session`.

```text
Event BeginPlay (BP_GameManager with an "AnimStream Actions" component: Actions = spawn, steal-points)
  └─ (component: Start Session = true, Auto Complete = true)

AnimStream Actions ▸ On Action (Action)
  └─ Switch on String (Action.ActionId)
       ├─ "spawn"        → Get Int Param (Action, "count", 1) → Add Score
       └─ "steal-points" → Get Int Param (Action, "amount", 10) → Subtract Score (min 0)
                           → Print/feed: Action.ViewerName, Action.Source.GiftName, Action.Source.GiftCount

Round over:
  Set Game State (Accepting Actions = false, Phase = "round-over", Score)
  └─ Submit Leaderboard Score (Score) ▸ On Submitted (Result) → Get Leaderboard (10)
       ▸ On Loaded (Leaderboard) → for each Entries: Name, Score, Rank;
            Load Leaderboard Picture (AvatarUrl) ▸ On Loaded (Texture) → Set Brush from Texture
                                                  ▸ On Failure → show Get Name Initial (Name)
       ▸ On Failure (Error = "unsupported" on older Studios) → show the round score only

Pause (Esc): Set Game State (false, "paused", Score) + Set Game Paused (true); closing: the previous phase again.
Language: Get Game Language (Override = saved choice) → Pick Language (de, en).
```

Turn `Auto Complete` off for effects that can fail or finish later, then call
`Complete Action (RequestId, Success)`; `On Action Cancelled` tells you to skip
the effect. Display viewer and gift names only with plain `Text` widgets (never
`Rich Text Block` with decorators).

## Help and sabotage (action effects)

Every action of an Original is classified in the manifest with
`actions[].effect`: `help` (mercy: helps the streamer, green in
`ART-DIRECTION.md`), `sabotage` (gets in the streamer's way, red) or `neutral`
(rarely). With `giftWall.split: true` Studio splits the game's Gift Wall: help
actions left, sabotage right, each under a header (extension `action-effects`;
older Studios receive the manifest without `effect` and `split` and show one
plain wall). Keep every preset balanced, ideally 50/50 (for example 2 help + 2
sabotage or 4 + 4); the kit warns when a preset has no help or no sabotage
action or one side has more than three times the other. The template's
`manifest.example.json` classifies all four actions (`spawn`, `double-points`
help; `steal-points`, `shake-screen` sabotage), sets `"split": true` and has
three 2 + 2 presets; `validate` prints `[help]`/`[sabotage]` per action and
"2 help · 2 sabotage" per preset.

In the game the plugin exposes the effect of each action, read from the
reviewed manifest in `ready`: C++ `Context.Effect` (`"help"`, `"sabotage"`,
`"neutral"` or empty) and `GetActionEffect(ActionId)`; Blueprint
`Action.Effect` (`EAnimStreamActionEffect`: Help, Sabotage, Neutral,
Unclassified), `Get Action Effect`, `Get Effect Color` (green/red/grey) and
`Get Effect Label` ("Hilft dem Streamer" / "Against the streamer"); List Gift
Rules fills `Effect` per rule. The template shows a green HELP / red SABOTAGE
banner for 2 s when an action fires. On older Studios the effect is
Unclassified: never make gameplay depend on it, only presentation.

## Window, input, audio

- Windowed portrait window up to ~1080×1180 (the template uses 864×944 and
  scales a 1080×1180 layout); F11 toggles `EWindowMode::WindowedFullscreen`
  (borderless), never `EWindowMode::Fullscreen`; never bind F7.
- Bind keys with `bExecuteWhenPaused = true` for the pause menu.
- `[Audio] UnfocusedVolumeMultiplier=1.0` in `DefaultEngine.ini`, otherwise the
  game is silent while the streamer focuses Studio or OBS.
- Only licensed music (AGENTS.md, "Music licensing"); list tracks in
  `[/Script/<Module>.CommunityCounterAudio]`.

## Test with the mock Studio

The protocol is engine-independent; the mock Studio launches any executable.

```powershell
# Editor binaries, no packaging needed (Windows; -game runs the game without the editor UI)
node tools/mock-studio/mock-studio.mjs run --manifest manifest.json --scenario smoke -- "C:\Program Files\Epic Games\UE_5.4\Engine\Binaries\Win64\UnrealEditor.exe" "C:\Games\MyGame\MyGame.uproject" -game -windowed -ResX=540 -ResY=590 -log
# Shorter rounds for the leaderboard scenario
node tools/mock-studio/mock-studio.mjs run --manifest manifest.json --scenario leaderboard -- "<UE>\Engine\Binaries\Win64\UnrealEditor.exe" "<abs>\MyGame.uproject" -game -windowed -LobbySeconds=2 -RoundSeconds=10 -BreakSeconds=2
# Packaged build (what Studio launches)
node tools/mock-studio/mock-studio.mjs run --manifest manifest.json --scenario smoke -- build/windows/MyGame/Binaries/Win64/MyGame-Win64-Shipping.exe
```

macOS: `"<UE>/Engine/Binaries/Mac/UnrealEditor.app/Contents/MacOS/UnrealEditor" "<abs>/MyGame.uproject" -game -windowed`,
packaged: `build/macos/MyGame.app/Contents/MacOS/MyGame`. Run every scenario of
checklist point 14 (`smoke`, `smoke --legacy`, `stacking`, `pause`,
`leaderboard`, `presets`, `lobby`) against the packaged build before release.
`-game` from the editor binaries starts slower (shader compilation on the first
run); raise `--connect-timeout` if needed. PIE never gets Studio's variables and
ends with `launch_required` (the editor stays open).

Plugin tests in the engine: `UnrealEditor-Cmd.exe "<abs>.uproject" -ExecCmds="Automation RunTests AnimStream" -TestExit="Automation Test Queue Empty" -unattended -nullrhi -log`.

## Package for Windows and macOS

```sh
# Prints the BuildCookRun command: Shipping, pak + IoStore, no prerequisites installer,
# no crash reporter, no debug info, app-local C++ runtime.
node tools/package/unreal-stage.mjs uat-command --project MyGame.uproject --platform win32 --engine "C:\Program Files\Epic Games\UE_5.4"
# Runs it and stages <archive>/Windows into build/windows (or: stage --from <folder>)
node tools/package/unreal-stage.mjs build --project MyGame.uproject --platform win32 --engine "<UE>" --crt auto
node tools/package/unreal-stage.mjs build --project MyGame.uproject --platform darwin --engine "/Users/Shared/Epic Games/UE_5.4"
node tools/package/animstream-pack.mjs --all
```

- Entrypoint: `<Project>/Binaries/Win64/<Project>-Win64-Shipping.exe`, never the
  root bootstrap `<Project>.exe` (it starts the game and exits; `--all` picks the
  Shipping executable and `stage` leaves the bootstrap out). macOS:
  `<Project>.app/Contents/MacOS/<Project>`.
- No installers: `UEPrereqSetup_x64.exe` (Engine/Extras/Redist) is refused.
  The Microsoft C++ runtime goes next to the Shipping executable instead
  ("Include app-local prerequisites", or `--crt auto` / `--crt <folder>`); the
  packer warns when `msvcp140.dll`, `vcruntime140.dll` or `vcruntime140_1.dll`
  is missing there.
- Leave out `CrashReportClient` (an additional executable) and debug symbols;
  declare any other helper executable (for example `EpicWebHelper.exe` of the
  WebBrowser plugin) in `RELEASE-NOTES.md`.
- Limits: 50,000 entries, 100 GiB per ZIP and 100 GiB expanded. ZIP64 supports
  files over 4 GiB. Use pak files with IoStore (default in the template) to keep
  the entry count small.
- macOS: symbolic links are not allowed; `stage` replaces links inside the app
  with copies. Ad-hoc sign at least (`codesign --force --deep -s - MyGame.app`)
  after staging; build universal (x64 + arm64) if you can test both.
- Version: `ProjectVersion=x.y.z` in `Config/DefaultGame.ini` (Unreal's default
  `1.0.0.0` is not a release version; then pass `--version`).
- Windows signing: AnimStream signs the Windows builds of AnimStream Originals
  (games owned by AnimStream) automatically after upload: every `.exe`/`.dll`
  without a valid vendor signature, including the Shipping executable. Developer
  games are not signed by AnimStream; sign them yourself before packing if you
  have a certificate (vendor signatures stay untouched).

Release, upload and review: skill `animstream-release`.

## Pitfalls

- Studio rejects WebSocket handshakes that carry an `Origin` header. The plugin
  therefore does not use `IWebSocket`; do not replace its transport.
- A handler that never completes blocks Studio's queue until the action
  expires. Complete as soon as the effect has started.
- `SetGamePaused` pauses actors and timers, not the subsystem; never block the
  game thread for seconds (map loads count: keep one map or load
  asynchronously). Eight seconds without a ping end the session.
- Register handlers before `StartFromEnvironment()`; with Auto Start
  (Project Settings) the session starts once the GameInstance started, after
  the first map's BeginPlay.
- Exclusive fullscreen can hide Studio's game control window; never bind F7.
- Do not log the launch token or put it on a command line.
