# 43 — BPC_TrialScenarioSystem

## Blueprint Spec — UE 5.5–5.7

---

### Parent Class
`ActorComponent`

### Dependencies
- [`BPC_NarrativeStateSystem`](58_BPC_NarrativeStateSystem.md)
- [`BPC_ObjectiveSystem`](39_BPC_ObjectiveSystem.md)
- [`DA_ScenarioData`](../12-content/48_DA_NarrativeDataAssets.md)
- [`BPC_CheckpointSystem`](../04-save/34_BPC_CheckpointSystem.md)
- [`BPC_DeathHandlingSystem`](../04-save/35_BPC_DeathHandlingSystem.md)

### Purpose
Manages trial-based gameplay scenarios: combat gauntlets, escape sequences, investigation time-limits, survival waves. Tracks trial state (setup / active / success / fail), enforces rules, and reports outcome to the narrative system.

### Responsibilities
- Load scenario definition from `DA_ScenarioData`
- Initialize world state for the trial (spawn enemies, lock doors, set lighting)
- Track trial objectives and completion conditions
- Monitor failure conditions (player death, time expiry, target escape)
- Broadcast success/failure to narrative state
- Clean up trial elements on completion

### Does NOT Handle
- Individual enemy AI (that is Phase 8 AI system)
- Lighting or atmosphere changes (that is Phase 9 AtmosphereController)
- Checkpoint creation (that is BPC_CheckpointSystem)

### Variables

| Name | Type | Description |
|------|------|-------------|
| `ActiveScenario` | DA_ScenarioData | Currently running scenario (null if none) |
| `ScenarioState` | EScenarioState | Current phase of scenario |
| `ScenarioStartTime` | Float | World time when scenario began |
| `SuccessTags` | Array of GameplayTag | Tags to set on success (fired to NarrativeState) |
| `FailureTags` | Array of GameplayTag | Tags to set on failure |
| `bHasCheckedFailure` | Bool | Already evaluated fail conditions this tick |

### Enums

| Enum | Values | Description |
|------|--------|-------------|
| `EScenarioState` | Inactive, SetupRunning, ActiveRunning, Success, Failure, Cleanup | Lifecycle of a trial scenario |

### Structs

| Struct | Fields | Description |
|--------|--------|-------------|
| `FScenarioObjective` | TargetTag: GameplayTag, RequiredCount: Integer, CurrentCount: Integer, bIsComplete: Bool | A tracked objective within the scenario |
| `FScenarioCompletionReport` | bSuccess: Bool, ElapsedTime: Float, ObjectivesCompleted: Integer, ObjectivesTotal: Integer, FlagsSet: Array of GameplayTag | Outcome report for narrative |

### Functions / Events

| Name | Inputs | Outputs | Description |
|------|--------|---------|-------------|
| `BeginScenario` | Scenario: DA_ScenarioData | — | Start a new trial scenario |
| `EndScenario` | bIsSuccess: Bool | — | End current scenario with outcome |
| `UpdateObjectiveProgress` | ObjectiveTag: GameplayTag, Delta: Integer | — | Increment/update objective tracker |
| `CheckAllObjectives` | — | Bool | Have all objectives been met? |
| `CheckFailureConditions` | — | Bool | Has any failure condition triggered? |
| `GetTimeRemaining` | — | Float | Time left if scenario has time limit |
| `GetElapsedTime` | — | Float | Seconds since scenario started |
| `GetScenarioCompletionReport` | — | FScenarioCompletionReport | |
| `AbortScenario` | — | — | Force-end with failure, clean up |
| `IsScenarioActive` | — | Bool | |

### Event Dispatchers

| Name | Parameters | Fired When |
|------|-----------|-----------|
| `OnScenarioStarted` | Scenario: DA_ScenarioData | Scenario begins setup |
| `OnScenarioActive` | Scenario: DA_ScenarioData | Setup complete, trial is live |
| `OnObjectiveProgressed` | ObjectiveTag: GameplayTag, Progress: Integer, Required: Integer | Any objective count changed |
| `OnScenarioSuccess` | Report: FScenarioCompletionReport | All objectives complete |
| `OnScenarioFailure` | Report: FScenarioCompletionReport | Failure condition met |
| `OnScenarioAborted` | Scenario: DA_ScenarioData | Force-aborted |
| `OnScenarioCleanup` | Scenario: DA_ScenarioData | Cleanup complete |

### Blueprint Flow

```
[BeginScenario: DA_ScenarioData]
  └─► Set ScenarioState = SetupRunning
  └─► Broadcast OnScenarioStarted
  └─► Trigger checkpoint auto-save (if configured)
  └─► Execute scenario setup actions from DA_ScenarioData:
      └─► Spawn enemies on spawn points
      └─► Lock / unlock doors by tag
      └─► Set initial objective state from scenario definition
      └─► Apply lighting overrides (via AtmosphereController if present)
  └─► Set ScenarioState = ActiveRunning
  └─► Broadcast OnScenarioActive
  └─► Record ScenarioStartTime + start tick monitors

[Tick / UpdateObjectiveProgress]
  └─► CheckAllObjectives → if true → EndScenario(success = true)
  └─► If not bHasCheckedFailure → CheckFailureConditions
  └─► If failure condition true → EndScenario(success = false)

[EndScenario: bIsSuccess]
  └─► ScenarioState = Success or Failure
  └─► Build FScenarioCompletionReport
  └─► Broadcast appropriate dispatcher
  └─► Set narrative success/failure tags via BPC_NarrativeStateSystem
  └─► ScenarioState = Cleanup
  └─► Execute cleanup actions:
      └─► Despawn trial-specific actors
      └─► Reset doors, lights, etc.
      └─► Unlock doors that were locked for trial
  └─► Broadcast OnScenarioCleanup
  └─► ScenarioState = Inactive
  └─► ActiveScenario = null
```

### Communications With

| Target System | Method | Why |
|---------------|--------|-----|
| [`BPC_NarrativeStateSystem`](58_BPC_NarrativeStateSystem.md) | Direct | Set success/failure flags upon completion |
| [`BPC_ObjectiveSystem`](39_BPC_ObjectiveSystem.md) | Direct | Sync scenario objectives with objective UI |
| [`BPC_CheckpointSystem`](../04-save/34_BPC_CheckpointSystem.md) | Direct | Create checkpoint on scenario start |
| [`BPC_DeathHandlingSystem`](../04-save/35_BPC_DeathHandlingSystem.md) | Dispatcher | Player death triggers scenario failure |
| Phase 8 AI | Indirect | Spawn/despawn enemy actors by tag |

### Reuse Notes
Scenarios are fully data-driven via `DA_ScenarioData`. Designers configure spawn tags, objective tags, time limits, and cleanup actions without blueprint modifications. Supports mixed scenarios: combat + investigation, timed + untimed, survival + objective.

---

## Manual Implementation Guide

### Class Setup
1. Create Blueprint Class: Parent = `ActorComponent`, Name = `BPC_TrialScenarioSystem`
2. Add to Player Character or GameMode

### Variable Init (BeginPlay)
```
Event BeginPlay
  ├─ Set ScenarioState = Inactive
  └─ Cache: BPC_NarrativeStateSystem, BPC_ObjectiveSystem
```

### Function Node-by-Node

#### `StartScenario(ScenarioData: DA_ScenarioData)` → `void`
```
Step 1: If ScenarioState != Inactive → Return (already running)
Step 2: Set ActiveScenario = ScenarioData, ScenarioState = SetupRunning
Step 3: Create checkpoint via SS_SaveManager (auto-save before trial)
Step 4: Spawn enemies: ForEach ScenarioData.SpawnTags → Spawn Actor from Class at SpawnPoints
Step 5: Lock doors/block exits: ForEach ScenarioData.BlockActor → Set enabled=false
Step 6: If ScenarioData.bShowObjective: ActivateObjective(ScenarioData.ObjectiveTag)
Step 7: Set ScenarioStartTime = Get Game Time
Step 8: ScenarioState = ActiveRunning
Step 9: Fire OnScenarioStarted
```

#### `EvaluateScenario()` → `void` *(Called on Tick or timer)*
```
Step 1: If ScenarioState != ActiveRunning → Return
Step 2: Check success conditions:
  If ScenarioData.SuccessFlags: HasAllFlags? → Call OnScenarioSuccess()
  If ScenarioData.SuccessKillCount: enemies killed >= count? → Success
Step 3: Check failure conditions:
  If ScenarioData.TimeLimit > 0 AND (Now - StartTime) >= TimeLimit → OnScenarioFailure("Time expired")
  If player death detected → OnScenarioFailure("Player died")
```

#### `OnScenarioSuccess()` → `void`
```
Step 1: ScenarioState = Success
Step 2: ForEach ScenarioData.SuccessFlags → BPC_NarrativeStateSystem.SetFlag(flag, true)
Step 3: If Objective active: CompleteObjective(ObjectiveTag)
Step 4: Fire OnScenarioCompleted(true)
Step 5: Call CleanupScenario()
```

### Build Checklist
- [ ] Create component with DA_ScenarioData reference
- [ ] Implement StartScenario: setup → spawn → lock → objective → active
- [ ] Implement EvaluateScenario: check win/loss conditions per tick
- [ ] Implement OnScenarioSuccess/Failure with flag setting
- [ ] Implement CleanupScenario: despawn enemies, unlock doors