# AnimStream Originals for Unreal Engine 5

Everything needed to build an AnimStream Original with Unreal Engine 5.3 or newer
on Windows and macOS: TikTok LIVE viewers send gifts, AnimStream Studio turns them
into game actions through gift rules, and your game plays them.

```text
AnimStreamOriginals/            the plugin (C++ with Blueprint support); drop it into <Project>/Plugins/
  Source/AnimStreamOriginals/
    Public/                     UAnimStreamGameSubsystem, Blueprint types, async nodes, component, settings
    Private/Core/               protocol core + WebSocket codec: engine-independent C++17, tested without Unreal
CommunityCounter/               complete template project (C++, no .uasset files), the plugin already in Plugins/
  Source/CommunityCounter/      CounterRules (game rules, plain C++), GameMode, Slate HUD, input, audio, settings
  Config/                       Entry map + GameMode, portrait window, packaging without installers
  manifest.example.json, media/actions/, tools/art/action-prompts.json
PROTOCOL.md  ANIMSTREAM-SDK.md  manifest.example.json  media/
```

The plugin implements protocol 1 completely, like the Godot SDK: launch
variables, one loopback WebSocket with `hello`/`ready`, heartbeat and lease,
actions with parameters, stacking (`source.giftCount`), dry runs, cancellation
and expiry, raw events, game state (`state`), leaderboard submit and top list
with validated profile pictures, the streamer's gift rules with change
notifications, request limits and timeouts, unknown-field tolerance and full
compatibility with older Studio versions (no `ready.features`: optional
features fail locally with `unsupported`, nothing unknown is ever sent).

## Verification status

- **Tested without Unreal**: the protocol core (`Private/Core/`: JSON,
  validation, session state machine, request handling, WebSocket codec) and the
  template's game rules (`CounterRules.*`) are plain C++. AnimStream compiles
  them with g++ under Unreal-like flags (C++17 and C++20, no exceptions, no RTTI,
  warnings as errors) and runs: 181 unit checks, the 12 local WebSocket boundary
  scenarios that the Godot and Unity SDKs pass (`scripts/game-sdk/smoke.mjs
  unreal`), and the mock Studio scenarios `smoke`, `smoke --legacy`,
  `stacking`, `pause`, `leaderboard`, `presets`, `presets --legacy`, `lobby`,
  `heartbeat` and `lease` against the headless template.
- **Not compiled by AnimStream**: the Unreal wrapper (subsystem, Blueprint
  types and nodes, component, settings, Slate HUD, GameMode). No Unreal
  toolchain is available where the SDK is built. It follows Epic's documented
  UE5 APIs; build it in your Unreal version, run the Automation tests and
  test the packaged game before release, and please report compile errors.

## Quickstart with the template

1. Install Unreal Engine 5.3+ and Visual Studio 2022 with "Game development
   with C++" (Windows) or Xcode (macOS).
2. Create the game in the developer dashboard
   (https://animstream.com/developers/games/dashboard) and note its game ID.
3. Copy `CommunityCounter/` to your project folder, rename
   `manifest.example.json` to `manifest.json` and set `gameId`. Optionally
   rename the project (`.uproject`, module folder, `Build.cs`, `Target.cs`,
   `COMMUNITYCOUNTER_API`, `/Script/CommunityCounter.` in `Config/`).
4. Right-click `CommunityCounter.uproject` → Generate Visual Studio project
   files, build the `Development Editor` target and open the project. There is
   nothing to import: the template uses the engine's empty Entry map and builds
   its HUD in Slate.
5. Implement your idea where the code says `GAME IDEA` (`grep -rn "GAME IDEA"
   Source`), mainly in `CounterRules.cpp` and the GameMode.
6. Test with the mock Studio from the agent kit (below), package with
   `tools/package/unreal-stage.mjs` and `tools/package/animstream-pack.mjs
   --all`, then publish with the dashboard or the release CLI.

## Add the plugin to an existing project

1. Copy `AnimStreamOriginals/` to `<Project>/Plugins/AnimStreamOriginals/`
   (a C++ project; a Blueprint-only project gets a module when you add any C++
   class) and enable the plugin.
2. Add `"AnimStreamOriginals"` to `PublicDependencyModuleNames` in
   `<Game>.Build.cs`, regenerate project files and rebuild.
3. Register every manifest action, then start the session (C++ or Blueprint,
   below). Gate player input and gameplay on `IsSessionReady()`.
4. Add the checklist behavior (lobby, pause menu, language, settings, audio,
   leaderboard screen, portrait window) following `CommunityCounter/`.

Project Settings → Plugins → **AnimStream Originals**: `Auto Start` (start once
the GameInstance started, after the first map's BeginPlay), `Quit On Session
End` (keep it on), `Connect Retry Seconds`, `Verbose Protocol Log`
(`LogAnimStreamOriginals`; the token and viewer names are never logged).

## C++

```cpp
#include "AnimStreamGameSubsystem.h"
#include "AnimStreamBlueprintLibrary.h"

void AMyGameMode::BeginPlay()
{
    Super::BeginPlay();
    UAnimStreamGameSubsystem* Studio = UAnimStreamGameSubsystem::Get(this);
    const TWeakObjectPtr<AMyGameMode> Weak(this);
    // Stackable ("stackable": "count"): Rose x99 may arrive as ONE action with count 99.
    Studio->RegisterAction(TEXT("spawn-zombies"), [Weak](const TSharedRef<FJsonObject>& Params, const FAnimStreamActionContext& Context, FAnimStreamCompletion Complete) {
        AMyGameMode* Game = Weak.Get();
        if (!Game || Context.IsCancelled()) { Complete(false, TEXT("not_ready")); return; }
        Game->PendingZombies += static_cast<int32>(Params->GetNumberField(TEXT("count"))); // kept outside rounds
        Complete(true, FString()); // acknowledge as soon as the effect has started
    });
    Studio->OnReady = [Weak](const TSharedRef<FJsonObject>&) { if (AMyGameMode* Game = Weak.Get()) Game->RefreshLeaderboard(); };
    Studio->SetState(true, TEXT("lobby"), 0.0); // sent once Studio is ready and announced "state"
    Studio->StartFromEnvironment();            // after every RegisterAction
}

void AMyGameMode::EndRound()
{
    UAnimStreamGameSubsystem* Studio = UAnimStreamGameSubsystem::Get(this);
    Studio->SetState(false, TEXT("round-over"), Score); // Studio holds new actions
    Studio->SubmitScore(Score, [Weak = TWeakObjectPtr<AMyGameMode>(this)](bool bOk, TSharedPtr<FJsonObject> Data, const FString& Error) {
        // Older Studio versions: bOk == false, Error == "unsupported". The game keeps working.
        if (AMyGameMode* Game = Weak.Get()) Game->RefreshLeaderboard();
    });
}

void AMyGameMode::RefreshLeaderboard()
{
    UAnimStreamGameSubsystem* Studio = UAnimStreamGameSubsystem::Get(this);
    Studio->GetLeaderboard(10, [Weak = TWeakObjectPtr<AMyGameMode>(this)](bool bOk, TSharedPtr<FJsonObject> Data, const FString&) {
        const FAnimStreamLeaderboard Board = UAnimStreamBlueprintLibrary::ParseLeaderboard(Data);
        // Board.Entries[i].AvatarUrl is validated or empty: LoadAvatar, initial as fallback.
    });
}
```

| API | Notes |
|-----|-------|
| `RegisterAction(id, handler)`, `UnregisterAction` | Game thread, before `StartFromEnvironment()`. The completion may be called later from any thread; a second or late completion never sends a second result. Dry runs never call the handler. |
| `Subscribe(code, handler)` → handle, `Unsubscribe` | Raw events of the manifest's `events`; display only (never the same effect as a gift rule). |
| `StartFromEnvironment()` | Without Studio's variables: `launch_required` (packaged game quits, PIE stays open). A failed first connection is retried for `Connect Retry Seconds`; a session never reconnects (protocol rule). |
| `SetState(accepting, phase, score)` | Phase `^[a-z0-9][a-z0-9-]{0,31}$`, \|score\| ≤ 10¹⁵; kept before ready, identical states once, at most 10 per second. `false` if invalid or unsupported. |
| `SubmitScore`, `GetLeaderboard`, `ListBindings`, `Request` | Callback on the game thread, never inside the call. Errors: `unsupported`, `not_ready`, `invalid`, `busy`, `timeout`, `stopped`, `invalid_response` (local), `rate_limited`, `unavailable` (Studio). |
| `LoadAvatar(url, callback)` | AnimStream CDN PNG (or the mock Studio), 5 s, ≤ 1 MiB, ≤ 1024 px, cached by URL; `nullptr` on any failure. |
| `HasFeature`, `GetFeatures`, `GetLanguage`, `GetStreamerHandle`, `GetManifestJson`, `IsReady`, `HasSessionEnded`, `GetStopReason` | Empty values on Studio 0.1.285 and older. |
| `OnReady`, `OnStopped`, `OnBindingsChangedNative`, `bQuitOnSessionEnd` | C++ callbacks; the Blueprint events below fire too. |

Context: `Id`, `ExpiresAt`, `Viewer` (`name`, `handle`), `Source` (`code`,
`giftId`, `giftName`, `giftCoins`, `giftCount`; an empty object without feature
`source`), `IsCancelled()`. Copy the context and the completion for delayed
effects and check `IsCancelled()` before each one. Viewer and gift strings are
untrusted: show them only as plain text.

## Blueprint

- **AnimStream Actions** component (`UAnimStreamComponent`): add it to any
  actor, list `Actions` (manifest IDs) and optionally `Event Codes`; with
  `Auto Complete` (default) every action completes right after **On Action**;
  `Start Session` starts the session in BeginPlay. Events: On Action, On Action
  Cancelled, On Stream Event, On Session Ready (also when the session was ready
  before the actor spawned), On Session Stopped.
- **AnimStream Game Subsystem** (Get AnimStream Subsystem / Get AnimStream):
  Start/Stop AnimStream Session, Is Session Ready, Register Blueprint Action,
  Complete Action, Set Game State, Subscribe Blueprint Event, Has Feature, Get
  Session Language, Get Streamer Handle, and the events On Session Ready, On
  Session Stopped, On Action, On Action Cancelled, On Stream Event, On Bindings
  Changed.
- Async nodes: **Submit Leaderboard Score**, **Get Leaderboard**, **List Gift
  Rules**, **Load Leaderboard Picture** (each with On … / On Failure).
- Helpers: Get Int/Number/Bool/String Param, Get Game Language, Pick Language,
  Is Avatar Url, Get Name Initial.

```text
BP_GameManager (level actor) + component "AnimStream Actions"
  Actions = [spawn, double-points, steal-points, shake-screen]   Auto Complete = true   Start Session = true

On Action (Action) ─ Switch on String (Action.ActionId)
  "spawn"        → Get Int Param (Action, "count", 1)   → Add To Score (x2 while Double Points runs)
  "steal-points" → Get Int Param (Action, "amount", 10) → Max(0, Score - Amount)
  "double-points"→ Get Int Param (Action, "seconds", 10) → Set Timer (Double Points)
  "shake-screen" → Get Int Param (Action, "seconds", 3)  → Start Camera Shake
  (lobby / round-over / pause: add to "next round" variables instead, never reject)
  Feed text: Action.ViewerName + Action.Source.GiftName + Action.Source.GiftCount (plain Text)

Begin round:  Set Game State (true, "playing", Score)
End round:    Set Game State (false, "round-over", Score)
              → Submit Leaderboard Score (Score) ▸ On Submitted → Get Leaderboard (10)
                ▸ On Loaded (Leaderboard) → rows: Rank, Name, Score; own row = Leaderboard.Own
                  → Load Leaderboard Picture (Entry.AvatarUrl) ▸ On Loaded → Image ▸ On Failure → Get Name Initial
                ▸ On Failure (Error "unsupported": older Studio) → show only the round score
Esc:          Set Game State (false, "paused", Score) + Set Game Paused (true) + pause widget
```

## Originals checklist in the template

| Point | Where |
|-------|-------|
| 1–6 Manifest, presets, Gift Wall, leaderboard, default rules, images | `manifest.example.json` (four actions: `spawn`, `double-points` help; `steal-points`, `shake-screen` sabotage; three balanced presets; `giftWall` with `sort: "preset"`, `split: true`), `media/actions/` (marked placeholders: replace them with the kit's `tools/art/generate-action-images.mjs`), `tools/art/action-prompts.json` |
| 7 Lobby | `CounterRules`: first state `lobby` (accepting), 15 s, early actions kept for round 1, Enter/Space starts at once |
| 8 Language | saved choice, else Studio's session language, else the OS culture; lobby button, L key, pause menu; `USaveGame` slot `Settings` |
| 9 Pause | Esc: controls, language, music, effects, mute; `SetState(false, "paused")`, `SetGamePaused`; the subsystem keeps ticking |
| 10 Leaderboard | `SubmitScore` at round end, `GetLeaderboard(10)`, own entry highlighted (or an extra "You" row), pictures with the initial as fallback |
| 11 Window | 864×944 portrait window, 1080×1180 layout scaled to it; F11 borderless fullscreen (`WindowedFullscreen`); F7 never bound |
| 12 Audio | `CommunityCounterAudio`: shuffled playlist and effect cues from `Config/DefaultGame.ini` (ships none: silent); `UnfocusedVolumeMultiplier=1.0` |

Only add music with a commercial licence that covers live streaming and selling
the game; keep the licence files.

## 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.

## Test with the mock Studio

The agent kit's mock Studio (`tools/mock-studio`, `npm ci --prefix
tools/mock-studio` once) launches the game like Studio and checks every frame.

```powershell
# From the editor binaries (no packaging); -game starts 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\CommunityCounter\CommunityCounter.uproject" -game -windowed -log
# The leaderboard scenario with short rounds (development switch; Studio never passes arguments)
node tools/mock-studio/mock-studio.mjs run --manifest manifest.json --scenario leaderboard -- "<UE>\Engine\Binaries\Win64\UnrealEditor.exe" "<abs>\CommunityCounter.uproject" -game -windowed -LobbySeconds=2 -RoundSeconds=10 -BreakSeconds=2
# The packaged game (what Studio launches)
node tools/mock-studio/mock-studio.mjs run --manifest manifest.json --scenario smoke -- build/windows/CommunityCounter/Binaries/Win64/CommunityCounter-Win64-Shipping.exe
```

macOS: `".../UE_5.4/Engine/Binaries/Mac/UnrealEditor.app/Contents/MacOS/UnrealEditor" "<abs>/CommunityCounter.uproject" -game -windowed`;
packaged `build/macos/CommunityCounter.app/Contents/MacOS/CommunityCounter`. Run
`smoke`, `smoke --legacy`, `stacking`, `pause`, `leaderboard`, `presets` and
`lobby` before every release. Raise `--connect-timeout` for the first editor
start (shader compilation). PIE (Play in Editor) never gets Studio's variables
and ends with `launch_required` while the editor stays open.

Automation tests of the plugin:

```powershell
& "<UE>\Engine\Binaries\Win64\UnrealEditor-Cmd.exe" "<abs>\CommunityCounter.uproject" -ExecCmds="Automation RunTests AnimStream" -TestExit="Automation Test Queue Empty" -unattended -nullrhi -log
```

## Package for Windows and macOS

```sh
# Prints the RunUAT 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 CommunityCounter.uproject --platform win32 --engine "C:\Program Files\Epic Games\UE_5.4"
# Runs it and stages the result into build/windows; --crt auto adds the C++ runtime if needed
node tools/package/unreal-stage.mjs build --project CommunityCounter.uproject --platform win32 --engine "C:\Program Files\Epic Games\UE_5.4" --crt auto
# macOS (on a Mac); then ad-hoc sign: codesign --force --deep -s - build/macos/CommunityCounter.app
node tools/package/unreal-stage.mjs build --project CommunityCounter.uproject --platform darwin --engine "/Users/Shared/Epic Games/UE_5.4"
# ZIPs with the action images, checks, dist/release.json (version from ProjectVersion)
node tools/package/animstream-pack.mjs --all
```

What AnimStream packages require, and what `unreal-stage stage` does with
Unreal's packaged folder (`<archive>/Windows` or `<archive>/Mac`):

| Rule | Unreal |
|------|--------|
| Entrypoint is the long-running game process | `<Project>/Binaries/Win64/<Project>-Win64-Shipping.exe`; the root `<Project>.exe` is a bootstrap that starts the game and exits: refused as entrypoint, left out by `stage` |
| No installers | `Engine/Extras/Redist/**/UEPrereqSetup_x64.exe` is refused; `IncludePrerequisites=False`, `stage` leaves the folder out |
| No missing runtime | Unreal links the Microsoft C++ runtime dynamically and Studio installs no prerequisites: `IncludeAppLocalPrerequisites=True` or `--crt` puts `msvcp140.dll`, `vcruntime140.dll`, `vcruntime140_1.dll` next to the Shipping executable; the packer warns when they are missing |
| Additional executables are declared | leave out `CrashReportClient` (`IncludeCrashReporter=False`; `stage` removes it); declare others such as `EpicWebHelper.exe` (WebBrowser plugin) in `RELEASE-NOTES.md` |
| ≤ 50,000 entries, ≤ 100 GiB per ZIP and expanded, ZIP64 supported | pak files with IoStore keep the entry count small; files over 4 GiB use ZIP64 |
| No symbolic links | `stage` replaces links inside a macOS app with copies of their targets (links leaving the package are refused) |
| No debug files needed | `-nodebuginfo`; `stage` leaves `.pdb`/`.dSYM` out |
| macOS | `<Project>.app/Contents/MacOS/<Project>`; ad-hoc sign at least; universal (x64 + arm64) only if you test both |

**Windows signing of AnimStream Originals.** Builds of games owned by AnimStream
are Authenticode-signed automatically after upload, before review: every
`.exe` and `.dll` without a valid vendor signature, always including the
entrypoint; vendor-signed files (for example Microsoft's runtime DLLs) stay
byte-identical. Developer games are not signed by AnimStream: sign your
executables yourself before packing if you have a code signing certificate.

## Runtime notes

- Studio rejects WebSocket handshakes that carry an `Origin` header (it refuses
  browser origins). The plugin therefore speaks the WebSocket protocol itself
  over a non-blocking loopback `FSocket` polled in Tick (the tested codec in
  `Private/Core/`) instead of Unreal's `IWebSocket`, whose libwebsockets client
  can send an `Origin` header.
- Everything runs on the game thread, also while the world is paused. Eight
  seconds without Studio's ping end the session: never block the game thread
  that long (map loads, synchronous asset loads, long loops).
- `[Audio] UnfocusedVolumeMultiplier=1.0`: streamers keep Studio or OBS
  focused; Unreal mutes unfocused games by default.
- Windowed or borderless fullscreen only (exclusive fullscreen can hide
  Studio's game control window); never bind F7.
- Never log, display or persist the launch token.
- Studio ends the whole process tree when a session ends (Windows `taskkill /T
  /F`); do not rely on shutdown work after `stop`, save at the end of a round.

The official protocol is `PROTOCOL.md`; publishing and the Originals checklist
are in `ANIMSTREAM-SDK.md` and the agent kit (`AGENTS.md`).
