10. Hoverboard in C++#
For: C++ programmers (advanced). Needs: Tutorials 6, 8 and 9. You will: read how a scenario gets a running world, how a latent (multi-frame) protocol driver counts ticks of the test world, how snapshots turn physics into assertions, and how a word like forward becomes a float.
This page describes the design; the source ships in the installed plugin under Source/ZagalaSpecExamples/Public/Hoverboard/, Source/ZagalaSpecToolkit/Public/ and the matching Private/ folders.
Class map#
flowchart LR
subgraph Shared context extensions
T["UZagalaSpecCESetTickLimit"]
W["UZagalaSpecCEEnsureTestWorld"]
SP["UZagalaSpecCESpawnHoverboard"]
end
SP --> DSP["UZagalaSpecDSLSpawnHoverboard<br/>(chainer)"] --> P1["UZagalaSpecPDSpawnHoverboard"] --> P2["UZagalaSpecPDQueryHoverboardState"]
subgraph Expectations
WH["UZagalaSpecStepWaitForHover"] --> DW["UZagalaSpecDSLWaitForTicks"] --> PW["UZagalaSpecPDWaitForTicks"]
AT["UZagalaSpecStepApplyThrottle<br/>UZagalaSpecStepApplySteering"] --> DA["UZagalaSpecDSLApplyInputsToSut"] --> PA["UZagalaSpecPDApplyInputs"]
AD["UZagalaSpecStepAssertDisplacement"] --> DD["UZagalaSpecDSLCheckDisplacement"] --> PD["UZagalaSpecPDCheckDisplacement<br/>: UZagalaSpecPDWaitForTicks"]
end
P1 --> SUT["AZagalaSpecExamplesHoverboardActor"]
PA --> SUT
PD --> SUT
Sentence |
Pattern |
Step |
|---|---|---|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
The system under test#
AZagalaSpecExamplesHoverboardActor is a physics-simulating AActor with a UBoxComponent root. Each tick it traces down, applies a hover-correction force toward HoverHeight (150 cm by default), and applies throttle and steering forces scaled by the current inputs. Its public surface is what the drivers use: SetThrottle(float), SetSteering(float) (both clamped to −1..1), GetHeightAboveGround(), GetYawDegrees(). Nothing about ZagalaSpec appears in it.
Getting a world: UZagalaSpecCEEnsureTestWorld#
This is the one step every world-based feature needs. It is latent, always gives the scenario a fresh world and has a timeout.
UPROPERTY(EditDefaultsOnly, BlueprintReadWrite, Category = "TestWorld")
TObjectPtr<UZagalaSpecPlaySessionSettings> SettingsAsset;
virtual void InternalExecute_Implementation(const TScriptInterface<IZagalaSpecTaggedDataCacher>& AssignedCacher) override;
virtual void InternalTeardown_Implementation() override;
What InternalExecute does, in order:
Remembers the cacher’s owner (the context) and resets its elapsed-time counter.
Calls
AddLocalSetupDataToCache, which turns the(test world)capture group into aUZagalaSpecDataPlaySessionSettings, then loads theUZagalaSpecPlaySessionSettingsasset it references. A missing asset is a failure.Editor builds: starts an
FTSTickertimeout. IfGEditor->PlayWorldalready exists (typically the previous scenario’s session, still ending), it callsGEditor->RequestEndPlayMap()unless an end is already queued, and waits on that ticker untilPlayWorldis gone; a running session is never reused. It then subscribes toFEditorDelegates::PostPIEStarted, fills anFRequestPlaySessionParamsfrom the settings asset (map override; aULevelEditorPlaySettingswith fixed FPS whenbUseFixedTimeStepand with net mode, player count and single-process play whenbListenServer) and callsGEditor->RequestPlaySession.Packaged builds: subscribes to
FCoreUObjectDelegates::PostLoadMapWithWorld, starts the same timeout and callsUGameplayStatics::OpenLevelwith the configured map; with no map and an active game world it reuses that world.
Points to copy:
The world comes from a capture group.
a (test world) is readycaptures the wordstest world; the capture group’s Group Value Class is a Blueprint subclass ofUZagalaSpecDataPlaySessionSettings(BP_Hoverboard_Data_PlaySettings) whose default points at aUZagalaSpecPlaySessionSettingsasset (DA_Hoverboard_PlaySettings: map, timeouts, fixed time step). The step itself has no hard-coded map.Latent steps do not return a result.
InternalExecutereturns after requesting play. The PIE-started handler writesUZagalaSpecDataPlaySessionWorldto the cache (the listen server world when the session is networked) and callsBroadcastSuccess(); the timeout tick accumulatesDeltaTimeand callsBroadcastFailure()afterStartupTimeoutSeconds, naming the phase that stalled (EnsureTestWorld: the previous PIE session did not end within %.1f seconds.orEnsureTestWorld: PIE did not start within %.1f seconds.). Whichever fires first removes the other’s handle so the link broadcasts exactly once.Teardown ends what it started.
InternalTeardown_ImplementationcallsGEditor->RequestEndPlayMap()and removes both handles. Because the feature puts this step in Shared Context Extensions, every scenario gets a fresh PIE session.Fixed time step is what makes
60 ticksdeterministic across machines and in-nullrhiruns. In the editor it is applied throughClientFixedFPS, which PIE reads for every non-dedicated instance;ServerFixedFPSonly affects dedicated servers.The timeout uses
FTSTickerbecause no play world exists while PIE or the map is starting. Everything that runs inside the world counts world ticks instead (see below).
UZagalaSpecCESetTickLimit is the trivial companion: AddLocalSetupDataToCache (the (\d+) becomes UZagalaSpecDataTickLimit) then BroadcastSuccess().
Spawning and snapshotting#
UZagalaSpecCESpawnHoverboard hands off to UZagalaSpecDSLSpawnHoverboard, which builds a UZagalaSpecDefaultExecutionChainer with two links via AddLinkT<>(): UZagalaSpecPDSpawnHoverboard then UZagalaSpecPDQueryHoverboardState.
UZagalaSpecPDSpawnHoverboard gets the world through FZagalaSpecWorldHelper::GetWorldFromCache(Cacher) (which reads UZagalaSpecDataPlaySessionWorld), spawns the actor at the origin with AlwaysSpawn collision handling, and writes UZagalaSpecDataHoverboardRef. UZagalaSpecPDQueryHoverboardState then fills a UZagalaSpecDataHoverboardSnapshot from the actor: Location, Velocity, ForwardVector, RightVector, Height (from GetHeightAboveGround()) and YawDegrees.
The snapshot is the baseline every later assertion compares against. Taking it in the same chain as the spawn guarantees it exists before any expectation runs. UZagalaSpecDSLSnapshotSut reuses the query driver when a step wants a fresh baseline mid-scenario.
The latent driver pattern: UZagalaSpecPDWaitForTicks#
Every wait and every “until” assertion in the examples derives from this one class.
UENUM(BlueprintType)
enum class EZagalaSpecTickCheckResult : uint8 { Continue, Succeed, Fail };
class ZAGALASPECTOOLKIT_API UZagalaSpecPDWaitForTicks : public UZagalaSpecDefaultChainLink
{
protected:
virtual void InternalExecute_Implementation(const TScriptInterface<IZagalaSpecTaggedDataCacher>& AssignedCacher) override;
virtual void InternalTeardown_Implementation() override;
/** Called each tick of the play session world; subclasses poll their condition here. Base returns Continue. */
virtual EZagalaSpecTickCheckResult OnTickCheck(IZagalaSpecTaggedDataCacher* Cacher, int32 TicksSoFar, FString& OutFailureReason);
};
Cache contract: reads UZagalaSpecDataWaitTicks (how long to wait), UZagalaSpecDataTickLimit (deadline) and UZagalaSpecDataPlaySessionWorld (whose ticks are counted). Wait and limit both missing is a failure; a missing limit defaults to twice the wait so it never fires; a missing wait means “until the condition holds or the limit”. A missing world fails with ProtocolDriver_WaitForTicks: PlaySessionWorld not found in chain cache.
InternalExecute caches the values, resets the tick counter and subscribes to FWorldDelegates::OnWorldPostActorTick, ignoring every world except the cached one. A tick therefore means “the test world ran its actors and physics once”. The application-wide FTSTicker is not used because, in the editor, it keeps running while the PIE world is skipped (Slate throttling, pause) or ticked several times in one frame (fixed time step), so the count drifts and physics scenarios become intermittent. FTimerManager is not used either: it ticks at most once per engine frame. On every tick of the test world the driver:
calls
OnTickCheck;Failbroadcasts the returned reason,Succeedbroadcasts success;otherwise, if the tick limit is reached, broadcasts
WaitForTicks: tick limit %d exceeded without satisfying condition.;otherwise, if the wait count is reached, broadcasts success;
otherwise keeps ticking.
Each terminal branch unsubscribes before broadcasting, so every outcome both broadcasts and stops, and a following wait started by a subscriber begins counting on the next world tick. If the test world is cleaned up mid-wait the driver fails with WaitForTicks: PlaySessionWorld was cleaned up after %d ticks. instead of hanging. InternalTeardown_Implementation unsubscribes if the chain is torn down mid-wait (for example because a sibling link failed). The plain wait (UZagalaSpecStepWaitForHover → UZagalaSpecDSLWaitForTicks) uses the base behaviour; conditional waits subclass and override OnTickCheck.
Assertions that wait: UZagalaSpecPDCheckDisplacement#
UZagalaSpecStepAssertDisplacement converts two capture groups (UZagalaSpecDataExpectedDirection, UZagalaSpecDataExpectedRelativeDisplacement) and runs UZagalaSpecDSLCheckDisplacement → UZagalaSpecPDCheckDisplacement, a UZagalaSpecPDWaitForTicks subclass that overrides both InternalExecute_Implementation and OnTickCheck.
In
InternalExecuteit callsSuper(which starts listening for world ticks) and returns ifSuperalready failed (IsWaitingForTicks()is false), then reads and validates everything it will need: the tick limit, the hoverboard ref, the baseline snapshot, the expected direction and the expected distance. Each missing input is its own failure string (HoverboardSnapshot missing in chain cache.and so on), reported throughFinishWithFailureso the tick subscription is removed too. It copies the snapshot’s location and forward vector into members so the tick check never touches the cache again.In
OnTickCheckit computes the displacement vector from the baseline, projects it onto the baseline forward vector to decide whether the board is moving forward or backward, and compares the distance against the expected minimum. Both conditions true →Succeed. At the tick limit it returnsFailwith a composed reason that names which part failed: wrong direction (listing the allowed words) and/orDisplacement %f is not > %f.Otherwise it defers toSuper::OnTickCheck.
UZagalaSpecPDCheckHeading and UZagalaSpecPDCheckHoverHeightRange follow the same shape with yaw and height.
Words as values: UZagalaSpecDataThrottleInput#
UZagalaSpecDataThrottleInput extends UZagalaSpecDataString and adds a float Throttle. Its StoreValue_Implementation keeps the raw text and maps it: forward → +1, backward → -1, anything else → 0, comparing case-insensitively against UZagalaSpecDataExpectedDirection::DirectionForward() and DirectionBackward(). UZagalaSpecDataSteeringInput does the same for left/right.
Because the word is parsed at conversion time, UZagalaSpecPDApplyInputs just reads both inputs from the cache (either may be absent and defaults to 0) and calls SetThrottle and SetSteering on the actor. The vocabulary lives in one place, so the regex alternatives, the parser and the assertion agree.
What to copy#
UZagalaSpecCEEnsureTestWorld+ a play-settings asset as the first shared extension of any world feature; start from a fresh session and give it a timeout.UZagalaSpecPDWaitForTicksas the base for anything that spans frames; overrideOnTickCheck, never block.Spawn-then-snapshot in one chainer so assertions always have a baseline.
Parse words into numbers in
StoreValue_Implementation, not in drivers.
Next: 11. Checkpoint in C++ adds a second actor, tuned Blueprint data classes and repeatable activations.