Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.
Python agent-orchestrationai-agentai-coding-assistantclaude-codecoding-agentcomputer-usedesktop-applocal-firstmcppersonal-jarvisvoice-assistantvoice-coding
feat(verse): add the networked first-person movement package (#1163)
Ruben Lütke4c6cf2166b94
diff --git a/unreal/Verse/Content/Verse/Movement/DA_MovementTuning.uasset b/unreal/Verse/Content/Verse/Movement/DA_MovementTuning.uassetnew file mode 100644index 0000000000..f6d8e10d55--- /dev/null+++ b/unreal/Verse/Content/Verse/Movement/DA_MovementTuning.uasset@@ -0,0 +1,3 @@+version https://git-lfs.github.com/spec/v1+oid sha256:4f5e14af2e724aea01f323351bb69df4241d93441cde838e1495f27e42ac4164+size 1254diff --git a/unreal/Verse/Content/Verse/Test/WP01/LV_Test_Movement.umap b/unreal/Verse/Content/Verse/Test/WP01/LV_Test_Movement.umapnew file mode 100644index 0000000000..fe59b68eeb--- /dev/null+++ b/unreal/Verse/Content/Verse/Test/WP01/LV_Test_Movement.umap@@ -0,0 +1,3 @@+version https://git-lfs.github.com/spec/v1+oid sha256:b5921664fe5c3a1fc5b39427b4d3b363f08f222857a2d77829a3ca639ea3f898+size 40936diff --git a/unreal/Verse/Content/Verse/Test/WP01/make_content.py b/unreal/Verse/Content/Verse/Test/WP01/make_content.pynew file mode 100644index 0000000000..6944a9a787--- /dev/null+++ b/unreal/Verse/Content/Verse/Test/WP01/make_content.py@@ -0,0 +1,107 @@+"""Regenerate the WP01 content from code (work-packages.md WP01.1 and WP01.9).++Runs inside the headless editor's pythonscript commandlet, under the machine lock:++ python scripts/unreal/with_lock.py --label wp01-content -- \+ "<UE>/Engine/Binaries/Win64/UnrealEditor-Cmd.exe" unreal/Verse/Verse.uproject \+ -run=pythonscript -script=<this file> -nullrhi -unattended -nosplash -NoSound++Creates (overwrites):+* /Game/Verse/Movement/DA_MovementTuning, imported from Data/movement/movement_tuning.json;+* /Game/Verse/Test/WP01/LV_Test_Movement, the fixture map: the AVerseMovementCourse actor (all+ geometry lives in its C++ table), four player starts, a sun, sky light and atmosphere, and the+ movement test game mode as the world's game mode override.+Prints "VERSE_WP01 OK" when everything verifies.+"""++import os++import unreal++MAP = "/Game/Verse/Test/WP01/LV_Test_Movement"+TUNING_DIR = "/Game/Verse/Movement"+TUNING = "DA_MovementTuning"+FAILURES = []+++def say(msg):+ unreal.log(f"VERSE_WP01 {msg}")+++def fail(msg):+ FAILURES.append(msg)+ unreal.log_error(f"VERSE_WP01 FAIL {msg}")+++def make_tuning():+ path = f"{TUNING_DIR}/{TUNING}"+ project = unreal.Paths.convert_relative_path_to_full(unreal.Paths.project_dir())+ json_path = os.path.join(project, "Data", "movement", "movement_tuning.json")+ if unreal.EditorAssetLibrary.does_asset_exist(path):+ asset = unreal.EditorAssetLibrary.load_asset(path)+ else:+ factory = unreal.DataAssetFactory()+ factory.set_editor_property("data_asset_class", unreal.VerseMovementTuning)+ tools = unreal.AssetToolsHelpers.get_asset_tools()+ asset = tools.create_asset(TUNING, TUNING_DIR, unreal.VerseMovementTuning, factory)+ # The binding returns (ok, error) or only the out string, depending on the engine version.+ result = asset.import_json_file(json_path)+ if isinstance(result, tuple):+ ok, error = (result + ("",))[:2] if len(result) < 2 else result[:2]+ elif isinstance(result, str):+ ok, error = result == "", result+ else:+ ok, error = bool(result), ""+ if not ok:+ fail(f"tuning import: {error}")+ return+ unreal.EditorAssetLibrary.save_loaded_asset(asset, False)+ say(f"saved {path} from {json_path}")+++def make_map():+ levels = unreal.get_editor_subsystem(unreal.LevelEditorSubsystem)+ actors = unreal.get_editor_subsystem(unreal.EditorActorSubsystem)+ if unreal.EditorAssetLibrary.does_asset_exist(MAP):+ unreal.EditorAssetLibrary.delete_asset(MAP)+ if not levels.new_level(MAP, False):+ fail("new_level failed")+ return+ course_class = unreal.load_class(None, "/Script/VerseMovement.VerseMovementCourse")+ mode_class = unreal.load_class(None, "/Script/VerseMovement.VerseMovementTestGameMode")+ actors.spawn_actor_from_class(course_class, unreal.Vector(0, 0, 0))+ # Player starts at the head of the ledge lanes (capsule centre above the floor).+ for index, y in enumerate((800.0, 1600.0, 2400.0, 3200.0)):+ start = actors.spawn_actor_from_class(unreal.PlayerStart, unreal.Vector(0.0, y, 100.0))+ start.set_actor_label(f"PlayerStart_{index}")+ sun = actors.spawn_actor_from_class(+ unreal.DirectionalLight, unreal.Vector(0, 0, 1000), unreal.Rotator(0.0, -50.0, 35.0)+ )+ sun.light_component.set_editor_property("intensity", 6.0)+ sun.light_component.set_editor_property("atmosphere_sun_light", True)+ actors.spawn_actor_from_class(unreal.SkyAtmosphere, unreal.Vector(0, 0, 0))+ sky = actors.spawn_actor_from_class(unreal.SkyLight, unreal.Vector(0, 0, 500))+ sky.light_component.set_editor_property("real_time_capture", True)+ actors.spawn_actor_from_class(unreal.ExponentialHeightFog, unreal.Vector(0, 0, 0))+ world = unreal.EditorLevelLibrary.get_editor_world()+ world.get_world_settings().set_editor_property("default_game_mode", mode_class)+ if not levels.save_current_level():+ fail("save_current_level failed")+ return+ say(f"saved {MAP}")+++def verify():+ asset = unreal.EditorAssetLibrary.load_asset(f"{TUNING_DIR}/{TUNING}")+ if not asset:+ fail("DA_MovementTuning missing")+ elif abs(asset.get_editor_property("values").get_editor_property("walk_speed") - 4.5) > 1e-4:+ fail("DA_MovementTuning walk speed is not the json value")+ if not unreal.EditorAssetLibrary.does_asset_exist(MAP):+ fail("LV_Test_Movement missing")+++make_tuning()+make_map()+verify()+say("OK" if not FAILURES else f"FAILED {len(FAILURES)}")diff --git a/unreal/Verse/Data/movement/movement_tuning.json b/unreal/Verse/Data/movement/movement_tuning.jsonnew file mode 100644index 0000000000..b115b7dd6e--- /dev/null+++ b/unreal/Verse/Data/movement/movement_tuning.json@@ -0,0 +1,46 @@+{+ "schema": "verse.movement-tuning/1",+ "_comment": "WP01 start values (work-packages.md WP01). Metres, seconds, degrees. Tuning, not contract.",+ "WalkSpeed": 4.5,+ "SprintSpeed": 6.5,+ "CrouchSpeed": 2.2,+ "ProneSpeed": 0.9,+ "SprintMaxAngleDeg": 45.0,+ "QuietWalkMaxSpeed": 2.6,+ "SlideMinEntrySpeed": 5.5,+ "SlideBoostSpeed": 7.5,+ "SlideMaxDuration": 1.1,+ "SlideCooldown": 1.0,+ "SlideDecayExponent": 1.4,+ "JumpApexHeight": 0.55,+ "MantleMinHeight": 0.5,+ "MantleLowMaxHeight": 1.2,+ "MantleHighMaxHeight": 2.0,+ "MantleLowDuration": 0.45,+ "MantleHighDuration": 0.85,+ "MantleReach": 0.6,+ "MantleRiseFraction": 0.55,+ "MantleMaxFaceAngleDeg": 55.0,+ "LeanCameraOffset": 0.35,+ "LeanRollDeg": 12.0,+ "LeanEnterTime": 0.15,+ "LeanCameraClearance": 0.12,+ "ProneEnterTime": 0.7,+ "ProneExitTime": 0.6,+ "ProneTurnCapDegPerSec": 90.0,+ "ProneMinClearance": 0.4,+ "ProneBodyLength": 1.8,+ "ProneBodyWidth": 0.5,+ "CapsuleRadius": 0.34,+ "StandHeight": 1.8,+ "CrouchHeight": 1.1,+ "ProneRadius": 0.2,+ "StandEyeHeight": 1.65,+ "CrouchEyeHeight": 0.98,+ "ProneEyeHeight": 0.3,+ "EyeBlendTime": 0.12,+ "WalkStride": 0.7,+ "RunStride": 0.95,+ "SprintStride": 1.25,+ "LandNoiseMinFallSpeed": 3.0+}diff --git a/unreal/Verse/Source/VerseMovement/Private/Fixture/VerseMovementCourse.cpp b/unreal/Verse/Source/VerseMovement/Private/Fixture/VerseMovementCourse.cppnew file mode 100644index 0000000000..daf331eec3--- /dev/null+++ b/unreal/Verse/Source/VerseMovement/Private/Fixture/VerseMovementCourse.cpp@@ -0,0 +1,192 @@+#include "Fixture/VerseMovementCourse.h"++#include "Components/BoxComponent.h"+#include "Components/StaticMeshComponent.h"+#include "Engine/StaticMesh.h"+#include "Engine/World.h"+#include "EngineUtils.h"+#include "GameFramework/PlayerStart.h"+#include "HAL/PlatformTime.h"+#include "Kismet/GameplayStatics.h"+#include "Misc/FileHelper.h"+#include "UObject/ConstructorHelpers.h"+#include "VerseCharacter.h"+#include "VerseCharacterMovement.h"+#include "VerseCollision.h"+#include "VerseInputFrameController.h"+#include "VerseLog.h"++namespace VerseMovementCourse+{+ namespace+ {+ TArray<FBlock> MakeBlocks()+ {+ TArray<FBlock> Out;+ Out.Add({TEXT("Floor"), FVector(0.f, 1000.f, -25.f), FVector(3000.f, 9000.f, 25.f)});+ for (int32 Index = 0; Index < LedgeCount; ++Index)+ {+ const float H = LedgeHeights[Index];+ Out.Add({TEXT("Ledge"), FVector(LedgeFaceX + 200.f, LedgeLaneY(Index), H * 0.5f), FVector(200.f, LedgeHalfWidth, H * 0.5f)});+ }+ for (const float Y : {CrawlTunnelY, CrouchTunnelY})+ {+ const float H = Y == CrawlTunnelY ? CrawlTunnelHeight : CrouchTunnelHeight;+ const float CenterX = TunnelEntryX + TunnelLength * 0.5f;+ Out.Add({TEXT("TunnelWall"), FVector(CenterX, Y - 125.f, H * 0.5f), FVector(TunnelLength * 0.5f, 25.f, H * 0.5f)});+ Out.Add({TEXT("TunnelWall"), FVector(CenterX, Y + 125.f, H * 0.5f), FVector(TunnelLength * 0.5f, 25.f, H * 0.5f)});+ Out.Add({TEXT("TunnelRoof"), FVector(CenterX, Y, H + 25.f), FVector(TunnelLength * 0.5f, 150.f, 25.f)});+ }+ {+ const float X = BreachWallX + 12.5f;+ Out.Add({TEXT("BreachSill"), FVector(X, BreachY, BreachSill * 0.5f), FVector(12.5f, 150.f, BreachSill * 0.5f)});+ Out.Add({TEXT("BreachLintel"), FVector(X, BreachY, BreachTop + 25.f), FVector(12.5f, 150.f, 25.f)});+ Out.Add({TEXT("BreachPost"), FVector(X, BreachY - 250.f, 125.f), FVector(12.5f, 100.f, 125.f)});+ Out.Add({TEXT("BreachPost"), FVector(X, BreachY + 250.f, 125.f), FVector(12.5f, 100.f, 125.f)});+ }+ Out.Add({TEXT("CornerWallRight"), FVector(CornerEndX - 400.f, CornerWallY + 100.f, 150.f), FVector(400.f, 15.f, 150.f)});+ Out.Add({TEXT("CornerWallLeft"), FVector(CornerEndX - 400.f, CornerWallY - 100.f, 150.f), FVector(400.f, 15.f, 150.f)});+ for (const float Pitch : {30.f, 46.f})+ {+ const float Rad = FMath::DegreesToRadians(Pitch);+ const float Z = 400.f * FMath::Sin(Rad) - 20.f * FMath::Cos(Rad);+ Out.Add({Pitch < 40.f ? TEXT("Slope30") : TEXT("Slope46"), FVector(800.f, Pitch < 40.f ? Slope30Y : Slope46Y, Z),+ FVector(400.f, 300.f, 20.f), Pitch});+ }+ for (int32 Step = 0; Step < 10; ++Step)+ {+ const float Top = (Step + 1) * 20.f;+ Out.Add({TEXT("Stair"), FVector(615.f + 30.f * Step, StairsY, Top * 0.5f), FVector(15.f, 150.f, Top * 0.5f)});+ }+ Out.Add({TEXT("StairLanding"), FVector(1050.f, StairsY, 100.f), FVector(150.f, 150.f, 100.f)});+ Out.Add({TEXT("DropPlatform"), FVector(1000.f, DropY, DropHeight * 0.5f), FVector(400.f, 300.f, DropHeight * 0.5f)});+ return Out;+ }+ }++ TConstArrayView<FBlock> Blocks()+ {+ static const TArray<FBlock> Table = MakeBlocks();+ return Table;+ }+}++AVerseMovementCourse::AVerseMovementCourse()+{+ PrimaryActorTick.bCanEverTick = false;+ USceneComponent* Root = CreateDefaultSubobject<USceneComponent>(TEXT("Root"));+ Root->SetMobility(EComponentMobility::Static);+ SetRootComponent(Root);+ static ConstructorHelpers::FObjectFinderOptional<UStaticMesh> Cube(TEXT("/Engine/BasicShapes/Cube.Cube"));+ int32 Index = 0;+ for (const VerseMovementCourse::FBlock& Block : VerseMovementCourse::Blocks())+ {+ const FString Name = FString::Printf(TEXT("%s_%02d"), Block.Name, Index++);+ UBoxComponent* Box = CreateDefaultSubobject<UBoxComponent>(*(Name + TEXT("_Collision")));+ Box->SetupAttachment(Root);+ Box->SetMobility(EComponentMobility::Static);+ Box->SetRelativeLocationAndRotation(Block.Center, FRotator(Block.PitchDeg, 0.f, 0.f));+ Box->InitBoxExtent(Block.Extent);+ Box->SetCollisionProfileName(VerseCollision::Profile::Architecture);+ Box->SetHiddenInGame(true);+ Boxes.Add(Box);+ if (Cube.Succeeded())+ {+ UStaticMeshComponent* Visual = CreateDefaultSubobject<UStaticMeshComponent>(*(Name + TEXT("_Visual")));+ Visual->SetupAttachment(Box);+ Visual->SetMobility(EComponentMobility::Static);+ Visual->SetStaticMesh(Cube.Get());+ Visual->SetRelativeScale3D(Block.Extent / 50.f);+ Visual->SetCollisionEnabled(ECollisionEnabled::NoCollision);+ Visual->SetCanEverAffectNavigation(false);+ Visuals.Add(Visual);+ }+ }+}++AVerseMovementTestGameMode::AVerseMovementTestGameMode()+{+ DefaultPawnClass = AVerseCharacter::StaticClass();+ PrimaryActorTick.bCanEverTick = true;+}++void AVerseMovementTestGameMode::InitGame(const FString& MapName, const FString& Options, FString& ErrorMessage)+{+ Super::InitGame(MapName, Options, ErrorMessage);+ ReportPath = UGameplayStatics::ParseOption(Options, TEXT("VerseNetReport"));+ QuitAfter = FCString::Atof(*UGameplayStatics::ParseOption(Options, TEXT("VerseQuitAfter")));+}++AActor* AVerseMovementTestGameMode::ChoosePlayerStart_Implementation(AController* Player)+{+ TArray<APlayerStart*> Starts;+ for (TActorIterator<APlayerStart> It(GetWorld()); It; ++It)+ {+ Starts.Add(*It);+ }+ Starts.Sort([](const APlayerStart& A, const APlayerStart& B) { return A.GetName() < B.GetName(); });+ if (Starts.IsEmpty())+ {+ return Super::ChoosePlayerStart_Implementation(Player);+ }+ return Starts[StartIndex++ % Starts.Num()];+}++FString AVerseMovementTestGameMode::BuildServerReport() const+{+ FString Pawns;+ double TotalMs = 0.0;+ for (TActorIterator<AVerseCharacter> It(GetWorld()); It; ++It)+ {+ const UVerseCharacterMovement* Movement = It->GetVerseMovement();+ if (!Movement)+ {+ continue;+ }+ // A1.9 on the dedicated server: the whole movement path of the pawn (client move RPCs,+ // input tick, component tick and body pose) per server tick.+ const double MsPerTick = FPlatformTime::ToMilliseconds64(Movement->GetTickCycles()) / FMath::Max(Movement->GetTickCount(), 1);+ TotalMs += MsPerTick;+ Pawns += FString::Printf(TEXT("%s{\"pawn\": \"%s\", \"mantles\": %d, \"movement_ms_per_tick\": %.4f, \"stats\": %s}"), Pawns.IsEmpty() ? TEXT("") : TEXT(", "),+ *It->GetName(), Movement->GetMantleCount(), MsPerTick, *Movement->GetNetStats().ToJson());+ }+ return FString::Printf(TEXT("{\"role\": \"server\", \"time\": %.2f, \"movement_ms_per_tick_all_pawns\": %.4f, \"pawns\": [%s]}"),+ GetWorld()->GetTimeSeconds(), TotalMs, *Pawns);+}++void AVerseMovementTestGameMode::Tick(float DeltaSeconds)+{+ Super::Tick(DeltaSeconds);+ Elapsed += DeltaSeconds;+ if (QuitAfter > 0.f && Elapsed >= QuitAfter)+ {+ QuitAfter = 0.f;+ if (!ReportPath.IsEmpty() && TActorIterator<AVerseCharacter>(GetWorld()))+ {+ FFileHelper::SaveStringToFile(BuildServerReport(), *ReportPath);+ }+ UE_LOG(LogVerseMovement, Display, TEXT("movement test server: quitting after %.0f s"), Elapsed);+ FPlatformMisc::RequestExit(false);+ return;+ }+ if (ReportPath.IsEmpty())+ {+ return;+ }+ ReportTimer += DeltaSeconds;+ // Keep the last report that still had pawns: the soak clients leave before the server quits.+ if (ReportTimer >= 5.f && TActorIterator<AVerseCharacter>(GetWorld()))+ {+ ReportTimer = 0.f;+ FFileHelper::SaveStringToFile(BuildServerReport(), *ReportPath);+ }+}++void AVerseMovementTestGameMode::EndPlay(const EEndPlayReason::Type Reason)+{+ if (!ReportPath.IsEmpty() && TActorIterator<AVerseCharacter>(GetWorld()))+ {+ FFileHelper::SaveStringToFile(BuildServerReport(), *ReportPath);+ }+ Super::EndPlay(Reason);+}diff --git a/unreal/Verse/Source/VerseMovement/Private/QA/VerseMovementQa.cpp b/unreal/Verse/Source/VerseMovement/Private/QA/VerseMovementQa.cppnew file mode 100644index 0000000000..29d3b901cf--- /dev/null+++ b/unreal/Verse/Source/VerseMovement/Private/QA/VerseMovementQa.cpp@@ -0,0 +1,351 @@+#include "QA/VerseMovementQa.h"++#include "Camera/CameraActor.h"+#include "Containers/Ticker.h"+#include "Engine/Engine.h"+#include "Engine/World.h"+#include "EngineUtils.h"+#include "Fixture/VerseMovementCourse.h"+#include "GameFramework/PlayerController.h"+#include "HAL/FileManager.h"+#include "Misc/CommandLine.h"+#include "Misc/FileHelper.h"+#include "Misc/Parse.h"+#include "Misc/Paths.h"+#include "Qa/VerseQaRegistry.h"+#include "Subsystems/EngineSubsystem.h"+#include "UnrealClient.h"+#include "VerseCharacter.h"+#include "VerseCharacterMovement.h"+#include "VerseLog.h"+#include "VerseMovementScripts.h"+++namespace+{+ AVerseCharacter* FindLocalPawn()+ {+ if (!GEngine)+ {+ return nullptr;+ }+ for (const FWorldContext& Context : GEngine->GetWorldContexts())+ {+ UWorld* World = Context.World();+ if (!World || (Context.WorldType != EWorldType::Game && Context.WorldType != EWorldType::PIE))+ {+ continue;+ }+ for (FConstPlayerControllerIterator It = World->GetPlayerControllerIterator(); It; ++It)+ {+ APlayerController* Controller = It->Get();+ if (Controller && Controller->IsLocalController())+ {+ if (AVerseCharacter* Pawn = Cast<AVerseCharacter>(Controller->GetPawn()))+ {+ return Pawn;+ }+ }+ }+ }+ return nullptr;+ }++ FString StateJson(const AVerseCharacter& Pawn)+ {+ const UVerseCharacterMovement* M = Pawn.GetVerseMovement();+ const FVector L = Pawn.GetActorLocation();+ return FString::Printf(+ TEXT("{\"pawn\": \"%s\", \"location\": [%.1f, %.1f, %.1f], \"stance\": \"%s\", \"lean\": %d, \"sprinting\": %s, \"airborne\": %s, \"mantling\": %s, \"blocks_firing\": %s, \"mantles\": %d, \"net\": %s}"),+ *Pawn.GetName(), L.X, L.Y, L.Z, *StaticEnum<EVerseStance>()->GetNameStringByValue(int64(M->GetStance())), int32(M->GetLeanQuantized()),+ M->IsSprinting() ? TEXT("true") : TEXT("false"), M->IsAirborne() ? TEXT("true") : TEXT("false"),+ M->IsMantling() ? TEXT("true") : TEXT("false"), M->BlocksFiring() ? TEXT("true") : TEXT("false"), M->GetMantleCount(),+ *M->GetNetStats().ToJson());+ }++ void Place(AVerseCharacter& Pawn, const FVector& Feet, float Yaw)+ {+ const float Half = Pawn.GetSimpleCollisionHalfHeight();+ Pawn.SetActorLocationAndRotation(Feet + FVector(0.f, 0.f, Half + 2.f), FRotator(0.f, Yaw, 0.f), false, nullptr, ETeleportType::TeleportPhysics);+ if (AController* Controller = Pawn.GetController())+ {+ Controller->SetControlRotation(FRotator(0.f, Yaw, 0.f));+ }+ Pawn.GetVerseMovement()->StopMovementImmediately();+ }+}++void UVerseMovementQa::Initialize(FSubsystemCollectionBase& Collection)+{+ Super::Initialize(Collection);+ Collection.InitializeDependency<UVerseQaRegistry>();+ if (UVerseQaRegistry* Registry = UVerseQaRegistry::Get())+ {+ auto Add = [this, Registry](const TCHAR* Name, const TCHAR* Help, FVerseQaHandler Handler)+ {+ if (Registry->Register(Name, Help, MoveTemp(Handler)))+ {+ Registered.Add(Name);+ }+ };+ Add(TEXT("Verse.QA.Movement.State"), TEXT("Movement state of the local pawn (stance, lean, flags, corrections)"),+ [](const TArray<FString>&) -> FString+ {+ const AVerseCharacter* Pawn = FindLocalPawn();+ return Pawn ? StateJson(*Pawn) : FString(TEXT("{\"error\": \"no local Verse pawn\"}"));+ });+ Add(TEXT("Verse.QA.Movement.Soak"), TEXT("Verse.QA.Movement.Soak <seconds> <seed> <report.json> [quit]: seeded movement soak"),+ [this](const TArray<FString>& Args) -> FString+ {+ if (Args.Num() < 3)+ {+ return TEXT("{\"error\": \"usage: <seconds> <seed> <report.json> [quit]\"}");+ }+ const bool bOk = StartSoak(FCString::Atof(*Args[0]), FCString::Strtoui64(*Args[1], nullptr, 10), Args[2], Args.Num() > 3 && Args[3] == TEXT("quit"));+ return bOk ? FString(TEXT("{\"started\": true}")) : FString(TEXT("{\"error\": \"no local Verse pawn\"}"));+ });+ Add(TEXT("Verse.QA.Movement.Shoot"), TEXT("Verse.QA.Movement.Shoot <folder>: capture mantle, slide and lean shots on LV_Test_Movement"),+ [this](const TArray<FString>& Args) -> FString+ {+ const FString Folder = Args.Num() ? Args[0] : FPaths::ProjectSavedDir() / TEXT("Harness/proof/WP01/1.9");+ return StartShoot(Folder) ? FString(TEXT("{\"started\": true}")) : FString(TEXT("{\"error\": \"no local Verse pawn\"}"));+ });+ }++ FString Soak;+ if (FParse::Value(FCommandLine::Get(), TEXT("VerseMovementSoak="), Soak))+ {+ TArray<FString> Parts;+ Soak.ParseIntoArray(Parts, TEXT(":"));+ if (Parts.Num() >= 3)+ {+ PendingSoakSeconds = FCString::Atof(*Parts[0]);+ PendingSoakSeed = FCString::Strtoui64(*Parts[1], nullptr, 10);+ PendingSoakReport = FString::Join(TArrayView<const FString>(Parts).RightChop(2), TEXT(":"));+ }+ }+ FParse::Value(FCommandLine::Get(), TEXT("VerseMovementShoot="), PendingShootFolder);+ TickHandle = FTSTicker::GetCoreTicker().AddTicker(FTickerDelegate::CreateUObject(this, &UVerseMovementQa::Tick));+}++void UVerseMovementQa::Deinitialize()+{+ FTSTicker::GetCoreTicker().RemoveTicker(TickHandle);+ if (UVerseQaRegistry* Registry = UVerseQaRegistry::Get())+ {+ for (const FString& Name : Registered)+ {+ Registry->Unregister(Name);+ }+ }+ Registered.Reset();+ Super::Deinitialize();+}++bool UVerseMovementQa::StartSoak(float Seconds, uint64 Seed, const FString& Report, bool bQuit)+{+ AVerseCharacter* Pawn = FindLocalPawn();+ if (!Pawn)+ {+ return false;+ }+ SoakPawn = Pawn;+ SoakReport = Report;+ SoakSeconds = Seconds;+ SoakElapsed = 0.f;+ bSoakRunning = true;+ bSoakQuit = bQuit;+ Pawn->GetVerseMovement()->GetNetStats() = FVerseMovementNetStats();+ Pawn->SetInputScript(VerseMovementScripts::MakeSoak(Seed, Seconds, Pawn, FVector::ZeroVector));+ UE_LOG(LogVerseQa, Display, TEXT("movement soak: %.0f s, seed %llu, report %s"), Seconds, Seed, *Report);+ return true;+}++bool UVerseMovementQa::Tick(float DeltaSeconds)+{+ if (PendingSoakSeconds > 0.f || !PendingShootFolder.IsEmpty())+ {+ WaitTime += DeltaSeconds;+ AVerseCharacter* Pawn = FindLocalPawn();+ // Give the connection a moment to settle before measuring.+ if (Pawn && Pawn->HasActorBegunPlay() && WaitTime > 3.f)+ {+ if (PendingSoakSeconds > 0.f)+ {+ StartSoak(PendingSoakSeconds, PendingSoakSeed, PendingSoakReport, true);+ PendingSoakSeconds = 0.f;+ }+ else+ {+ StartShoot(PendingShootFolder);+ PendingShootFolder.Reset();+ }+ }+ else if (WaitTime > 120.f)+ {+ UE_LOG(LogVerseQa, Error, TEXT("movement QA driver: no local Verse pawn after 120 s"));+ PendingSoakSeconds = 0.f;+ PendingShootFolder.Reset();+ FPlatformMisc::RequestExit(false);+ }+ }+ if (bSoakRunning)+ {+ SoakElapsed += DeltaSeconds;+ AVerseCharacter* Pawn = SoakPawn.Get();+ if (!Pawn || !Pawn->HasInputScript())+ {+ bSoakRunning = false;+ const UVerseCharacterMovement* M = Pawn ? Pawn->GetVerseMovement() : nullptr;+ const FString Json = M+ ? FString::Printf(TEXT("{\"role\": \"client\", \"seconds\": %.2f, \"mantles\": %d, \"stats\": %s}"), SoakElapsed, M->GetMantleCount(), *M->GetNetStats().ToJson())+ : FString(TEXT("{\"role\": \"client\", \"error\": \"pawn lost\"}"));+ FFileHelper::SaveStringToFile(Json, *SoakReport);+ UE_LOG(LogVerseQa, Display, TEXT("movement soak done: %s"), *Json);+ if (bSoakQuit)+ {+ FPlatformMisc::RequestExit(false);+ }+ }+ }+ if (ShootStep >= 0)+ {+ TickShoot(DeltaSeconds);+ }+ return true;+}++bool UVerseMovementQa::StartShoot(const FString& Folder)+{+ AVerseCharacter* Pawn = FindLocalPawn();+ if (!Pawn)+ {+ return false;+ }+ ShootPawn = Pawn;+ ShootFolder = Folder;+ IFileManager::Get().MakeDirectory(*Folder, true);+ ShootCamera = Pawn->GetWorld()->SpawnActor<ACameraActor>();+ ShootStep = 0;+ ShootTime = 0.f;+ bShotTaken = false;+ return true;+}++void UVerseMovementQa::TickShoot(float DeltaSeconds)+{+ using namespace VerseMovementCourse;+ AVerseCharacter* Pawn = ShootPawn.Get();+ ACameraActor* Camera = ShootCamera.Get();+ APlayerController* Controller = Pawn ? Cast<APlayerController>(Pawn->GetController()) : nullptr;+ if (!Pawn || !Camera || !Controller)+ {+ ShootStep = -1;+ return;+ }+ UVerseCharacterMovement* M = Pawn->GetVerseMovement();+ auto Shot = [this](const TCHAR* Name)+ {+ FScreenshotRequest::RequestScreenshot(FPaths::Combine(ShootFolder, FString(Name) + TEXT(".png")), false, false);+ UE_LOG(LogVerseQa, Display, TEXT("movement shot %s"), Name);+ };+ auto Look = [Camera, Controller](const FVector& From, const FVector& At)+ {+ Camera->SetActorLocationAndRotation(From, (At - From).Rotation());+ Controller->SetViewTarget(Camera);+ };+ auto Next = [this]() { ++ShootStep; ShootTime = 0.f; bShotTaken = false; };+ ShootTime += DeltaSeconds;+ const float LaneY = LedgeLaneY(2); // 1.5 m ledge+ switch (ShootStep)+ {+ case 0: // mantle: walk at the 1.5 m ledge and hold jump+ Place(*Pawn, FVector(LedgeFaceX - 160.f, LaneY, 0.f), 0.f);+ Pawn->SetInputScript([](float T, float, FVerseInputFrame& F)+ {+ F.Move = FVector2f(1.f, 0.f);+ F.Buttons = T > 0.2f ? uint32(EVerseInputButton::Jump) : 0u;+ F.Pressed = (T > 0.2f && T < 0.25f) ? uint32(EVerseInputButton::Jump) : 0u;+ return T < 2.f;+ });+ Look(FVector(LedgeFaceX - 70.f, LaneY - 360.f, 150.f), FVector(LedgeFaceX - 40.f, LaneY, 140.f));+ Next();+ break;+ case 1:+ if (M->IsMantling() && M->GetMantleElapsed() > M->GetMantleDuration() * 0.4f && !bShotTaken)+ {+ Shot(TEXT("mantle_side"));+ bShotTaken = true;+ }+ if ((bShotTaken && ShootTime > 1.5f) || ShootTime > 4.f)+ {+ Next();+ }+ break;+ case 2: // slide on the open floor+ Place(*Pawn, FVector(-600.f, OpenFloorY, 0.f), 0.f);+ Pawn->SetInputScript([](float T, float, FVerseInputFrame& F)+ {+ F.Move = FVector2f(1.f, 0.f);+ F.Buttons = uint32(EVerseInputButton::Sprint) | (T > 1.4f ? uint32(EVerseInputButton::Crouch) : 0u);+ F.Pressed = (T > 1.4f && T < 1.45f) ? uint32(EVerseInputButton::Crouch) : 0u;+ return T < 3.f;+ });+ Next();+ break;+ case 3:+ if (M->IsSliding() && !bShotTaken)+ {+ const FVector At = Pawn->GetActorLocation();+ Look(At + FVector(250.f, -450.f, 60.f), At + FVector(120.f, 0.f, -40.f));+ if (ShootTime > 1.65f)+ {+ Shot(TEXT("slide_side"));+ bShotTaken = true;+ }+ }+ if ((bShotTaken && ShootTime > 3.f) || ShootTime > 5.f)+ {+ Next();+ }+ break;+ case 4: // lean left into the open corridor, seen from behind+ Place(*Pawn, FVector(CornerEndX - 150.f, CornerLaneY, 0.f), 0.f);+ Pawn->SetInputScript([](float T, float, FVerseInputFrame& F)+ {+ F.Buttons = uint32(EVerseInputButton::LeanLeft);+ return T < 3.f;+ });+ Look(FVector(CornerEndX - 520.f, CornerLaneY, 190.f), FVector(CornerEndX - 150.f, CornerLaneY, 130.f));+ Next();+ break;+ case 5:+ if (ShootTime > 0.6f && !bShotTaken)+ {+ Shot(TEXT("lean_behind"));+ bShotTaken = true;+ }+ if (ShootTime > 1.2f)+ {+ Controller->SetViewTarget(Pawn);+ Next();+ }+ break;+ case 6:+ if (ShootTime > 0.5f && !bShotTaken)+ {+ Shot(TEXT("lean_first_person"));+ bShotTaken = true;+ }+ if (ShootTime > 1.5f)+ {+ Next();+ }+ break;+ default:+ UE_LOG(LogVerseQa, Display, TEXT("movement shots done: %s"), *ShootFolder);+ ShootStep = -1;+ FPlatformMisc::RequestExit(false);+ break;+ }+}diff --git a/unreal/Verse/Source/VerseMovement/Private/QA/VerseMovementQa.h b/unreal/Verse/Source/VerseMovement/Private/QA/VerseMovementQa.hnew file mode 100644index 0000000000..52110455ef--- /dev/null+++ b/unreal/Verse/Source/VerseMovement/Private/QA/VerseMovementQa.h@@ -0,0 +1,58 @@+#pragma once++#include "Containers/Ticker.h"+#include "CoreMinimal.h"+#include "Subsystems/EngineSubsystem.h"++#include "VerseMovementQa.generated.h"++class ACameraActor;+class AVerseCharacter;++/**+ * Verse.QA.Movement.* commands (work-packages.md 0.2: each package registers its own) and the+ * command-line drivers the netcode soak and the evidence capture use:+ * -VerseMovementSoak=<seconds>:<seed>:<report.json> drive the local pawn, write its corrections, quit+ * -VerseMovementShoot=<folder> capture mantle, slide and lean shots, quit+ */+UCLASS()+class UVerseMovementQa : public UEngineSubsystem+{+ GENERATED_BODY()++public:+ virtual void Initialize(FSubsystemCollectionBase& Collection) override;+ virtual void Deinitialize() override;++private:+ bool Tick(float DeltaSeconds);+ bool StartSoak(float Seconds, uint64 Seed, const FString& Report, bool bQuit);+ bool StartShoot(const FString& Folder);+ void TickShoot(float DeltaSeconds);++ FTSTicker::FDelegateHandle TickHandle;+ TArray<FString> Registered;++ // Pending command-line drivers (they wait for a possessed pawn).+ float PendingSoakSeconds = 0.f;+ uint64 PendingSoakSeed = 0;+ FString PendingSoakReport;+ FString PendingShootFolder;+ float WaitTime = 0.f;++ // Running soak.+ TWeakObjectPtr<AVerseCharacter> SoakPawn;+ FString SoakReport;+ float SoakSeconds = 0.f;+ float SoakElapsed = 0.f;+ bool bSoakRunning = false;+ bool bSoakQuit = false;++ // Running capture.+ TWeakObjectPtr<AVerseCharacter> ShootPawn;+ TWeakObjectPtr<ACameraActor> ShootCamera;+ FString ShootFolder;+ int32 ShootStep = -1;+ float ShootTime = 0.f;+ bool bShotTaken = false;+};diff --git a/unreal/Verse/Source/VerseMovement/Private/Tests/Movement/VerseMovementBasicsTest.cpp b/unreal/Verse/Source/VerseMovement/Private/Tests/Movement/VerseMovementBasicsTest.cppnew file mode 100644index 0000000000..5db2321495--- /dev/null+++ b/unreal/Verse/Source/VerseMovement/Private/Tests/Movement/VerseMovementBasicsTest.cpp@@ -0,0 +1,371 @@+#include "Misc/AutomationTest.h"++#if WITH_DEV_AUTOMATION_TESTS++#include "Engine/World.h"+#include "EngineUtils.h"+#include "Fixture/VerseMovementCourse.h"+#include "GameFramework/PlayerStart.h"+#include "GameFramework/WorldSettings.h"+#include "Misc/FileHelper.h"+#include "Misc/PackageName.h"+#include "Misc/Paths.h"+#include "Tests/Movement/VerseMovementTestWorld.h"+#include "VerseCharacter.h"+#include "VerseCharacterMovement.h"+#include "VerseMovementNetworking.h"+#include "VerseMovementScripts.h"+#include "VerseMovementTuning.h"+#include "VerseRng.h"++namespace+{+ constexpr EAutomationTestFlags BasicsTestFlags = EAutomationTestFlags_ApplicationContextMask | EAutomationTestFlags::EngineFilter;++ /** Steady horizontal speed after accelerating for Settle seconds, averaged over Measure seconds. */+ float SteadySpeed(FVerseMovementTestWorld& W, AVerseCharacter& Pawn, uint32 Buttons, const FVector2f& Move, float Settle = 2.5f, float Measure = 1.f)+ {+ uint32 Prev = 0;+ const int32 SettleTicks = FMath::RoundToInt(Settle / FVerseMovementTestWorld::Dt);+ const int32 MeasureTicks = FMath::RoundToInt(Measure / FVerseMovementTestWorld::Dt);+ FVector Start = FVector::ZeroVector;+ for (int32 Tick = 0; Tick < SettleTicks + MeasureTicks; ++Tick)+ {+ if (Tick == SettleTicks)+ {+ Start = Pawn.GetActorLocation();+ }+ W.Drive(Pawn, VerseTestFrame(Move, Buttons, Prev));+ Prev = Buttons;+ W.Tick();+ }+ return FVector::Dist2D(Pawn.GetActorLocation(), Start) / Measure / 100.f;+ }+}++// WP01.1: DA_MovementTuning loads from Data/movement/movement_tuning.json; the file holds the start values.+IMPLEMENT_SIMPLE_AUTOMATION_TEST(FVerseMovementTuningTest, "Verse.Movement.Tuning", BasicsTestFlags)+bool FVerseMovementTuningTest::RunTest(const FString& Parameters)+{+ const FString Path = UVerseMovementTuning::DefaultJsonPath();+ TestTrue(TEXT("movement_tuning.json exists"), FPaths::FileExists(Path));+ UVerseMovementTuning* Tuning = NewObject<UVerseMovementTuning>();+ FString Error;+ TestTrue(FString::Printf(TEXT("json loads (%s)"), *Error), Tuning->LoadFromJsonFile(Path, Error));+ const FVerseMovementTuningValues Defaults;+ for (TFieldIterator<FFloatProperty> It(FVerseMovementTuningValues::StaticStruct()); It; ++It)+ {+ TestEqual(FString::Printf(TEXT("json %s equals the start value"), *It->GetName()),+ It->GetPropertyValue_InContainer(&Tuning->Values), It->GetPropertyValue_InContainer(&Defaults), 1e-5f);+ }+ FVerseMovementTuningValues RoundTrip;+ TestTrue(TEXT("ToJson parses back"), UVerseMovementTuning::ParseJson(UVerseMovementTuning::ToJson(Defaults), RoundTrip, Error));+ TestEqual(TEXT("round trip keeps the walk speed"), RoundTrip.WalkSpeed, Defaults.WalkSpeed);+ TestFalse(TEXT("unknown field fails"), UVerseMovementTuning::ParseJson(TEXT("{\"WalkSped\": 4.5}"), RoundTrip, Error));+ TestFalse(TEXT("wrong case fails"), UVerseMovementTuning::ParseJson(TEXT("{\"walkspeed\": 4.5}"), RoundTrip, Error));+ TestFalse(TEXT("inverted speeds fail"), UVerseMovementTuning::ParseJson(TEXT("{\"WalkSpeed\": 7.0}"), RoundTrip, Error));+ TestFalse(TEXT("non-number fails"), UVerseMovementTuning::ParseJson(TEXT("{\"WalkSpeed\": \"fast\"}"), RoundTrip, Error));+ TestEqual(TEXT("start values: walk 4.5"), Defaults.WalkSpeed, 4.5f);+ TestEqual(TEXT("start values: sprint 6.5"), Defaults.SprintSpeed, 6.5f);+ TestEqual(TEXT("start values: crouch 2.2"), Defaults.CrouchSpeed, 2.2f);+ TestEqual(TEXT("start values: prone 0.9"), Defaults.ProneSpeed, 0.9f);+ TestEqual(TEXT("start values: slide cooldown 1.0"), Defaults.SlideCooldown, 1.0f);+ if (const UVerseMovementTuning* Asset = LoadObject<UVerseMovementTuning>(nullptr, TEXT("/Game/Verse/Movement/DA_MovementTuning.DA_MovementTuning"), nullptr, LOAD_NoWarn | LOAD_Quiet))+ {+ for (TFieldIterator<FFloatProperty> It(FVerseMovementTuningValues::StaticStruct()); It; ++It)+ {+ TestEqual(FString::Printf(TEXT("DA_MovementTuning %s matches the json"), *It->GetName()),+ It->GetPropertyValue_InContainer(&Asset->Values), It->GetPropertyValue_InContainer(&Tuning->Values), 1e-5f);+ }+ }+ else+ {+ AddError(TEXT("DA_MovementTuning asset is missing (/Game/Verse/Movement/DA_MovementTuning)"));+ }+ return true;+}++// WP01.1, WP01.3: IVerseMovementQuery on the movement component; sprint and mantle block firing.+IMPLEMENT_SIMPLE_AUTOMATION_TEST(FVerseMovementQueryTest, "Verse.Movement.Query", BasicsTestFlags)+bool FVerseMovementQueryTest::RunTest(const FString& Parameters)+{+ FVerseMovementTestWorld W;+ if (!TestTrue(TEXT("test world"), W.IsValid())) return false;+ AVerseCharacter* Pawn = W.SpawnPawn(FVector(0.f, VerseMovementCourse::OpenFloorY, 0.f), 0.f);+ if (!TestNotNull(TEXT("pawn"), Pawn)) return false;+ UVerseCharacterMovement* M = Pawn->GetVerseMovement();+ TestTrue(TEXT("movement implements IVerseMovementQuery"), M->GetClass()->ImplementsInterface(UVerseMovementQuery::StaticClass()));+ const IVerseMovementQuery* Query = Cast<IVerseMovementQuery>(M);+ TestNotNull(TEXT("query cast"), Query);+ TestEqual(TEXT("starts standing"), int32(Query->GetStance()), int32(EVerseStance::Stand));+ TestFalse(TEXT("idle does not block firing"), Query->BlocksFiring());+ const uint32 Sprint = uint32(EVerseInputButton::Sprint);+ SteadySpeed(W, *Pawn, Sprint, FVector2f(1.f, 0.f), 1.f, 0.2f);+ TestTrue(TEXT("sprinting"), Query->IsSprinting());+ TestTrue(TEXT("sprint blocks firing"), Query->BlocksFiring());+ SteadySpeed(W, *Pawn, Sprint, FVector2f(0.f, 1.f), 1.f, 0.2f);+ TestFalse(TEXT("sprint key while strafing is not a sprint"), Query->IsSprinting());+ SteadySpeed(W, *Pawn, uint32(EVerseInputButton::Crouch), FVector2f(1.f, 0.f), 0.5f, 0.2f);+ TestEqual(TEXT("crouch stance"), int32(Query->GetStance()), int32(EVerseStance::Crouch));+ TestFalse(TEXT("crouch does not block firing"), Query->BlocksFiring());+ // Jump: airborne flag.+ W.Place(*Pawn, FVector(0.f, VerseMovementCourse::OpenFloorY, 0.f), 0.f);+ W.TickSeconds(0.5f);+ W.Drive(*Pawn, VerseTestFrame(FVector2f::ZeroVector, uint32(EVerseInputButton::Jump), 0));+ W.Tick(6);+ TestTrue(TEXT("airborne after a jump"), Query->IsAirborne());+ W.Drive(*Pawn, VerseTestFrame(FVector2f::ZeroVector, 0, 0));+ W.TickSeconds(1.5f);+ // Mantle: blocks firing while it runs.+ W.Place(*Pawn, FVector(VerseMovementCourse::LedgeFaceX - 80.f, VerseMovementCourse::LedgeLaneY(1), 0.f), 0.f);+ W.TickSeconds(0.3f);+ bool bSawMantleBlock = false;+ uint32 Prev = 0;+ for (int32 Tick = 0; Tick < 60; ++Tick)+ {+ const uint32 Buttons = uint32(EVerseInputButton::Jump);+ W.Drive(*Pawn, VerseTestFrame(FVector2f(1.f, 0.f), Buttons, Prev));+ Prev = Buttons;+ W.Tick();+ bSawMantleBlock |= Query->IsMantling() && Query->BlocksFiring();+ }+ TestTrue(TEXT("mantle blocks firing"), bSawMantleBlock);+ TestEqual(TEXT("lean quantisation"), int32(IVerseMovementQuery::QuantizeLean(1.f)), 127);+ return true;+}++// A1.1: each stance's steady speed within 2 % of the DataAsset value on flat floor.+IMPLEMENT_SIMPLE_AUTOMATION_TEST(FVerseMovementSpeedsTest, "Verse.Movement.Speeds", BasicsTestFlags)+bool FVerseMovementSpeedsTest::RunTest(const FString& Parameters)+{+ FVerseMovementTestWorld W;+ if (!TestTrue(TEXT("test world"), W.IsValid())) return false;+ struct FCase { const TCHAR* Name; uint32 Buttons; float Settle; };+ const FCase Cases[] = {+ {TEXT("walk"), 0u, 2.f},+ {TEXT("sprint"), uint32(EVerseInputButton::Sprint), 2.f},+ {TEXT("crouch"), uint32(EVerseInputButton::Crouch), 2.f},+ {TEXT("prone"), uint32(EVerseInputButton::Prone), 3.f},+ };+ const FVector Start(-2500.f, VerseMovementCourse::OpenFloorY, 0.f);+ AVerseCharacter* Pawn = W.SpawnPawn(Start, 0.f);+ if (!TestNotNull(TEXT("pawn"), Pawn)) return false;+ const FVerseMovementTuningValues& T = Pawn->GetVerseMovement()->Tuning();+ const float Expected[] = {T.WalkSpeed, T.SprintSpeed, T.CrouchSpeed, T.ProneSpeed};+ for (int32 Index = 0; Index < UE_ARRAY_COUNT(Cases); ++Index)+ {+ W.Place(*Pawn, Start, 0.f);+ W.Drive(*Pawn, VerseTestFrame(FVector2f::ZeroVector, 0, 0));+ W.TickSeconds(1.f); // stand up again+ const float Speed = SteadySpeed(W, *Pawn, Cases[Index].Buttons, FVector2f(1.f, 0.f), Cases[Index].Settle, 1.f);+ const float Error = FMath::Abs(Speed - Expected[Index]) / Expected[Index];+ AddInfo(FString::Printf(TEXT("%s: %.3f m/s, DataAsset %.3f m/s, error %.2f %%"), Cases[Index].Name, Speed, Expected[Index], Error * 100.f));+ TestTrue(FString::Printf(TEXT("%s speed within 2 %%"), Cases[Index].Name), Error <= 0.02f);+ }+ return true;+}++// WP01.3: jump apex at the DataAsset height.+IMPLEMENT_SIMPLE_AUTOMATION_TEST(FVerseMovementJumpTest, "Verse.Movement.Jump", BasicsTestFlags)+bool FVerseMovementJumpTest::RunTest(const FString& Parameters)+{+ FVerseMovementTestWorld W;+ if (!TestTrue(TEXT("test world"), W.IsValid())) return false;+ AVerseCharacter* Pawn = W.SpawnPawn(FVector(0.f, VerseMovementCourse::OpenFloorY, 0.f), 0.f);+ if (!TestNotNull(TEXT("pawn"), Pawn)) return false;+ W.TickSeconds(0.5f);+ const float Floor = FVerseMovementTestWorld::Feet(*Pawn).Z;+ float Apex = Floor;+ W.Drive(*Pawn, VerseTestFrame(FVector2f::ZeroVector, uint32(EVerseInputButton::Jump), 0));+ W.Tick();+ W.Drive(*Pawn, VerseTestFrame(FVector2f::ZeroVector, 0, uint32(EVerseInputButton::Jump)));+ for (int32 Tick = 0; Tick < 90; ++Tick)+ {+ W.Tick();+ Apex = FMath::Max(Apex, FVerseMovementTestWorld::Feet(*Pawn).Z);+ }+ const float Height = (Apex - Floor) / 100.f;+ AddInfo(FString::Printf(TEXT("jump apex %.3f m"), Height));+ TestEqual(TEXT("jump apex 0.55 m within 3 cm"), Height, Pawn->GetVerseMovement()->Tuning().JumpApexHeight, 0.03f);+ TestFalse(TEXT("landed again"), Pawn->GetVerseMovement()->IsAirborne());+ return true;+}++namespace+{+ /** A seeded 60 s stream of frames exercising every movement button. */+ TArray<FVerseInputFrame> MakeParityFrames(uint64 Seed, int32 Count)+ {+ FVerseRng Rng(Seed, 0, EVerseRngSalt::Harness);+ TArray<FVerseInputFrame> Frames;+ Frames.Reserve(Count);+ uint32 Buttons = 0;+ uint32 Prev = 0;+ FVector2f Move(1.f, 0.f);+ float TurnRate = 0.f;+ int32 Next = 0;+ const uint32 Pool[] = {+ 0u, uint32(EVerseInputButton::Sprint), uint32(EVerseInputButton::Crouch), uint32(EVerseInputButton::Prone),+ uint32(EVerseInputButton::LeanLeft), uint32(EVerseInputButton::LeanRight), uint32(EVerseInputButton::Jump),+ uint32(EVerseInputButton::Sprint) | uint32(EVerseInputButton::Crouch)};+ for (int32 Index = 0; Index < Count; ++Index)+ {+ if (Index >= Next)+ {+ Buttons = Pool[Rng.RangeInt(0, UE_ARRAY_COUNT(Pool) - 1)];+ Move = FVector2f(float(Rng.Range(-0.2, 1.0)), float(Rng.Range(-1.0, 1.0)));+ TurnRate = float(Rng.Range(-90.0, 90.0));+ Next = Index + Rng.RangeInt(20, 150);+ }+ Frames.Add(VerseTestFrame(Move, Buttons, Prev, FVector2f(float(Rng.Range(-0.5, 0.5)), TurnRate / 60.f)));+ Prev = Buttons;+ }+ return Frames;+ }++ TArray<FVector> RunParity(EVerseInputButton /*Unused*/, FVerseMovementTestWorld::EDriver Driver, const TArray<FVerseInputFrame>& Frames)+ {+ FVerseMovementTestWorld W;+ TArray<FVector> Path;+ if (!W.IsValid())+ {+ return Path;+ }+ AVerseCharacter* Pawn = W.SpawnPawn(FVector(-1500.f, 2400.f, 0.f), 0.f, Driver);+ if (!Pawn)+ {+ return Path;+ }+ Path.Reserve(Frames.Num());+ for (const FVerseInputFrame& Frame : Frames)+ {+ W.Drive(*Pawn, Frame);+ W.Tick();+ Path.Add(Pawn->GetActorLocation());+ }+ return Path;+ }+}++// A1.7: the same frame stream through the person path and the bot path gives the same capsule path.+IMPLEMENT_SIMPLE_AUTOMATION_TEST(FVerseMovementInputParityTest, "Verse.Movement.InputParity", BasicsTestFlags)+bool FVerseMovementInputParityTest::RunTest(const FString& Parameters)+{+ const TArray<FVerseInputFrame> Frames = MakeParityFrames(1701, 60 * 60);+ const TArray<FVector> Person = RunParity(EVerseInputButton::None, FVerseMovementTestWorld::EDriver::Person, Frames);+ const TArray<FVector> Bot = RunParity(EVerseInputButton::None, FVerseMovementTestWorld::EDriver::Bot, Frames);+ if (!TestEqual(TEXT("both paths ran 60 s"), Person.Num(), Frames.Num()) || !TestEqual(TEXT("bot path ran 60 s"), Bot.Num(), Frames.Num()))+ {+ return false;+ }+ double MaxError = 0.0;+ double Travel = 0.0;+ for (int32 Index = 0; Index < Person.Num(); ++Index)+ {+ MaxError = FMath::Max(MaxError, FVector::Dist(Person[Index], Bot[Index]));+ if (Index > 0)+ {+ Travel += FVector::Dist(Person[Index], Person[Index - 1]);+ }+ }+ AddInfo(FString::Printf(TEXT("max capsule distance %.4f cm over %.1f m travelled"), MaxError, Travel / 100.0));+ TestTrue(TEXT("the pawn really moved (over 50 m)"), Travel > 5000.0);+ TestTrue(TEXT("capsule paths within 0.1 cm"), MaxError <= 0.1);+ return true;+}++// A1.9: movement for 2 pawns costs at most 0.3 ms of game thread per tick.+IMPLEMENT_SIMPLE_AUTOMATION_TEST(FVerseMovementCostTest, "Verse.Movement.Cost", BasicsTestFlags)+bool FVerseMovementCostTest::RunTest(const FString& Parameters)+{+ FVerseMovementTestWorld W;+ if (!TestTrue(TEXT("test world"), W.IsValid())) return false;+ AVerseCharacter* A = W.SpawnPawn(FVector(0.f, 1200.f, 0.f), 0.f);+ AVerseCharacter* B = W.SpawnPawn(FVector(0.f, 2000.f, 0.f), 0.f);+ if (!TestNotNull(TEXT("pawn a"), A) || !TestNotNull(TEXT("pawn b"), B)) return false;+ A->SetInputScript(VerseMovementScripts::MakeSoak(11, 30.f, A, FVector::ZeroVector));+ B->SetInputScript(VerseMovementScripts::MakeSoak(12, 30.f, B, FVector::ZeroVector));+ W.TickSeconds(2.f); // warm up+ const uint64 StartCycles = A->GetVerseMovement()->GetTickCycles() + B->GetVerseMovement()->GetTickCycles();+ const int32 StartTicks = A->GetVerseMovement()->GetTickCount();+ W.TickSeconds(20.f);+ const uint64 Cycles = A->GetVerseMovement()->GetTickCycles() + B->GetVerseMovement()->GetTickCycles() - StartCycles;+ const int32 Ticks = A->GetVerseMovement()->GetTickCount() - StartTicks;+ const double MsPerTick = FPlatformTime::ToMilliseconds64(Cycles) / FMath::Max(Ticks, 1);+ AddInfo(FString::Printf(TEXT("movement of 2 pawns (input tick, movement, body pose): %.4f ms per tick over %d ticks; mantles %d + %d"), MsPerTick, Ticks,+ A->GetVerseMovement()->GetMantleCount(), B->GetVerseMovement()->GetMantleCount()));+ TestTrue(TEXT("at most 0.3 ms per tick"), MsPerTick <= 0.3);+ return true;+}++// WP01.10: flags and lean ride in the saved move, so a replay re-simulates the same inputs.+IMPLEMENT_SIMPLE_AUTOMATION_TEST(FVerseMovementSavedMoveTest, "Verse.Movement.SavedMove", BasicsTestFlags)+bool FVerseMovementSavedMoveTest::RunTest(const FString& Parameters)+{+ FVerseSavedMove Move;+ Move.bSavedWantsSprint = true;+ Move.bSavedWantsMantle = true;+ const uint8 Flags = Move.GetCompressedFlags();+ TestTrue(TEXT("sprint flag set"), (Flags & VerseMoveFlags::Sprint) != 0);+ TestFalse(TEXT("prone flag clear"), (Flags & VerseMoveFlags::Prone) != 0);+ TestTrue(TEXT("mantle flag set"), (Flags & VerseMoveFlags::Mantle) != 0);+ TestTrue(TEXT("flags avoid the stock bits"), (VerseMoveFlags::Sprint | VerseMoveFlags::Prone | VerseMoveFlags::Mantle)+ & (FSavedMove_Character::FLAG_JumpPressed | FSavedMove_Character::FLAG_WantsToCrouch) ? false : true);+ Move.Clear();+ TestEqual(TEXT("clear resets"), int32(Move.GetCompressedFlags() & VerseMoveFlags::Sprint), 0);++ FVerseMovementTestWorld W;+ if (!TestTrue(TEXT("test world"), W.IsValid())) return false;+ AVerseCharacter* Pawn = W.SpawnPawn(FVector(0.f, VerseMovementCourse::OpenFloorY, 0.f), 0.f);+ if (!TestNotNull(TEXT("pawn"), Pawn)) return false;+ UVerseCharacterMovement* M = Pawn->GetVerseMovement();+ M->UpdateFromCompressedFlags(VerseMoveFlags::Prone | FSavedMove_Character::FLAG_WantsToCrouch);+ TestTrue(TEXT("compressed crouch reaches the movement"), M->bWantsToCrouch);+ FVerseMovementNetStats Stats;+ Stats.Corrections[int32(EVerseMoveKind::Mantle)] = 2;+ Stats.Corrections[int32(EVerseMoveKind::Walk)] = 1;+ TestEqual(TEXT("stats total"), Stats.Total(), 3);+ TestTrue(TEXT("stats json names the kinds"), Stats.ToJson().Contains(TEXT("\"mantle\": 2")));+ return true;+}++// WP01.9: LV_Test_Movement exists with the course, player starts and the movement game mode.+IMPLEMENT_SIMPLE_AUTOMATION_TEST(FVerseMovementFixtureMapTest, "Verse.Movement.FixtureMap", BasicsTestFlags)+bool FVerseMovementFixtureMapTest::RunTest(const FString& Parameters)+{+ const TCHAR* MapPath = TEXT("/Game/Verse/Test/WP01/LV_Test_Movement");+ if (!TestTrue(TEXT("LV_Test_Movement package exists"), FPackageName::DoesPackageExist(MapPath)))+ {+ return false;+ }+ UWorld* Map = LoadObject<UWorld>(nullptr, TEXT("/Game/Verse/Test/WP01/LV_Test_Movement.LV_Test_Movement"));+ if (!TestNotNull(TEXT("map loads"), Map) || !Map->PersistentLevel)+ {+ return false;+ }+ int32 Courses = 0;+ int32 Starts = 0;+ for (AActor* Actor : Map->PersistentLevel->Actors)+ {+ Courses += Cast<AVerseMovementCourse>(Actor) ? 1 : 0;+ Starts += Cast<APlayerStart>(Actor) ? 1 : 0;+ }+ TestEqual(TEXT("one course actor"), Courses, 1);+ TestTrue(TEXT("at least two player starts"), Starts >= 2);+ const AWorldSettings* Settings = Map->PersistentLevel->GetWorldSettings();+ TestTrue(TEXT("movement game mode override"), Settings && Settings->DefaultGameMode == AVerseMovementTestGameMode::StaticClass());+ // The course table covers every fixture of WP01.9.+ TSet<FString> Names;+ for (const VerseMovementCourse::FBlock& Block : VerseMovementCourse::Blocks())+ {+ Names.Add(Block.Name);+ }+ for (const TCHAR* Needed : {TEXT("Ledge"), TEXT("TunnelRoof"), TEXT("Slope30"), TEXT("Slope46"), TEXT("Stair"), TEXT("DropPlatform"),+ TEXT("CornerWallLeft"), TEXT("CornerWallRight"), TEXT("BreachSill"), TEXT("BreachLintel")})+ {+ TestTrue(FString::Printf(TEXT("course has %s"), Needed), Names.Contains(Needed));+ }+ return true;+}++#endif // WITH_DEV_AUTOMATION_TESTSdiff --git a/unreal/Verse/Source/VerseMovement/Private/Tests/Movement/VerseMovementMovesTest.cpp b/unreal/Verse/Source/VerseMovement/Private/Tests/Movement/VerseMovementMovesTest.cppnew file mode 100644index 0000000000..b151d6cafb--- /dev/null+++ b/unreal/Verse/Source/VerseMovement/Private/Tests/Movement/VerseMovementMovesTest.cpp@@ -0,0 +1,467 @@+#include "Misc/AutomationTest.h"++#if WITH_DEV_AUTOMATION_TESTS++#include "Camera/CameraComponent.h"+#include "Components/BoxComponent.h"+#include "Engine/World.h"+#include "Fixture/VerseMovementCourse.h"+#include "Tests/Movement/VerseMovementTestWorld.h"+#include "VerseCharacter.h"+#include "VerseCharacterMovement.h"+#include "VerseRng.h"++namespace+{+ constexpr EAutomationTestFlags MovesTestFlags = EAutomationTestFlags_ApplicationContextMask | EAutomationTestFlags::EngineFilter;+ using namespace VerseMovementCourse;++ /** Holds Buttons and Move for Seconds; Pressed only on the first tick. */+ void Hold(FVerseMovementTestWorld& W, AVerseCharacter& Pawn, uint32 Buttons, const FVector2f& Move, float Seconds, uint32& Prev,+ TFunctionRef<void()> PerTick = [] {})+ {+ const int32 Ticks = FMath::Max(1, FMath::RoundToInt(Seconds / FVerseMovementTestWorld::Dt));+ for (int32 Tick = 0; Tick < Ticks; ++Tick)+ {+ W.Drive(Pawn, VerseTestFrame(Move, Buttons, Prev));+ Prev = Buttons;+ W.Tick();+ PerTick();+ }+ }++ void Settle(FVerseMovementTestWorld& W, AVerseCharacter& Pawn, uint32& Prev)+ {+ Hold(W, Pawn, 0u, FVector2f::ZeroVector, 0.9f, Prev);+ }+}++// A1.3: prone passes the 0.75 m tunnel, standing and crouch do not; prone never starts with less+// than 0.4 m clearance.+IMPLEMENT_SIMPLE_AUTOMATION_TEST(FVerseMovementProneClearanceTest, "Verse.Movement.Prone.Clearance", MovesTestFlags)+bool FVerseMovementProneClearanceTest::RunTest(const FString& Parameters)+{+ FVerseMovementTestWorld W;+ if (!TestTrue(TEXT("test world"), W.IsValid())) return false;+ const FVector Entry(TunnelEntryX - 120.f, CrawlTunnelY, 0.f);+ AVerseCharacter* Pawn = W.SpawnPawn(Entry, 0.f);+ if (!TestNotNull(TEXT("pawn"), Pawn)) return false;+ UVerseCharacterMovement* M = Pawn->GetVerseMovement();+ const float Exit = TunnelEntryX + TunnelLength;+ uint32 Prev = 0;+ struct FCase { const TCHAR* Name; uint32 Buttons; float Seconds; bool bPasses; };+ const FCase Cases[] = {+ {TEXT("standing"), 0u, 4.f, false},+ {TEXT("crouched"), uint32(EVerseInputButton::Crouch), 6.f, false},+ {TEXT("prone"), uint32(EVerseInputButton::Prone), 8.f, true},+ };+ for (const FCase& Case : Cases)+ {+ W.Place(*Pawn, Entry, 0.f);+ Settle(W, *Pawn, Prev);+ Hold(W, *Pawn, Case.Buttons, FVector2f(1.f, 0.f), Case.Seconds, Prev);+ const float X = Pawn->GetActorLocation().X;+ AddInfo(FString::Printf(TEXT("%s reached x = %.1f (tunnel %0.f..%0.f)"), Case.Name, X, TunnelEntryX, Exit));+ TestTrue(FString::Printf(TEXT("%s %s the 0.75 m tunnel"), Case.Name, Case.bPasses ? TEXT("passes") : TEXT("is blocked by")), (X > Exit) == Case.bPasses);+ Hold(W, *Pawn, Case.Buttons, FVector2f(-1.f, 0.f), Case.Seconds, Prev);+ }+ // Crouch passes the 1.2 m tunnel, standing does not.+ const FVector CrouchEntry(TunnelEntryX - 120.f, CrouchTunnelY, 0.f);+ for (const bool bCrouch : {false, true})+ {+ W.Place(*Pawn, CrouchEntry, 0.f);+ Settle(W, *Pawn, Prev);+ Hold(W, *Pawn, bCrouch ? uint32(EVerseInputButton::Crouch) : 0u, FVector2f(1.f, 0.f), 4.f, Prev);+ TestTrue(FString::Printf(TEXT("%s %s the 1.2 m tunnel"), bCrouch ? TEXT("crouch") : TEXT("standing"), bCrouch ? TEXT("passes") : TEXT("is blocked by")),+ (Pawn->GetActorLocation().X > Exit) == bCrouch);+ }++ // Seeded clearance poses: a slab over the prone body footprint at a random height.+ FVerseRng Rng(4242, 0, EVerseRngSalt::Harness);+ const FVector Open(0.f, OpenFloorY, 0.f);+ int32 Refused = 0;+ int32 Allowed = 0;+ int32 Violations = 0;+ for (int32 Pose = 0; Pose < 200; ++Pose)+ {+ const float Bottom = float(Rng.Range(20.0, 70.0));+ const float Along = float(Rng.Range(-150.0, -55.0)); // behind the standing capsule, over the prone legs+ UBoxComponent* Slab = W.AddBox(Open + FVector(Along, 0.f, Bottom + 25.f), FVector(15.f, 60.f, 25.f));+ W.Place(*Pawn, Open, 0.f);+ Settle(W, *Pawn, Prev);+ Hold(W, *Pawn, uint32(EVerseInputButton::Prone), FVector2f::ZeroVector, 0.2f, Prev);+ const bool bProne = M->IsProne();+ const bool bBodyUnder = Along - 15.f < 40.f && Along + 15.f > -140.f;+ if (bProne && Bottom < 40.f && bBodyUnder)+ {+ ++Violations;+ }+ (bProne ? Allowed : Refused) += 1;+ Hold(W, *Pawn, 0u, FVector2f::ZeroVector, 1.0f, Prev);+ Slab->GetOwner()->Destroy();+ }+ AddInfo(FString::Printf(TEXT("clearance poses: %d prone, %d refused, %d under 0.4 m"), Allowed, Refused, Violations));+ TestEqual(TEXT("prone never starts under 0.4 m clearance"), Violations, 0);+ TestTrue(TEXT("prone starts where it fits"), Allowed > 20);+ TestTrue(TEXT("prone is refused where it does not"), Refused > 20);+ return true;+}++// WP01.4: prone transitions (enter 0.7 s, exit 0.6 s, no movement meanwhile) and the 90 deg/s turn cap.+IMPLEMENT_SIMPLE_AUTOMATION_TEST(FVerseMovementProneTransitionsTest, "Verse.Movement.Prone.Transitions", MovesTestFlags)+bool FVerseMovementProneTransitionsTest::RunTest(const FString& Parameters)+{+ FVerseMovementTestWorld W;+ if (!TestTrue(TEXT("test world"), W.IsValid())) return false;+ const FVector Open(0.f, OpenFloorY, 0.f);+ AVerseCharacter* Pawn = W.SpawnPawn(Open, 0.f);+ if (!TestNotNull(TEXT("pawn"), Pawn)) return false;+ UVerseCharacterMovement* M = Pawn->GetVerseMovement();+ const FVerseMovementTuningValues& T = M->Tuning();+ uint32 Prev = 0;+ Settle(W, *Pawn, Prev);+ const FVector Before = Pawn->GetActorLocation();+ int32 Frozen = 0;+ Hold(W, *Pawn, uint32(EVerseInputButton::Prone), FVector2f(1.f, 0.f), 1.5f, Prev, [&]+ {+ if (M->GetProneTransitionAlpha() > 0.f)+ {+ ++Frozen;+ }+ });+ const float EnterSeconds = Frozen * FVerseMovementTestWorld::Dt;+ AddInfo(FString::Printf(TEXT("prone enter %.3f s"), EnterSeconds));+ TestEqual(TEXT("prone enter takes 0.7 s (within a tick)"), EnterSeconds, T.ProneEnterTime, FVerseMovementTestWorld::Dt * 1.5f);+ TestTrue(TEXT("prone crawls after the transition"), FVector::Dist2D(Pawn->GetActorLocation(), Before) > 30.f);+ TestEqual(TEXT("prone stance"), int32(M->GetStance()), int32(EVerseStance::Prone));+ TestTrue(TEXT("prone capsule is 0.4 m"), FMath::IsNearlyEqual(Pawn->GetSimpleCollisionHalfHeight() * 2.f, T.ProneMinClearance * 100.f, 1.f));++ // Turn cap: ask for 600 deg/s.+ const float YawBefore = Pawn->GetControlRotation().Yaw;+ for (int32 Tick = 0; Tick < 60; ++Tick)+ {+ W.Drive(*Pawn, VerseTestFrame(FVector2f::ZeroVector, uint32(EVerseInputButton::Prone), Prev, FVector2f(0.f, 10.f)));+ Prev = uint32(EVerseInputButton::Prone);+ W.Tick();+ }+ const float Turned = FMath::Abs(FRotator::NormalizeAxis(Pawn->GetControlRotation().Yaw - YawBefore));+ AddInfo(FString::Printf(TEXT("prone turned %.1f deg in 1 s"), Turned));+ TestTrue(TEXT("prone turn capped at 90 deg/s"), Turned <= T.ProneTurnCapDegPerSec + 0.5f && Turned >= T.ProneTurnCapDegPerSec - 2.f);++ // Exit.+ const FVector Down = Pawn->GetActorLocation();+ int32 ExitFrozen = 0;+ Hold(W, *Pawn, 0u, FVector2f(1.f, 0.f), 1.2f, Prev, [&]+ {+ if (M->GetProneTransitionAlpha() < 0.f)+ {+ ++ExitFrozen;+ }+ });+ TestEqual(TEXT("prone exit takes 0.6 s (within a tick)"), ExitFrozen * FVerseMovementTestWorld::Dt, T.ProneExitTime, FVerseMovementTestWorld::Dt * 1.5f);+ TestEqual(TEXT("standing again"), int32(M->GetStance()), int32(EVerseStance::Stand));+ TestTrue(TEXT("standing capsule restored"), FMath::IsNearlyEqual(Pawn->GetSimpleCollisionHalfHeight(), T.StandHalfHeightCm(), 0.5f));+ TestTrue(TEXT("walks off after standing"), FVector::Dist2D(Pawn->GetActorLocation(), Down) > 10.f);+ return true;+}++// A1.4: slide only from sprint at 5.5 m/s or more; ends in crouch within 1.1 s; a second slide is blocked for 1.0 s.+IMPLEMENT_SIMPLE_AUTOMATION_TEST(FVerseMovementSlideTest, "Verse.Movement.Slide", MovesTestFlags)+bool FVerseMovementSlideTest::RunTest(const FString& Parameters)+{+ FVerseMovementTestWorld W;+ if (!TestTrue(TEXT("test world"), W.IsValid())) return false;+ const FVector Start(-2600.f, OpenFloorY, 0.f);+ AVerseCharacter* Pawn = W.SpawnPawn(Start, 0.f);+ if (!TestNotNull(TEXT("pawn"), Pawn)) return false;+ UVerseCharacterMovement* M = Pawn->GetVerseMovement();+ const FVerseMovementTuningValues& T = M->Tuning();+ const uint32 Sprint = uint32(EVerseInputButton::Sprint);+ const uint32 Crouch = uint32(EVerseInputButton::Crouch);+ uint32 Prev = 0;++ // Walk speed: no slide.+ Hold(W, *Pawn, 0u, FVector2f(1.f, 0.f), 1.5f, Prev);+ Hold(W, *Pawn, Crouch, FVector2f(1.f, 0.f), 0.2f, Prev);+ TestFalse(TEXT("no slide from a walk"), M->IsSliding());+ // Sprint key held but still below 5.5 m/s.+ W.Place(*Pawn, Start, 0.f);+ Settle(W, *Pawn, Prev);+ Hold(W, *Pawn, Sprint, FVector2f(1.f, 0.f), 0.08f, Prev);+ const float EarlySpeed = Pawn->GetVelocity().Size2D() / 100.f;+ Hold(W, *Pawn, Sprint | Crouch, FVector2f(1.f, 0.f), 0.1f, Prev);+ AddInfo(FString::Printf(TEXT("early crouch at %.2f m/s"), EarlySpeed));+ TestTrue(TEXT("slow sprint below the floor"), EarlySpeed < T.SlideMinEntrySpeed);+ TestFalse(TEXT("no slide below 5.5 m/s"), M->IsSliding());++ // Full sprint: slide.+ W.Place(*Pawn, Start, 0.f);+ Settle(W, *Pawn, Prev);+ Hold(W, *Pawn, Sprint, FVector2f(1.f, 0.f), 1.5f, Prev);+ TestTrue(TEXT("sprinting at full speed"), Pawn->GetVelocity().Size2D() >= T.SlideMinEntrySpeed * 100.f);+ int32 SlideTicks = 0;+ float PeakSpeed = 0.f;+ bool bStarted = false;+ // Hold sprint and crouch until the slide has ended (the cooldown starts there).+ for (int32 Tick = 0; Tick < 150; ++Tick)+ {+ W.Drive(*Pawn, VerseTestFrame(FVector2f(1.f, 0.f), Sprint | Crouch, Prev));+ Prev = Sprint | Crouch;+ W.Tick();+ if (M->IsSliding())+ {+ bStarted = true;+ ++SlideTicks;+ PeakSpeed = FMath::Max(PeakSpeed, float(Pawn->GetVelocity().Size2D()));+ }+ else if (bStarted)+ {+ break;+ }+ }+ const float SlideSeconds = SlideTicks * FVerseMovementTestWorld::Dt;+ AddInfo(FString::Printf(TEXT("slide %.3f s, peak %.2f m/s"), SlideSeconds, PeakSpeed / 100.f));+ TestTrue(TEXT("slide starts from sprint"), bStarted);+ TestTrue(TEXT("slide ends within 1.1 s"), SlideSeconds <= T.SlideMaxDuration + FVerseMovementTestWorld::Dt * 0.5f);+ TestTrue(TEXT("slide boosts toward 7.5 m/s"), PeakSpeed >= T.SlideBoostSpeed * 100.f - 30.f);+ TestEqual(TEXT("slide ends in crouch"), int32(M->GetStance()), int32(EVerseStance::Crouch));++ // Cooldown: stand, sprint up again and try within 1.0 s, then after.+ Hold(W, *Pawn, Sprint, FVector2f(1.f, 0.f), 0.5f, Prev);+ TestTrue(TEXT("back to sprint speed within the cooldown"), Pawn->GetVelocity().Size2D() >= T.SlideMinEntrySpeed * 100.f);+ TestTrue(TEXT("cooldown still running"), M->GetSlideCooldownRemaining() > 0.f);+ Hold(W, *Pawn, Sprint | Crouch, FVector2f(1.f, 0.f), 0.1f, Prev);+ TestFalse(TEXT("second slide blocked during the 1.0 s cooldown"), M->IsSliding());+ Hold(W, *Pawn, Sprint, FVector2f(1.f, 0.f), 0.8f, Prev);+ TestEqual(TEXT("cooldown over"), M->GetSlideCooldownRemaining(), 0.f);+ Hold(W, *Pawn, Sprint | Crouch, FVector2f(1.f, 0.f), 0.1f, Prev);+ TestTrue(TEXT("slide allowed after the cooldown"), M->IsSliding());+ return true;+}++namespace+{+ struct FMantleResult+ {+ bool bMantled = false;+ bool bOnTop = false;+ int32 MantleTicks = 0;+ };++ /** One seeded approach at ledge Index: walk or sprint in, press jump at PressDistance. */+ FMantleResult Approach(FVerseMovementTestWorld& W, AVerseCharacter& Pawn, int32 Index, FVerseRng& Rng)+ {+ UVerseCharacterMovement* M = Pawn.GetVerseMovement();+ const float Height = LedgeHeights[Index];+ const float Distance = float(Rng.Range(120.0, 420.0));+ const float Lateral = float(Rng.Range(-80.0, 80.0));+ const float Yaw = float(Rng.Range(-20.0, 20.0));+ const bool bSprint = Rng.Chance(0.5);+ const float PressAt = float(Rng.Range(45.0, 140.0)); // capsule centre to face, cm+ W.Place(Pawn, FVector(LedgeFaceX - Distance, LedgeLaneY(Index) + Lateral, 0.f), Yaw);+ uint32 Prev = 0;+ Hold(W, Pawn, 0u, FVector2f::ZeroVector, 0.1f, Prev);+ const int32 Before = M->GetMantleCount();+ FMantleResult Result;+ for (int32 Tick = 0; Tick < 180; ++Tick)+ {+ const float ToFace = LedgeFaceX - Pawn.GetActorLocation().X;+ uint32 Buttons = bSprint ? uint32(EVerseInputButton::Sprint) : 0u;+ if (ToFace <= PressAt / FMath::Cos(FMath::DegreesToRadians(Yaw)))+ {+ Buttons |= uint32(EVerseInputButton::Jump);+ }+ W.Drive(Pawn, VerseTestFrame(FVector2f(1.f, 0.f), Buttons, Prev));+ Prev = Buttons;+ const bool bBefore = M->IsMantling();+ W.Tick();+ if (bBefore || M->IsMantling())+ {+ ++Result.MantleTicks; // every tick that simulated part of the mantle+ }+ if (bBefore && !M->IsMantling())+ {+ break;+ }+ }+ Hold(W, Pawn, 0u, FVector2f::ZeroVector, 0.1f, Prev);+ Result.bMantled = M->GetMantleCount() > Before;+ Result.bOnTop = FMath::Abs(FVerseMovementTestWorld::Feet(Pawn).Z - Height) < 6.f && Pawn.GetActorLocation().X > LedgeFaceX;+ return Result;+ }+}++// A1.2: 1,000 seeded approaches: 0.5-2.0 m succeed at least 99.5 %; 2.1 m never mantles; time within a tick.+IMPLEMENT_SIMPLE_AUTOMATION_TEST(FVerseMovementMantleTest, "Verse.Movement.Mantle.Ledges", MovesTestFlags)+bool FVerseMovementMantleTest::RunTest(const FString& Parameters)+{+ FVerseMovementTestWorld W;+ if (!TestTrue(TEXT("test world"), W.IsValid())) return false;+ AVerseCharacter* Pawn = W.SpawnPawn(FVector(0.f, LedgeLaneY(0), 0.f), 0.f);+ if (!TestNotNull(TEXT("pawn"), Pawn)) return false;+ const FVerseMovementTuningValues& T = Pawn->GetVerseMovement()->Tuning();+ FVerseRng Rng(90210, 0, EVerseRngSalt::Harness);+ int32 Attempts[LedgeCount] = {};+ int32 Successes[LedgeCount] = {};+ int32 Mantled[LedgeCount] = {};+ int32 TimingMisses = 0;+ for (int32 Run = 0; Run < 1000; ++Run)+ {+ const int32 Index = Run % LedgeCount;+ const FMantleResult Result = Approach(W, *Pawn, Index, Rng);+ ++Attempts[Index];+ Successes[Index] += Result.bOnTop ? 1 : 0;+ Mantled[Index] += Result.bMantled ? 1 : 0;+ if (Result.bMantled && Index < LedgeCount - 1)+ {+ const float Expected = LedgeHeights[Index] > T.MantleLowMaxHeight * 100.f ? T.MantleHighDuration : T.MantleLowDuration;+ const float Seconds = Result.MantleTicks * FVerseMovementTestWorld::Dt;+ if (FMath::Abs(Seconds - Expected) > FVerseMovementTestWorld::Dt + KINDA_SMALL_NUMBER)+ {+ ++TimingMisses;+ AddInfo(FString::Printf(TEXT("mantle %.0f cm took %.3f s, want %.3f s"), LedgeHeights[Index], Seconds, Expected));+ }+ }+ if (Index == LedgeCount - 1 && Result.bMantled)+ {+ AddError(FString::Printf(TEXT("approach %d mantled the 2.1 m wall"), Run));+ }+ }+ for (int32 Index = 0; Index < LedgeCount; ++Index)+ {+ const float Rate = float(Successes[Index]) / FMath::Max(Attempts[Index], 1);+ AddInfo(FString::Printf(TEXT("ledge %.1f m: on top %d / %d (%.1f %%), mantled %d"), LedgeHeights[Index] / 100.f, Successes[Index], Attempts[Index], Rate * 100.f, Mantled[Index]));+ if (Index < LedgeCount - 1)+ {+ TestTrue(FString::Printf(TEXT("ledge %.1f m succeeds at least 99.5 %%"), LedgeHeights[Index] / 100.f), Rate >= 0.995f);+ }+ else+ {+ TestEqual(TEXT("2.1 m never mantles"), Mantled[Index], 0);+ TestEqual(TEXT("2.1 m is never climbed"), Successes[Index], 0);+ }+ }+ TestEqual(TEXT("mantle time within one tick of the DataAsset"), TimingMisses, 0);+ return true;+}++// WP01.6: mantle through a low breach (destruction.md 6.1 mantle links): crouched, ends beyond the wall.+IMPLEMENT_SIMPLE_AUTOMATION_TEST(FVerseMovementMantleBreachTest, "Verse.Movement.Mantle.Breach", MovesTestFlags)+bool FVerseMovementMantleBreachTest::RunTest(const FString& Parameters)+{+ FVerseMovementTestWorld W;+ if (!TestTrue(TEXT("test world"), W.IsValid())) return false;+ AVerseCharacter* Pawn = W.SpawnPawn(FVector(BreachWallX - 200.f, BreachY, 0.f), 0.f);+ if (!TestNotNull(TEXT("pawn"), Pawn)) return false;+ UVerseCharacterMovement* M = Pawn->GetVerseMovement();+ FVerseRng Rng(777, 0, EVerseRngSalt::Harness);+ int32 Through = 0;+ const int32 Runs = 50;+ for (int32 Run = 0; Run < Runs; ++Run)+ {+ W.Place(*Pawn, FVector(BreachWallX - float(Rng.Range(110.0, 300.0)), BreachY + float(Rng.Range(-60.0, 60.0)), 0.f), float(Rng.Range(-10.0, 10.0)));+ uint32 Prev = 0;+ Hold(W, *Pawn, 0u, FVector2f::ZeroVector, 0.1f, Prev);+ bool bCrouchedMantle = false;+ for (int32 Tick = 0; Tick < 240; ++Tick)+ {+ const float ToWall = BreachWallX - Pawn->GetActorLocation().X;+ const uint32 Buttons = ToWall < 95.f ? uint32(EVerseInputButton::Jump) : 0u;+ W.Drive(*Pawn, VerseTestFrame(FVector2f(1.f, 0.f), Buttons, Prev));+ Prev = Buttons;+ W.Tick();+ bCrouchedMantle |= M->IsMantling() && Pawn->GetSimpleCollisionHalfHeight() < M->Tuning().StandHalfHeightCm() - 1.f;+ }+ const bool bBeyond = Pawn->GetActorLocation().X > BreachWallX + 25.f + 30.f && FVerseMovementTestWorld::Feet(*Pawn).Z < 10.f;+ Through += (bBeyond && bCrouchedMantle) ? 1 : 0;+ }+ AddInfo(FString::Printf(TEXT("breach mantles: %d / %d"), Through, Runs));+ TestTrue(TEXT("mantle through the low breach at least 98 %"), Through >= Runs - 1);+ return true;+}++// WP01.7: lean offset, roll and enter time in free space.+IMPLEMENT_SIMPLE_AUTOMATION_TEST(FVerseMovementLeanValuesTest, "Verse.Movement.Lean.Values", MovesTestFlags)+bool FVerseMovementLeanValuesTest::RunTest(const FString& Parameters)+{+ FVerseMovementTestWorld W;+ if (!TestTrue(TEXT("test world"), W.IsValid())) return false;+ AVerseCharacter* Pawn = W.SpawnPawn(FVector(0.f, OpenFloorY, 0.f), 30.f);+ if (!TestNotNull(TEXT("pawn"), Pawn)) return false;+ UVerseCharacterMovement* M = Pawn->GetVerseMovement();+ const FVerseMovementTuningValues& T = M->Tuning();+ uint32 Prev = 0;+ Settle(W, *Pawn, Prev);+ const FVector Eye = Pawn->GetEyeLocation();+ int32 TicksToFull = -1;+ int32 Tick = 0;+ Hold(W, *Pawn, uint32(EVerseInputButton::LeanRight), FVector2f::ZeroVector, 0.5f, Prev, [&]+ {+ ++Tick;+ if (TicksToFull < 0 && M->GetLeanQuantized() == 127)+ {+ TicksToFull = Tick;+ }+ });+ const FVector Offset = Pawn->GetEyeLocation() - Eye;+ const float Side = Offset | Pawn->GetActorRightVector();+ AddInfo(FString::Printf(TEXT("lean right: %.2f cm, roll %.2f deg, %d ticks"), Side, Pawn->GetEyeRotation().Roll, TicksToFull));+ TestEqual(TEXT("lean camera offset 35 cm"), Side, T.LeanCameraOffset * 100.f, 0.5f);+ TestEqual(TEXT("lean roll 12 deg"), float(FMath::Abs(Pawn->GetEyeRotation().Roll)), T.LeanRollDeg, 0.2f);+ TestEqual(TEXT("lean enters in 0.15 s"), TicksToFull * FVerseMovementTestWorld::Dt, T.LeanEnterTime, FVerseMovementTestWorld::Dt * 1.01f);+ Hold(W, *Pawn, uint32(EVerseInputButton::LeanLeft), FVector2f::ZeroVector, 0.5f, Prev);+ TestEqual(TEXT("lean left reaches -127"), int32(M->GetLeanQuantized()), -127);+ Hold(W, *Pawn, uint32(EVerseInputButton::LeanLeft) | uint32(EVerseInputButton::Sprint), FVector2f(1.f, 0.f), 0.8f, Prev);+ TestEqual(TEXT("sprinting cancels the lean"), int32(M->GetLeanQuantized()), 0);+ return true;+}++// A1.5: leaning against a wall never puts the camera inside geometry (0 of 500 seeded corner poses).+IMPLEMENT_SIMPLE_AUTOMATION_TEST(FVerseMovementLeanWallTest, "Verse.Movement.Lean.Wall", MovesTestFlags)+bool FVerseMovementLeanWallTest::RunTest(const FString& Parameters)+{+ FVerseMovementTestWorld W;+ if (!TestTrue(TEXT("test world"), W.IsValid())) return false;+ AVerseCharacter* Pawn = W.SpawnPawn(FVector(CornerEndX - 200.f, CornerLaneY, 0.f), 0.f);+ if (!TestNotNull(TEXT("pawn"), Pawn)) return false;+ UVerseCharacterMovement* M = Pawn->GetVerseMovement();+ UWorld* World = W.GetWorld();+ FVerseRng Rng(31337, 0, EVerseRngSalt::Harness);+ int32 Inside = 0;+ int32 Limited = 0;+ int32 Full = 0;+ FCollisionQueryParams Params(SCENE_QUERY_STAT(VerseLeanTest), false, Pawn);+ for (int32 Pose = 0; Pose < 500; ++Pose)+ {+ // Corridor between the walls (faces at +-85 cm from the lane), the capsule radius keeps 34 cm.+ const float Y = CornerLaneY + float(Rng.Range(-50.0, 50.0));+ const float X = CornerEndX - float(Rng.Range(-60.0, 500.0));+ const float Yaw = float(Rng.Range(-180.0, 180.0));+ const bool bCrouch = Rng.Chance(0.3);+ const uint32 Lean = Rng.Chance(0.5) ? uint32(EVerseInputButton::LeanLeft) : uint32(EVerseInputButton::LeanRight);+ W.Place(*Pawn, FVector(X, Y, 0.f), Yaw);+ uint32 Prev = 0;+ const uint32 Base = bCrouch ? uint32(EVerseInputButton::Crouch) : 0u;+ Hold(W, *Pawn, Base, FVector2f::ZeroVector, 0.3f, Prev);+ Hold(W, *Pawn, Base | Lean, FVector2f::ZeroVector, 0.35f, Prev);+ const FVector Camera = Pawn->GetEyeLocation();+ const FVector Eye = M->GetUnleanedEyeLocation();+ FHitResult Hit;+ const bool bOverlap = World->OverlapBlockingTestByChannel(Camera, FQuat::Identity, ECC_Visibility, FCollisionShape::MakeSphere(5.f), Params);+ const bool bBlocked = World->LineTraceSingleByChannel(Hit, Eye, Camera, ECC_Visibility, Params);+ if (bOverlap || bBlocked)+ {+ ++Inside;+ AddInfo(FString::Printf(TEXT("pose %d: camera inside geometry at %s (lean %d)"), Pose, *Camera.ToCompactString(), int32(M->GetLeanQuantized())));+ }+ (FMath::Abs(M->GetLeanQuantized()) == 127 ? Full : Limited) += 1;+ Hold(W, *Pawn, 0u, FVector2f::ZeroVector, 0.3f, Prev);+ }+ AddInfo(FString::Printf(TEXT("lean poses: %d full, %d limited by the wall check, %d inside geometry"), Full, Limited, Inside));+ TestEqual(TEXT("camera never inside geometry"), Inside, 0);+ TestTrue(TEXT("the wall check limited some leans"), Limited > 20);+ TestTrue(TEXT("open leans reach full"), Full > 20);+ return true;+}++#endif // WITH_DEV_AUTOMATION_TESTSdiff --git a/unreal/Verse/Source/VerseMovement/Private/Tests/Movement/VerseMovementNetEyeTest.cpp b/unreal/Verse/Source/VerseMovement/Private/Tests/Movement/VerseMovementNetEyeTest.cppnew file mode 100644index 0000000000..fc8134c254--- /dev/null+++ b/unreal/Verse/Source/VerseMovement/Private/Tests/Movement/VerseMovementNetEyeTest.cpp@@ -0,0 +1,395 @@+#include "Misc/AutomationTest.h"++#if WITH_DEV_AUTOMATION_TESTS++#include "Components/BoxComponent.h"+#include "Components/InputComponent.h"+#include "Engine/World.h"+#include "Fixture/VerseMovementCourse.h"+#include "GameFramework/Controller.h"+#include "InputCoreTypes.h"+#include "Serialization/MemoryReader.h"+#include "Serialization/MemoryWriter.h"+#include "Tests/Movement/VerseMovementTestWorld.h"+#include "VerseCharacter.h"+#include "VerseCharacterMovement.h"+#include "VerseMovementNetworking.h"++namespace+{+ constexpr EAutomationTestFlags NetEyeTestFlags = EAutomationTestFlags_ApplicationContextMask | EAutomationTestFlags::EngineFilter;+ using namespace VerseMovementCourse;++ void HoldFor(FVerseMovementTestWorld& W, AVerseCharacter& Pawn, uint32 Buttons, const FVector2f& Move, float Seconds, uint32& Prev,+ TFunctionRef<void()> PerTick = [] {}, const FVector2f& Look = FVector2f::ZeroVector)+ {+ const int32 Ticks = FMath::Max(1, FMath::RoundToInt(Seconds / FVerseMovementTestWorld::Dt));+ for (int32 Tick = 0; Tick < Ticks; ++Tick)+ {+ W.Drive(Pawn, VerseTestFrame(Move, Buttons, Prev, Look));+ Prev = Buttons;+ W.Tick();+ PerTick();+ }+ }++ /** Fires the pawn's own key binding for Key and Event, as the player input would. */+ int32 FireKey(UInputComponent& Input, const FKey& Key, EInputEvent Event)+ {+ int32 Fired = 0;+ for (FInputKeyBinding& Binding : Input.KeyBindings)+ {+ if (Binding.Chord.Key == Key && Binding.KeyEvent == Event)+ {+ Binding.KeyDelegate.Execute(Key);+ ++Fired;+ }+ }+ return Fired;+ }++ int32 FireAxis(UInputComponent& Input, const FKey& Key, float Value)+ {+ int32 Fired = 0;+ for (FInputAxisKeyBinding& Binding : Input.AxisKeyBindings)+ {+ if (Binding.AxisKey == Key)+ {+ Binding.AxisDelegate.Execute(Value);+ ++Fired;+ }+ }+ return Fired;+ }+}++// bot.md 3.1: the eye is the skeleton's Camera bone, the bone the person's camera uses. Camera,+// bone, the bot's view point and the movement's eye agree in every stance and lean.+IMPLEMENT_SIMPLE_AUTOMATION_TEST(FVerseMovementEyeTest, "Verse.Movement.Eye", NetEyeTestFlags)+bool FVerseMovementEyeTest::RunTest(const FString& Parameters)+{+ FVerseMovementTestWorld W;+ if (!TestTrue(TEXT("test world"), W.IsValid())) return false;+ AVerseCharacter* Pawn = W.SpawnPawn(FVector(0.f, OpenFloorY, 0.f), 20.f);+ if (!TestNotNull(TEXT("pawn"), Pawn)) return false;+ UVerseCharacterMovement* M = Pawn->GetVerseMovement();+ const FVerseMovementTuningValues& T = M->Tuning();+ if (!TestTrue(TEXT("SK_Test_Human has the Camera bone"), Pawn->GetMesh()->GetBoneIndex(AVerseCharacter::CameraBoneName) != INDEX_NONE))+ {+ return false;+ }+ struct FCase { const TCHAR* Name; uint32 Buttons; float Seconds; };+ const FCase Cases[] = {+ {TEXT("stand"), 0u, 1.f},+ {TEXT("crouch"), uint32(EVerseInputButton::Crouch), 1.f},+ {TEXT("lean left"), uint32(EVerseInputButton::LeanLeft), 1.f},+ {TEXT("lean right"), uint32(EVerseInputButton::LeanRight), 1.f},+ {TEXT("crouch lean right"), uint32(EVerseInputButton::Crouch) | uint32(EVerseInputButton::LeanRight), 1.f},+ {TEXT("prone"), uint32(EVerseInputButton::Prone), 1.6f},+ };+ uint32 Prev = 0;+ for (const FCase& Case : Cases)+ {+ W.Place(*Pawn, FVector(0.f, OpenFloorY, 0.f), 20.f);+ HoldFor(W, *Pawn, 0u, FVector2f::ZeroVector, 1.f, Prev);+ HoldFor(W, *Pawn, Case.Buttons, FVector2f::ZeroVector, Case.Seconds, Prev);+ const FVector Camera = Pawn->GetEyeLocation();+ const FVector Bone = Pawn->GetCameraBoneLocation();+ FVector View;+ FRotator ViewRotation;+ Pawn->GetActorEyesViewPoint(View, ViewRotation);+ const FVector Model = M->GetLeanedEyeLocation(M->GetLean());+ AddInfo(FString::Printf(TEXT("%s: camera %s, bone off %.3f cm, model off %.3f cm, eye %.1f cm over the feet"), Case.Name,+ *Camera.ToCompactString(), FVector::Dist(Camera, Bone), FVector::Dist(Camera, Model), Camera.Z - FVerseMovementTestWorld::Feet(*Pawn).Z));+ TestTrue(FString::Printf(TEXT("%s: camera on the Camera bone (0.5 cm)"), Case.Name), FVector::Dist(Camera, Bone) <= 0.5);+ TestTrue(FString::Printf(TEXT("%s: bot view point is the camera"), Case.Name), FVector::Dist(Camera, View) <= 0.01);+ TestTrue(FString::Printf(TEXT("%s: movement eye model matches the camera (1 cm)"), Case.Name), FVector::Dist(Camera, Model) <= 1.0);+ }+ // Prone: the eye moved forward with the lying head, at the prone eye height.+ const FVector Camera = Pawn->GetEyeLocation();+ TestTrue(TEXT("prone eye sits ahead of the capsule, over the head"), ((Camera - Pawn->GetActorLocation()) | Pawn->GetActorForwardVector()) > 15.f);+ TestEqual(TEXT("prone eye height"), float(Camera.Z - FVerseMovementTestWorld::Feet(*Pawn).Z), T.ProneEyeHeight * 100.f, 2.f);+ return true;+}++// WP01.2: the person's default keys (holds, toggles, axes) produce the frames a bot would send,+// and a key-driven pawn walks the same capsule path as a bot fed those frames.+IMPLEMENT_SIMPLE_AUTOMATION_TEST(FVerseMovementPersonKeysTest, "Verse.Movement.PersonKeys", NetEyeTestFlags)+bool FVerseMovementPersonKeysTest::RunTest(const FString& Parameters)+{+ using EB = EVerseInputButton;+ {+ FVerseMovementTestWorld W;+ if (!TestTrue(TEXT("test world"), W.IsValid())) return false;+ AVerseCharacter* Pawn = W.SpawnPawn(FVector(0.f, OpenFloorY, 0.f), 0.f, FVerseMovementTestWorld::EDriver::Person);+ if (!TestNotNull(TEXT("pawn"), Pawn)) return false;+ UInputComponent* Input = NewObject<UInputComponent>(Pawn);+ Pawn->SetupPlayerInputComponent(Input);+ FVerseInputFrameBuilder& B = Pawn->GetPersonInput();+ B.Reset();+ TestTrue(TEXT("W is bound"), FireKey(*Input, VerseKey(TEXT("W")), IE_Pressed) > 0);+ TestTrue(TEXT("W: forward"), B.Consume(0).Move.Equals(FVector2f(1.f, 0.f), 1e-4f));+ FireKey(*Input, VerseKey(TEXT("D")), IE_Pressed);+ TestTrue(TEXT("W+D: forward right"), B.Consume(0).Move.Equals(FVector2f(1.f, 1.f), 1e-4f));+ FireKey(*Input, VerseKey(TEXT("W")), IE_Released);+ FireKey(*Input, VerseKey(TEXT("D")), IE_Released);+ FireKey(*Input, VerseKey(TEXT("A")), IE_Pressed);+ TestTrue(TEXT("A: left"), B.Consume(0).Move.Equals(FVector2f(0.f, -1.f), 1e-4f));+ FireKey(*Input, VerseKey(TEXT("A")), IE_Released);+ TestTrue(TEXT("released: still"), B.Consume(0).Move.Equals(FVector2f::ZeroVector, 1e-4f));++ FireKey(*Input, VerseKey(TEXT("C")), IE_Pressed);+ FVerseInputFrame Frame = B.Consume(0);+ TestTrue(TEXT("C toggles crouch on, pressed this frame"), Frame.IsHeld(EB::Crouch) && Frame.WasPressed(EB::Crouch));+ TestTrue(TEXT("crouch stays held without a key event"), B.Consume(0).IsHeld(EB::Crouch));+ FireKey(*Input, VerseKey(TEXT("Z")), IE_Pressed);+ Frame = B.Consume(0);+ TestTrue(TEXT("Z toggles prone on and releases crouch"), Frame.IsHeld(EB::Prone) && !Frame.IsHeld(EB::Crouch));+ FireKey(*Input, VerseKey(TEXT("Z")), IE_Pressed);+ TestFalse(TEXT("Z again toggles prone off"), B.Consume(0).IsHeld(EB::Prone));+ FireKey(*Input, VerseKey(TEXT("LeftShift")), IE_Pressed);+ FireKey(*Input, VerseKey(TEXT("E")), IE_Pressed);+ Frame = B.Consume(0);+ TestTrue(TEXT("shift holds sprint, E holds lean right"), Frame.IsHeld(EB::Sprint) && Frame.IsHeld(EB::LeanRight));+ FireKey(*Input, VerseKey(TEXT("LeftShift")), IE_Released);+ FireKey(*Input, VerseKey(TEXT("E")), IE_Released);+ Frame = B.Consume(0);+ TestTrue(TEXT("releasing ends the holds"), !Frame.IsHeld(EB::Sprint) && !Frame.IsHeld(EB::LeanRight));+ FireKey(*Input, VerseKey(TEXT("SpaceBar")), IE_Pressed);+ Frame = B.Consume(0);+ TestTrue(TEXT("space presses and holds jump"), Frame.WasPressed(EB::Jump) && Frame.IsHeld(EB::Jump));+ FireKey(*Input, VerseKey(TEXT("SpaceBar")), IE_Released);+ B.Consume(0);+ TestTrue(TEXT("mouse X is bound"), FireAxis(*Input, VerseKey(TEXT("MouseX")), 2.f) > 0);+ FireAxis(*Input, VerseKey(TEXT("MouseY")), -1.f);+ Frame = B.Consume(0);+ TestEqual(TEXT("mouse look in degrees (yaw)"), Frame.LookDeltaDeg.Y, 2.f * VersePersonInput::MouseDegPerValue);+ TestEqual(TEXT("mouse look in degrees (pitch)"), Frame.LookDeltaDeg.X, -1.f * VersePersonInput::MouseDegPerValue);+ FireAxis(*Input, VerseKey(TEXT("Gamepad_LeftY")), 0.6f);+ FireAxis(*Input, VerseKey(TEXT("Gamepad_LeftX")), -0.3f);+ TestTrue(TEXT("gamepad stick moves"), B.Consume(0).Move.Equals(FVector2f(0.6f, -0.3f), 1e-4f));+ }++ // The same 20 s through keys (person) and through frames (bot).+ struct FEvent { int32 Tick; FKey Key; EInputEvent Event; };+ const TArray<FEvent> Events = {+ {0, VerseKey(TEXT("W")), IE_Pressed}, {60, VerseKey(TEXT("LeftShift")), IE_Pressed}, {300, VerseKey(TEXT("LeftShift")), IE_Released},+ {360, VerseKey(TEXT("C")), IE_Pressed}, {600, VerseKey(TEXT("C")), IE_Pressed}, {700, VerseKey(TEXT("Z")), IE_Pressed}, {900, VerseKey(TEXT("Z")), IE_Pressed},+ {1000, VerseKey(TEXT("E")), IE_Pressed}, {1100, VerseKey(TEXT("E")), IE_Released}, {1150, VerseKey(TEXT("D")), IE_Pressed}};+ auto ButtonsAt = [](int32 Tick)+ {+ uint32 Buttons = 0;+ if (Tick >= 60 && Tick < 300) Buttons |= uint32(EB::Sprint);+ if (Tick >= 360 && Tick < 600) Buttons |= uint32(EB::Crouch);+ if (Tick >= 700 && Tick < 900) Buttons |= uint32(EB::Prone);+ if (Tick >= 1000 && Tick < 1100) Buttons |= uint32(EB::LeanRight);+ return Buttons;+ };+ constexpr int32 Ticks = 1200;+ constexpr float YawPerTick = 0.4f;+ TArray<FVector> PersonPath;+ TArray<FVector> BotPath;+ for (const bool bPerson : {true, false})+ {+ FVerseMovementTestWorld W;+ if (!TestTrue(TEXT("parity world"), W.IsValid())) return false;+ AVerseCharacter* Pawn = W.SpawnPawn(FVector(-1500.f, 2400.f, 0.f), 0.f,+ bPerson ? FVerseMovementTestWorld::EDriver::Person : FVerseMovementTestWorld::EDriver::Bot);+ if (!TestNotNull(TEXT("parity pawn"), Pawn)) return false;+ UInputComponent* Input = NewObject<UInputComponent>(Pawn);+ Pawn->SetupPlayerInputComponent(Input);+ Pawn->GetPersonInput().Reset();+ TArray<FVector>& Path = bPerson ? PersonPath : BotPath;+ uint32 Prev = 0;+ for (int32 Tick = 0; Tick < Ticks; ++Tick)+ {+ if (bPerson)+ {+ for (const FEvent& Event : Events)+ {+ if (Event.Tick == Tick)+ {+ FireKey(*Input, Event.Key, Event.Event);+ }+ }+ FireAxis(*Input, VerseKey(TEXT("MouseX")), YawPerTick / VersePersonInput::MouseDegPerValue);+ }+ else+ {+ const uint32 Buttons = ButtonsAt(Tick);+ const FVector2f Move(1.f, Tick >= 1150 ? 1.f : 0.f);+ W.Drive(*Pawn, VerseTestFrame(Move, Buttons, Prev, FVector2f(0.f, YawPerTick)));+ Prev = Buttons;+ }+ W.Tick();+ Path.Add(Pawn->GetActorLocation());+ }+ }+ double MaxError = 0.0;+ for (int32 Index = 0; Index < Ticks; ++Index)+ {+ MaxError = FMath::Max(MaxError, FVector::Dist(PersonPath[Index], BotPath[Index]));+ }+ const double Travel = FVector::Dist2D(PersonPath[0], PersonPath.Last());+ AddInfo(FString::Printf(TEXT("keys vs frames: max capsule distance %.4f cm, %.1f m from the start"), MaxError, Travel / 100.0));+ TestTrue(TEXT("the key-driven pawn moved"), Travel > 1000.0);+ TestTrue(TEXT("key and frame paths within 0.1 cm"), MaxError <= 0.1);+ return true;+}++// WP01.4: the prone body never pushes into walls, whether the pawn turns or crawls backwards.+IMPLEMENT_SIMPLE_AUTOMATION_TEST(FVerseMovementProneWallsTest, "Verse.Movement.Prone.Walls", NetEyeTestFlags)+bool FVerseMovementProneWallsTest::RunTest(const FString& Parameters)+{+ FVerseMovementTestWorld W;+ if (!TestTrue(TEXT("test world"), W.IsValid())) return false;+ const FVector Open(-2400.f, OpenFloorY, 0.f);+ // A wall along the pawn's left at 45 cm, and one behind the prone feet end.+ W.AddBox(Open + FVector(0.f, -65.f, 100.f), FVector(400.f, 20.f, 100.f));+ W.AddBox(Open + FVector(-200.f, 0.f, 100.f), FVector(20.f, 40.f, 100.f));+ AVerseCharacter* Pawn = W.SpawnPawn(Open, 0.f);+ if (!TestNotNull(TEXT("pawn"), Pawn)) return false;+ UVerseCharacterMovement* M = Pawn->GetVerseMovement();+ uint32 Prev = 0;+ HoldFor(W, *Pawn, 0u, FVector2f::ZeroVector, 0.5f, Prev);+ HoldFor(W, *Pawn, uint32(EVerseInputButton::Prone), FVector2f::ZeroVector, 1.2f, Prev);+ if (!TestTrue(TEXT("prone beside the wall"), M->IsProne()))+ {+ return false;+ }+ int32 Inside = 0;+ auto Check = [&]+ {+ if (M->ProneBodyBlocked(FVerseMovementTestWorld::Feet(*Pawn), Pawn->GetActorRotation().Yaw))+ {+ ++Inside;+ }+ };+ const float YawStart = Pawn->GetActorRotation().Yaw;+ // Turn right at the full prone rate for 2 s: the trailing legs swing into the left wall.+ HoldFor(W, *Pawn, uint32(EVerseInputButton::Prone), FVector2f::ZeroVector, 2.f, Prev, Check, FVector2f(0.f, 90.f * FVerseMovementTestWorld::Dt));+ const float Turned = FMath::Abs(FRotator::NormalizeAxis(Pawn->GetActorRotation().Yaw - YawStart));+ AddInfo(FString::Printf(TEXT("turned %.1f deg toward the wall before the body stopped it"), Turned));+ TestTrue(TEXT("the wall stopped the turn"), Turned < 60.f);+ TestTrue(TEXT("the pawn could still turn a little"), Turned > 1.f);+ // Crawl backwards into the wall behind for 3 s.+ W.Place(*Pawn, Open, 0.f);+ Prev = 0;+ HoldFor(W, *Pawn, 0u, FVector2f::ZeroVector, 1.2f, Prev);+ HoldFor(W, *Pawn, uint32(EVerseInputButton::Prone), FVector2f::ZeroVector, 1.2f, Prev);+ HoldFor(W, *Pawn, uint32(EVerseInputButton::Prone), FVector2f(-1.f, 0.f), 3.f, Prev, Check);+ const float FeetEnd = Pawn->GetActorLocation().X - (M->Tuning().ProneBodyLength * 100.f - M->Tuning().ProneRadius * 200.f);+ AddInfo(FString::Printf(TEXT("crawled back to x %.1f, feet end at %.1f (wall face at %.1f)"), Pawn->GetActorLocation().X, FeetEnd, Open.X - 180.f));+ TestTrue(TEXT("the feet end stays in front of the wall behind"), FeetEnd >= Open.X - 181.f);+ TestTrue(TEXT("the pawn crawled backwards"), Pawn->GetActorLocation().X < Open.X - 5.f);+ TestEqual(TEXT("the prone body never ends a move inside a wall"), Inside, 0);+ return true;+}++// WP01.4: the prone turn cap is enforced by the movement itself (server authoritative), not only by the input.+IMPLEMENT_SIMPLE_AUTOMATION_TEST(FVerseMovementProneTurnCapTest, "Verse.Movement.Prone.ServerTurnCap", NetEyeTestFlags)+bool FVerseMovementProneTurnCapTest::RunTest(const FString& Parameters)+{+ FVerseMovementTestWorld W;+ if (!TestTrue(TEXT("test world"), W.IsValid())) return false;+ AVerseCharacter* Pawn = W.SpawnPawn(FVector(0.f, OpenFloorY, 0.f), 0.f);+ if (!TestNotNull(TEXT("pawn"), Pawn)) return false;+ UVerseCharacterMovement* M = Pawn->GetVerseMovement();+ uint32 Prev = 0;+ HoldFor(W, *Pawn, uint32(EVerseInputButton::Prone), FVector2f::ZeroVector, 1.5f, Prev);+ float MaxStep = 0.f;+ for (int32 Tick = 0; Tick < 30; ++Tick)+ {+ // A controller that sets its rotation directly (as a modified client's ServerMove would).+ AController* Controller = Pawn->GetController();+ FRotator Rotation = Controller->GetControlRotation();+ Rotation.Yaw = FRotator::NormalizeAxis(Rotation.Yaw + 30.f);+ Controller->SetControlRotation(Rotation);+ const float Before = Pawn->GetActorRotation().Yaw;+ W.Drive(*Pawn, VerseTestFrame(FVector2f::ZeroVector, uint32(EVerseInputButton::Prone), Prev));+ W.Tick();+ MaxStep = FMath::Max(MaxStep, FMath::Abs(FRotator::NormalizeAxis(Pawn->GetActorRotation().Yaw - Before)));+ }+ const float Cap = M->Tuning().ProneTurnCapDegPerSec * FVerseMovementTestWorld::Dt;+ AddInfo(FString::Printf(TEXT("largest yaw step %.3f deg per tick (cap %.3f)"), MaxStep, Cap));+ TestTrue(TEXT("yaw per move stays within the prone cap"), MaxStep <= Cap * 1.05f + 0.06f);+ TestTrue(TEXT("the pawn still turned at the cap"), MaxStep >= Cap * 0.9f);+ return true;+}++// WP01.10: corrections carry the server's state; a replayed move restores only its inputs and+// facing; corrections are booked by the kind of the corrected move.+IMPLEMENT_SIMPLE_AUTOMATION_TEST(FVerseMovementNetStateTest, "Verse.Movement.NetState", NetEyeTestFlags)+bool FVerseMovementNetStateTest::RunTest(const FString& Parameters)+{+ for (const bool bMantling : {false, true})+ {+ FVerseMoveState A;+ A.Stance = EVerseStance::Crouch;+ A.BodyShape = EVerseBodyShape::Crouch;+ A.LeanQuantized = -77;+ A.LeanValue = -0.6f;+ A.ProneTransitionRemaining = 0.25f;+ A.bProneExiting = true;+ A.SlideElapsed = 0.4f;+ A.SlideCooldownRemaining = 0.7f;+ A.bMantleLatched = true;+ A.MantleElapsed = bMantling ? 0.2f : -1.f;+ A.MantlePlanDuration = 0.85f;+ A.MantleRiseDuration = 0.4f;+ A.MantleRise = FVector(1.f, 2.f, 3.f);+ A.MantleTarget = FVector(4.f, 5.f, 6.f);+ A.LastMoveYaw = 123.5f;+ A.bHasLastMoveYaw = true;+ A.bYawClamped = true;+ TArray<uint8> Bytes;+ FMemoryWriter Writer(Bytes);+ A.Serialize(Writer);+ FVerseMoveState B;+ FMemoryReader Reader(Bytes);+ B.Serialize(Reader);+ const FString Tag = bMantling ? TEXT(" (mantling)") : TEXT("");+ TestEqual(TEXT("stance round trip") + Tag, int32(B.Stance), int32(A.Stance));+ TestEqual(TEXT("shape round trip") + Tag, int32(B.BodyShape), int32(A.BodyShape));+ TestEqual(TEXT("lean round trip") + Tag, int32(B.LeanQuantized), int32(A.LeanQuantized));+ TestEqual(TEXT("prone timer round trip") + Tag, B.ProneTransitionRemaining, A.ProneTransitionRemaining);+ TestTrue(TEXT("flags round trip") + Tag, B.bProneExiting && B.bMantleLatched && B.bHasLastMoveYaw && B.bYawClamped && !B.bMantleVault);+ TestEqual(TEXT("slide timers round trip") + Tag, B.SlideCooldownRemaining + B.SlideElapsed, A.SlideCooldownRemaining + A.SlideElapsed);+ TestEqual(TEXT("yaw round trip") + Tag, B.LastMoveYaw, A.LastMoveYaw);+ TestEqual(TEXT("mantle time round trip") + Tag, B.MantleElapsed, A.MantleElapsed);+ if (bMantling)+ {+ TestTrue(TEXT("mantle plan round trip"), B.MantleTarget.Equals(A.MantleTarget) && B.MantleRise.Equals(A.MantleRise) && B.MantlePlanDuration == A.MantlePlanDuration);+ }+ }++ FVerseSavedMove Move;+ Move.StartKind = EVerseMoveKind::Walk;+ Move.EndKind = EVerseMoveKind::Mantle;+ TestEqual(TEXT("a move that starts a mantle books as mantle"), int32(Move.GetCorrectionKind()), int32(EVerseMoveKind::Mantle));+ Move.StartKind = EVerseMoveKind::Prone;+ Move.EndKind = EVerseMoveKind::Walk;+ TestEqual(TEXT("a move leaving prone books as prone"), int32(Move.GetCorrectionKind()), int32(EVerseMoveKind::Prone));+ Move.StartKind = EVerseMoveKind::Walk;+ Move.EndKind = EVerseMoveKind::Airborne;+ TestEqual(TEXT("otherwise the end kind"), int32(Move.GetCorrectionKind()), int32(EVerseMoveKind::Airborne));++ FVerseMovementTestWorld W;+ if (!TestTrue(TEXT("test world"), W.IsValid())) return false;+ AVerseCharacter* Pawn = W.SpawnPawn(FVector(0.f, OpenFloorY, 0.f), 0.f);+ if (!TestNotNull(TEXT("pawn"), Pawn)) return false;+ UVerseCharacterMovement* M = Pawn->GetVerseMovement();+ FVerseSavedMove Replayed;+ Replayed.StartState.Stance = EVerseStance::Prone;+ Replayed.StartState.BodyShape = EVerseBodyShape::Prone;+ Replayed.StartState.MantleElapsed = 0.3f;+ Replayed.StartRotation = FRotator(0.f, 45.f, 0.f);+ Replayed.SavedLeanTarget = 127;+ Replayed.PrepMoveFor(Pawn);+ TestEqual(TEXT("replay keeps the simulated stance (no restore of the old prediction)"), int32(M->GetStance()), int32(EVerseStance::Stand));+ TestFalse(TEXT("replay does not restart an old mantle"), M->IsMantling());+ TestEqual(TEXT("replay restores the move's facing"), float(Pawn->GetActorRotation().Yaw), 45.f, 0.01f);+ return true;+}++#endif // WITH_DEV_AUTOMATION_TESTSdiff --git a/unreal/Verse/Source/VerseMovement/Private/Tests/Movement/VerseMovementNoiseHitTest.cpp b/unreal/Verse/Source/VerseMovement/Private/Tests/Movement/VerseMovementNoiseHitTest.cppnew file mode 100644index 0000000000..e199a0e4e2--- /dev/null+++ b/unreal/Verse/Source/VerseMovement/Private/Tests/Movement/VerseMovementNoiseHitTest.cpp@@ -0,0 +1,447 @@+#include "Misc/AutomationTest.h"++#if WITH_DEV_AUTOMATION_TESTS++#include "Components/BoxComponent.h"+#include "Components/SkeletalMeshComponent.h"+#include "Engine/SkeletalMesh.h"+#include "Engine/World.h"+#include "Events/VerseEventHub.h"+#include "Fixture/VerseMovementCourse.h"+#include "Noise/VerseAudibilityTable.h"+#include "PhysicsEngine/BodyInstance.h"+#include "PhysicsEngine/BodySetup.h"+#include "PhysicsEngine/PhysicsAsset.h"+#include "PhysicsEngine/SkeletalBodySetup.h"+#include "Tests/Movement/VerseMovementTestWorld.h"+#include "VerseCharacter.h"+#include "VerseCharacterMovement.h"+#include "VerseCollision.h"+#include "VerseGameplayTags.h"+#include "VerseHitZones.h"+#include "UObject/StrongObjectPtr.h"++namespace+{+ constexpr EAutomationTestFlags NoiseTestFlags = EAutomationTestFlags_ApplicationContextMask | EAutomationTestFlags::EngineFilter;+ using namespace VerseMovementCourse;++ /** Collects the hub's noise events of one pawn session. */+ struct FNoiseLog+ {+ TArray<FVerseNoiseEvent> Events;+ FDelegateHandle Handle;+ UVerseEventHub* Hub = nullptr;++ explicit FNoiseLog(UWorld* World) : Hub(UVerseEventHub::Get(World))+ {+ if (Hub)+ {+ Handle = Hub->OnNoise.AddLambda([this](const FVerseNoiseEvent& Event) { Events.Add(Event); });+ }+ }+ ~FNoiseLog()+ {+ if (Hub)+ {+ Hub->OnNoise.Remove(Handle);+ }+ }+ int32 Count(const FGameplayTag& Tag) const+ {+ return Events.FilterByPredicate([&Tag](const FVerseNoiseEvent& Event) { return Event.Noise == Tag; }).Num();+ }+ };++ /**+ * G0.9's PHYS_Test_Human carries bodies scaled 100x by the bone scale of its import, so one+ * body covers the whole pawn. The test traces against a copy whose shapes are divided by each+ * body's bone scale: the same bodies, bones and zones at their intended size.+ */+ UPhysicsAsset* MakeSaneCopy(USkeletalMeshComponent& Mesh, int32& OutFixed)+ {+ OutFixed = 0;+ UPhysicsAsset* Source = Mesh.GetPhysicsAsset();+ if (!Source)+ {+ return nullptr;+ }+ // Body transforms carry no scale (it is baked into the shapes): compare each body's bounds+ // with the size its shapes should have at the component's scale.+ TMap<FName, float> Scales;+ const float ComponentScale = FMath::Max(float(Mesh.GetComponentScale().GetAbsMax()), KINDA_SMALL_NUMBER);+ for (const USkeletalBodySetup* Setup : Source->SkeletalBodySetups)+ {+ const FBodyInstance* Instance = Setup ? Mesh.GetBodyInstance(Setup->BoneName) : nullptr;+ if (!Instance)+ {+ continue;+ }+ float Expected = 0.f;+ for (const FKSphylElem& Elem : Setup->AggGeom.SphylElems)+ {+ Expected = FMath::Max(Expected, Elem.Radius); // the bounds' smallest extent is the radius+ }+ for (const FKSphereElem& Elem : Setup->AggGeom.SphereElems)+ {+ Expected = FMath::Max(Expected, Elem.Radius);+ }+ for (const FKBoxElem& Elem : Setup->AggGeom.BoxElems)+ {+ Expected = FMath::Max(Expected, FMath::Min3(Elem.X, Elem.Y, Elem.Z) * 0.5f);+ }+ if (Expected > 0.f)+ {+ Scales.Add(Setup->BoneName, float(Instance->GetBodyBounds().GetExtent().GetMin()) / (Expected * ComponentScale));+ }+ }+ UPhysicsAsset* Copy = DuplicateObject<UPhysicsAsset>(Source, GetTransientPackage());+ for (USkeletalBodySetup* Setup : Copy->SkeletalBodySetups)+ {+ const float Factor = Setup ? Scales.FindRef(Setup->BoneName) : 0.f;+ if (Factor < 1.5f)+ {+ continue;+ }+ for (FKSphylElem& Elem : Setup->AggGeom.SphylElems)+ {+ Elem.Radius /= Factor;+ Elem.Length /= Factor;+ Elem.Center /= Factor;+ }+ for (FKSphereElem& Elem : Setup->AggGeom.SphereElems)+ {+ Elem.Radius /= Factor;+ Elem.Center /= Factor;+ }+ for (FKBoxElem& Elem : Setup->AggGeom.BoxElems)+ {+ Elem.X /= Factor;+ Elem.Y /= Factor;+ Elem.Z /= Factor;+ Elem.Center /= Factor;+ }+ Setup->InvalidatePhysicsData();+ Setup->CreatePhysicsMeshes();+ ++OutFixed;+ }+ Copy->UpdateBodySetupIndexMap();+ Copy->UpdateBoundsBodiesArray();+ Mesh.SetPhysicsAsset(Copy, true);+ return Copy;+ }++ void Run(FVerseMovementTestWorld& W, AVerseCharacter& Pawn, uint32 Buttons, const FVector2f& Move, float Seconds, float TurnDegPerSec = 0.f)+ {+ uint32 Prev = 0;+ const int32 Ticks = FMath::RoundToInt(Seconds / FVerseMovementTestWorld::Dt);+ for (int32 Tick = 0; Tick < Ticks; ++Tick)+ {+ W.Drive(Pawn, VerseTestFrame(Move, Buttons, Prev, FVector2f(0.f, TurnDegPerSec * FVerseMovementTestWorld::Dt)));+ Prev = Buttons;+ W.Tick();+ }+ }+}++// A1.8: footstep tags per stance match DA_Audibility's ranges (walk 4 m, run 10 m, sprint 20 m);+// crouch walk and prone crawl emit nothing over 60 s; slide, land and mantle raise their tags.+IMPLEMENT_SIMPLE_AUTOMATION_TEST(FVerseMovementNoiseTest, "Verse.Movement.Noise", NoiseTestFlags)+bool FVerseMovementNoiseTest::RunTest(const FString& Parameters)+{+ using namespace VerseTags;+ FVerseMovementTestWorld W;+ if (!TestTrue(TEXT("test world"), W.IsValid())) return false;+ if (!TestNotNull(TEXT("event hub"), UVerseEventHub::Get(W.GetWorld()))) return false;+ const TStrongObjectPtr<UVerseAudibilityTable> Audibility(NewObject<UVerseAudibilityTable>());+ const FVector Open(-2400.f, OpenFloorY, 0.f);+ AVerseCharacter* Pawn = W.SpawnPawn(Open, 0.f);+ if (!TestNotNull(TEXT("pawn"), Pawn)) return false;+ const FVerseMovementTuningValues& T = Pawn->GetVerseMovement()->Tuning();++ struct FCase { const TCHAR* Name; uint32 Buttons; FVector2f Move; FGameplayTag Tag; float RangeM; float Stride; };+ const FCase Cases[] = {+ {TEXT("walk"), 0u, FVector2f(0.5f, 0.f), Noise_Footstep_Walk, 4.f, T.WalkStride},+ {TEXT("run"), 0u, FVector2f(1.f, 0.f), Noise_Footstep_Run, 10.f, T.RunStride},+ {TEXT("sprint"), uint32(EVerseInputButton::Sprint), FVector2f(1.f, 0.f), Noise_Footstep_Sprint, 20.f, T.SprintStride},+ };+ for (const FCase& Case : Cases)+ {+ W.Place(*Pawn, Open, 0.f);+ Run(W, *Pawn, 0u, FVector2f::ZeroVector, 0.5f);+ FNoiseLog Log(W.GetWorld());+ const FVector Start = Pawn->GetActorLocation();+ Run(W, *Pawn, Case.Buttons, Case.Move, 5.f);+ const float Travel = FVector::Dist2D(Start, Pawn->GetActorLocation());+ const int32 Expected = FMath::FloorToInt(Travel / (Case.Stride * 100.f));+ const int32 Own = Log.Count(Case.Tag);+ AddInfo(FString::Printf(TEXT("%s: %d events (%d of the stance tag) over %.1f m"), Case.Name, Log.Events.Num(), Own, Travel / 100.f));+ TestTrue(FString::Printf(TEXT("%s raises its footstep tag"), Case.Name), Own >= Expected - 2 && Own <= Expected + 2);+ TestTrue(FString::Printf(TEXT("%s raises only its tag (after the first stride)"), Case.Name), Log.Events.Num() - Own <= 2);+ TestEqual(FString::Printf(TEXT("%s audible range matches DA_Audibility"), Case.Name), Audibility->GetAudibleRangeM(Case.Tag, 1.f), Case.RangeM);+ if (Log.Events.Num())+ {+ TestEqual(TEXT("noise at the feet"), float(Log.Events.Last().Location.Z), float(FVerseMovementTestWorld::Feet(*Pawn).Z), 5.f);+ }+ }++ for (const uint32 Quiet : {uint32(EVerseInputButton::Crouch), uint32(EVerseInputButton::Prone)})+ {+ W.Place(*Pawn, Open + FVector(2400.f, 0.f, 0.f), 0.f);+ Run(W, *Pawn, Quiet, FVector2f::ZeroVector, 1.f);+ FNoiseLog Log(W.GetWorld());+ const FVector Start = Pawn->GetActorLocation();+ float Travel = 0.f;+ FVector Last = Start;+ const int32 Ticks = FMath::RoundToInt(60.f / FVerseMovementTestWorld::Dt);+ uint32 Prev = Quiet;+ for (int32 Tick = 0; Tick < Ticks; ++Tick)+ {+ W.Drive(*Pawn, VerseTestFrame(FVector2f(1.f, 0.f), Quiet, Prev, FVector2f(0.f, 30.f * FVerseMovementTestWorld::Dt)));+ W.Tick();+ Travel += FVector::Dist2D(Last, Pawn->GetActorLocation());+ Last = Pawn->GetActorLocation();+ }+ const TCHAR* Name = Quiet == uint32(EVerseInputButton::Crouch) ? TEXT("crouch walk") : TEXT("prone crawl");+ AddInfo(FString::Printf(TEXT("%s: %d events over %.1f m in 60 s"), Name, Log.Events.Num(), Travel / 100.f));+ TestTrue(FString::Printf(TEXT("%s really moved"), Name), Travel > 2000.f);+ TestEqual(FString::Printf(TEXT("%s emits no noise in 60 s"), Name), Log.Events.Num(), 0);+ Run(W, *Pawn, 0u, FVector2f::ZeroVector, 1.2f);+ }++ {+ // Land from the 4 m drop.+ W.Place(*Pawn, FVector(1300.f, DropY, DropHeight), 0.f);+ Run(W, *Pawn, 0u, FVector2f::ZeroVector, 0.3f);+ FNoiseLog Log(W.GetWorld());+ Run(W, *Pawn, 0u, FVector2f(1.f, 0.f), 2.f);+ TestEqual(TEXT("one land noise from the 4 m drop"), Log.Count(Noise_Move_Land), 1);+ TestEqual(TEXT("land range 12 m"), Audibility->GetAudibleRangeM(Noise_Move_Land, 1.f), 12.f);+ }+ {+ // Slide.+ W.Place(*Pawn, Open, 0.f);+ Run(W, *Pawn, 0u, FVector2f::ZeroVector, 0.5f);+ Run(W, *Pawn, uint32(EVerseInputButton::Sprint), FVector2f(1.f, 0.f), 1.5f);+ FNoiseLog Log(W.GetWorld());+ uint32 Prev = uint32(EVerseInputButton::Sprint);+ const uint32 Buttons = uint32(EVerseInputButton::Sprint) | uint32(EVerseInputButton::Crouch);+ for (int32 Tick = 0; Tick < 30; ++Tick)+ {+ W.Drive(*Pawn, VerseTestFrame(FVector2f(1.f, 0.f), Buttons, Prev));+ Prev = Buttons;+ W.Tick();+ }+ TestEqual(TEXT("one slide noise"), Log.Count(Noise_Move_Slide), 1);+ Run(W, *Pawn, 0u, FVector2f::ZeroVector, 1.5f);+ }+ {+ // Mantle the 1.0 m ledge.+ W.Place(*Pawn, FVector(LedgeFaceX - 80.f, LedgeLaneY(1), 0.f), 0.f);+ Run(W, *Pawn, 0u, FVector2f::ZeroVector, 0.3f);+ FNoiseLog Log(W.GetWorld());+ Run(W, *Pawn, uint32(EVerseInputButton::Jump), FVector2f(1.f, 0.f), 1.f);+ TestEqual(TEXT("one mantle noise"), Log.Count(Noise_Move_Mantle), 1);+ TestEqual(TEXT("mantle range 12 m"), Audibility->GetAudibleRangeM(Noise_Move_Mantle, 1.f), 12.f);+ }+ return true;+}++// WP01.11: bone to hit zone table from the physics asset; lean and prone move the hit bodies.+IMPLEMENT_SIMPLE_AUTOMATION_TEST(FVerseMovementHitZonesTest, "Verse.Movement.HitZones", NoiseTestFlags)+bool FVerseMovementHitZonesTest::RunTest(const FString& Parameters)+{+ TestEqual(TEXT("Head"), int32(VerseHitZones::ZoneForBoneName(TEXT("Head"))), int32(EVerseHitZone::Head));+ TestEqual(TEXT("Neck"), int32(VerseHitZones::ZoneForBoneName(TEXT("Neck"))), int32(EVerseHitZone::Neck));+ TestEqual(TEXT("Spine_03"), int32(VerseHitZones::ZoneForBoneName(TEXT("Spine_03"))), int32(EVerseHitZone::UpperTorso));+ TestEqual(TEXT("Spine_01"), int32(VerseHitZones::ZoneForBoneName(TEXT("Spine_01"))), int32(EVerseHitZone::LowerTorso));+ TestEqual(TEXT("Hips"), int32(VerseHitZones::ZoneForBoneName(TEXT("Hips"))), int32(EVerseHitZone::LowerTorso));+ TestEqual(TEXT("LowerArm_L"), int32(VerseHitZones::ZoneForBoneName(TEXT("LowerArm_L"))), int32(EVerseHitZone::Arm));+ TestEqual(TEXT("Calf_R"), int32(VerseHitZones::ZoneForBoneName(TEXT("Calf_R"))), int32(EVerseHitZone::Leg));+ TestEqual(TEXT("Root has no zone"), int32(VerseHitZones::ZoneForBoneName(TEXT("Root"))), int32(EVerseHitZone::None));++ FVerseMovementTestWorld W;+ if (!TestTrue(TEXT("test world"), W.IsValid())) return false;+ const FVector Open(0.f, OpenFloorY, 0.f);+ AVerseCharacter* Pawn = W.SpawnPawn(Open, 0.f);+ if (!TestNotNull(TEXT("pawn"), Pawn)) return false;+ USkeletalMeshComponent* Mesh = Pawn->GetMesh();+ if (!TestNotNull(TEXT("SK_Test_Human on the pawn"), Mesh->GetSkeletalMeshAsset()) || !TestNotNull(TEXT("physics asset"), Mesh->GetPhysicsAsset()))+ {+ return false;+ }+ TMap<FName, EVerseHitZone> Table;+ FString Error;+ TestTrue(FString::Printf(TEXT("every physics body has a zone (%s)"), *Error), VerseHitZones::BuildTable(Mesh->GetPhysicsAsset(), Mesh->GetSkeletalMeshAsset(), Table, Error));+ TSet<EVerseHitZone> Zones;+ for (const TPair<FName, EVerseHitZone>& Entry : Table)+ {+ Zones.Add(Entry.Value);+ }+ for (const EVerseHitZone Zone : {EVerseHitZone::Head, EVerseHitZone::Neck, EVerseHitZone::UpperTorso, EVerseHitZone::LowerTorso, EVerseHitZone::Arm, EVerseHitZone::Leg})+ {+ TestTrue(FString::Printf(TEXT("table covers zone %d"), int32(Zone)), Zones.Contains(Zone));+ }++ auto BodyLocation = [Mesh](FName Bone)+ {+ const FBodyInstance* Body = Mesh->GetBodyInstance(Bone);+ return Body ? Body->GetUnrealWorldTransform().GetLocation() : Mesh->GetBoneLocation(Bone);+ };+ // Scan: one trace from the front every 5 cm of height; the zone hit first at each height.+ auto Scan = [&W, Pawn](const FVector& Through, TMap<EVerseHitZone, FVector2f>& OutRange, FString& OutProfile)+ {+ OutRange.Reset();+ OutProfile.Reset();+ const float Floor = FVerseMovementTestWorld::Feet(*Pawn).Z;+ const FVector Forward = Pawn->GetActorForwardVector();+ for (float Height = 2.5f; Height < 200.f; Height += 5.f)+ {+ const FVector Point(Through.X, Through.Y, Floor + Height);+ FHitResult Hit;+ const bool bHit = W.GetWorld()->LineTraceSingleByChannel(Hit, Point + Forward * 300.f, Point - Forward * 300.f,+ VerseCollision::HitBody, FCollisionQueryParams(SCENE_QUERY_STAT(VerseHitZoneScan), false));+ const EVerseHitZone Zone = bHit ? VerseHitZones::ZoneForHit(Hit) : EVerseHitZone::None;+ OutProfile += FString::Printf(TEXT("%d"), int32(Zone));+ if (bHit && FMath::IsNearlyEqual(FMath::Fmod(Height, 40.f), 2.5f))+ {+ OutProfile += FString::Printf(TEXT("[%s %s z%.0f]"), *Hit.BoneName.ToString(), *GetNameSafe(Hit.GetComponent()), Hit.ImpactPoint.Z - Floor);+ }+ if (Zone != EVerseHitZone::None)+ {+ FVector2f& Range = OutRange.FindOrAdd(Zone, FVector2f(Height, Height));+ Range.X = FMath::Min(Range.X, Height);+ Range.Y = FMath::Max(Range.Y, Height);+ }+ }+ };+ Run(W, *Pawn, 0u, FVector2f::ZeroVector, 0.5f);+ for (const USkeletalBodySetup* Setup : Mesh->GetPhysicsAsset()->SkeletalBodySetups)+ {+ const FBodyInstance* Instance = Setup ? Mesh->GetBodyInstance(Setup->BoneName) : nullptr;+ const FKSphylElem* Sphyl = Setup && Setup->AggGeom.SphylElems.Num() ? &Setup->AggGeom.SphylElems[0] : nullptr;+ AddInfo(FString::Printf(TEXT("body %s: at %s, capsule r %.1f len %.1f, bounds %s"), Setup ? *Setup->BoneName.ToString() : TEXT("?"),+ Instance ? *(Instance->GetUnrealWorldTransform().GetLocation() - Pawn->GetActorLocation()).ToCompactString() : TEXT("-"),+ Sphyl ? Sphyl->Radius : -1.f, Sphyl ? Sphyl->Length : -1.f, Instance ? *Instance->GetBodyBounds().GetExtent().ToCompactString() : TEXT("-")));+ }+ int32 Fixed = 0;+ if (!TestNotNull(TEXT("scale-corrected copy of the physics asset"), MakeSaneCopy(*Mesh, Fixed)))+ {+ return false;+ }+ AddInfo(FString::Printf(TEXT("%d bodies of PHYS_Test_Human scale-corrected for the trace checks (G0.9 import scale)"), Fixed));+ Run(W, *Pawn, 0u, FVector2f::ZeroVector, 0.2f);+ const FVector Head = BodyLocation(TEXT("Head"));+ const FBodyInstance* HeadBody = Mesh->GetBodyInstance(TEXT("Head"));+ const bool bTraceable = HeadBody && HeadBody->GetBodyBounds().GetExtent().Z < 50.f;+ if (!TestTrue(TEXT("hit bodies have a traceable size (head body under 50 cm)"), bTraceable))+ {+ return false;+ }+ const bool bHasCamera = Mesh->GetBoneIndex(TEXT("Camera")) != INDEX_NONE;+ const FVector CameraBone = bHasCamera ? Mesh->GetBoneLocation(TEXT("Camera")) : FVector::ZeroVector;+ TMap<EVerseHitZone, FVector2f> Standing;+ FString Profile;+ // The rig's bodies are joint spheres; the legs sit 10 cm off the centre line, so the scan+ // runs through the right thigh's line (head and spine are on it too).+ const FVector LegLine = BodyLocation(TEXT("Thigh_R"));+ Scan(FVector(LegLine.X, LegLine.Y, Pawn->GetActorLocation().Z), Standing, Profile);+ AddInfo(FString::Printf(TEXT("standing zone profile, 5 cm steps from the floor: %s"), *Profile));+ for (const EVerseHitZone Zone : {EVerseHitZone::Head, EVerseHitZone::UpperTorso, EVerseHitZone::LowerTorso, EVerseHitZone::Leg})+ {+ if (bTraceable) TestTrue(FString::Printf(TEXT("standing: a front trace hits zone %d"), int32(Zone)), Standing.Contains(Zone));+ }+ if (bTraceable && Standing.Contains(EVerseHitZone::Head) && Standing.Contains(EVerseHitZone::Leg) && Standing.Contains(EVerseHitZone::LowerTorso))+ {+ TestTrue(TEXT("head zone sits above the lower torso"), Standing[EVerseHitZone::Head].Y > Standing[EVerseHitZone::LowerTorso].Y);+ TestTrue(TEXT("lower torso sits above the legs"), Standing[EVerseHitZone::LowerTorso].X > Standing[EVerseHitZone::Leg].X);+ TestTrue(TEXT("standing head above 1.4 m"), Standing[EVerseHitZone::Head].Y > 140.f);+ }++ Run(W, *Pawn, uint32(EVerseInputButton::LeanRight), FVector2f::ZeroVector, 0.5f);+ const FVector LeanHead = BodyLocation(TEXT("Head"));+ const float Moved = (LeanHead - Head) | Pawn->GetActorRightVector();+ AddInfo(FString::Printf(TEXT("lean right moved the head body %.1f cm to the right"), Moved));+ TestTrue(TEXT("lean moves the head body at least 25 cm"), Moved >= 25.f);+ TMap<EVerseHitZone, FVector2f> LeanSide;+ Scan(LeanHead, LeanSide, Profile);+ AddInfo(FString::Printf(TEXT("leaning: profile through the leaned head: %s"), *Profile));+ if (bTraceable)+ {+ TestTrue(TEXT("leaning: the head is hit where the leaned head is"), LeanSide.Contains(EVerseHitZone::Head));+ }+ if (bHasCamera)+ {+ TestTrue(TEXT("the Camera bone (bot eye) moves with the lean"), ((Mesh->GetBoneLocation(TEXT("Camera")) - CameraBone) | Pawn->GetActorRightVector()) >= 25.f);+ }+ Run(W, *Pawn, 0u, FVector2f::ZeroVector, 0.5f);++ Run(W, *Pawn, uint32(EVerseInputButton::Prone), FVector2f::ZeroVector, 1.5f);+ for (const USkeletalBodySetup* Setup : Mesh->GetPhysicsAsset()->SkeletalBodySetups)+ {+ const FBodyInstance* Instance = Setup ? Mesh->GetBodyInstance(Setup->BoneName) : nullptr;+ AddInfo(FString::Printf(TEXT("prone body %s: at %s from the feet, bounds %s"), Setup ? *Setup->BoneName.ToString() : TEXT("?"),+ Instance ? *(Instance->GetUnrealWorldTransform().GetLocation() - FVerseMovementTestWorld::Feet(*Pawn)).ToCompactString() : TEXT("-"),+ Instance ? *Instance->GetBodyBounds().GetExtent().ToCompactString() : TEXT("-")));+ }+ const FVector ProneHead = BodyLocation(TEXT("Head"));+ const float Feet = FVerseMovementTestWorld::Feet(*Pawn).Z;+ AddInfo(FString::Printf(TEXT("prone head body %.1f cm above the floor"), ProneHead.Z - Feet));+ TestTrue(TEXT("prone lays the head body below 50 cm"), ProneHead.Z - Feet < 50.f);+ TestTrue(TEXT("prone moves the head body forward"), ((ProneHead - Pawn->GetActorLocation()) | Pawn->GetActorForwardVector()) > 10.f);+ TMap<EVerseHitZone, FVector2f> Prone;+ Scan(Pawn->GetActorLocation(), Prone, Profile);+ AddInfo(FString::Printf(TEXT("prone profile through the capsule: %s"), *Profile));+ for (const TPair<EVerseHitZone, FVector2f>& Entry : Prone)+ {+ if (bTraceable) TestTrue(FString::Printf(TEXT("prone: zone %d stays below 60 cm"), int32(Entry.Key)), Entry.Value.Y < 60.f);+ }+ // Legs trail behind the capsule: a side trace there hits a leg (mesh body or prone body box).+ const FVector Behind = Pawn->GetActorLocation() - Pawn->GetActorForwardVector() * 110.f;+ bool bLeg = false;+ for (float Height = 2.5f; Height < 45.f && !bLeg; Height += 5.f)+ {+ const FVector Point(Behind.X, Behind.Y, Feet + Height);+ FHitResult Hit;+ const FVector Side = Pawn->GetActorRightVector() * 300.f;+ bLeg = W.GetWorld()->LineTraceSingleByChannel(Hit, Point + Side, Point - Side, VerseCollision::HitBody,+ FCollisionQueryParams(SCENE_QUERY_STAT(VerseProneLegs), false)) && VerseHitZones::ZoneForHit(Hit) == EVerseHitZone::Leg;+ }+ if (bTraceable)+ {+ TestTrue(TEXT("the prone legs behind the capsule can be hit"), bLeg);+ }+ // The prone leg box is ours: it lies over the legs behind the capsule while prone, never under the head or torso.+ const FBox ProneBox = Pawn->GetProneBody()->Bounds.GetBox();+ TestTrue(TEXT("prone leg box is active while prone"), Pawn->GetProneBody()->GetCollisionEnabled() == ECollisionEnabled::QueryOnly);+ TestTrue(TEXT("prone leg box lies behind the capsule, under 0.45 m"), ProneBox.IsInsideXY(Behind) && ProneBox.Max.Z - Feet < 45.f);+ const FVector Forward = Pawn->GetActorForwardVector();+ const float BoxFront = FMath::Max(float((ProneBox.Min - Pawn->GetActorLocation()) | Forward), float((ProneBox.Max - Pawn->GetActorLocation()) | Forward));+ TestTrue(FString::Printf(TEXT("prone leg box ends behind the hips (front edge %.0f cm)"), BoxFront), BoxFront < -30.f);++ // Head shots on a prone pawn: from above and from the side, the trace through the head scores Head.+ {+ const FVector HeadNow = BodyLocation(TEXT("Head"));+ FHitResult Hit;+ const FCollisionQueryParams Query(SCENE_QUERY_STAT(VerseProneHead), false);+ const bool bTop = W.GetWorld()->LineTraceSingleByChannel(Hit, HeadNow + FVector(0.f, 0.f, 200.f), HeadNow - FVector(0.f, 0.f, 50.f), VerseCollision::HitBody, Query);+ AddInfo(FString::Printf(TEXT("prone head shot from above: %s %s"), *GetNameSafe(Hit.GetComponent()), *Hit.BoneName.ToString()));+ TestTrue(TEXT("prone: a shot from above at the head scores Head"), bTop && VerseHitZones::ZoneForHit(Hit) == EVerseHitZone::Head);+ const FVector Side = Pawn->GetActorRightVector() * 300.f;+ const bool bSide = W.GetWorld()->LineTraceSingleByChannel(Hit, HeadNow + Side, HeadNow - Side, VerseCollision::HitBody, Query);+ TestTrue(TEXT("prone: a shot from the side at the head scores Head"), bSide && VerseHitZones::ZoneForHit(Hit) == EVerseHitZone::Head);+ const FVector Chest = BodyLocation(TEXT("Spine_03"));+ const bool bChest = W.GetWorld()->LineTraceSingleByChannel(Hit, Chest + FVector(0.f, 0.f, 200.f), Chest - FVector(0.f, 0.f, 50.f), VerseCollision::HitBody, Query);+ const EVerseHitZone ChestZone = bChest ? VerseHitZones::ZoneForHit(Hit) : EVerseHitZone::None;+ TestTrue(TEXT("prone: a shot from above at the chest scores a torso zone, not Leg"), ChestZone == EVerseHitZone::UpperTorso || ChestZone == EVerseHitZone::LowerTorso || ChestZone == EVerseHitZone::Arm);+ }+ // Body motion: every body sits below 60 cm while prone.+ for (const USkeletalBodySetup* Setup : Mesh->GetPhysicsAsset()->SkeletalBodySetups)+ {+ const FVector At = BodyLocation(Setup->BoneName);+ TestTrue(FString::Printf(TEXT("prone: body %s below 60 cm"), *Setup->BoneName.ToString()), At.Z - Feet < 60.f);+ }+ return true;+}++#endif // WITH_DEV_AUTOMATION_TESTSdiff --git a/unreal/Verse/Source/VerseMovement/Private/Tests/Movement/VerseMovementTestWorld.cpp b/unreal/Verse/Source/VerseMovement/Private/Tests/Movement/VerseMovementTestWorld.cppnew file mode 100644index 0000000000..a9551edb50--- /dev/null+++ b/unreal/Verse/Source/VerseMovement/Private/Tests/Movement/VerseMovementTestWorld.cpp@@ -0,0 +1,129 @@+#include "Tests/Movement/VerseMovementTestWorld.h"++#if WITH_DEV_AUTOMATION_TESTS++#include "Components/BoxComponent.h"+#include "Components/CapsuleComponent.h"+#include "Engine/World.h"+#include "Fixture/VerseMovementCourse.h"+#include "GameFramework/PlayerController.h"+#include "VerseCharacter.h"+#include "VerseCharacterMovement.h"+#include "VerseCollision.h"+#include "VerseInputFrameController.h"++FVerseMovementTestWorld::FVerseMovementTestWorld(bool bWithCourse)+{+ if (!Wrapper.CreateTestWorld(EWorldType::Game) || !Wrapper.BeginPlayInTestWorld())+ {+ return;+ }+ World = Wrapper.GetTestWorld();+ if (bWithCourse)+ {+ World->SpawnActor<AVerseMovementCourse>(FVector::ZeroVector, FRotator::ZeroRotator);+ }+}++FVerseMovementTestWorld::~FVerseMovementTestWorld()+{+ if (World)+ {+ Wrapper.DestroyTestWorld(false);+ }+}++AVerseCharacter* FVerseMovementTestWorld::SpawnPawn(const FVector& FeetAt, float Yaw, EDriver Driver)+{+ FActorSpawnParameters Params;+ Params.SpawnCollisionHandlingOverride = ESpawnActorCollisionHandlingMethod::AlwaysSpawn;+ AVerseCharacter* Pawn = World->SpawnActor<AVerseCharacter>(FeetAt + FVector(0.f, 0.f, 92.f), FRotator(0.f, Yaw, 0.f), Params);+ if (!Pawn)+ {+ return nullptr;+ }+ AController* Controller = nullptr;+ if (Driver == EDriver::Person)+ {+ // A person's controller without a viewport: mark it local, as a local player would.+ APlayerController* Person = World->SpawnActor<APlayerController>();+ Person->SetAsLocalPlayerController();+ Controller = Person;+ }+ else+ {+ Controller = World->SpawnActor<AVerseInputFrameController>();+ }+ Controller->Possess(Pawn);+ Place(*Pawn, FeetAt, Yaw);+ Tick(2);+ return Pawn;+}++void FVerseMovementTestWorld::Place(AVerseCharacter& Pawn, const FVector& FeetLocation, float Yaw) const+{+ UVerseCharacterMovement* Movement = Pawn.GetVerseMovement();+ Pawn.SetInputScript(nullptr);+ Movement->SetMovementMode(MOVE_Walking);+ const float Half = Pawn.GetCapsuleComponent()->GetScaledCapsuleHalfHeight();+ Pawn.SetActorLocationAndRotation(FeetLocation + FVector(0.f, 0.f, Half + 1.f), FRotator(0.f, Yaw, 0.f), false, nullptr, ETeleportType::TeleportPhysics);+ if (AController* Controller = Pawn.GetController())+ {+ Controller->SetControlRotation(FRotator(0.f, Yaw, 0.f));+ }+ Movement->StopMovementImmediately();+ Movement->bForceNextFloorCheck = true;+}++void FVerseMovementTestWorld::Drive(AVerseCharacter& Pawn, const FVerseInputFrame& Frame) const+{+ if (AVerseInputFrameController* Bot = Cast<AVerseInputFrameController>(Pawn.GetController()))+ {+ Bot->SubmitFrame(Frame);+ return;+ }+ FVerseInputFrameBuilder& Person = Pawn.GetPersonInput();+ Person.SetMove(Frame.Move);+ Person.AddLook(Frame.LookDeltaDeg);+ for (uint32 Bit = 1; Bit != 0 && Bit <= uint32(EVerseInputButton::Interact); Bit <<= 1)+ {+ Person.SetButton(EVerseInputButton(Bit), (Frame.Buttons & Bit) != 0);+ }+}++void FVerseMovementTestWorld::Tick(int32 Count)+{+ for (int32 Index = 0; Index < Count; ++Index)+ {+ Wrapper.TickTestWorld(Dt);+ }+}++UBoxComponent* FVerseMovementTestWorld::AddBox(const FVector& Center, const FVector& Extent)+{+ AActor* Owner = World->SpawnActor<AActor>(Center, FRotator::ZeroRotator);+ UBoxComponent* Box = NewObject<UBoxComponent>(Owner);+ Box->SetBoxExtent(Extent, false);+ Box->SetCollisionProfileName(VerseCollision::Profile::Architecture);+ Owner->SetRootComponent(Box);+ Box->RegisterComponent();+ Box->SetWorldLocation(Center);+ return Box;+}++FVector FVerseMovementTestWorld::Feet(const AVerseCharacter& Pawn)+{+ return Pawn.GetActorLocation() - FVector(0.f, 0.f, Pawn.GetCapsuleComponent()->GetScaledCapsuleHalfHeight());+}++FVerseInputFrame VerseTestFrame(const FVector2f& Move, uint32 Buttons, uint32 PreviousButtons, const FVector2f& Look)+{+ FVerseInputFrame Frame;+ Frame.Move = Move;+ Frame.Buttons = Buttons;+ Frame.Pressed = Buttons & ~PreviousButtons;+ Frame.LookDeltaDeg = Look;+ return Frame;+}++#endifdiff --git a/unreal/Verse/Source/VerseMovement/Private/Tests/Movement/VerseMovementTestWorld.h b/unreal/Verse/Source/VerseMovement/Private/Tests/Movement/VerseMovementTestWorld.hnew file mode 100644index 0000000000..d14312c8ea--- /dev/null+++ b/unreal/Verse/Source/VerseMovement/Private/Tests/Movement/VerseMovementTestWorld.h@@ -0,0 +1,64 @@+#pragma once++#include "CoreMinimal.h"++#if WITH_DEV_AUTOMATION_TESTS++#include "Combat/VerseCombatTypes.h"+#include "Tests/AutomationCommon.h"++class AVerseCharacter;+class AController;+class UBoxComponent;+class UVerseCharacterMovement;+class UWorld;++/**+ * A manually ticked game world with the fixture course (LV_Test_Movement's geometry) for the+ * Verse.Movement.* tests. Ticks at the server rate, 60 Hz.+ */+class FVerseMovementTestWorld+{+public:+ static constexpr float Dt = 1.f / 60.f;++ explicit FVerseMovementTestWorld(bool bWithCourse = true);+ ~FVerseMovementTestWorld();++ bool IsValid() const { return World != nullptr; }+ UWorld* GetWorld() const { return World; }++ enum class EDriver : uint8+ {+ /** A local APlayerController; frames go through the person's FVerseInputFrameBuilder. */+ Person,+ /** An AVerseInputFrameController; frames go through SubmitFrame (bot path). */+ Bot+ };++ /** A pawn standing with its feet at Feet, facing Yaw. */+ AVerseCharacter* SpawnPawn(const FVector& FeetAt, float Yaw, EDriver Driver = EDriver::Bot);++ /** Teleports a pawn: feet at Feet, facing Yaw, at rest, standing. */+ void Place(AVerseCharacter& Pawn, const FVector& FeetLocation, float Yaw) const;++ /** Feeds one frame to the pawn through its driver. */+ void Drive(AVerseCharacter& Pawn, const FVerseInputFrame& Frame) const;++ void Tick(int32 Count = 1);+ void TickSeconds(float Seconds) { Tick(FMath::Max(1, FMath::RoundToInt(Seconds / Dt))); }++ /** An extra blocking box (architecture profile) at a world center. */+ UBoxComponent* AddBox(const FVector& Center, const FVector& Extent);++ static FVector Feet(const AVerseCharacter& Pawn);++private:+ FTestWorldWrapper Wrapper;+ UWorld* World = nullptr;+};++/** A frame that holds Buttons, with Pressed derived from the previous frame's buttons. */+FVerseInputFrame VerseTestFrame(const FVector2f& Move, uint32 Buttons, uint32 PreviousButtons, const FVector2f& Look = FVector2f::ZeroVector);++#endifdiff --git a/unreal/Verse/Source/VerseMovement/Private/VerseCharacter.cpp b/unreal/Verse/Source/VerseMovement/Private/VerseCharacter.cppnew file mode 100644index 0000000000..bb8d49d4c6--- /dev/null+++ b/unreal/Verse/Source/VerseMovement/Private/VerseCharacter.cpp@@ -0,0 +1,435 @@+#include "VerseCharacter.h"++#include "AnimationRuntime.h"+#include "Camera/CameraComponent.h"+#include "Components/BoxComponent.h"+#include "Components/CapsuleComponent.h"+#include "Components/InputComponent.h"+#include "Components/SkeletalMeshComponent.h"+#include "Engine/SkeletalMesh.h"+#include "Engine/World.h"+#include "GameFramework/PlayerController.h"+#include "HAL/PlatformTime.h"+#include "Misc/ScopeExit.h"+#include "Net/UnrealNetwork.h"+#include "PhysicsEngine/PhysicsAsset.h"+#include "UObject/ConstructorHelpers.h"+#include "VerseCharacterMovement.h"+#include "VerseCollision.h"++namespace+{+ const TCHAR* TestHumanMesh = TEXT("/Game/Verse/Test/G0/SK_Test_Human.SK_Test_Human");+ const TCHAR* TestHumanPhysics = TEXT("/Game/Verse/Test/G0/PHYS_Test_Human.PHYS_Test_Human");+ /** The mesh faces +Y in its own space (coordinates.md 3.3: mesh yaw = heading - 90). */+ const FRotator MeshBaseRotation(0.f, -90.f, 0.f);+ /** Placeholder prone pose: the feet rest this high, the body rises toward the head. */+ constexpr float ProneFeetLift = 12.f;+ /** Share of the prone body length from the feet to the hips (the leg hit box). */+ constexpr float ProneLegShare = 0.53f;+}++const FName AVerseCharacter::CameraBoneName(TEXT("Camera"));++AVerseCharacter::AVerseCharacter(const FObjectInitializer& ObjectInitializer)+ : Super(ObjectInitializer.SetDefaultSubobjectClass<UVerseCharacterMovement>(ACharacter::CharacterMovementComponentName))+{+ PrimaryActorTick.bCanEverTick = true;+ PrimaryActorTick.TickGroup = TG_PrePhysics;+ bUseControllerRotationYaw = true;+ bUseControllerRotationPitch = false;+ bUseControllerRotationRoll = false;+ // The input frame (Tick) runs before the movement simulates it; see BeginPlay.+ GetCharacterMovement()->bTickBeforeOwner = false;++ const FVerseMovementTuningValues Defaults;+ GetCapsuleComponent()->InitCapsuleSize(Defaults.CapsuleRadius * 100.f, Defaults.StandHalfHeightCm());++ FirstPersonCamera = CreateDefaultSubobject<UCameraComponent>(TEXT("FirstPersonCamera"));+ FirstPersonCamera->SetupAttachment(GetCapsuleComponent());+ FirstPersonCamera->SetRelativeLocation(FVector(0.f, 0.f, Defaults.StandEyeHeight * 100.f - Defaults.StandHalfHeightCm()));+ FirstPersonCamera->bUsePawnControlRotation = false;+ FirstPersonCamera->SetFieldOfView(100.f);++ ProneBody = CreateDefaultSubobject<UBoxComponent>(TEXT("ProneBody"));+ ProneBody->SetupAttachment(GetCapsuleComponent());+ ProneBody->SetCollisionEnabled(ECollisionEnabled::NoCollision);+ ProneBody->SetCollisionObjectType(ECC_Pawn);+ ProneBody->SetCollisionResponseToAllChannels(ECR_Ignore);+ ProneBody->SetCollisionResponseToChannel(VerseCollision::HitBody, ECR_Block);+ ProneBody->SetCanEverAffectNavigation(false);+ ProneBody->SetGenerateOverlapEvents(false);++ if (USkeletalMeshComponent* Body = GetMesh())+ {+ static ConstructorHelpers::FObjectFinderOptional<USkeletalMesh> MeshFinder(TestHumanMesh);+ if (MeshFinder.Succeeded())+ {+ Body->SetSkeletalMeshAsset(MeshFinder.Get());+ }+ Body->SetRelativeLocationAndRotation(FVector(0.f, 0.f, -Defaults.StandHalfHeightCm()), MeshBaseRotation);+ Body->VisibilityBasedAnimTickOption = EVisibilityBasedAnimTickOption::AlwaysTickPoseAndRefreshBones;+ Body->bOwnerNoSee = false;+ }+}++UVerseCharacterMovement* AVerseCharacter::GetVerseMovement() const+{+ return Cast<UVerseCharacterMovement>(GetCharacterMovement());+}++void AVerseCharacter::BeginPlay()+{+ Super::BeginPlay();+ // Input before movement: the frame applied in Tick (look, turn, move, buttons) is the one the+ // movement simulates in the same frame, and the turn cap and prone body constraint see it.+ if (UCharacterMovementComponent* Movement = GetCharacterMovement())+ {+ Movement->PrimaryComponentTick.AddPrerequisite(this, PrimaryActorTick);+ }+ if (USkeletalMeshComponent* Body = GetMesh())+ {+ if (Body->GetSkeletalMeshAsset() && !Body->GetPhysicsAsset())+ {+ if (UPhysicsAsset* Physics = LoadObject<UPhysicsAsset>(nullptr, TestHumanPhysics, nullptr, LOAD_NoWarn | LOAD_Quiet))+ {+ Body->SetPhysicsAsset(Physics, true);+ }+ }+ }+ CacheCameraBone();+ // The leg box covers the lying legs only: from the feet end of the prone body to the hips.+ const FVerseMovementTuningValues& Tuning = GetVerseMovement()->Tuning();+ const float Length = Tuning.ProneBodyLength * 100.f;+ const float HeadForward = Tuning.ProneRadius * 200.f;+ const float Legs = Length * ProneLegShare;+ ProneBody->SetBoxExtent(FVector(Legs * 0.5f, Tuning.ProneBodyWidth * 50.f, Tuning.ProneMinClearance * 50.f - 2.f), false);+ ProneBody->SetRelativeLocation(FVector(HeadForward - Length + Legs * 0.5f, 0.f, 0.f));+ UpdateBodyPose(0.f);+}++void AVerseCharacter::CacheCameraBone()+{+ bHasCameraBone = false;+ const USkeletalMeshComponent* Body = GetMesh();+ const USkeletalMesh* Asset = Body ? Body->GetSkeletalMeshAsset() : nullptr;+ if (!Asset)+ {+ return;+ }+ const FReferenceSkeleton& Skeleton = Asset->GetRefSkeleton();+ const int32 Index = Skeleton.FindBoneIndex(CameraBoneName);+ if (Index == INDEX_NONE)+ {+ return;+ }+ CameraBoneLocal = FAnimationRuntime::GetComponentSpaceTransformRefPose(Skeleton, Index).GetLocation();+ bHasCameraBone = CameraBoneLocal.Z > 1.f;+}++void AVerseCharacter::GetLifetimeReplicatedProps(TArray<FLifetimeProperty>& OutLifetimeProps) const+{+ Super::GetLifetimeReplicatedProps(OutLifetimeProps);+ FDoRepLifetimeParams Params;+ Params.Condition = COND_SkipOwner;+ DOREPLIFETIME_WITH_PARAMS_FAST(AVerseCharacter, ReplicatedStance, Params);+ DOREPLIFETIME_WITH_PARAMS_FAST(AVerseCharacter, ReplicatedLean, Params);+ DOREPLIFETIME_WITH_PARAMS_FAST(AVerseCharacter, bReplicatedSprinting, Params);+ DOREPLIFETIME_WITH_PARAMS_FAST(AVerseCharacter, bReplicatedMantling, Params);+}++void AVerseCharacter::SetReplicatedMovementState(EVerseStance Stance, int8 Lean, bool bSprinting, bool bMantling)+{+ ReplicatedStance = uint8(Stance);+ ReplicatedLean = Lean;+ bReplicatedSprinting = bSprinting;+ bReplicatedMantling = bMantling;+}++void AVerseCharacter::OnRep_MovementState()+{+ if (UVerseCharacterMovement* Movement = GetVerseMovement())+ {+ Movement->ApplyReplicatedStance(EVerseStance(ReplicatedStance));+ }+}++// ---------------------------------------------------------------------------------------------+// Input++void AVerseCharacter::ApplyInputFrame(const FVerseInputFrame& Frame, float DeltaSeconds)+{+ UVerseCharacterMovement* Movement = GetVerseMovement();+ if (!Movement)+ {+ return;+ }+ LastAppliedFrame = Frame;+ if (Controller)+ {+ FRotator Rotation = Controller->GetControlRotation();+ float Yaw = Frame.LookDeltaDeg.Y;+ if (Movement->IsProne() || Movement->GetProneTransitionAlpha() != 0.f)+ {+ const float Cap = Movement->Tuning().ProneTurnCapDegPerSec * DeltaSeconds;+ Yaw = FMath::Clamp(Yaw, -Cap, Cap);+ }+ Rotation.Yaw = FRotator::NormalizeAxis(Rotation.Yaw + Yaw);+ Rotation.Pitch = FMath::Clamp(FRotator::NormalizeAxis(Rotation.Pitch + Frame.LookDeltaDeg.X), -85.f, 85.f);+ Rotation.Roll = 0.f;+ Controller->SetControlRotation(Rotation);+ // Plain controllers (bots, harness) never rotate their pawn; turn the body here for all.+ FaceRotation(Rotation, DeltaSeconds);+ }+ FVector2f Move = Frame.Move;+ if (Move.SizeSquared() > 1.f)+ {+ Move.Normalize();+ }+ const FRotator YawOnly(0.f, Controller ? Controller->GetControlRotation().Yaw : GetActorRotation().Yaw, 0.f);+ const FRotationMatrix Basis(YawOnly);+ AddMovementInput(Basis.GetUnitAxis(EAxis::X), Move.X);+ AddMovementInput(Basis.GetUnitAxis(EAxis::Y), Move.Y);++ Movement->SetWantsSprint(Frame.IsHeld(EVerseInputButton::Sprint));+ Movement->bWantsToCrouch = Frame.IsHeld(EVerseInputButton::Crouch);+ Movement->SetWantsProne(Frame.IsHeld(EVerseInputButton::Prone));+ Movement->SetWantsMantle(Frame.IsHeld(EVerseInputButton::Jump));+ const int32 Lean = (Frame.IsHeld(EVerseInputButton::LeanRight) ? 1 : 0) - (Frame.IsHeld(EVerseInputButton::LeanLeft) ? 1 : 0);+ Movement->SetLeanTarget(int8(Lean * 127));+ if (Frame.WasPressed(EVerseInputButton::Jump))+ {+ Jump();+ }+ else if (!Frame.IsHeld(EVerseInputButton::Jump))+ {+ StopJumping();+ }+}++void AVerseCharacter::SubmitInputFrame(const FVerseInputFrame& Frame)+{+ SubmittedFrame = Frame;+ bHasSubmittedFrame = true;+ bSubmittedFrameFresh = true;+}++void AVerseCharacter::SetInputScript(FVerseInputScript Script)+{+ InputScript = MoveTemp(Script);+ InputScriptTime = 0.f;+}++void AVerseCharacter::Tick(float DeltaSeconds)+{+ const uint64 StartCycles = FPlatformTime::Cycles64();+ ON_SCOPE_EXIT+ {+ if (UVerseCharacterMovement* Movement = GetVerseMovement())+ {+ Movement->AddMovementCycles(FPlatformTime::Cycles64() - StartCycles);+ }+ };+ Super::Tick(DeltaSeconds);+ if (!IsLocallyControlled() && !HasAuthority())+ {+ return;+ }+ const uint32 TimeMs = GetWorld() ? uint32(GetWorld()->GetTimeSeconds() * 1000.0) : 0;+ if (InputScript)+ {+ FVerseInputFrame Frame;+ Frame.ServerTimeMs = TimeMs;+ const bool bContinue = InputScript(InputScriptTime, DeltaSeconds, Frame);+ InputScriptTime += DeltaSeconds;+ ApplyInputFrame(Frame, DeltaSeconds);+ if (!bContinue)+ {+ InputScript = nullptr;+ }+ return;+ }+ if (bHasSubmittedFrame)+ {+ // A frame holds until the next one; its one-shot parts (presses, look) apply once.+ FVerseInputFrame Frame = SubmittedFrame;+ if (!bSubmittedFrameFresh)+ {+ Frame.Pressed = 0;+ Frame.LookDeltaDeg = FVector2f::ZeroVector;+ }+ bSubmittedFrameFresh = false;+ ApplyInputFrame(Frame, DeltaSeconds);+ return;+ }+ if (IsLocallyControlled() && Cast<APlayerController>(Controller))+ {+ ApplyInputFrame(PersonInput.Consume(TimeMs), DeltaSeconds);+ }+}++void AVerseCharacter::SetupPlayerInputComponent(UInputComponent* PlayerInputComponent)+{+ Super::SetupPlayerInputComponent(PlayerInputComponent);+ if (!PlayerInputComponent)+ {+ return;+ }+ TWeakObjectPtr<AVerseCharacter> Self(this);+ VersePersonInput::BindDefaults(*PlayerInputComponent, PersonInput, [Self]()+ {+ const UWorld* World = Self.IsValid() ? Self->GetWorld() : nullptr;+ return World ? World->GetDeltaSeconds() : 0.f;+ });+}++void AVerseCharacter::PawnClientRestart()+{+ Super::PawnClientRestart();+ PersonInput.Reset();+}++// ---------------------------------------------------------------------------------------------+// Camera and placeholder body++void AVerseCharacter::UpdateBodyPose(float DeltaSeconds)+{+ const UVerseCharacterMovement* Movement = GetVerseMovement();+ if (!Movement || !GetCapsuleComponent())+ {+ return;+ }+ const FVerseMovementTuningValues& Tuning = Movement->Tuning();+ const float HalfHeight = GetCapsuleComponent()->GetUnscaledCapsuleHalfHeight();+ const EVerseStance Stance = Movement->GetStance();+ const bool bProne = Stance == EVerseStance::Prone;++ // Prone alpha: 1 lying, 0 upright; transitions blend over the enter and exit times.+ float ProneAlpha = bProne ? 1.f : 0.f;+ const float Transition = Movement->GetProneTransitionAlpha();+ if (Transition > 0.f)+ {+ ProneAlpha = Transition;+ }+ else if (Transition < 0.f)+ {+ ProneAlpha = 1.f + Transition;+ }+ SmoothedProneAlpha = ProneAlpha;+ // The upright eye height settles over EyeBlendTime; lying blends in through the prone alpha.+ const float UprightEye = bProne ? Tuning.CrouchEyeHeight * 100.f : Movement->GetTargetEyeHeight();+ if (SmoothedEyeHeight < 0.f || DeltaSeconds <= 0.f)+ {+ SmoothedEyeHeight = UprightEye;+ }+ else+ {+ const float Blend = FMath::Clamp(DeltaSeconds / FMath::Max(Tuning.EyeBlendTime, KINDA_SMALL_NUMBER), 0.f, 1.f);+ SmoothedEyeHeight = FMath::Lerp(SmoothedEyeHeight, UprightEye, Blend);+ }+ const float Lean = Movement->GetLean();+ // The eye in the capsule's frame: one formula for the camera, the bone and the bot's eye.+ const FVector Eye = Movement->GetEyeOffset(SmoothedEyeHeight, Lean, SmoothedProneAlpha) - FVector(0.f, 0.f, HalfHeight);++ ProneBody->SetCollisionEnabled(bProne ? ECollisionEnabled::QueryOnly : ECollisionEnabled::NoCollision);++ USkeletalMeshComponent* Body = GetMesh();+ const bool bAnimated = Body && Body->GetAnimInstance();+ if (bPlaceholderPose && Body && !bAnimated)+ {+ const FQuat Upright = MeshBaseRotation.Quaternion();+ // Lying face down, head forward: mesh up (+Z) along the facing, mesh front (+Y) down, the+ // body raised toward the head so the feet rest on the floor and the eye sits at its height.+ FQuat Lying = FRotationMatrix::MakeFromYZ(FVector(0.f, 0.f, -1.f), FVector(1.f, 0.f, 0.f)).ToQuat();+ if (bHasCameraBone)+ {+ const float Rise = FMath::Clamp((Tuning.ProneEyeHeight * 100.f - ProneFeetLift + CameraBoneLocal.Y) / CameraBoneLocal.Z, -0.5f, 0.5f);+ Lying = FRotator(FMath::RadiansToDegrees(FMath::Asin(Rise)), 0.f, 0.f).Quaternion() * Lying; // head end up+ }+ const FQuat Pose = FQuat::Slerp(Upright, Lying, SmoothedProneAlpha);+ // Lean rolls the whole placeholder; > 0 moves the head to the right.+ const float Roll = FMath::DegreesToRadians(Lean * Tuning.LeanRollDeg) * (1.f - SmoothedProneAlpha);+ const FQuat LeanQuat(FVector::ForwardVector, -Roll);+ const float SlideTilt = Stance == EVerseStance::Slide ? FMath::DegreesToRadians(-30.f) : 0.f;+ const FQuat SlideQuat(FVector::RightVector, SlideTilt);+ const FQuat Rotation = SlideQuat * LeanQuat * Pose;+ // The placeholder is never scaled: a component scale change rescales the physics bodies+ // differently from their creation (bone scale), so the hit bodies would change size with+ // the stance. Crouching lowers the whole placeholder instead.+ const FVector Scale(1.f);+ FVector Location;+ if (bHasCameraBone)+ {+ // The mesh goes where its Camera bone lands exactly on the eye.+ Location = Eye - Rotation.RotateVector(CameraBoneLocal);+ }+ else+ {+ const bool bLow = Stance == EVerseStance::Crouch || Stance == EVerseStance::Slide;+ const FVector UprightLocation(0.f, 0.f, -HalfHeight - (bLow ? (Tuning.StandEyeHeight - Tuning.CrouchEyeHeight) * 100.f : 0.f));+ const FVector LyingLocation(Tuning.ProneRadius * 200.f - Tuning.ProneBodyLength * 100.f, 0.f, -HalfHeight + 15.f);+ Location = FMath::Lerp(UprightLocation, LyingLocation, SmoothedProneAlpha);+ }+ const FRotator Rotator = Rotation.Rotator();+ if (!Body->GetRelativeScale3D().Equals(Scale, 0.0001))+ {+ Body->SetRelativeScale3D(Scale);+ }+ if (!Body->GetRelativeLocation().Equals(Location, 0.001) || !Body->GetRelativeRotation().Equals(Rotator, 0.001))+ {+ CacheInitialMeshOffset(Location, Rotator);+ Body->SetRelativeLocationAndRotation(Location, Rotator, false, nullptr, ETeleportType::TeleportPhysics);+ }+ }++ // The camera sits on the Camera bone: an animated mesh (WP13) moves the bone, the placeholder+ // pose puts it on the eye above.+ if (bAnimated && bHasCameraBone)+ {+ FirstPersonCamera->SetWorldLocation(Body->GetSocketLocation(CameraBoneName));+ }+ else+ {+ FirstPersonCamera->SetRelativeLocation(Eye);+ }+ const FRotator Aim = GetAimRotation();+ FirstPersonCamera->SetWorldRotation(FRotator(Aim.Pitch, Aim.Yaw, Lean * Tuning.LeanRollDeg));+}++FVector AVerseCharacter::GetCameraBoneLocation() const+{+ const USkeletalMeshComponent* Body = GetMesh();+ if (Body && bHasCameraBone && Body->GetBoneIndex(CameraBoneName) != INDEX_NONE)+ {+ return Body->GetSocketLocation(CameraBoneName);+ }+ return FirstPersonCamera->GetComponentLocation();+}++FVector AVerseCharacter::GetEyeLocation() const+{+ return FirstPersonCamera->GetComponentLocation();+}++FRotator AVerseCharacter::GetEyeRotation() const+{+ return FirstPersonCamera->GetComponentRotation();+}++void AVerseCharacter::GetActorEyesViewPoint(FVector& OutLocation, FRotator& OutRotation) const+{+ OutLocation = GetEyeLocation();+ OutRotation = GetAimRotation();+}++FRotator AVerseCharacter::GetAimRotation() const+{+ // Not GetBaseAimRotation: that asks GetActorEyesViewPoint, which asks back here.+ if (Controller)+ {+ return Controller->GetControlRotation();+ }+ FRotator Aim = GetActorRotation();+ Aim.Pitch = FRotator::NormalizeAxis(float(GetRemoteViewPitch()) * 360.f / 65536.f);+ return Aim;+}diff --git a/unreal/Verse/Source/VerseMovement/Private/VerseCharacterMovement.cpp b/unreal/Verse/Source/VerseMovement/Private/VerseCharacterMovement.cppnew file mode 100644index 0000000000..a019a59e6d--- /dev/null+++ b/unreal/Verse/Source/VerseMovement/Private/VerseCharacterMovement.cpp@@ -0,0 +1,1588 @@+#include "VerseCharacterMovement.h"++#include "Components/CapsuleComponent.h"+#include "Engine/World.h"+#include "Events/VerseEventHub.h"+#include "GameFramework/Controller.h"+#include "GameFramework/PlayerState.h"+#include "GameFramework/RootMotionSource.h"+#include "HAL/PlatformTime.h"+#include "PhysicalMaterials/PhysicalMaterial.h"+#include "VerseCharacter.h"+#include "VerseGameplayTags.h"+#include "VerseLog.h"+#include "VerseMovementNetworking.h"++namespace+{+ const FName MantleRiseSource(TEXT("VerseMantleRise"));+ const FName MantleMoveSource(TEXT("VerseMantleMove"));+ constexpr int16 NoClientLean = -128;+ /** Lean steps (of 127) within which the server adopts the client's lean. */+ constexpr int32 LeanAdoptTolerance = 8;+ /** Prone turn cap slack: compressed rotations and timestamps of an honest client stay inside it. */+ constexpr float ProneTurnSlack = 1.05f;+ constexpr float ProneTurnSlackDeg = 0.05f;+ /** The prone body constraint ignores geometry below this height (floor, low steps). */+ constexpr float ProneBodyFloorGap = 10.f;+ /** Seconds the server waits for a client to apply a correction before checking its moves again. */+ constexpr double CorrectionAckTimeout = 0.5;+ /** Sphere radius of the mantle top probes. */+ constexpr float ProbeRadius = 4.f;+ constexpr float WallProbeRadius = 10.f;+}++// ---------------------------------------------------------------------------------------------+// Net stats++int32 FVerseMovementNetStats::Total() const+{+ int32 Sum = 0;+ for (int32 Count : Corrections)+ {+ Sum += Count;+ }+ return Sum;+}++FString FVerseMovementNetStats::ToJson() const+{+ FString Kinds;+ const UEnum* Enum = StaticEnum<EVerseMoveKind>();+ for (int32 Index = 0; Index < int32(EVerseMoveKind::Count); ++Index)+ {+ Kinds += FString::Printf(TEXT("%s\"%s\": %d"), Index ? TEXT(", ") : TEXT(""),+ *Enum->GetNameStringByValue(Index).ToLower(), Corrections[Index]);+ }+ return FString::Printf(TEXT("{\"corrections_total\": %d, \"corrections\": {%s}, \"server_moves\": %d, \"lean_mismatches\": %d, \"lean_sim_diffs\": %d, \"yaw_clamps\": %d, \"mantle_syncs\": %d, \"mantles_declined\": %d}"),+ Total(), *Kinds, ServerMoves, LeanMismatches, LeanSimDiffs, YawClamps, MantleSyncs, MantlesDeclined);+}++// ---------------------------------------------------------------------------------------------+// Construction and tuning++UVerseCharacterMovement::UVerseCharacterMovement(const FObjectInitializer& ObjectInitializer)+ : Super(ObjectInitializer)+{+ TuningValues = FVerseMovementTuningValues();+ // Stance and capsule heights are ours; the stock crouch path stays off (see SetBodyShape).+ GetNavAgentPropertiesRef().bCanCrouch = false;+ GetNavAgentPropertiesRef().bCanJump = true;+ bOrientRotationToMovement = false;+ bUseControllerDesiredRotation = false;+ SetCrouchedHalfHeight(TuningValues.CrouchHalfHeightCm());+ MaxStepHeight = 45.f;+ SetWalkableFloorAngle(44.765f);+ AirControl = 0.25f;+ bCanWalkOffLedgesWhenCrouching = true;+ MoveDataContainer = MakeUnique<FVerseCharacterNetworkMoveDataContainer>();+ SetNetworkMoveDataContainer(*MoveDataContainer);+ MoveResponseContainer = MakeUnique<FVerseMoveResponseDataContainer>();+ SetMoveResponseDataContainer(*MoveResponseContainer);+ ApplyTuningToMovement();+}++void UVerseCharacterMovement::InitializeComponent()+{+ Super::InitializeComponent();+ if (!TuningAsset)+ {+ TuningAsset = LoadObject<UVerseMovementTuning>(nullptr, TEXT("/Game/Verse/Movement/DA_MovementTuning.DA_MovementTuning"),+ nullptr, LOAD_NoWarn | LOAD_Quiet);+ }+ SetTuning(TuningAsset ? TuningAsset->Values : UVerseMovementTuning::GetDefaultTuning()->Values);+}++void UVerseCharacterMovement::SetTuning(const FVerseMovementTuningValues& Values)+{+ TuningValues = Values;+ ApplyTuningToMovement();+ if (UpdatedComponent)+ {+ SetBodyShape(BodyShape, false);+ }+}++void UVerseCharacterMovement::ApplyTuningToMovement()+{+ MaxWalkSpeed = TuningValues.WalkSpeedCm();+ MaxWalkSpeedCrouched = TuningValues.CrouchSpeedCm();+ SetCrouchedHalfHeight(TuningValues.CrouchHalfHeightCm());+ const float Gravity = GetWorld() ? GetGravityZ() : -980.f;+ JumpZVelocity = TuningValues.JumpZVelocityCm(Gravity);+}++AVerseCharacter* UVerseCharacterMovement::GetVerseCharacter() const+{+ return Cast<AVerseCharacter>(CharacterOwner);+}++// ---------------------------------------------------------------------------------------------+// IVerseMovementQuery++EVerseStance UVerseCharacterMovement::GetStance() const+{+ if (CharacterOwner && CharacterOwner->GetLocalRole() == ROLE_SimulatedProxy)+ {+ if (const AVerseCharacter* Character = GetVerseCharacter())+ {+ return EVerseStance(Character->ReplicatedStance);+ }+ }+ return Stance;+}++bool UVerseCharacterMovement::IsSprinting() const+{+ if (CharacterOwner && CharacterOwner->GetLocalRole() == ROLE_SimulatedProxy)+ {+ const AVerseCharacter* Character = GetVerseCharacter();+ return Character && Character->bReplicatedSprinting;+ }+ if (!bWantsSprint || Stance != EVerseStance::Stand || MovementMode != MOVE_Walking || ProneTransitionRemaining > 0.f || MantleElapsed >= 0.f)+ {+ return false;+ }+ const FVector Accel = Acceleration.GetSafeNormal2D();+ if (Accel.IsNearlyZero() || !UpdatedComponent)+ {+ return false;+ }+ const FVector Facing = UpdatedComponent->GetForwardVector().GetSafeNormal2D();+ return (Accel | Facing) >= FMath::Cos(FMath::DegreesToRadians(TuningValues.SprintMaxAngleDeg)) - KINDA_SMALL_NUMBER;+}++bool UVerseCharacterMovement::IsAirborne() const+{+ return IsFalling();+}++bool UVerseCharacterMovement::IsMantling() const+{+ if (CharacterOwner && CharacterOwner->GetLocalRole() == ROLE_SimulatedProxy)+ {+ const AVerseCharacter* Character = GetVerseCharacter();+ return Character && Character->bReplicatedMantling;+ }+ return MantleElapsed >= 0.f;+}++float UVerseCharacterMovement::GetLean() const+{+ if (CharacterOwner && CharacterOwner->GetLocalRole() == ROLE_SimulatedProxy)+ {+ return IVerseMovementQuery::LeanFromQuantized(GetLeanQuantized());+ }+ return LeanValue;+}++int8 UVerseCharacterMovement::GetLeanQuantized() const+{+ if (CharacterOwner && CharacterOwner->GetLocalRole() == ROLE_SimulatedProxy)+ {+ const AVerseCharacter* Character = GetVerseCharacter();+ return Character ? Character->ReplicatedLean : 0;+ }+ return LeanQuantized;+}++float UVerseCharacterMovement::GetProneTransitionAlpha() const+{+ if (ProneTransitionRemaining <= 0.f)+ {+ return 0.f;+ }+ const float Total = bProneExiting ? TuningValues.ProneExitTime : TuningValues.ProneEnterTime;+ const float Alpha = 1.f - ProneTransitionRemaining / FMath::Max(Total, KINDA_SMALL_NUMBER);+ return bProneExiting ? -Alpha : Alpha;+}++EVerseMoveKind UVerseCharacterMovement::GetMoveKind() const+{+ if (IsMantling()) return EVerseMoveKind::Mantle;+ if (IsSliding()) return EVerseMoveKind::Slide;+ if (Stance == EVerseStance::Prone || ProneTransitionRemaining > 0.f) return EVerseMoveKind::Prone;+ if (IsFalling()) return EVerseMoveKind::Airborne;+ if (Stance == EVerseStance::Crouch) return EVerseMoveKind::Crouch;+ if (IsSprinting()) return EVerseMoveKind::Sprint;+ if (LeanQuantized != 0) return EVerseMoveKind::Lean;+ return EVerseMoveKind::Walk;+}++float UVerseCharacterMovement::GetTargetEyeHeight() const+{+ switch (GetStance())+ {+ case EVerseStance::Crouch:+ case EVerseStance::Slide:+ return TuningValues.CrouchEyeHeight * 100.f;+ case EVerseStance::Prone:+ return TuningValues.ProneEyeHeight * 100.f;+ default:+ return TuningValues.StandEyeHeight * 100.f;+ }+}++// ---------------------------------------------------------------------------------------------+// Body shapes++float UVerseCharacterMovement::HalfHeightFor(EVerseBodyShape Shape) const+{+ switch (Shape)+ {+ case EVerseBodyShape::Crouch: return TuningValues.CrouchHalfHeightCm();+ case EVerseBodyShape::Prone: return TuningValues.ProneHalfHeightCm();+ default: return TuningValues.StandHalfHeightCm();+ }+}++float UVerseCharacterMovement::RadiusFor(EVerseBodyShape Shape) const+{+ return Shape == EVerseBodyShape::Prone ? TuningValues.ProneRadius * 100.f : TuningValues.CapsuleRadius * 100.f;+}++FVector UVerseCharacterMovement::GetFeetLocation() const+{+ if (!CharacterOwner || !CharacterOwner->GetCapsuleComponent())+ {+ return FVector::ZeroVector;+ }+ const UCapsuleComponent* Capsule = CharacterOwner->GetCapsuleComponent();+ return Capsule->GetComponentLocation() - FVector(0.f, 0.f, Capsule->GetScaledCapsuleHalfHeight());+}++bool UVerseCharacterMovement::BodyShapeFits(EVerseBodyShape Shape, const FVector& FeetLocation) const+{+ if (!CharacterOwner || !GetWorld())+ {+ return false;+ }+ const float HalfHeight = HalfHeightFor(Shape);+ const float Radius = RadiusFor(Shape);+ FCollisionQueryParams Params(SCENE_QUERY_STAT(VerseBodyFit), false, CharacterOwner);+ FCollisionResponseParams Response;+ InitCollisionParams(Params, Response);+ const FCollisionShape Capsule = FCollisionShape::MakeCapsule(Radius - 1.f, HalfHeight - 1.f);+ const FVector Center = FeetLocation + FVector(0.f, 0.f, HalfHeight + 1.5f);+ return !GetWorld()->OverlapBlockingTestByChannel(Center, FQuat::Identity, UpdatedComponent->GetCollisionObjectType(), Capsule, Params, Response);+}++bool UVerseCharacterMovement::SetBodyShape(EVerseBodyShape Shape, bool bCheckFit, bool bKeepFeet)+{+ if (!CharacterOwner || !CharacterOwner->GetCapsuleComponent())+ {+ BodyShape = Shape;+ return true;+ }+ UCapsuleComponent* Capsule = CharacterOwner->GetCapsuleComponent();+ const float OldHalf = Capsule->GetUnscaledCapsuleHalfHeight();+ const float NewHalf = HalfHeightFor(Shape);+ const float NewRadius = RadiusFor(Shape);+ const bool bSame = FMath::IsNearlyEqual(OldHalf, NewHalf) && FMath::IsNearlyEqual(Capsule->GetUnscaledCapsuleRadius(), NewRadius);+ const FVector Feet = GetFeetLocation();+ if (!bSame && bCheckFit && NewHalf > OldHalf + KINDA_SMALL_NUMBER && !BodyShapeFits(Shape, Feet))+ {+ return false;+ }+ BodyShape = Shape;+ if (bSame)+ {+ return true;+ }+ Capsule->SetCapsuleSize(NewRadius, NewHalf, true);+ // Keep the feet planted. Simulated proxies get their location from the server.+ if (bKeepFeet && CharacterOwner->GetLocalRole() != ROLE_SimulatedProxy)+ {+ UpdatedComponent->SetWorldLocation(Feet + FVector(0.f, 0.f, NewHalf), false, nullptr, ETeleportType::TeleportPhysics);+ bForceNextFloorCheck = true;+ }+ if (AVerseCharacter* Character = GetVerseCharacter())+ {+ Character->UpdateBodyPose(0.f);+ }+ return true;+}++void UVerseCharacterMovement::ApplyReplicatedStance(EVerseStance NewStance)+{+ const EVerseBodyShape Shape = NewStance == EVerseStance::Prone ? EVerseBodyShape::Prone+ : (NewStance == EVerseStance::Stand ? EVerseBodyShape::Stand : EVerseBodyShape::Crouch);+ SetBodyShape(Shape, false);+}++bool UVerseCharacterMovement::CanEnterProne() const+{+ if (!CharacterOwner || !GetWorld() || !UpdatedComponent)+ {+ return false;+ }+ const FVector Feet = GetFeetLocation();+ const FVector Forward = UpdatedComponent->GetForwardVector().GetSafeNormal2D();+ const float Length = TuningValues.ProneBodyLength * 100.f;+ const float Clearance = TuningValues.ProneMinClearance * 100.f;+ const float HeadForward = TuningValues.ProneRadius * 100.f * 2.f;+ // The body lies from HeadForward in front of the feet point back over Length.+ const float CenterOffset = HeadForward - Length * 0.5f;+ const FVector Center = Feet + Forward * CenterOffset + FVector(0.f, 0.f, 2.f + Clearance * 0.5f);+ const FVector Extent(Length * 0.5f, TuningValues.ProneBodyWidth * 50.f, Clearance * 0.5f - 0.5f);+ const FQuat Rotation = Forward.ToOrientationQuat();+ FCollisionQueryParams Params(SCENE_QUERY_STAT(VerseProneFit), false, CharacterOwner);+ FCollisionResponseParams Response;+ InitCollisionParams(Params, Response);+ const ECollisionChannel Channel = UpdatedComponent->GetCollisionObjectType();+ if (GetWorld()->OverlapBlockingTestByChannel(Center, Rotation, Channel, FCollisionShape::MakeBox(Extent), Params, Response))+ {+ return false;+ }+ // Floor under both ends: no prone body hanging over a ledge.+ for (const float Along : {HeadForward, HeadForward - Length + 10.f})+ {+ const FVector Top = Feet + Forward * Along + FVector(0.f, 0.f, 20.f);+ FHitResult Floor;+ if (!GetWorld()->LineTraceSingleByChannel(Floor, Top, Top - FVector(0.f, 0.f, 50.f), Channel, Params, Response))+ {+ return false;+ }+ }+ return true;+}++bool UVerseCharacterMovement::ProneBodyBlocked(const FVector& FeetLocation, float Yaw) const+{+ if (!CharacterOwner || !GetWorld() || !UpdatedComponent)+ {+ return false;+ }+ const FVector Forward = FRotator(0.f, Yaw, 0.f).Vector();+ const float Length = TuningValues.ProneBodyLength * 100.f;+ const float HeadForward = TuningValues.ProneRadius * 100.f * 2.f;+ const float Top = TuningValues.ProneMinClearance * 100.f - 2.f;+ const FVector Center = FeetLocation + Forward * (HeadForward - Length * 0.5f) + FVector(0.f, 0.f, (ProneBodyFloorGap + Top) * 0.5f);+ const FVector Extent(Length * 0.5f - 1.f, TuningValues.ProneBodyWidth * 50.f - 1.f, (Top - ProneBodyFloorGap) * 0.5f);+ FCollisionQueryParams Params(SCENE_QUERY_STAT(VerseProneBody), false, CharacterOwner);+ FCollisionResponseParams Response;+ InitCollisionParams(Params, Response);+ // World geometry only: other pawns sit at different places on the client (simulated proxies)+ // and on the server, so a pawn contact would make the prediction disagree.+ Response.CollisionResponse.SetResponse(ECC_Pawn, ECR_Ignore);+ return GetWorld()->OverlapBlockingTestByChannel(Center, Forward.ToOrientationQuat(), UpdatedComponent->GetCollisionObjectType(),+ FCollisionShape::MakeBox(Extent), Params, Response);+}++void UVerseCharacterMovement::SetActorYaw(float Yaw, bool bAlsoControl)+{+ if (!UpdatedComponent)+ {+ return;+ }+ FRotator Rotation = UpdatedComponent->GetComponentRotation();+ Rotation.Yaw = Yaw;+ UpdatedComponent->SetWorldRotation(Rotation, false, nullptr, ETeleportType::TeleportPhysics);+ AController* Controller = CharacterOwner ? CharacterOwner->GetController() : nullptr;+ if (bAlsoControl && Controller && CharacterOwner->IsLocallyControlled() && !CharacterOwner->bClientUpdating)+ {+ FRotator Control = Controller->GetControlRotation();+ Control.Yaw = Yaw;+ Controller->SetControlRotation(Control);+ }+}++void UVerseCharacterMovement::ApplyProneTurnCap(float DeltaSeconds)+{+ if (!bHasLastMoveYaw || !UpdatedComponent || !(Stance == EVerseStance::Prone || ProneTransitionRemaining > 0.f))+ {+ return;+ }+ const float Delta = FRotator::NormalizeAxis(UpdatedComponent->GetComponentRotation().Yaw - LastMoveYaw);+ const float Cap = TuningValues.ProneTurnCapDegPerSec * DeltaSeconds;+ if (FMath::Abs(Delta) <= Cap * ProneTurnSlack + ProneTurnSlackDeg)+ {+ return;+ }+ SetActorYaw(FRotator::NormalizeAxis(LastMoveYaw + FMath::Sign(Delta) * Cap), true);+ if (CharacterOwner->GetLocalRole() == ROLE_Authority && CharacterOwner->GetRemoteRole() == ROLE_AutonomousProxy)+ {+ // The client turned faster than prone allows: the server keeps its yaw and corrects it.+ ++NetStats.YawClamps;+ if (FNetworkPredictionData_Server_Character* ServerData = GetPredictionData_Server_Character())+ {+ ServerData->bForceClientUpdate = true;+ }+ static_cast<FVerseMoveResponseDataContainer&>(*MoveResponseContainer).bYawClampedPending = true;+ }+}++void UVerseCharacterMovement::ConstrainProneBody()+{+ if (Stance != EVerseStance::Prone || !bHasLastMoveYaw || !UpdatedComponent)+ {+ return;+ }+ const FVector Feet = GetFeetLocation();+ const float Yaw = UpdatedComponent->GetComponentRotation().Yaw;+ if (!ProneBodyBlocked(Feet, Yaw))+ {+ return;+ }+ const FVector StartFeet = MoveStartLocation - FVector(0.f, 0.f, CharacterOwner->GetCapsuleComponent()->GetScaledCapsuleHalfHeight());+ if (ProneBodyBlocked(StartFeet, LastMoveYaw))+ {+ return; // blocked before this move (something moved into the body): never pin the pawn+ }+ // Undo the turn first, then the move, then both.+ if (!ProneBodyBlocked(Feet, LastMoveYaw))+ {+ SetActorYaw(LastMoveYaw, true);+ return;+ }+ UpdatedComponent->SetWorldLocation(MoveStartLocation, false, nullptr, ETeleportType::TeleportPhysics);+ Velocity = FVector::ZeroVector;+ bForceNextFloorCheck = true;+ if (ProneBodyBlocked(StartFeet, Yaw))+ {+ SetActorYaw(LastMoveYaw, true);+ }+}++// ---------------------------------------------------------------------------------------------+// Speeds and jump++float UVerseCharacterMovement::GetMaxSpeed() const+{+ if (IsSliding())+ {+ return TuningValues.SlideBoostSpeed * 100.f;+ }+ if (MovementMode != MOVE_Walking && MovementMode != MOVE_NavWalking)+ {+ return Super::GetMaxSpeed();+ }+ if (ProneTransitionRemaining > 0.f)+ {+ return 0.f;+ }+ switch (Stance)+ {+ case EVerseStance::Prone: return TuningValues.ProneSpeedCm();+ case EVerseStance::Crouch: return TuningValues.CrouchSpeedCm();+ default: return IsSprinting() ? TuningValues.SprintSpeedCm() : TuningValues.WalkSpeedCm();+ }+}++float UVerseCharacterMovement::GetMaxBrakingDeceleration() const+{+ return IsSliding() ? 0.f : Super::GetMaxBrakingDeceleration();+}++bool UVerseCharacterMovement::CanAttemptJump() const+{+ if (Stance == EVerseStance::Prone || ProneTransitionRemaining > 0.f || MantleElapsed >= 0.f)+ {+ return false;+ }+ return IsJumpAllowed() && (IsMovingOnGround() || IsFalling() || IsSliding());+}++bool UVerseCharacterMovement::DoJump(bool bReplayingMoves, float DeltaTime)+{+ if (IsSliding())+ {+ EndSlide(false);+ }+ return Super::DoJump(bReplayingMoves, DeltaTime);+}++bool UVerseCharacterMovement::CanCrouchInCurrentState() const+{+ // The stock crouch path is unused: VerseMovement owns the capsule heights.+ return false;+}++// ---------------------------------------------------------------------------------------------+// Per-move state++void UVerseCharacterMovement::UpdateFromCompressedFlags(uint8 Flags)+{+ Super::UpdateFromCompressedFlags(Flags);+ bWantsSprint = (Flags & VerseMoveFlags::Sprint) != 0;+ bWantsProne = (Flags & VerseMoveFlags::Prone) != 0;+ bWantsMantle = (Flags & VerseMoveFlags::Mantle) != 0;+}++void UVerseCharacterMovement::UpdateCharacterStateBeforeMovement(float DeltaSeconds)+{+ Super::UpdateCharacterStateBeforeMovement(DeltaSeconds);+ if (!CharacterOwner || CharacterOwner->GetLocalRole() == ROLE_SimulatedProxy)+ {+ return;+ }+ ApplyProneTurnCap(DeltaSeconds);+ MoveStartLocation = UpdatedComponent->GetComponentLocation();+ if (!IsSliding() && SlideCooldownRemaining > 0.f)+ {+ SlideCooldownRemaining = FMath::Max(0.f, SlideCooldownRemaining - DeltaSeconds);+ }+ if (!bWantsMantle)+ {+ bMantleLatched = false;+ }+ if (MantleElapsed >= 0.f)+ {+ UpdateMantle(DeltaSeconds);+ }+ else+ {+ if (bWantsMantle && !bMantleLatched && Stance != EVerseStance::Prone && ProneTransitionRemaining <= 0.f+ && (IsMovingOnGround() || IsFalling() || IsSliding()))+ {+ TryStartMantle();+ }+ if (MantleElapsed < 0.f)+ {+ if (bWantsToCrouch && !bPrevWantsCrouch && !IsSliding())+ {+ TryStartSlide();+ }+ UpdateStance(DeltaSeconds);+ }+ }+ bPrevWantsCrouch = bWantsToCrouch;+ UpdateLean(DeltaSeconds);+}++void UVerseCharacterMovement::UpdateCharacterStateAfterMovement(float DeltaSeconds)+{+ Super::UpdateCharacterStateAfterMovement(DeltaSeconds);+ if (!CharacterOwner || CharacterOwner->GetLocalRole() == ROLE_SimulatedProxy)+ {+ return;+ }+ if (MantleElapsed >= 0.f)+ {+ MantleElapsed += DeltaSeconds;+ if (MantleElapsed >= MantlePlanDuration - 1e-4f)+ {+ FinishMantle();+ }+ }+ ConstrainProneBody();+ LastMoveYaw = UpdatedComponent->GetComponentRotation().Yaw;+ bHasLastMoveYaw = true;+ if (CharacterOwner->HasAuthority())+ {+ if (AVerseCharacter* Character = GetVerseCharacter())+ {+ Character->SetReplicatedMovementState(Stance, LeanQuantized, IsSprinting(), MantleElapsed >= 0.f);+ }+ }+}++void UVerseCharacterMovement::UpdateStance(float DeltaSeconds)+{+ if (ProneTransitionRemaining > 0.f)+ {+ ProneTransitionRemaining = FMath::Max(0.f, ProneTransitionRemaining - DeltaSeconds);+ if (ProneTransitionRemaining > 0.f)+ {+ return;+ }+ bProneExiting = false;+ }+ if (IsSliding())+ {+ return;+ }+ const bool bOnGround = IsMovingOnGround();+ if (Stance == EVerseStance::Prone)+ {+ if (bWantsProne)+ {+ return;+ }+ // Leave prone: stand if it fits, else crouch, else stay down.+ const EVerseStance Target = bWantsToCrouch ? EVerseStance::Crouch : EVerseStance::Stand;+ if (Target == EVerseStance::Stand && SetBodyShape(EVerseBodyShape::Stand, true))+ {+ Stance = EVerseStance::Stand;+ }+ else if (SetBodyShape(EVerseBodyShape::Crouch, true))+ {+ Stance = EVerseStance::Crouch;+ }+ else+ {+ return;+ }+ ProneTransitionRemaining = TuningValues.ProneExitTime;+ bProneExiting = true;+ return;+ }+ if (bWantsProne)+ {+ if (bOnGround && CanEnterProne())+ {+ SetBodyShape(EVerseBodyShape::Prone, false);+ Stance = EVerseStance::Prone;+ ProneTransitionRemaining = TuningValues.ProneEnterTime;+ bProneExiting = false;+ Velocity = FVector::ZeroVector;+ return;+ }+ }+ const bool bWantsLow = bWantsToCrouch || bWantsProne;+ if (bWantsLow && Stance == EVerseStance::Stand)+ {+ SetBodyShape(EVerseBodyShape::Crouch, false);+ Stance = EVerseStance::Crouch;+ }+ else if (!bWantsLow && Stance == EVerseStance::Crouch)+ {+ if (SetBodyShape(EVerseBodyShape::Stand, true))+ {+ Stance = EVerseStance::Stand;+ }+ }+}++// ---------------------------------------------------------------------------------------------+// Lean++FVector UVerseCharacterMovement::GetEyeOffset(float EyeHeight, float Lean, float ProneAlpha) const+{+ const float RollMax = FMath::DegreesToRadians(FMath::Max(TuningValues.LeanRollDeg, 0.1f));+ // Distance from the roll pivot to the eye, so a full lean moves the eye LeanCameraOffset sideways.+ const float Reach = TuningValues.LeanCameraOffset * 100.f / FMath::Sin(RollMax);+ const float Roll = RollMax * FMath::Clamp(Lean, -1.f, 1.f);+ const FVector Upright(0.f, Reach * FMath::Sin(Roll), EyeHeight - Reach * (1.f - FMath::Cos(Roll)));+ // Lying: the head (and its Camera bone) sits in front of the prone capsule, the body behind it.+ const FVector Lying(TuningValues.ProneRadius * 200.f - 10.f, 0.f, TuningValues.ProneEyeHeight * 100.f);+ return FMath::Lerp(Upright, Lying, FMath::Clamp(ProneAlpha, 0.f, 1.f));+}++FVector UVerseCharacterMovement::GetUnleanedEyeLocation() const+{+ return GetLeanedEyeLocation(0.f);+}++FVector UVerseCharacterMovement::GetLeanedEyeLocation(float Lean) const+{+ const bool bProne = GetStance() == EVerseStance::Prone;+ const FVector Offset = GetEyeOffset(GetTargetEyeHeight(), bProne ? 0.f : Lean, bProne ? 1.f : 0.f);+ const FRotator Yaw(0.f, UpdatedComponent ? UpdatedComponent->GetComponentRotation().Yaw : 0.f, 0.f);+ return GetFeetLocation() + Yaw.RotateVector(Offset);+}++float UVerseCharacterMovement::ComputeLeanAllowance(float Side) const+{+ if (!GetWorld() || !UpdatedComponent || FMath::IsNearlyZero(Side))+ {+ return 1.f;+ }+ const float Radius = TuningValues.LeanCameraClearance * 100.f;+ const FVector From = GetUnleanedEyeLocation();+ const FVector To = GetLeanedEyeLocation(FMath::Sign(Side));+ const float Offset = FMath::Max(float(FVector::Dist(From, To)), 1.f);+ FCollisionQueryParams Params(SCENE_QUERY_STAT(VerseLeanWall), false, CharacterOwner);+ FHitResult Hit;+ if (!GetWorld()->SweepSingleByChannel(Hit, From, To, FQuat::Identity, ECC_Visibility, FCollisionShape::MakeSphere(Radius), Params))+ {+ return 1.f;+ }+ if (Hit.bStartPenetrating)+ {+ return 0.f;+ }+ return FMath::Clamp((Hit.Distance - 1.f) / Offset, 0.f, 1.f);+}++bool UVerseCharacterMovement::CanLeanNow() const+{+ return (Stance == EVerseStance::Stand || Stance == EVerseStance::Crouch) && !IsSprinting() && MantleElapsed < 0.f && ProneTransitionRemaining <= 0.f;+}++void UVerseCharacterMovement::UpdateLean(float DeltaSeconds)+{+ const bool bAllowed = CanLeanNow();+ const float Target = bAllowed ? IVerseMovementQuery::LeanFromQuantized(LeanTargetQuantized) : 0.f;+ const float Current = LeanValue;+ const float Step = DeltaSeconds / FMath::Max(TuningValues.LeanEnterTime, KINDA_SMALL_NUMBER);+ float Next = FMath::Abs(Target - Current) <= Step ? Target : Current + FMath::Sign(Target - Current) * Step;+ if (!FMath::IsNearlyZero(Next))+ {+ const float Allowance = ComputeLeanAllowance(Next);+ Next = FMath::Sign(Next) * FMath::Min(FMath::Abs(Next), Allowance);+ }+ LeanValue = FMath::Clamp(Next, -1.f, 1.f);+ LeanQuantized = IVerseMovementQuery::QuantizeLean(LeanValue);+}++// ---------------------------------------------------------------------------------------------+// Slide (MOVE_Custom / CMOVE_Slide)++bool UVerseCharacterMovement::TryStartSlide()+{+ if (Stance != EVerseStance::Stand || !IsSprinting() || SlideCooldownRemaining > 0.f)+ {+ return false;+ }+ const float Speed = Velocity.Size2D();+ if (Speed < TuningValues.SlideMinEntrySpeed * 100.f - 0.5f)+ {+ return false;+ }+ SetBodyShape(EVerseBodyShape::Crouch, false);+ Stance = EVerseStance::Slide;+ SlideElapsed = 0.f;+ Velocity = Velocity.GetSafeNormal2D() * FMath::Max(Speed, TuningValues.SlideBoostSpeed * 100.f);+ SetMovementMode(MOVE_Custom, uint8(EVerseCustomMove::Slide));+ EmitNoise(VerseTags::Noise_Move_Slide, GetFeetLocation());+ return true;+}++void UVerseCharacterMovement::EndSlide(bool bToFalling)+{+ if (!IsSliding())+ {+ return;+ }+ SlideCooldownRemaining = TuningValues.SlideCooldown;+ Stance = EVerseStance::Crouch;+ SetMovementMode(bToFalling ? MOVE_Falling : MOVE_Walking);+}++void UVerseCharacterMovement::PhysCustom(float DeltaTime, int32 Iterations)+{+ if (CustomMovementMode == uint8(EVerseCustomMove::Slide))+ {+ PhysSlide(DeltaTime, Iterations);+ return;+ }+ Super::PhysCustom(DeltaTime, Iterations);+}++void UVerseCharacterMovement::PhysSlide(float DeltaTime, int32 Iterations)+{+ if (DeltaTime < MIN_TICK_TIME)+ {+ return;+ }+ SlideElapsed += DeltaTime;+ const float CrouchCm = TuningValues.CrouchSpeedCm();+ const float BoostCm = TuningValues.SlideBoostSpeed * 100.f;+ const float Alpha = FMath::Clamp(SlideElapsed / FMath::Max(TuningValues.SlideMaxDuration, KINDA_SMALL_NUMBER), 0.f, 1.f);+ const float Cap = CrouchCm + (BoostCm - CrouchCm) * FMath::Pow(1.f - Alpha, FMath::Max(TuningValues.SlideDecayExponent, 0.1f));+ FVector Direction = Velocity.GetSafeNormal2D();+ if (Direction.IsNearlyZero())+ {+ EndSlide(false);+ return;+ }+ const float Speed = FMath::Min(Velocity.Size2D(), Cap);+ Velocity = Direction * Speed;++ const FVector OldLocation = UpdatedComponent->GetComponentLocation();+ FVector Delta = Velocity * DeltaTime;+ if (CurrentFloor.IsWalkableFloor())+ {+ Delta = ComputeGroundMovementDelta(Delta, CurrentFloor.HitResult, CurrentFloor.bLineTrace);+ }+ FHitResult Hit(1.f);+ SafeMoveUpdatedComponent(Delta, UpdatedComponent->GetComponentQuat(), true, Hit);+ if (Hit.IsValidBlockingHit() && Hit.Time < 1.f)+ {+ const FVector Remaining = Delta * (1.f - Hit.Time);+ const bool bStepped = CanStepUp(Hit) && IsWalkable(Hit) == false && StepUp(-GetGravityDirection(), Remaining, Hit);+ if (!bStepped)+ {+ HandleImpact(Hit, DeltaTime, Delta);+ SlideAlongSurface(Remaining, 1.f, Hit.Normal, Hit, true);+ }+ }++ FindFloor(UpdatedComponent->GetComponentLocation(), CurrentFloor, false);+ if (!CurrentFloor.IsWalkableFloor())+ {+ EndSlide(true);+ return;+ }+ AdjustFloorHeight();+ SetBaseFromFloor(CurrentFloor);+ if (!bJustTeleported)+ {+ const FVector Moved = (UpdatedComponent->GetComponentLocation() - OldLocation) / DeltaTime;+ const float MovedSpeed = FMath::Min(Moved.Size2D(), Speed);+ Velocity = Moved.GetSafeNormal2D() * MovedSpeed;+ }+ if (Alpha >= 1.f || Velocity.Size2D() <= CrouchCm + 1.f || !bWantsToCrouch)+ {+ EndSlide(false);+ }+}++// ---------------------------------------------------------------------------------------------+// Mantle++bool UVerseCharacterMovement::FindMantle(FVerseMantlePlan& OutPlan) const+{+ if (!CharacterOwner || !GetWorld() || !UpdatedComponent)+ {+ return false;+ }+ const UWorld* World = GetWorld();+ const FVector Feet = GetFeetLocation();+ const FVector Forward = UpdatedComponent->GetForwardVector().GetSafeNormal2D();+ FCollisionQueryParams Params(SCENE_QUERY_STAT(VerseMantle), false, CharacterOwner);+ FCollisionResponseParams Response;+ InitCollisionParams(Params, Response);+ const ECollisionChannel Channel = UpdatedComponent->GetCollisionObjectType();+ const float MinHeight = TuningValues.MantleMinHeight * 100.f;+ const float MaxHeight = TuningValues.MantleHighMaxHeight * 100.f;+ const float Radius = TuningValues.CapsuleRadius * 100.f;++ // Heights count from the floor the person stands (or jumped) on, so a jump never stretches the range.+ float FloorZ = Feet.Z;+ if (!IsMovingOnGround() && !IsSliding())+ {+ FHitResult Floor;+ if (World->LineTraceSingleByChannel(Floor, Feet, Feet - FVector(0.f, 0.f, 250.f), Channel, Params, Response))+ {+ FloorZ = Floor.ImpactPoint.Z;+ }+ }++ // 1. A ledge face ahead, low enough to be under the shortest ledge's top.+ const FVector ProbeStart(Feet.X, Feet.Y, FMath::Max(FloorZ + MinHeight - 12.f, Feet.Z + WallProbeRadius + 2.f));+ const FVector ProbeEnd = ProbeStart + Forward * (Radius + TuningValues.MantleReach * 100.f);+ FHitResult Wall;+ if (!World->SweepSingleByChannel(Wall, ProbeStart, ProbeEnd, FQuat::Identity, Channel, FCollisionShape::MakeSphere(WallProbeRadius), Params, Response)+ || Wall.bStartPenetrating)+ {+ return false;+ }+ const FVector Normal = Wall.ImpactNormal.GetSafeNormal2D();+ if (Normal.IsNearlyZero() || Wall.ImpactNormal.Z > 0.7f+ || (Normal | -Forward) < FMath::Cos(FMath::DegreesToRadians(TuningValues.MantleMaxFaceAngleDeg)))+ {+ return false;+ }+ const FVector Into = -Normal;+ const FVector Face = Wall.ImpactPoint;+ const FVector Inside = Face + Into * 15.f;++ // 2. The top: trace down from the highest free start above the face. A wall taller than the+ // mantle range has no free start, so it never mantles; a breach has one inside its opening.+ bool bFound = false;+ float LedgeZ = 0.f;+ for (float StartZ = FloorZ + MaxHeight + ProbeRadius + 1.f; StartZ >= FloorZ + MinHeight; StartZ -= 40.f)+ {+ const FVector Start(Inside.X, Inside.Y, StartZ);+ if (World->OverlapBlockingTestByChannel(Start, FQuat::Identity, Channel, FCollisionShape::MakeSphere(ProbeRadius), Params, Response))+ {+ continue;+ }+ FHitResult Top;+ const FVector End(Inside.X, Inside.Y, FloorZ + MinHeight - 15.f);+ if (World->SweepSingleByChannel(Top, Start, End, FQuat::Identity, Channel, FCollisionShape::MakeSphere(ProbeRadius), Params, Response)+ && !Top.bStartPenetrating && Top.ImpactNormal.Z >= 0.7f)+ {+ LedgeZ = Top.ImpactPoint.Z;+ bFound = true;+ }+ break;+ }+ if (!bFound)+ {+ return false;+ }+ const float Height = LedgeZ - FloorZ;+ if (Height < MinHeight - 2.f || Height > MaxHeight + 0.5f)+ {+ return false;+ }++ // 3. Deep top or thin wall (vault through a breach or over a parapet).+ float Thickness = -1.f;+ {+ const FVector Back = Face + Into * 160.f + FVector(0.f, 0.f, LedgeZ - Face.Z - 8.f);+ const FVector BackEnd(Face.X, Face.Y, Back.Z);+ FHitResult FarFace;+ if (World->LineTraceSingleByChannel(FarFace, Back, BackEnd, Channel, Params, Response) && !FarFace.bStartPenetrating+ && (FarFace.ImpactNormal | Into) > 0.5f)+ {+ Thickness = (FarFace.ImpactPoint - Face) | Into;+ }+ }+ const bool bVault = Thickness > 0.f && Thickness < Radius * 2.f;+ const float Along = bVault ? Thickness + Radius + 8.f : Radius + 8.f;+ const FVector TargetXY = Face + Into * Along;++ // 4. The body that fits: standing, else crouched.+ const FVector StartCenter = UpdatedComponent->GetComponentLocation();+ for (const EVerseBodyShape Shape : {EVerseBodyShape::Stand, EVerseBodyShape::Crouch})+ {+ const float Half = HalfHeightFor(Shape);+ const float ShapeRadius = RadiusFor(Shape);+ const FVector Target(TargetXY.X, TargetXY.Y, LedgeZ + Half + 2.f);+ if (!BodyShapeFits(Shape, Target - FVector(0.f, 0.f, Half + 1.5f)))+ {+ continue;+ }+ const FVector Start(StartCenter.X, StartCenter.Y, Feet.Z + Half);+ const FVector Rise(StartCenter.X, StartCenter.Y, FMath::Max(Target.Z, Start.Z));+ const FCollisionShape Body = FCollisionShape::MakeCapsule(ShapeRadius - 2.f, Half - 2.f);+ FHitResult Block;+ if (World->SweepSingleByChannel(Block, Start, Rise, FQuat::Identity, Channel, Body, Params, Response)+ || World->SweepSingleByChannel(Block, Rise, Target, FQuat::Identity, Channel, Body, Params, Response))+ {+ continue;+ }+ OutPlan.Start = Start;+ OutPlan.Rise = Rise;+ OutPlan.Target = Target;+ OutPlan.LedgeHeight = Height;+ OutPlan.bHigh = Height > TuningValues.MantleLowMaxHeight * 100.f;+ OutPlan.Duration = OutPlan.bHigh ? TuningValues.MantleHighDuration : TuningValues.MantleLowDuration;+ OutPlan.bCrouched = Shape == EVerseBodyShape::Crouch;+ OutPlan.bVault = bVault;+ return true;+ }+ return false;+}++bool UVerseCharacterMovement::TryStartMantle()+{+ FVerseMantlePlan Plan;+ const bool bServerOfRemote = CharacterOwner && CharacterOwner->GetLocalRole() == ROLE_Authority+ && CharacterOwner->GetRemoteRole() == ROLE_AutonomousProxy;+ const FCharacterNetworkMoveData* Move = bServerOfRemote ? GetCurrentNetworkMoveData() : nullptr;+ if (!Move)+ {+ if (!FindMantle(Plan))+ {+ return false;+ }+ }+ else+ {+ // A remote client and the server sit up to ServerCorrectionToleranceCm apart, so the ledge+ // reach test can pass one move apart. Start the mantle in the move the client started it:+ // never before (the client may always decline), and from the client's location when the+ // server's own trace just misses. The server's geometry still validates the plan.+ const bool bClientMantles = (Move->MovementMode & 0x0F) == MOVE_Flying;+ if (!bClientMantles)+ {+ if (FindMantle(Plan))+ {+ ++NetStats.MantlesDeclined;+ }+ return false;+ }+ if (!FindMantle(Plan))+ {+ const FVector Own = UpdatedComponent->GetComponentLocation();+ if (!bHasServerLastClientLocation || FVector::DistSquared(Own, ServerLastClientLocation) > FMath::Square(ServerCorrectionToleranceCm))+ {+ return false;+ }+ UpdatedComponent->SetWorldLocation(ServerLastClientLocation, false, nullptr, ETeleportType::TeleportPhysics);+ if (!FindMantle(Plan))+ {+ UpdatedComponent->SetWorldLocation(Own, false, nullptr, ETeleportType::TeleportPhysics);+ return false;+ }+ ++NetStats.MantleSyncs;+ }+ }+ if (IsSliding())+ {+ EndSlide(false);+ }+ if (Plan.bCrouched)+ {+ SetBodyShape(EVerseBodyShape::Crouch, false);+ Stance = EVerseStance::Crouch;+ }+ bMantleLatched = true;+ MantleElapsed = 0.f;+ MantlePlanDuration = Plan.Duration;+ MantleRiseDuration = Plan.Duration * FMath::Clamp(TuningValues.MantleRiseFraction, 0.1f, 0.9f);+ MantleRise = Plan.Rise;+ MantleTarget = Plan.Target;+ bMantleVault = Plan.bVault;+ ++MantleCount;+ Velocity = FVector::ZeroVector;+ SetMovementMode(MOVE_Flying);+ ApplyMantleSource(UpdatedComponent->GetComponentLocation(), MantleRise, MantleRiseDuration);+ EmitNoise(VerseTags::Noise_Move_Mantle, GetFeetLocation());+ return true;+}++void UVerseCharacterMovement::ApplyMantleSource(const FVector& From, const FVector& To, float Duration)+{+ const bool bRise = MantleElapsed < MantleRiseDuration - 1e-4f;+ TSharedPtr<FRootMotionSource_MoveToForce> Source = MakeShared<FRootMotionSource_MoveToForce>();+ Source->InstanceName = bRise ? MantleRiseSource : MantleMoveSource;+ Source->AccumulateMode = ERootMotionAccumulateMode::Override;+ Source->Priority = 500;+ Source->StartLocation = From;+ Source->TargetLocation = To;+ Source->Duration = FMath::Max(Duration, 1e-3f);+ Source->bRestrictSpeedToExpected = true;+ Source->FinishVelocityParams.Mode = ERootMotionFinishVelocityMode::SetVelocity;+ Source->FinishVelocityParams.SetVelocity = FVector::ZeroVector;+ ApplyRootMotionSource(Source);+}++void UVerseCharacterMovement::UpdateMantle(float DeltaSeconds)+{+ if (MantleElapsed >= MantleRiseDuration - 1e-4f && GetRootMotionSource(MantleRiseSource).IsValid())+ {+ RemoveRootMotionSource(MantleRiseSource);+ ApplyMantleSource(UpdatedComponent->GetComponentLocation(), MantleTarget, MantlePlanDuration - MantleElapsed);+ }+ else if (MantleElapsed >= MantleRiseDuration - 1e-4f && !GetRootMotionSource(MantleMoveSource).IsValid())+ {+ // Replayed or restored mid-mantle without the second source: re-apply it.+ ApplyMantleSource(UpdatedComponent->GetComponentLocation(), MantleTarget, MantlePlanDuration - MantleElapsed);+ }+}++void UVerseCharacterMovement::FinishMantle()+{+ RemoveRootMotionSource(MantleRiseSource);+ RemoveRootMotionSource(MantleMoveSource);+ MantleElapsed = -1.f;+ const FVector Forward = UpdatedComponent->GetForwardVector().GetSafeNormal2D();+ if (bMantleVault)+ {+ SetMovementMode(MOVE_Falling);+ Velocity = Forward * 150.f;+ }+ else+ {+ Velocity = FVector::ZeroVector;+ SetMovementMode(MOVE_Walking);+ }+ bMantleVault = false;+}++// ---------------------------------------------------------------------------------------------+// Noise++void UVerseCharacterMovement::EmitNoise(const FGameplayTag& Noise, const FVector& Location)+{+ if (!CharacterOwner || CharacterOwner->bClientUpdating)+ {+ return; // never twice for a replayed move+ }+ FVerseNoiseEvent Event;+ Event.Noise = Noise;+ Event.SourceId = CharacterOwner->GetPlayerState() ? CharacterOwner->GetPlayerState()->GetPlayerId() : 0;+ Event.Location = Location;+ Event.Loudness = 1.f;+ Event.ServerTime = GetWorld() ? float(GetWorld()->GetTimeSeconds()) : 0.f;+ OnFootstep.Broadcast(Event, CurrentFloor.HitResult.PhysMaterial.Get());+ if (CharacterOwner->HasAuthority())+ {+ if (UVerseEventHub* Hub = UVerseEventHub::Get(this))+ {+ Hub->OnNoise.Broadcast(Event);+ }+ }+}++void UVerseCharacterMovement::UpdateFootsteps(float DeltaSeconds, const FVector& OldLocation)+{+ if (MovementMode != MOVE_Walking || Stance != EVerseStance::Stand || ProneTransitionRemaining > 0.f)+ {+ // Crouch walk and prone crawl are silent (bot.md 3.2); the stride restarts on standing.+ StrideRemaining = 0.f;+ return;+ }+ const float Moved = FVector::Dist2D(UpdatedComponent->GetComponentLocation(), OldLocation);+ if (Moved < KINDA_SMALL_NUMBER)+ {+ return;+ }+ StrideRemaining -= Moved;+ if (StrideRemaining > 0.f)+ {+ return;+ }+ const float Speed = DeltaSeconds > 0.f ? Moved / DeltaSeconds : 0.f;+ FGameplayTag Tag = VerseTags::Noise_Footstep_Walk;+ float Stride = TuningValues.WalkStride;+ if (IsSprinting())+ {+ Tag = VerseTags::Noise_Footstep_Sprint;+ Stride = TuningValues.SprintStride;+ }+ else if (Speed > TuningValues.QuietWalkMaxSpeed * 100.f)+ {+ Tag = VerseTags::Noise_Footstep_Run;+ Stride = TuningValues.RunStride;+ }+ StrideRemaining += Stride * 100.f;+ EmitNoise(Tag, GetFeetLocation());+}++void UVerseCharacterMovement::OnMovementUpdated(float DeltaSeconds, const FVector& OldLocation, const FVector& OldVelocity)+{+ Super::OnMovementUpdated(DeltaSeconds, OldLocation, OldVelocity);+ if (CharacterOwner && CharacterOwner->GetLocalRole() != ROLE_SimulatedProxy)+ {+ UpdateFootsteps(DeltaSeconds, OldLocation);+ }+}++void UVerseCharacterMovement::ProcessLanded(const FHitResult& Hit, float RemainingTime, int32 Iterations)+{+ if (-Velocity.Z >= TuningValues.LandNoiseMinFallSpeed * 100.f)+ {+ EmitNoise(VerseTags::Noise_Move_Land, GetFeetLocation());+ }+ Super::ProcessLanded(Hit, RemainingTime, Iterations);+}++void UVerseCharacterMovement::OnMovementModeChanged(EMovementMode PreviousMovementMode, uint8 PreviousCustomMode)+{+ Super::OnMovementModeChanged(PreviousMovementMode, PreviousCustomMode);+ const bool bWasSliding = PreviousMovementMode == MOVE_Custom && PreviousCustomMode == uint8(EVerseCustomMove::Slide);+ if (bWasSliding && !IsSliding() && Stance == EVerseStance::Slide)+ {+ Stance = EVerseStance::Crouch;+ SlideCooldownRemaining = TuningValues.SlideCooldown;+ }+}++// ---------------------------------------------------------------------------------------------+// Tick, networking++void UVerseCharacterMovement::TickComponent(float DeltaTime, ELevelTick TickType, FActorComponentTickFunction* ThisTickFunction)+{+ const uint64 Start = FPlatformTime::Cycles64();+ Super::TickComponent(DeltaTime, TickType, ThisTickFunction);+ if (AVerseCharacter* Character = GetVerseCharacter())+ {+ Character->UpdateBodyPose(DeltaTime);+ }+ TickCycles += FPlatformTime::Cycles64() - Start;+ ++TickCountTotal;+}++void UVerseCharacterMovement::ServerMove_PerformMovement(const FCharacterNetworkMoveData& MoveData)+{+ const uint64 Start = FPlatformTime::Cycles64();+ Super::ServerMove_PerformMovement(MoveData);+ TickCycles += FPlatformTime::Cycles64() - Start;+}++FNetworkPredictionData_Client* UVerseCharacterMovement::GetPredictionData_Client() const+{+ if (!ClientPredictionData)+ {+ UVerseCharacterMovement* MutableThis = const_cast<UVerseCharacterMovement*>(this);+ MutableThis->ClientPredictionData = new FVerseNetworkPredictionData_Client(*this);+ }+ return ClientPredictionData;+}++void UVerseCharacterMovement::MoveAutonomous(float ClientTimeStamp, float DeltaTime, uint8 CompressedFlags, const FVector& NewAccel)+{+ const bool bServerOfRemote = CharacterOwner && CharacterOwner->GetLocalRole() == ROLE_Authority+ && CharacterOwner->GetRemoteRole() == ROLE_AutonomousProxy;+ const int8 LeanBefore = LeanQuantized;+ if (bServerOfRemote)+ {+ if (const FVerseCharacterNetworkMoveData* Data = static_cast<const FVerseCharacterNetworkMoveData*>(GetCurrentNetworkMoveData()))+ {+ LeanTargetQuantized = Data->LeanTarget;+ PendingClientLean = Data->LeanResult;+ }+ }+ Super::MoveAutonomous(ClientTimeStamp, DeltaTime, CompressedFlags, NewAccel);+ if (bServerOfRemote && PendingClientLean != NoClientLean)+ {+ ++NetStats.ServerMoves;+ // Adopt the client's lean when it is one the move could reach: within the lean rate of this+ // move's (server-timed) delta from the previous value, and inside the wall check. A lost+ // packet stretches the server's delta, so the server's own value may lag; the client's wins.+ const int32 Client = PendingClientLean;+ const float MaxStep = DeltaTime / FMath::Max(TuningValues.LeanEnterTime, KINDA_SMALL_NUMBER) * 127.f + LeanAdoptTolerance;+ // The same rule as UpdateLean (no lean while sprinting, mantling, prone or in a prone+ // transition), plus the wall allowance; only then the reach checks.+ const bool bAllowedNow = Client == 0 || (CanLeanNow() && FMath::Abs(float(Client)) <= ComputeLeanAllowance(float(Client)) * 127.f + LeanAdoptTolerance);+ if (FMath::Abs(Client - int32(LeanQuantized)) > LeanAdoptTolerance)+ {+ ++NetStats.LeanSimDiffs;+ }+ if (bAllowedNow && (FMath::Abs(Client - int32(LeanQuantized)) <= LeanAdoptTolerance || FMath::Abs(Client - int32(LeanBefore)) <= MaxStep))+ {+ LeanQuantized = int8(Client);+ LeanValue = IVerseMovementQuery::LeanFromQuantized(LeanQuantized);+ }+ else+ {+ ++NetStats.LeanMismatches;+ UE_LOG(LogVerseMovement, Display, TEXT("lean refused: client %d, server %d, before %d, dt %.3f"), Client, int32(LeanQuantized), int32(LeanBefore), DeltaTime);+ }+ PendingClientLean = NoClientLean;+ if (const FCharacterNetworkMoveData* Move = GetCurrentNetworkMoveData())+ {+ bHasServerLastClientLocation = !MovementBaseUtility::UseRelativeLocation(Move->MovementBase);+ ServerLastClientLocation = Move->Location;+ }+ if (AVerseCharacter* Character = GetVerseCharacter())+ {+ Character->SetReplicatedMovementState(Stance, LeanQuantized, IsSprinting(), MantleElapsed >= 0.f);+ }+ }+}++void UVerseCharacterMovement::OnClientCorrectionReceived(FNetworkPredictionData_Client_Character& ClientData, float TimeStamp, FVector NewLocation,+ FVector NewVelocity, UPrimitiveComponent* NewBase, FName NewBaseBoneName, bool bHasBase, bool bBaseRelativePosition, uint8 ServerMovementMode,+ FVector ServerGravityDirection)+{+ // AckMove already ran: LastAckedMove is the corrected move. Book the correction against what+ // that move did, not against what the pawn does one round trip later.+ EVerseMoveKind Kind = GetMoveKind();+ double MoveError = -1.0;+ if (const FVerseSavedMove* Move = static_cast<const FVerseSavedMove*>(ClientData.LastAckedMove.Get()))+ {+ Kind = Move->GetCorrectionKind();+ MoveError = FVector::Dist(Move->SavedLocation, NewLocation);+ }+ ++NetStats.Corrections[int32(Kind)];+ bCorrectionAccepted = true;+ LastAppliedCorrectionStamp = TimeStamp;+ UE_LOG(LogVerseMovement, Display, TEXT("correction of a %s move at %.3f: move error %.1f cm, server mode %d, client stance %d"),+ *StaticEnum<EVerseMoveKind>()->GetNameStringByValue(int64(Kind)), TimeStamp, MoveError, int32(ServerMovementMode), int32(Stance));+ Super::OnClientCorrectionReceived(ClientData, TimeStamp, NewLocation, NewVelocity, NewBase, NewBaseBoneName, bHasBase, bBaseRelativePosition,+ ServerMovementMode, ServerGravityDirection);+}++void UVerseCharacterMovement::ClientHandleMoveResponse(const FCharacterMoveResponseDataContainer& MoveResponse)+{+ bCorrectionAccepted = false;+ Super::ClientHandleMoveResponse(MoveResponse);+ if (!MoveResponse.IsCorrection() || !bCorrectionAccepted)+ {+ return;+ }+ bCorrectionAccepted = false;+ // The server's simulated state at the corrected move: the replay starts from it.+ const FVerseMoveState& Server = static_cast<const FVerseMoveResponseDataContainer&>(MoveResponse).State;+ Server.Restore(*this);+ if (MantleElapsed < 0.f && !MoveResponse.bRootMotionSourceCorrection)+ {+ RemoveRootMotionSource(MantleRiseSource);+ RemoveRootMotionSource(MantleMoveSource);+ }+ if (Server.bYawClamped && Server.bHasLastMoveYaw)+ {+ SetActorYaw(Server.LastMoveYaw, true);+ }+ if (AVerseCharacter* Character = GetVerseCharacter())+ {+ Character->UpdateBodyPose(0.f);+ }+}++bool UVerseCharacterMovement::ClientUpdatePositionAfterServerUpdate()+{+ // Replayed moves restore their own facing; afterwards the pawn faces where the input has it now.+ const FQuat Rotation = UpdatedComponent ? UpdatedComponent->GetComponentQuat() : FQuat::Identity;+ const bool bResult = Super::ClientUpdatePositionAfterServerUpdate();+ if (UpdatedComponent && !UpdatedComponent->GetComponentQuat().Equals(Rotation, 1e-6))+ {+ UpdatedComponent->SetWorldRotation(Rotation, false, nullptr, ETeleportType::TeleportPhysics);+ }+ return bResult;+}++void UVerseCharacterMovement::ServerMoveHandleClientError(float ClientTimeStamp, float DeltaTime, const FVector& Accel, const FVector& RelativeClientLocation,+ UPrimitiveComponent* ClientMovementBase, FName ClientBaseBoneName, uint8 ClientMovementMode)+{+ // Moves the client made before it applied the last correction still carry the old error:+ // checking them again would only send the same correction twice. Wait for the client (at most+ // CorrectionAckTimeout, in case the correction packet was lost).+ const double Now = GetWorld() ? GetWorld()->GetTimeSeconds() : 0.0;+ const FVerseCharacterNetworkMoveData* MoveData = static_cast<const FVerseCharacterNetworkMoveData*>(GetCurrentNetworkMoveData());+ if (MoveData && LastSentCorrectionStamp >= 0.f && MoveData->AppliedCorrectionStamp < LastSentCorrectionStamp - 1e-4f+ && ClientTimeStamp > LastSentCorrectionStamp && Now - LastSentCorrectionTime < CorrectionAckTimeout)+ {+ return;+ }+ Super::ServerMoveHandleClientError(ClientTimeStamp, DeltaTime, Accel, RelativeClientLocation, ClientMovementBase, ClientBaseBoneName, ClientMovementMode);+ const FNetworkPredictionData_Server_Character* ServerData = GetPredictionData_Server_Character();+ if (ServerData && !ServerData->PendingAdjustment.bAckGoodMove && ServerData->PendingAdjustment.TimeStamp == ClientTimeStamp)+ {+ LastSentCorrectionStamp = ClientTimeStamp;+ LastSentCorrectionTime = Now;+ // A correction for this move: send the state as it is now, at the end of the move.+ FVerseMoveResponseDataContainer& Response = static_cast<FVerseMoveResponseDataContainer&>(*MoveResponseContainer);+ Response.PendingState.Capture(*this);+ Response.PendingState.bYawClamped = Response.bYawClampedPending;+ Response.bYawClampedPending = false;+ }+}++bool UVerseCharacterMovement::ServerCheckClientError(float ClientTimeStamp, float DeltaTime, const FVector& Accel, const FVector& ClientWorldLocation,+ const FVector& RelativeClientLocation, UPrimitiveComponent* ClientMovementBase, FName ClientBaseBoneName, uint8 ClientMovementMode)+{+ bool bError = Super::ServerCheckClientError(ClientTimeStamp, DeltaTime, Accel, ClientWorldLocation, RelativeClientLocation, ClientMovementBase,+ ClientBaseBoneName, ClientMovementMode);+ if (bError && UpdatedComponent && ClientMovementMode == PackNetworkMovementMode()+ && FVector::DistSquared(UpdatedComponent->GetComponentLocation(), ClientWorldLocation) < FMath::Square(ServerCorrectionToleranceCm))+ {+ // Same mode, a few centimetres apart: leave the client alone. The server keeps its own+ // location (nothing of the client's is adopted), so it stays authoritative.+ bError = false;+ }+ if (bError && UpdatedComponent)+ {+ const FVector Server = UpdatedComponent->GetComponentLocation();+ UE_LOG(LogVerseMovement, Display, TEXT("server correction at %.3f: error %.1f cm (%s), server mode %d stance %d kind %s speed %.0f, client mode %d, dt %.4f"),+ ClientTimeStamp, FVector::Dist(Server, ClientWorldLocation), *(Server - ClientWorldLocation).ToCompactString(), int32(PackNetworkMovementMode()), int32(Stance),+ *StaticEnum<EVerseMoveKind>()->GetNameStringByValue(int64(GetMoveKind())), Velocity.Size2D(), int32(ClientMovementMode), DeltaTime);+ }+ return bError;+}++// ---------------------------------------------------------------------------------------------+// Saved moves and move data++void FVerseMoveState::Capture(const UVerseCharacterMovement& M)+{+ Stance = M.Stance;+ BodyShape = M.BodyShape;+ LeanQuantized = M.LeanQuantized;+ LeanValue = M.LeanValue;+ ProneTransitionRemaining = M.ProneTransitionRemaining;+ bProneExiting = M.bProneExiting;+ SlideElapsed = M.SlideElapsed;+ SlideCooldownRemaining = M.SlideCooldownRemaining;+ bPrevWantsCrouch = M.bPrevWantsCrouch;+ bMantleLatched = M.bMantleLatched;+ MantleElapsed = M.MantleElapsed;+ MantlePlanDuration = M.MantlePlanDuration;+ MantleRiseDuration = M.MantleRiseDuration;+ MantleRise = M.MantleRise;+ MantleTarget = M.MantleTarget;+ bMantleVault = M.bMantleVault;+ StrideRemaining = M.StrideRemaining;+ LastMoveYaw = M.LastMoveYaw;+ bHasLastMoveYaw = M.bHasLastMoveYaw;+}++void FVerseMoveState::Restore(UVerseCharacterMovement& M) const+{+ M.Stance = Stance;+ if (M.BodyShape != BodyShape)+ {+ M.SetBodyShape(BodyShape, false, false);+ }+ M.LeanQuantized = LeanQuantized;+ M.LeanValue = LeanValue;+ M.ProneTransitionRemaining = ProneTransitionRemaining;+ M.bProneExiting = bProneExiting;+ M.SlideElapsed = SlideElapsed;+ M.SlideCooldownRemaining = SlideCooldownRemaining;+ M.bPrevWantsCrouch = bPrevWantsCrouch;+ M.bMantleLatched = bMantleLatched;+ M.MantleElapsed = MantleElapsed;+ M.MantlePlanDuration = MantlePlanDuration;+ M.MantleRiseDuration = MantleRiseDuration;+ M.MantleRise = MantleRise;+ M.MantleTarget = MantleTarget;+ M.bMantleVault = bMantleVault;+ M.StrideRemaining = StrideRemaining;+ M.LastMoveYaw = LastMoveYaw;+ M.bHasLastMoveYaw = bHasLastMoveYaw;+}++void FVerseMoveState::Serialize(FArchive& Ar)+{+ uint8 StanceByte = uint8(Stance);+ uint8 ShapeByte = uint8(BodyShape);+ uint8 Bits = (bProneExiting ? 1 : 0) | (bPrevWantsCrouch ? 2 : 0) | (bMantleLatched ? 4 : 0) | (bMantleVault ? 8 : 0)+ | (bHasLastMoveYaw ? 16 : 0) | (bYawClamped ? 32 : 0);+ Ar << StanceByte << ShapeByte << Bits << LeanQuantized << LeanValue << ProneTransitionRemaining << SlideElapsed << SlideCooldownRemaining;+ Ar << MantleElapsed;+ if (MantleElapsed >= 0.f)+ {+ Ar << MantlePlanDuration << MantleRiseDuration << MantleRise << MantleTarget;+ }+ Ar << LastMoveYaw;+ if (Ar.IsLoading())+ {+ Stance = EVerseStance(FMath::Min<uint8>(StanceByte, uint8(EVerseStance::Slide)));+ BodyShape = EVerseBodyShape(FMath::Min<uint8>(ShapeByte, uint8(EVerseBodyShape::Prone)));+ bProneExiting = (Bits & 1) != 0;+ bPrevWantsCrouch = (Bits & 2) != 0;+ bMantleLatched = (Bits & 4) != 0;+ bMantleVault = (Bits & 8) != 0;+ bHasLastMoveYaw = (Bits & 16) != 0;+ bYawClamped = (Bits & 32) != 0;+ }+}++void FVerseMoveResponseDataContainer::ServerFillResponseData(const UCharacterMovementComponent& CharacterMovement, const FClientAdjustment& PendingAdjustment)+{+ FCharacterMoveResponseDataContainer::ServerFillResponseData(CharacterMovement, PendingAdjustment);+ if (IsCorrection())+ {+ State = PendingState;+ }+}++bool FVerseMoveResponseDataContainer::Serialize(UCharacterMovementComponent& CharacterMovement, FArchive& Ar, UPackageMap* PackageMap)+{+ if (!FCharacterMoveResponseDataContainer::Serialize(CharacterMovement, Ar, PackageMap))+ {+ return false;+ }+ if (IsCorrection())+ {+ State.Serialize(Ar);+ }+ return !Ar.IsError();+}++EVerseMoveKind FVerseSavedMove::GetCorrectionKind() const+{+ for (const EVerseMoveKind Kind : {EVerseMoveKind::Mantle, EVerseMoveKind::Prone, EVerseMoveKind::Slide})+ {+ if (StartKind == Kind || EndKind == Kind)+ {+ return Kind;+ }+ }+ return EndKind;+}++void FVerseSavedMove::Clear()+{+ Super::Clear();+ bSavedWantsSprint = false;+ bSavedWantsProne = false;+ bSavedWantsMantle = false;+ SavedLeanTarget = 0;+ SavedLeanResult = 0;+ SavedAppliedCorrectionStamp = -1.f;+ StartState = FVerseMoveState();+ StartKind = EVerseMoveKind::Walk;+ EndKind = EVerseMoveKind::Walk;+}++uint8 FVerseSavedMove::GetCompressedFlags() const+{+ uint8 Flags = Super::GetCompressedFlags();+ if (bSavedWantsSprint) Flags |= VerseMoveFlags::Sprint;+ if (bSavedWantsProne) Flags |= VerseMoveFlags::Prone;+ if (bSavedWantsMantle) Flags |= VerseMoveFlags::Mantle;+ return Flags;+}++bool FVerseSavedMove::CanCombineWith(const FSavedMovePtr& NewMove, ACharacter* InCharacter, float MaxDelta) const+{+ const FVerseSavedMove* Other = static_cast<const FVerseSavedMove*>(NewMove.Get());+ if (bSavedWantsSprint != Other->bSavedWantsSprint || bSavedWantsProne != Other->bSavedWantsProne+ || bSavedWantsMantle != Other->bSavedWantsMantle || SavedLeanTarget != Other->SavedLeanTarget+ || StartState.Stance != Other->StartState.Stance || StartState.LeanQuantized != Other->StartState.LeanQuantized+ || StartState.MantleElapsed >= 0.f || Other->StartState.MantleElapsed >= 0.f+ || StartState.ProneTransitionRemaining > 0.f || StartState.Stance == EVerseStance::Slide)+ {+ return false;+ }+ return Super::CanCombineWith(NewMove, InCharacter, MaxDelta);+}++void FVerseSavedMove::SetMoveFor(ACharacter* C, float InDeltaTime, FVector const& NewAccel, FNetworkPredictionData_Client_Character& ClientData)+{+ if (const UVerseCharacterMovement* M = Cast<UVerseCharacterMovement>(C->GetCharacterMovement()))+ {+ bSavedWantsSprint = M->bWantsSprint;+ bSavedWantsProne = M->bWantsProne;+ bSavedWantsMantle = M->bWantsMantle;+ SavedLeanTarget = M->LeanTargetQuantized;+ SavedAppliedCorrectionStamp = M->LastAppliedCorrectionStamp;+ }+ Super::SetMoveFor(C, InDeltaTime, NewAccel, ClientData);+}++void FVerseSavedMove::SetInitialPosition(ACharacter* C)+{+ Super::SetInitialPosition(C);+ if (const UVerseCharacterMovement* M = Cast<UVerseCharacterMovement>(C->GetCharacterMovement()))+ {+ StartState.Capture(*M);+ StartKind = M->GetMoveKind();+ }+}++void FVerseSavedMove::PrepMoveFor(ACharacter* C)+{+ Super::PrepMoveFor(C);+ // A replay re-simulates: only the move's inputs and facing come back. The simulated state+ // carries over from the previous replayed move (the first starts from the server's state).+ if (UVerseCharacterMovement* M = Cast<UVerseCharacterMovement>(C->GetCharacterMovement()))+ {+ M->bWantsSprint = bSavedWantsSprint;+ M->bWantsProne = bSavedWantsProne;+ M->bWantsMantle = bSavedWantsMantle;+ M->LeanTargetQuantized = SavedLeanTarget;+ if (M->UpdatedComponent)+ {+ M->UpdatedComponent->SetWorldRotation(StartRotation, false, nullptr, ETeleportType::TeleportPhysics);+ }+ }+}++void FVerseSavedMove::CombineWith(const FSavedMove_Character* OldMove, ACharacter* InCharacter, APlayerController* PC, const FVector& OldStartLocation)+{+ Super::CombineWith(OldMove, InCharacter, PC, OldStartLocation);+ // The combined move re-runs from the pending move's start: its simulated state too.+ if (UVerseCharacterMovement* M = Cast<UVerseCharacterMovement>(InCharacter->GetCharacterMovement()))+ {+ static_cast<const FVerseSavedMove*>(OldMove)->StartState.Restore(*M);+ }+}++void FVerseSavedMove::PostUpdate(ACharacter* C, EPostUpdateMode PostUpdateMode)+{+ Super::PostUpdate(C, PostUpdateMode);+ if (const UVerseCharacterMovement* M = Cast<UVerseCharacterMovement>(C->GetCharacterMovement()))+ {+ SavedLeanResult = M->LeanQuantized;+ EndKind = M->GetMoveKind();+ }+}++bool FVerseSavedMove::IsImportantMove(const FSavedMovePtr& LastAckedMove) const+{+ const FVerseSavedMove* Acked = static_cast<const FVerseSavedMove*>(LastAckedMove.Get());+ if (Acked && (Acked->bSavedWantsProne != bSavedWantsProne || Acked->bSavedWantsMantle != bSavedWantsMantle))+ {+ return true;+ }+ return Super::IsImportantMove(LastAckedMove);+}++void FVerseCharacterNetworkMoveData::ClientFillNetworkMoveData(const FSavedMove_Character& ClientMove, ENetworkMoveType MoveType)+{+ FCharacterNetworkMoveData::ClientFillNetworkMoveData(ClientMove, MoveType);+ const FVerseSavedMove& Move = static_cast<const FVerseSavedMove&>(ClientMove);+ LeanTarget = Move.SavedLeanTarget;+ LeanResult = Move.SavedLeanResult;+ AppliedCorrectionStamp = Move.SavedAppliedCorrectionStamp;+}++bool FVerseCharacterNetworkMoveData::Serialize(UCharacterMovementComponent& CharacterMovement, FArchive& Ar, UPackageMap* PackageMap, ENetworkMoveType MoveType)+{+ FCharacterNetworkMoveData::Serialize(CharacterMovement, Ar, PackageMap, MoveType);+ Ar << LeanTarget;+ Ar << LeanResult;+ Ar << AppliedCorrectionStamp;+ return !Ar.IsError();+}diff --git a/unreal/Verse/Source/VerseMovement/Private/VerseHitZones.cpp b/unreal/Verse/Source/VerseMovement/Private/VerseHitZones.cppnew file mode 100644index 0000000000..09ca8af29d--- /dev/null+++ b/unreal/Verse/Source/VerseMovement/Private/VerseHitZones.cpp@@ -0,0 +1,107 @@+#include "VerseHitZones.h"++#include "Components/BoxComponent.h"+#include "Components/SkeletalMeshComponent.h"+#include "Engine/HitResult.h"+#include "Engine/SkeletalMesh.h"+#include "PhysicsEngine/BodySetup.h"+#include "PhysicsEngine/PhysicsAsset.h"+#include "PhysicsEngine/SkeletalBodySetup.h"+#include "VerseCharacter.h"++EVerseHitZone VerseHitZones::ZoneForBoneName(FName Bone)+{+ const FString Name = Bone.ToString();+ if (Name == TEXT("Head") || Name == TEXT("Camera"))+ {+ return EVerseHitZone::Head;+ }+ if (Name == TEXT("Neck"))+ {+ return EVerseHitZone::Neck;+ }+ if (Name == TEXT("Spine_02") || Name == TEXT("Spine_03") || Name.StartsWith(TEXT("Clavicle_")))+ {+ return EVerseHitZone::UpperTorso;+ }+ if (Name == TEXT("Spine_01") || Name == TEXT("Hips"))+ {+ return EVerseHitZone::LowerTorso;+ }+ if (Name.StartsWith(TEXT("UpperArm_")) || Name.StartsWith(TEXT("LowerArm_")) || Name.StartsWith(TEXT("Hand_")))+ {+ return EVerseHitZone::Arm;+ }+ if (Name.StartsWith(TEXT("Thigh_")) || Name.StartsWith(TEXT("Calf_")) || Name.StartsWith(TEXT("Foot_")) || Name.StartsWith(TEXT("Ball_")))+ {+ return EVerseHitZone::Leg;+ }+ return EVerseHitZone::None;+}++EVerseHitZone VerseHitZones::ZoneForBone(const USkeletalMesh* Mesh, FName Bone)+{+ if (!Mesh)+ {+ return ZoneForBoneName(Bone);+ }+ const FReferenceSkeleton& Skeleton = Mesh->GetRefSkeleton();+ int32 Index = Skeleton.FindBoneIndex(Bone);+ while (Index != INDEX_NONE)+ {+ const EVerseHitZone Zone = ZoneForBoneName(Skeleton.GetBoneName(Index));+ if (Zone != EVerseHitZone::None)+ {+ return Zone;+ }+ Index = Skeleton.GetParentIndex(Index);+ }+ return EVerseHitZone::None;+}++bool VerseHitZones::BuildTable(const UPhysicsAsset* Physics, const USkeletalMesh* Mesh, TMap<FName, EVerseHitZone>& OutTable, FString& OutError)+{+ OutTable.Reset();+ if (!Physics)+ {+ OutError = TEXT("no physics asset");+ return false;+ }+ for (const USkeletalBodySetup* Body : Physics->SkeletalBodySetups)+ {+ if (!Body)+ {+ continue;+ }+ const EVerseHitZone Zone = ZoneForBone(Mesh, Body->BoneName);+ if (Zone == EVerseHitZone::None)+ {+ OutError = FString::Printf(TEXT("body %s maps to no hit zone"), *Body->BoneName.ToString());+ return false;+ }+ OutTable.Add(Body->BoneName, Zone);+ }+ if (OutTable.IsEmpty())+ {+ OutError = TEXT("physics asset has no bodies");+ return false;+ }+ return true;+}++EVerseHitZone VerseHitZones::ZoneForHit(const FHitResult& Hit)+{+ const UPrimitiveComponent* Component = Hit.GetComponent();+ if (const AVerseCharacter* Character = Cast<AVerseCharacter>(Hit.GetActor()))+ {+ if (Component && Component == Character->GetProneBody())+ {+ return EVerseHitZone::Leg;+ }+ }+ if (const USkeletalMeshComponent* Mesh = Cast<USkeletalMeshComponent>(Component))+ {+ return ZoneForBone(Mesh->GetSkeletalMeshAsset(), Hit.BoneName);+ }+ return EVerseHitZone::None;+}diff --git a/unreal/Verse/Source/VerseMovement/Private/VerseInputFrameBuilder.cpp b/unreal/Verse/Source/VerseMovement/Private/VerseInputFrameBuilder.cppnew file mode 100644index 0000000000..a2e7245084--- /dev/null+++ b/unreal/Verse/Source/VerseMovement/Private/VerseInputFrameBuilder.cpp@@ -0,0 +1,140 @@+#include "VerseInputFrameBuilder.h"++#include "Components/InputComponent.h"++void FVerseInputFrameBuilder::SetButton(EVerseInputButton Button, bool bHeld)+{+ if (bHeld)+ {+ Buttons |= uint32(Button);+ }+ else+ {+ Buttons &= ~uint32(Button);+ }+}++void FVerseInputFrameBuilder::ToggleButton(EVerseInputButton Button)+{+ SetButton(Button, !IsHeld(Button));+ // Crouch and prone exclude each other: toggling one on releases the other.+ if (IsHeld(Button) && Button == EVerseInputButton::Crouch)+ {+ SetButton(EVerseInputButton::Prone, false);+ }+ else if (IsHeld(Button) && Button == EVerseInputButton::Prone)+ {+ SetButton(EVerseInputButton::Crouch, false);+ }+}++void FVerseInputFrameBuilder::SetMoveKey(EVerseMoveKey Key, bool bHeld)+{+ const uint8 Bit = uint8(1u << uint8(Key));+ MoveKeys = bHeld ? (MoveKeys | Bit) : (MoveKeys & ~Bit);+}++void FVerseInputFrameBuilder::SetStickAxis(int32 Axis, float Value)+{+ if (Axis == 0)+ {+ Stick.X = Value;+ }+ else+ {+ Stick.Y = Value;+ }+}++FVerseInputFrame FVerseInputFrameBuilder::Consume(uint32 ServerTimeMs)+{+ auto Held = [this](EVerseMoveKey Key) { return (MoveKeys & (1u << uint8(Key))) ? 1.f : 0.f; };+ FVector2f Move = Move2D;+ if (MoveKeys)+ {+ Move = FVector2f(Held(EVerseMoveKey::Forward) - Held(EVerseMoveKey::Back), Held(EVerseMoveKey::Right) - Held(EVerseMoveKey::Left));+ }+ else if (!Stick.IsNearlyZero())+ {+ Move = Stick;+ }+ FVerseInputFrame Frame;+ Frame.Move = Move * (bWalk ? WalkScale : 1.f);+ Frame.LookDeltaDeg = LookAccum;+ Frame.Buttons = Buttons;+ Frame.Pressed = Buttons & ~PrevButtons;+ Frame.ServerTimeMs = ServerTimeMs;+ PrevButtons = Buttons;+ LookAccum = FVector2f::ZeroVector;+ return Frame;+}++void FVerseInputFrameBuilder::Reset()+{+ *this = FVerseInputFrameBuilder();+}++namespace+{+ void BindKeyEvent(UInputComponent& Input, const FKey& Key, EInputEvent Event, TFunction<void()> Handler)+ {+ FInputKeyBinding Binding(FInputChord(Key, false, false, false, false), Event);+ Binding.bConsumeInput = false;+ Binding.KeyDelegate.GetDelegateForManualSet().BindLambda(MoveTemp(Handler));+ Input.KeyBindings.Emplace(MoveTemp(Binding));+ }++ void BindAxis(UInputComponent& Input, const FKey& Key, TFunction<void(float)> Handler)+ {+ // The default constructor: the FKey one asserts through InputCore, which this module does not link.+ FInputAxisKeyBinding Binding;+ Binding.AxisKey = Key;+ Binding.bConsumeInput = false;+ Binding.AxisDelegate.GetDelegateForManualSet().BindLambda(MoveTemp(Handler));+ Input.AxisKeyBindings.Emplace(MoveTemp(Binding));+ }+}++void VersePersonInput::BindDefaults(UInputComponent& Input, FVerseInputFrameBuilder& Builder, TFunction<float()> DeltaSeconds)+{+ FVerseInputFrameBuilder* B = &Builder;+ auto MoveKey = [&Input, B](const FKey& Key, EVerseMoveKey Move)+ {+ BindKeyEvent(Input, Key, IE_Pressed, [B, Move] { B->SetMoveKey(Move, true); });+ BindKeyEvent(Input, Key, IE_Released, [B, Move] { B->SetMoveKey(Move, false); });+ };+ auto Hold = [&Input, B](const FKey& Key, EVerseInputButton Button)+ {+ BindKeyEvent(Input, Key, IE_Pressed, [B, Button] { B->SetButton(Button, true); });+ BindKeyEvent(Input, Key, IE_Released, [B, Button] { B->SetButton(Button, false); });+ };+ auto Toggle = [&Input, B](const FKey& Key, EVerseInputButton Button)+ {+ BindKeyEvent(Input, Key, IE_Pressed, [B, Button] { B->ToggleButton(Button); });+ };++ MoveKey(VerseKey(TEXT("W")), EVerseMoveKey::Forward);+ MoveKey(VerseKey(TEXT("S")), EVerseMoveKey::Back);+ MoveKey(VerseKey(TEXT("D")), EVerseMoveKey::Right);+ MoveKey(VerseKey(TEXT("A")), EVerseMoveKey::Left);+ BindAxis(Input, VerseKey(TEXT("Gamepad_LeftY")), [B](float Value) { B->SetStickAxis(0, Value); });+ BindAxis(Input, VerseKey(TEXT("Gamepad_LeftX")), [B](float Value) { B->SetStickAxis(1, Value); });++ BindAxis(Input, VerseKey(TEXT("MouseX")), [B](float Value) { B->AddLook(FVector2f(0.f, Value * MouseDegPerValue)); });+ BindAxis(Input, VerseKey(TEXT("MouseY")), [B](float Value) { B->AddLook(FVector2f(Value * MouseDegPerValue, 0.f)); });+ BindAxis(Input, VerseKey(TEXT("Gamepad_RightX")), [B, DeltaSeconds](float Value) { B->AddLook(FVector2f(0.f, Value * StickDegPerSecond * DeltaSeconds())); });+ BindAxis(Input, VerseKey(TEXT("Gamepad_RightY")), [B, DeltaSeconds](float Value) { B->AddLook(FVector2f(Value * StickDegPerSecond * DeltaSeconds(), 0.f)); });++ Hold(VerseKey(TEXT("SpaceBar")), EVerseInputButton::Jump);+ Hold(VerseKey(TEXT("Gamepad_FaceButton_Bottom")), EVerseInputButton::Jump);+ Hold(VerseKey(TEXT("LeftShift")), EVerseInputButton::Sprint);+ Hold(VerseKey(TEXT("Gamepad_LeftThumbstick")), EVerseInputButton::Sprint);+ Hold(VerseKey(TEXT("Q")), EVerseInputButton::LeanLeft);+ Hold(VerseKey(TEXT("E")), EVerseInputButton::LeanRight);+ Toggle(VerseKey(TEXT("LeftControl")), EVerseInputButton::Crouch);+ Toggle(VerseKey(TEXT("C")), EVerseInputButton::Crouch);+ Toggle(VerseKey(TEXT("Gamepad_FaceButton_Right")), EVerseInputButton::Crouch);+ Toggle(VerseKey(TEXT("Z")), EVerseInputButton::Prone);+ BindKeyEvent(Input, VerseKey(TEXT("LeftAlt")), IE_Pressed, [B] { B->SetWalkModifier(true); });+ BindKeyEvent(Input, VerseKey(TEXT("LeftAlt")), IE_Released, [B] { B->SetWalkModifier(false); });+}diff --git a/unreal/Verse/Source/VerseMovement/Private/VerseInputFrameController.cpp b/unreal/Verse/Source/VerseMovement/Private/VerseInputFrameController.cppnew file mode 100644index 0000000000..258833f9e6--- /dev/null+++ b/unreal/Verse/Source/VerseMovement/Private/VerseInputFrameController.cpp@@ -0,0 +1,17 @@+#include "VerseInputFrameController.h"++#include "VerseCharacter.h"++AVerseInputFrameController::AVerseInputFrameController()+{+ bReplicates = false;+}++void AVerseInputFrameController::SubmitFrame(const FVerseInputFrame& Frame)+{+ if (AVerseCharacter* Driven = Cast<AVerseCharacter>(GetPawn()))+ {+ Driven->SubmitInputFrame(Frame);+ ++SubmittedCount;+ }+}diff --git a/unreal/Verse/Source/VerseMovement/Private/VerseMovementNetworking.h b/unreal/Verse/Source/VerseMovement/Private/VerseMovementNetworking.hnew file mode 100644index 0000000000..35ee8716c5--- /dev/null+++ b/unreal/Verse/Source/VerseMovement/Private/VerseMovementNetworking.h@@ -0,0 +1,132 @@+#pragma once++#include "CoreMinimal.h"+#include "GameFramework/CharacterMovementComponent.h"+#include "GameFramework/CharacterMovementReplication.h"+#include "VerseCharacterMovement.h"++// Saved moves, move data and move responses of UVerseCharacterMovement (architecture.md 3.3):+// sprint, prone and mantle intent ride as compressed flags; lean (target and the client's result)+// rides in the custom move data. A server correction carries the server's simulated state+// (stance, body shape, slide, prone and mantle timers, yaw), so a corrected client replays its+// unacknowledged moves from the server's state; a replayed move restores only its inputs and facing.++namespace VerseMoveFlags+{+ inline constexpr uint8 Sprint = FSavedMove_Character::FLAG_Custom_0;+ inline constexpr uint8 Prone = FSavedMove_Character::FLAG_Custom_1;+ inline constexpr uint8 Mantle = FSavedMove_Character::FLAG_Custom_2;+}++/** The simulated state of one move start (see UVerseCharacterMovement). */+struct FVerseMoveState+{+ EVerseStance Stance = EVerseStance::Stand;+ EVerseBodyShape BodyShape = EVerseBodyShape::Stand;+ int8 LeanQuantized = 0;+ float LeanValue = 0.f;+ float ProneTransitionRemaining = 0.f;+ bool bProneExiting = false;+ float SlideElapsed = 0.f;+ float SlideCooldownRemaining = 0.f;+ bool bPrevWantsCrouch = false;+ bool bMantleLatched = false;+ float MantleElapsed = -1.f;+ float MantlePlanDuration = 0.f;+ float MantleRiseDuration = 0.f;+ FVector MantleRise = FVector::ZeroVector;+ FVector MantleTarget = FVector::ZeroVector;+ bool bMantleVault = false;+ float StrideRemaining = 0.f;+ /** Actor yaw at the end of the move (prone turn cap and prone body constraint). */+ float LastMoveYaw = 0.f;+ bool bHasLastMoveYaw = false;+ /** Server corrections only: the prone turn cap clamped the client's yaw since the last correction. */+ bool bYawClamped = false;++ void Capture(const UVerseCharacterMovement& Movement);+ /** Writes the state back; the capsule keeps its centre (the location already belongs to the shape). */+ void Restore(UVerseCharacterMovement& Movement) const;+ /** Network form of the state (server corrections). */+ void Serialize(FArchive& Ar);+};++class FVerseSavedMove : public FSavedMove_Character+{+ using Super = FSavedMove_Character;++public:+ bool bSavedWantsSprint = false;+ bool bSavedWantsProne = false;+ bool bSavedWantsMantle = false;+ int8 SavedLeanTarget = 0;+ /** Lean after the move ran; the client sends it so the server can adopt it. */+ int8 SavedLeanResult = 0;+ /** Timestamp of the last server correction the client had applied when it made this move. */+ float SavedAppliedCorrectionStamp = -1.f;+ FVerseMoveState StartState;+ /** Move kind at the start and at the end of the move (correction counters, WP01.10). */+ EVerseMoveKind StartKind = EVerseMoveKind::Walk;+ EVerseMoveKind EndKind = EVerseMoveKind::Walk;++ /** The kind a correction of this move is booked as: mantle, then prone, then slide win. */+ EVerseMoveKind GetCorrectionKind() const;++ virtual void Clear() override;+ virtual uint8 GetCompressedFlags() const override;+ virtual bool CanCombineWith(const FSavedMovePtr& NewMove, ACharacter* InCharacter, float MaxDelta) const override;+ virtual void SetMoveFor(ACharacter* C, float InDeltaTime, FVector const& NewAccel, FNetworkPredictionData_Client_Character& ClientData) override;+ virtual void SetInitialPosition(ACharacter* C) override;+ virtual void PrepMoveFor(ACharacter* C) override;+ virtual void CombineWith(const FSavedMove_Character* OldMove, ACharacter* InCharacter, APlayerController* PC, const FVector& OldStartLocation) override;+ virtual void PostUpdate(ACharacter* C, EPostUpdateMode PostUpdateMode) override;+ virtual bool IsImportantMove(const FSavedMovePtr& LastAckedMove) const override;+};++class FVerseNetworkPredictionData_Client : public FNetworkPredictionData_Client_Character+{+public:+ explicit FVerseNetworkPredictionData_Client(const UCharacterMovementComponent& Movement)+ : FNetworkPredictionData_Client_Character(Movement)+ {+ }++ virtual FSavedMovePtr AllocateNewMove() override { return FSavedMovePtr(new FVerseSavedMove()); }+};++struct FVerseCharacterNetworkMoveData : public FCharacterNetworkMoveData+{+ int8 LeanTarget = 0;+ int8 LeanResult = 0;+ /** The last correction (its move timestamp) the client had applied: the server waits for it. */+ float AppliedCorrectionStamp = -1.f;++ virtual void ClientFillNetworkMoveData(const FSavedMove_Character& ClientMove, ENetworkMoveType MoveType) override;+ virtual bool Serialize(UCharacterMovementComponent& CharacterMovement, FArchive& Ar, UPackageMap* PackageMap, ENetworkMoveType MoveType) override;+};++struct FVerseCharacterNetworkMoveDataContainer : public FCharacterNetworkMoveDataContainer+{+ FVerseCharacterNetworkMoveDataContainer()+ {+ NewMoveData = &Storage[0];+ PendingMoveData = &Storage[1];+ OldMoveData = &Storage[2];+ }++ FVerseCharacterNetworkMoveData Storage[3];+};++/** Server move responses: a correction also carries the server's FVerseMoveState. */+struct FVerseMoveResponseDataContainer : public FCharacterMoveResponseDataContainer+{+ /** Sent with a correction (filled from PendingState). */+ FVerseMoveState State;+ /** Server: the state at the end of the move the pending correction is for. */+ FVerseMoveState PendingState;+ /** Server: a yaw clamp happened since the last correction was captured. */+ bool bYawClampedPending = false;++ virtual void ServerFillResponseData(const UCharacterMovementComponent& CharacterMovement, const FClientAdjustment& PendingAdjustment) override;+ virtual bool Serialize(UCharacterMovementComponent& CharacterMovement, FArchive& Ar, UPackageMap* PackageMap) override;+};diff --git a/unreal/Verse/Source/VerseMovement/Private/VerseMovementScripts.cpp b/unreal/Verse/Source/VerseMovement/Private/VerseMovementScripts.cppnew file mode 100644index 0000000000..7b31172832--- /dev/null+++ b/unreal/Verse/Source/VerseMovement/Private/VerseMovementScripts.cpp@@ -0,0 +1,152 @@+#include "VerseMovementScripts.h"++#include "Fixture/VerseMovementCourse.h"+#include "VerseCharacterMovement.h"+#include "VerseRng.h"++namespace+{+ enum class ESegment : uint8+ {+ Run,+ Sprint,+ SprintSlide,+ CrouchWalk,+ ProneCrawl,+ LeanPeek,+ Jump,+ MantleRun,+ Count+ };++ struct FSoakState+ {+ FVerseRng Rng;+ ESegment Segment = ESegment::Run;+ float SegmentEnd = 0.f;+ float SegmentStart = 0.f;+ float TurnRate = 0.f;+ FVector Goal = FVector::ZeroVector;+ bool bHasGoal = false;+ bool bJumped = false;+ explicit FSoakState(uint64 Seed) : Rng(Seed, 0, EVerseRngSalt::Harness) {}+ };++ float SteerYaw(const AVerseCharacter& Pawn, const FVector& Goal, float MaxStep)+ {+ const FVector To = (Goal - Pawn.GetActorLocation()).GetSafeNormal2D();+ if (To.IsNearlyZero())+ {+ return 0.f;+ }+ const float Want = FMath::RadiansToDegrees(FMath::Atan2(To.Y, To.X));+ const float Delta = FRotator::NormalizeAxis(Want - Pawn.GetControlRotation().Yaw);+ return FMath::Clamp(Delta, -MaxStep, MaxStep);+ }+}++FVerseInputScript VerseMovementScripts::MakeSoak(uint64 Seed, float Duration, TWeakObjectPtr<AVerseCharacter> Pawn, const FVector& CourseOrigin)+{+ TSharedRef<FSoakState> State = MakeShared<FSoakState>(Seed);+ return [State, Seed, Duration, Pawn, CourseOrigin](float Time, float DeltaSeconds, FVerseInputFrame& Frame) -> bool+ {+ AVerseCharacter* Character = Pawn.Get();+ if (!Character || Time >= Duration)+ {+ return false;+ }+ FSoakState& S = *State;+ // Each seed keeps to its own half of the ledge lanes, so two soak pawns rarely collide.+ const int32 Half = int32(Seed % 2);+ const FVector Home = CourseOrigin + FVector(300.f, Half ? 2800.f : 400.f, 0.f);+ if (Time >= S.SegmentEnd)+ {+ // A third of the segments are mantle runs; the rest is spread over the other moves.+ S.Segment = S.Rng.Chance(0.33) ? ESegment::MantleRun : ESegment(S.Rng.RangeInt(0, int32(ESegment::MantleRun) - 1));+ S.SegmentStart = Time;+ S.SegmentEnd = Time + float(S.Rng.Range(1.2, 3.5));+ S.TurnRate = float(S.Rng.Range(-60.0, 60.0));+ S.bJumped = false;+ S.bHasGoal = false;+ if (S.Segment == ESegment::MantleRun)+ {+ const int32 Lane = Half * 2 + S.Rng.RangeInt(0, 1);+ S.Goal = CourseOrigin + FVector(VerseMovementCourse::LedgeFaceX + 100.f,+ VerseMovementCourse::LedgeLaneY(Lane) + float(S.Rng.Range(-150.0, 150.0)), 0.f);+ S.bHasGoal = true;+ S.SegmentEnd = Time + 6.f;+ }+ else if (FVector::Dist2D(Character->GetActorLocation(), Home) > 2200.f)+ {+ S.Goal = Home;+ S.bHasGoal = true;+ }+ }+ const float Local = Time - S.SegmentStart;+ const float MaxTurn = 240.f * DeltaSeconds;+ float Yaw = S.bHasGoal ? SteerYaw(*Character, S.Goal, MaxTurn) : S.TurnRate * DeltaSeconds;+ uint32 Buttons = 0;+ FVector2f Move(1.f, 0.f);+ switch (S.Segment)+ {+ case ESegment::Run:+ break;+ case ESegment::Sprint:+ Buttons |= uint32(EVerseInputButton::Sprint);+ break;+ case ESegment::SprintSlide:+ Buttons |= uint32(EVerseInputButton::Sprint);+ if (Local > 1.2f && Local < 2.4f)+ {+ Buttons |= uint32(EVerseInputButton::Crouch);+ }+ Yaw *= 0.2f;+ break;+ case ESegment::CrouchWalk:+ Buttons |= uint32(EVerseInputButton::Crouch);+ Move = FVector2f(0.8f, Local > 1.f ? 0.4f : -0.4f);+ break;+ case ESegment::ProneCrawl:+ Buttons |= uint32(EVerseInputButton::Prone);+ Move = Local > 0.9f ? FVector2f(1.f, 0.f) : FVector2f::ZeroVector;+ S.SegmentEnd = FMath::Max(S.SegmentEnd, S.SegmentStart + 3.5f);+ break;+ case ESegment::LeanPeek:+ Move = FVector2f(0.4f, 0.f);+ Buttons |= uint32(FMath::Fmod(Local, 1.2f) < 0.6f ? EVerseInputButton::LeanLeft : EVerseInputButton::LeanRight);+ break;+ case ESegment::Jump:+ if (FMath::Fmod(Local, 0.9f) < 0.15f)+ {+ Buttons |= uint32(EVerseInputButton::Jump);+ }+ break;+ case ESegment::MantleRun:+ {+ const float Distance = FVector::Dist2D(Character->GetActorLocation(), S.Goal);+ if (Distance < 200.f && !S.bJumped)+ {+ Buttons |= uint32(EVerseInputButton::Jump);+ if (Character->GetVerseMovement()->IsMantling())+ {+ S.bJumped = true;+ S.SegmentEnd = FMath::Min(S.SegmentEnd, Time + 1.2f);+ }+ }+ if (S.bJumped)+ {+ S.bHasGoal = false;+ Move = FVector2f(0.5f, 0.f);+ }+ break;+ }+ default:+ break;+ }+ Frame.Move = Move;+ Frame.LookDeltaDeg = FVector2f(0.f, Yaw);+ Frame.Buttons = Buttons;+ Frame.Pressed = Buttons & ~Character->GetLastAppliedFrame().Buttons;+ return true;+ };+}diff --git a/unreal/Verse/Source/VerseMovement/Private/VerseMovementScripts.h b/unreal/Verse/Source/VerseMovement/Private/VerseMovementScripts.hnew file mode 100644index 0000000000..ad1e398e17--- /dev/null+++ b/unreal/Verse/Source/VerseMovement/Private/VerseMovementScripts.h@@ -0,0 +1,18 @@+#pragma once++#include "CoreMinimal.h"+#include "VerseCharacter.h"++/**+ * Seeded input scripts that exercise every move (the netcode soak, the cost test, QA). They+ * produce plain FVerseInputFrames, so they drive a pawn exactly like a person or a bot.+ */+namespace VerseMovementScripts+{+ /**+ * A mixed session on the fixture course (whose origin is CourseOrigin): runs, sprints,+ * slides, crouch and prone crawls, lean peeks, jumps and mantle runs at the ledge lanes.+ * Ends after Duration seconds.+ */+ FVerseInputScript MakeSoak(uint64 Seed, float Duration, TWeakObjectPtr<AVerseCharacter> Pawn, const FVector& CourseOrigin);+}diff --git a/unreal/Verse/Source/VerseMovement/Private/VerseMovementTuning.cpp b/unreal/Verse/Source/VerseMovement/Private/VerseMovementTuning.cppnew file mode 100644index 0000000000..c2640925e0--- /dev/null+++ b/unreal/Verse/Source/VerseMovement/Private/VerseMovementTuning.cpp@@ -0,0 +1,212 @@+#include "VerseMovementTuning.h"++#include "Misc/FileHelper.h"+#include "Misc/Paths.h"+#include "UObject/Package.h"+#include "UObject/StrongObjectPtr.h"+#include "UObject/UnrealType.h"+#include "VerseLog.h"++bool FVerseMovementTuningValues::Validate(FString& OutError) const+{+ for (TFieldIterator<FFloatProperty> It(StaticStruct()); It; ++It)+ {+ const float Value = It->GetPropertyValue_InContainer(this);+ if (!FMath::IsFinite(Value) || Value < 0.f || Value > 1000.f)+ {+ OutError = FString::Printf(TEXT("%s = %f is out of range"), *It->GetName(), Value);+ return false;+ }+ }+ auto Fail = [&OutError](const TCHAR* Why) { OutError = Why; return false; };+ if (!(CrouchSpeed < WalkSpeed && WalkSpeed < SprintSpeed && ProneSpeed < CrouchSpeed)) return Fail(TEXT("speeds must rise prone < crouch < walk < sprint"));+ if (!(SlideMinEntrySpeed <= SprintSpeed)) return Fail(TEXT("slide entry speed above sprint speed: the slide can never start"));+ if (!(SlideBoostSpeed > CrouchSpeed && SlideMaxDuration > 0.f)) return Fail(TEXT("slide boost must exceed crouch speed"));+ if (!(MantleMinHeight < MantleLowMaxHeight && MantleLowMaxHeight < MantleHighMaxHeight)) return Fail(TEXT("mantle heights must rise"));+ if (!(MantleRiseFraction > 0.1f && MantleRiseFraction < 0.9f)) return Fail(TEXT("mantle rise fraction outside 0.1..0.9"));+ if (!(CrouchHeight < StandHeight && ProneMinClearance < CrouchHeight)) return Fail(TEXT("body heights must rise prone < crouch < stand"));+ if (!(ProneRadius <= CapsuleRadius && CapsuleRadius * 2.f <= CrouchHeight)) return Fail(TEXT("capsule radius does not fit the crouch height"));+ if (!(StandEyeHeight < StandHeight && CrouchEyeHeight < CrouchHeight && ProneEyeHeight > 0.f)) return Fail(TEXT("eyes must sit inside the body"));+ if (!(LeanEnterTime > 0.f && ProneEnterTime > 0.f && ProneExitTime > 0.f)) return Fail(TEXT("transition times must be positive"));+ return true;+}++namespace+{+ /**+ * Reader for the flat tuning file: one object of "name": number pairs plus string-valued+ * "schema" and "_comment" keys. Own code, so VerseMovement needs no Json module link.+ */+ struct FFlatJsonReader+ {+ const FString& Text;+ int32 Pos = 0;++ explicit FFlatJsonReader(const FString& InText) : Text(InText) {}++ void SkipSpace()+ {+ while (Pos < Text.Len() && FChar::IsWhitespace(Text[Pos]))+ {+ ++Pos;+ }+ }+ bool Consume(TCHAR Char)+ {+ SkipSpace();+ if (Pos < Text.Len() && Text[Pos] == Char)+ {+ ++Pos;+ return true;+ }+ return false;+ }+ bool Peek(TCHAR Char)+ {+ SkipSpace();+ return Pos < Text.Len() && Text[Pos] == Char;+ }+ bool ReadString(FString& Out)+ {+ Out.Reset();+ if (!Consume(TEXT('"')))+ {+ return false;+ }+ while (Pos < Text.Len() && Text[Pos] != TEXT('"'))+ {+ if (Text[Pos] == TEXT('\\') && Pos + 1 < Text.Len())+ {+ ++Pos;+ }+ Out.AppendChar(Text[Pos++]);+ }+ return Consume(TEXT('"'));+ }+ /** A number, or false (and the value skipped) for anything else. */+ bool ReadNumber(double& Out, bool& bOutOk)+ {+ SkipSpace();+ bOutOk = false;+ if (Peek(TEXT('"')))+ {+ FString Ignored;+ return ReadString(Ignored);+ }+ const int32 Start = Pos;+ while (Pos < Text.Len() && (FChar::IsDigit(Text[Pos]) || FCString::Strchr(TEXT("+-.eE"), Text[Pos])))+ {+ ++Pos;+ }+ if (Pos == Start)+ {+ while (Pos < Text.Len() && FChar::IsAlpha(Text[Pos]))+ {+ ++Pos; // true, false, null+ }+ return Pos > Start;+ }+ const FString Number = Text.Mid(Start, Pos - Start);+ bOutOk = Number.IsNumeric() || FCString::Strchr(*Number, TEXT('e')) || FCString::Strchr(*Number, TEXT('E'));+ Out = FCString::Atod(*Number);+ return true;+ }+ };+}++bool UVerseMovementTuning::ParseJson(const FString& Json, FVerseMovementTuningValues& Out, FString& OutError)+{+ FFlatJsonReader Reader(Json);+ if (!Reader.Consume(TEXT('{')))+ {+ OutError = TEXT("not a JSON object");+ return false;+ }+ FVerseMovementTuningValues Parsed;+ while (!Reader.Consume(TEXT('}')))+ {+ FString Key;+ if (!Reader.ReadString(Key) || !Reader.Consume(TEXT(':')))+ {+ OutError = TEXT("not a JSON object");+ return false;+ }+ double Number = 0.0;+ bool bNumber = false;+ if (!Reader.ReadNumber(Number, bNumber))+ {+ OutError = FString::Printf(TEXT("field %s has no value"), *Key);+ return false;+ }+ if (!Reader.Consume(TEXT(',')) && !Reader.Peek(TEXT('}')))+ {+ OutError = TEXT("not a JSON object");+ return false;+ }+ if (Key == TEXT("schema") || Key.StartsWith(TEXT("_")))+ {+ continue;+ }+ FProperty* Property = FVerseMovementTuningValues::StaticStruct()->FindPropertyByName(FName(*Key));+ if (!Property || !Property->GetName().Equals(Key, ESearchCase::CaseSensitive))+ {+ OutError = FString::Printf(TEXT("unknown field %s"), *Key);+ return false;+ }+ if (!bNumber)+ {+ OutError = FString::Printf(TEXT("field %s is not a number"), *Key);+ return false;+ }+ CastFieldChecked<FFloatProperty>(Property)->SetPropertyValue_InContainer(&Parsed, float(Number));+ }+ if (!Parsed.Validate(OutError))+ {+ return false;+ }+ Out = Parsed;+ return true;+}++bool UVerseMovementTuning::LoadFromJsonFile(const FString& Path, FString& OutError)+{+ FString Text;+ if (!FFileHelper::LoadFileToString(Text, *Path))+ {+ OutError = FString::Printf(TEXT("cannot read %s"), *Path);+ return false;+ }+ return ParseJson(Text, Values, OutError);+}++FString UVerseMovementTuning::ToJson(const FVerseMovementTuningValues& Values)+{+ FString Out = TEXT("{\n \"schema\": \"verse.movement-tuning/1\"");+ for (TFieldIterator<FFloatProperty> It(FVerseMovementTuningValues::StaticStruct()); It; ++It)+ {+ Out += FString::Printf(TEXT(",\n \"%s\": %s"), *It->GetName(), *FString::SanitizeFloat(It->GetPropertyValue_InContainer(&Values)));+ }+ Out += TEXT("\n}\n");+ return Out;+}++FString UVerseMovementTuning::DefaultJsonPath()+{+ return FPaths::Combine(FPaths::ProjectDir(), TEXT("Data"), TEXT("movement"), TEXT("movement_tuning.json"));+}++const UVerseMovementTuning* UVerseMovementTuning::GetDefaultTuning()+{+ static TStrongObjectPtr<UVerseMovementTuning> Default;+ if (!Default.IsValid())+ {+ UVerseMovementTuning* Tuning = NewObject<UVerseMovementTuning>(GetTransientPackage(), TEXT("DA_MovementTuning_Default"));+ FString Error;+ if (FPaths::FileExists(DefaultJsonPath()) && !Tuning->LoadFromJsonFile(DefaultJsonPath(), Error))+ {+ UE_LOG(LogVerseMovement, Error, TEXT("movement tuning: %s; using the start values"), *Error);+ }+ Default.Reset(Tuning);+ }+ return Default.Get();+}diff --git a/unreal/Verse/Source/VerseMovement/Public/Fixture/VerseMovementCourse.h b/unreal/Verse/Source/VerseMovement/Public/Fixture/VerseMovementCourse.hnew file mode 100644index 0000000000..adc1808797--- /dev/null+++ b/unreal/Verse/Source/VerseMovement/Public/Fixture/VerseMovementCourse.h@@ -0,0 +1,105 @@+#pragma once++#include "CoreMinimal.h"+#include "GameFramework/Actor.h"+#include "GameFramework/GameModeBase.h"++#include "VerseMovementCourse.generated.h"++class UBoxComponent;+class UStaticMeshComponent;++/**+ * The geometry of LV_Test_Movement (work-packages.md WP01.9), in one table shared by the map+ * and the automation tests: ledges 0.5/1.0/1.5/2.0/2.1 m, a 0.75 m crawl tunnel, a 1.2 m crouch+ * tunnel, 30 and 46 deg slopes, stairs, a 4 m drop, lean corners and a low breach. Actor-local+ * centimetres; the floor top is z = 0 and every lane runs along +X.+ */+namespace VerseMovementCourse+{+ struct FBlock+ {+ const TCHAR* Name;+ FVector Center;+ FVector Extent;+ float PitchDeg = 0.f;+ };++ /** Every collision block of the course. */+ VERSEMOVEMENT_API TConstArrayView<FBlock> Blocks();++ inline constexpr float LedgeHeights[] = {50.f, 100.f, 150.f, 200.f, 210.f};+ inline constexpr int32 LedgeCount = 5;+ /** The ledge faces sit at this X; lanes start at X = 0. */+ inline constexpr float LedgeFaceX = 600.f;+ inline constexpr float LedgeHalfWidth = 300.f;+ inline float LedgeLaneY(int32 Index) { return 800.f * Index; }++ inline constexpr float CrawlTunnelY = 4400.f;+ inline constexpr float CrawlTunnelHeight = 75.f;+ inline constexpr float CrouchTunnelY = 5200.f;+ inline constexpr float CrouchTunnelHeight = 120.f;+ inline constexpr float TunnelEntryX = 600.f;+ inline constexpr float TunnelLength = 400.f;++ inline constexpr float BreachY = 6000.f;+ inline constexpr float BreachWallX = 600.f;+ inline constexpr float BreachSill = 80.f;+ inline constexpr float BreachTop = 200.f;++ /** Lean corners: a wall along +X at y = CornerWallY, its end at x = CornerEndX. */+ inline constexpr float CornerLaneY = 6800.f;+ inline constexpr float CornerWallY = 6800.f;+ inline constexpr float CornerEndX = 1000.f;++ inline constexpr float Slope30Y = -800.f;+ inline constexpr float Slope46Y = -1600.f;+ inline constexpr float StairsY = -2400.f;+ inline constexpr float DropY = -3200.f;+ inline constexpr float DropHeight = 400.f;+ /** Flat open floor for speed tests. */+ inline constexpr float OpenFloorY = -4800.f;+}++/** Spawns the course blocks: collision boxes plus a visible cube each. */+UCLASS()+class VERSEMOVEMENT_API AVerseMovementCourse : public AActor+{+ GENERATED_BODY()++public:+ AVerseMovementCourse();++private:+ UPROPERTY(VisibleAnywhere, Category = "Course")+ TArray<TObjectPtr<UBoxComponent>> Boxes;++ UPROPERTY(VisibleAnywhere, Category = "Course")+ TArray<TObjectPtr<UStaticMeshComponent>> Visuals;+};++/** Game mode of LV_Test_Movement and the netcode soak: AVerseCharacter pawns, soak reports. */+UCLASS()+class VERSEMOVEMENT_API AVerseMovementTestGameMode : public AGameModeBase+{+ GENERATED_BODY()++public:+ AVerseMovementTestGameMode();++ virtual void InitGame(const FString& MapName, const FString& Options, FString& ErrorMessage) override;+ virtual AActor* ChoosePlayerStart_Implementation(AController* Player) override;+ virtual void Tick(float DeltaSeconds) override;+ virtual void EndPlay(const EEndPlayReason::Type Reason) override;++ /** Server: movement net stats of every pawn as JSON. */+ FString BuildServerReport() const;++private:+ FString ReportPath;+ float ReportTimer = 0.f;+ /** ?VerseQuitAfter=<seconds>: the soak server writes its report and exits by itself. */+ float QuitAfter = 0.f;+ float Elapsed = 0.f;+ int32 StartIndex = 0;+};diff --git a/unreal/Verse/Source/VerseMovement/Public/VerseCharacter.h b/unreal/Verse/Source/VerseMovement/Public/VerseCharacter.hnew file mode 100644index 0000000000..6b61890db7--- /dev/null+++ b/unreal/Verse/Source/VerseMovement/Public/VerseCharacter.h@@ -0,0 +1,124 @@+#pragma once++#include "Combat/VerseCombatTypes.h"+#include "CoreMinimal.h"+#include "GameFramework/Character.h"+#include "VerseInputFrameBuilder.h"++#include "VerseCharacter.generated.h"++class UBoxComponent;+class UCameraComponent;+class UVerseCharacterMovement;++/** A scripted input source: returns false when it is done (QA drivers, the netcode soak). */+using FVerseInputScript = TFunction<bool(float ScriptTime, float DeltaSeconds, FVerseInputFrame& OutFrame)>;++/**+ * The Verse first-person character (work-packages.md WP01, architecture.md 3.3). Every move+ * comes from one FVerseInputFrame per tick, whoever produces it: the person's keys+ * (VersePersonInput through FVerseInputFrameBuilder), a bot or harness controller (SubmitInputFrame on the+ * server, bot.md B1, 8.3) or a QA script. ApplyInputFrame is the single consumer.+ *+ * Combat state is not here (decision C8): UVerseCombatStateComponent lives on the primary+ * module's pawn, which derives from this class.+ */+UCLASS()+class VERSEMOVEMENT_API AVerseCharacter : public ACharacter+{+ GENERATED_BODY()++public:+ AVerseCharacter(const FObjectInitializer& ObjectInitializer);++ UVerseCharacterMovement* GetVerseMovement() const;+ UCameraComponent* GetFirstPersonCamera() const { return FirstPersonCamera; }+ UBoxComponent* GetProneBody() const { return ProneBody; }++ /** The one input consumer: look, move and every movement button of one tick. */+ void ApplyInputFrame(const FVerseInputFrame& Frame, float DeltaSeconds);++ /** Bot and harness controllers (server): the frame applied on this pawn's next tick. */+ void SubmitInputFrame(const FVerseInputFrame& Frame);++ /** Replaces the input source until the script returns false (nullptr clears it). */+ void SetInputScript(FVerseInputScript Script);+ bool HasInputScript() const { return bool(InputScript); }++ /** The person's input state; other packages bind their own actions into it (fire, reload). */+ FVerseInputFrameBuilder& GetPersonInput() { return PersonInput; }++ /**+ * World camera position and rotation (eye, stance and lean applied). The eye is the+ * skeleton's Camera bone (bot.md 3.1): the camera sits on it, the bot's eye reads the same.+ */+ FVector GetEyeLocation() const;+ FRotator GetEyeRotation() const;+ /** Aim: the control rotation, or the actor yaw plus the replicated view pitch on proxies. */+ FRotator GetAimRotation() const;++ /** Last frame ApplyInputFrame consumed. */+ const FVerseInputFrame& GetLastAppliedFrame() const { return LastAppliedFrame; }++ /** Re-poses camera and placeholder body after a stance or lean change (called by the movement). */+ void UpdateBodyPose(float DeltaSeconds);++ /** The Camera bone's world location (the eye), or the camera's when the mesh has no such bone. */+ FVector GetCameraBoneLocation() const;+ static const FName CameraBoneName;++ /** Placeholder pose until WP13's animation layer: lean rolls and prone lays the mesh down. */+ UPROPERTY(EditAnywhere, Category = "Verse|Movement")+ bool bPlaceholderPose = true;++ // Replicated to simulated proxies (the owner predicts its own).+ UPROPERTY(ReplicatedUsing = OnRep_MovementState)+ uint8 ReplicatedStance = 0;+ UPROPERTY(Replicated)+ int8 ReplicatedLean = 0;+ UPROPERTY(Replicated)+ bool bReplicatedSprinting = false;+ UPROPERTY(Replicated)+ bool bReplicatedMantling = false;++ /** Server: publish the movement state for simulated proxies. */+ void SetReplicatedMovementState(EVerseStance Stance, int8 Lean, bool bSprinting, bool bMantling);++ // AActor / APawn+ virtual void Tick(float DeltaSeconds) override;+ virtual void BeginPlay() override;+ virtual void GetLifetimeReplicatedProps(TArray<FLifetimeProperty>& OutLifetimeProps) const override;+ virtual void SetupPlayerInputComponent(UInputComponent* PlayerInputComponent) override;+ virtual void PawnClientRestart() override;+ virtual void GetActorEyesViewPoint(FVector& OutLocation, FRotator& OutRotation) const override;++protected:+ UFUNCTION()+ void OnRep_MovementState();++ /** Caches the Camera bone's reference-pose location in mesh space (placeholder pose). */+ void CacheCameraBone();++ UPROPERTY(VisibleAnywhere, Category = "Verse|Movement")+ TObjectPtr<UCameraComponent> FirstPersonCamera;++ /**+ * Hit box over the lying legs (feet to hips) while prone, scored as Leg. Head and torso hits+ * come from the mesh's physics bodies.+ */+ UPROPERTY(VisibleAnywhere, Category = "Verse|Movement")+ TObjectPtr<UBoxComponent> ProneBody;++ FVerseInputFrameBuilder PersonInput;+ FVerseInputFrame SubmittedFrame;+ bool bHasSubmittedFrame = false;+ bool bSubmittedFrameFresh = false;+ FVerseInputFrame LastAppliedFrame;+ FVerseInputScript InputScript;+ float InputScriptTime = 0.f;+ float SmoothedEyeHeight = -1.f;+ float SmoothedProneAlpha = 0.f;+ /** Camera bone in mesh space (reference pose); valid when bHasCameraBone. */+ FVector CameraBoneLocal = FVector::ZeroVector;+ bool bHasCameraBone = false;+};diff --git a/unreal/Verse/Source/VerseMovement/Public/VerseCharacterMovement.h b/unreal/Verse/Source/VerseMovement/Public/VerseCharacterMovement.hnew file mode 100644index 0000000000..b6c06cc6e2--- /dev/null+++ b/unreal/Verse/Source/VerseMovement/Public/VerseCharacterMovement.h@@ -0,0 +1,303 @@+#pragma once++#include "CoreMinimal.h"+#include "GameFramework/CharacterMovementComponent.h"+#include "Movement/VerseMovementQuery.h"+#include "VerseMovementTuning.h"++#include "VerseCharacterMovement.generated.h"++class AVerseCharacter;+class UPhysicalMaterial;++/** Custom movement modes (MOVE_Custom sub-modes, architecture.md 3.3). */+UENUM(BlueprintType)+enum class EVerseCustomMove : uint8+{+ None = 0,+ Slide = 1 // CMOVE_Slide+};++/** Move kinds the correction counters are kept per (work-packages.md WP01.10). */+UENUM(BlueprintType)+enum class EVerseMoveKind : uint8+{+ Walk,+ Sprint,+ Crouch,+ Prone,+ Slide,+ Mantle,+ Airborne,+ Lean,+ Count UMETA(Hidden)+};++/** Capsule shapes of the three body heights. */+enum class EVerseBodyShape : uint8+{+ Stand,+ Crouch,+ Prone+};++/** A ledge the mantle trace found (computed identically on client and server). */+struct FVerseMantlePlan+{+ FVector Start = FVector::ZeroVector;+ FVector Rise = FVector::ZeroVector;+ FVector Target = FVector::ZeroVector;+ float LedgeHeight = 0.f;+ float Duration = 0.f;+ bool bHigh = false;+ bool bCrouched = false;+ /** Through a breach or over a thin wall: the target is beyond the wall, in the air. */+ bool bVault = false;+};++/** Per-move-kind client correction counts plus the server's lean comparison. */+USTRUCT(BlueprintType)+struct VERSEMOVEMENT_API FVerseMovementNetStats+{+ GENERATED_BODY()++ /** Client: corrections received, indexed by EVerseMoveKind. */+ int32 Corrections[int32(EVerseMoveKind::Count)] = {};+ /** Server: client moves received / moves whose lean the server could not adopt. */+ int32 ServerMoves = 0;+ int32 LeanMismatches = 0;+ /** Server: moves whose own lean simulation differed from the client's by more than the tolerance. */+ int32 LeanSimDiffs = 0;+ /** Server: moves whose yaw the prone turn cap clamped (a client turning faster than allowed). */+ int32 YawClamps = 0;+ /** Server: mantles started from the client's location (within the correction tolerance). */+ int32 MantleSyncs = 0;+ /** Server: mantles the server found but held back because the client did not start one. */+ int32 MantlesDeclined = 0;++ int32 Total() const;+ FString ToJson() const;+};++DECLARE_MULTICAST_DELEGATE_TwoParams(FOnVerseFootstep, const FVerseNoiseEvent& /*Noise*/, const UPhysicalMaterial* /*Surface*/);++/**+ * The Verse character movement (architecture.md 3.3): stock CMC walk, sprint, crouch and jump+ * plus slide (MOVE_Custom / CMOVE_Slide), prone (a third capsule height plus a prone body box),+ * mantle (a predicted FRootMotionSource_MoveToForce after a ledge trace both sides run at the+ * same move time) and lean (a quantised value in the custom move data). It implements+ * IVerseMovementQuery; nothing outside VerseMovement touches this component.+ *+ * Inputs come only from AVerseCharacter::ApplyInputFrame (person and bot, bot.md B1); they set+ * the "wants" below, which travel as compressed flags and move data.+ */+UCLASS()+class VERSEMOVEMENT_API UVerseCharacterMovement : public UCharacterMovementComponent, public IVerseMovementQuery+{+ GENERATED_BODY()++ friend class FVerseSavedMove;+ friend struct FVerseCharacterNetworkMoveData;+ friend struct FVerseMoveState;+ friend struct FVerseMoveResponseDataContainer;++public:+ UVerseCharacterMovement(const FObjectInitializer& ObjectInitializer);++ // IVerseMovementQuery+ virtual EVerseStance GetStance() const override;+ virtual bool IsSprinting() const override;+ virtual bool IsAirborne() const override;+ virtual bool IsMantling() const override;+ virtual int8 GetLeanQuantized() const override;++ /** Tuning in use (DA_MovementTuning or the JSON default). */+ const FVerseMovementTuningValues& Tuning() const { return TuningValues; }+ void SetTuning(const FVerseMovementTuningValues& Values);++ // Wants, set by AVerseCharacter::ApplyInputFrame on the controlling machine.+ void SetWantsSprint(bool bWants) { bWantsSprint = bWants; }+ void SetWantsProne(bool bWants) { bWantsProne = bWants; }+ void SetWantsMantle(bool bWants) { bWantsMantle = bWants; }+ void SetLeanTarget(int8 Target) { LeanTargetQuantized = Target; }++ /** Lean -1..1 as the camera and hit bodies use it (the dequantised move value). */+ float GetLean() const;+ /** Feet-relative eye height of the current stance and transition. */+ float GetTargetEyeHeight() const;+ bool IsSliding() const { return MovementMode == MOVE_Custom && CustomMovementMode == uint8(EVerseCustomMove::Slide); }+ bool IsProne() const { return Stance == EVerseStance::Prone; }+ /** 0..1 progress of a prone enter (positive) or exit (negative); 0 when settled. */+ float GetProneTransitionAlpha() const;+ float GetSlideCooldownRemaining() const { return SlideCooldownRemaining; }+ float GetMantleElapsed() const { return MantleElapsed; }+ float GetMantleDuration() const { return MantlePlanDuration; }+ /** Mantles started (server and client count their own). */+ int32 GetMantleCount() const { return MantleCount; }+ EVerseMoveKind GetMoveKind() const;++ /** The mantle a jump press would start now, without starting it. */+ bool FindMantle(FVerseMantlePlan& OutPlan) const;+ /** True when the prone body fits at the current location and facing. */+ bool CanEnterProne() const;+ /** True when the prone body (feet to head, above the lowest step) overlaps geometry at a feet point and yaw. */+ bool ProneBodyBlocked(const FVector& FeetLocation, float Yaw) const;+ /** Largest lean (0..1) toward Side (-1 left, +1 right) the wall check allows now. */+ float ComputeLeanAllowance(float Side) const;+ /**+ * The eye (the skeleton's Camera bone, bot.md 3.1) relative to the feet in the actor's yaw frame+ * (X forward, Y right, Z up) for an eye height, a lean and a prone blend (0 upright, 1 lying).+ * Lean rolls the body about a pivot below the eye so the eye moves LeanCameraOffset sideways at+ * full lean. The placeholder pose puts the Camera bone exactly here; the camera reads the bone.+ */+ FVector GetEyeOffset(float EyeHeight, float Lean, float ProneAlpha) const;+ /** Eye location without lean (world), for the settled current stance. */+ FVector GetUnleanedEyeLocation() const;+ /** Eye location with the lean applied (world), for the settled current stance. */+ FVector GetLeanedEyeLocation(float Lean) const;+ FVector GetFeetLocation() const;++ FVerseMovementNetStats& GetNetStats() { return NetStats; }+ const FVerseMovementNetStats& GetNetStats() const { return NetStats; }++ /**+ * Game-thread cycles of this pawn's whole movement path (WP01 A1.9): the component tick with+ * the body pose, the character's input tick and, on a server, the client move RPC handling.+ */+ uint64 GetTickCycles() const { return TickCycles; }+ int32 GetTickCount() const { return TickCountTotal; }+ void AddMovementCycles(uint64 Cycles) { TickCycles += Cycles; }++ /** Footsteps and movement noise on every machine, with the surface (audio, WP19). */+ FOnVerseFootstep OnFootstep;++ /**+ * Applies the capsule of a body shape, keeping the feet planted (bKeepFeet) or the centre+ * (replays: the server's corrected location already belongs to that shape). False when it does not fit.+ */+ bool SetBodyShape(EVerseBodyShape Shape, bool bCheckFit, bool bKeepFeet = true);+ EVerseBodyShape GetBodyShape() const { return BodyShape; }+ /** For simulated proxies: adopt the replicated stance without checks. */+ void ApplyReplicatedStance(EVerseStance NewStance);++ // UCharacterMovementComponent+ virtual void InitializeComponent() override;+ virtual void TickComponent(float DeltaTime, ELevelTick TickType, FActorComponentTickFunction* ThisTickFunction) override;+ virtual float GetMaxSpeed() const override;+ virtual float GetMaxBrakingDeceleration() const override;+ virtual bool CanAttemptJump() const override;+ using UCharacterMovementComponent::DoJump;+ virtual bool DoJump(bool bReplayingMoves, float DeltaTime) override;+ virtual bool CanCrouchInCurrentState() const override;+ virtual void UpdateCharacterStateBeforeMovement(float DeltaSeconds) override;+ virtual void UpdateCharacterStateAfterMovement(float DeltaSeconds) override;+ virtual void OnMovementUpdated(float DeltaSeconds, const FVector& OldLocation, const FVector& OldVelocity) override;+ virtual void OnMovementModeChanged(EMovementMode PreviousMovementMode, uint8 PreviousCustomMode) override;+ virtual void PhysCustom(float DeltaTime, int32 Iterations) override;+ virtual void ProcessLanded(const FHitResult& Hit, float RemainingTime, int32 Iterations) override;+ virtual void UpdateFromCompressedFlags(uint8 Flags) override;+ virtual FNetworkPredictionData_Client* GetPredictionData_Client() const override;+ virtual void MoveAutonomous(float ClientTimeStamp, float DeltaTime, uint8 CompressedFlags, const FVector& NewAccel) override;+ virtual void OnClientCorrectionReceived(FNetworkPredictionData_Client_Character& ClientData, float TimeStamp, FVector NewLocation, FVector NewVelocity,+ UPrimitiveComponent* NewBase, FName NewBaseBoneName, bool bHasBase, bool bBaseRelativePosition, uint8 ServerMovementMode, FVector ServerGravityDirection) override;+ virtual void ClientHandleMoveResponse(const FCharacterMoveResponseDataContainer& MoveResponse) override;+ virtual bool ClientUpdatePositionAfterServerUpdate() override;+ virtual void ServerMove_PerformMovement(const FCharacterNetworkMoveData& MoveData) override;+ virtual void ServerMoveHandleClientError(float ClientTimeStamp, float DeltaTime, const FVector& Accel, const FVector& RelativeClientLocation,+ UPrimitiveComponent* ClientMovementBase, FName ClientBaseBoneName, uint8 ClientMovementMode) override;+ virtual bool ServerCheckClientError(float ClientTimeStamp, float DeltaTime, const FVector& Accel, const FVector& ClientWorldLocation, const FVector& RelativeClientLocation,+ UPrimitiveComponent* ClientMovementBase, FName ClientBaseBoneName, uint8 ClientMovementMode) override;++protected:+ AVerseCharacter* GetVerseCharacter() const;++ void UpdateStance(float DeltaSeconds);+ void UpdateLean(float DeltaSeconds);+ /** Lean may be held now (stand or crouch, not sprinting, mantling or in a prone transition). */+ bool CanLeanNow() const;+ /** Server-authoritative prone turn cap: clamps the yaw change since the last move. */+ void ApplyProneTurnCap(float DeltaSeconds);+ /** Keeps the prone body out of walls: undoes the turn, then the move, that pushed it in. */+ void ConstrainProneBody();+ void SetActorYaw(float Yaw, bool bAlsoControl);+ bool TryStartSlide();+ void EndSlide(bool bToFalling);+ void PhysSlide(float DeltaTime, int32 Iterations);+ bool TryStartMantle();+ void UpdateMantle(float DeltaSeconds);+ void FinishMantle();+ void ApplyMantleSource(const FVector& From, const FVector& To, float Duration);+ void EmitNoise(const FGameplayTag& Noise, const FVector& Location);+ void UpdateFootsteps(float DeltaSeconds, const FVector& OldLocation);+ bool BodyShapeFits(EVerseBodyShape Shape, const FVector& FeetLocation) const;+ float HalfHeightFor(EVerseBodyShape Shape) const;+ float RadiusFor(EVerseBodyShape Shape) const;+ void ApplyTuningToMovement();++ UPROPERTY(EditAnywhere, Category = "Verse|Movement")+ TObjectPtr<UVerseMovementTuning> TuningAsset;++public:+ /**+ * Server: a client location within this distance of the server's (same movement mode) is not+ * corrected. Lost and reordered move packets leave errors of 1-5 cm that the stock 1.73 cm+ * threshold would correct. The server never adopts the client's location.+ */+ UPROPERTY(EditAnywhere, Category = "Verse|Movement")+ float ServerCorrectionToleranceCm = 5.f;++protected:++ FVerseMovementTuningValues TuningValues;++ // Wants (inputs; flags and move data).+ bool bWantsSprint = false;+ bool bWantsProne = false;+ bool bWantsMantle = false;+ int8 LeanTargetQuantized = 0;++ // Simulated state; saved and restored per move (FVerseSavedMove).+ EVerseStance Stance = EVerseStance::Stand;+ EVerseBodyShape BodyShape = EVerseBodyShape::Stand;+ int8 LeanQuantized = 0;+ /** Lean as simulated; LeanQuantized is what travels and what other modules read. */+ float LeanValue = 0.f;+ float ProneTransitionRemaining = 0.f;+ bool bProneExiting = false;+ float SlideElapsed = 0.f;+ float SlideCooldownRemaining = 0.f;+ bool bPrevWantsCrouch = false;+ bool bMantleLatched = false;+ float MantleElapsed = -1.f;+ float MantlePlanDuration = 0.f;+ float MantleRiseDuration = 0.f;+ FVector MantleRise = FVector::ZeroVector;+ FVector MantleTarget = FVector::ZeroVector;+ bool bMantleVault = false;+ uint16 MantleSourceId = 0;+ float StrideRemaining = 0.f;+ float LastMoveYaw = 0.f;+ bool bHasLastMoveYaw = false;+ /** Location at the start of the running move (prone body constraint). */+ FVector MoveStartLocation = FVector::ZeroVector;+ /** Client: the last correction was accepted (its move was still saved). */+ bool bCorrectionAccepted = false;+ /** Client: move timestamp of the last correction applied (sent with every move). */+ float LastAppliedCorrectionStamp = -1.f;+ /** Server: move timestamp and server time of the last correction sent. */+ float LastSentCorrectionStamp = -1.f;+ double LastSentCorrectionTime = -1.0;+ /** Server: the remote client's location at the end of its previous move (world, no moving base). */+ FVector ServerLastClientLocation = FVector::ZeroVector;+ bool bHasServerLastClientLocation = false;++ // Server: the lean value the client sent with the current move (-128 = none).+ int16 PendingClientLean = -128;++ int32 MantleCount = 0;+ FVerseMovementNetStats NetStats;+ TUniquePtr<FCharacterNetworkMoveDataContainer> MoveDataContainer;+ TUniquePtr<FCharacterMoveResponseDataContainer> MoveResponseContainer;+ uint64 TickCycles = 0;+ int32 TickCountTotal = 0;+};diff --git a/unreal/Verse/Source/VerseMovement/Public/VerseHitZones.h b/unreal/Verse/Source/VerseMovement/Public/VerseHitZones.hnew file mode 100644index 0000000000..9919f05f85--- /dev/null+++ b/unreal/Verse/Source/VerseMovement/Public/VerseHitZones.h@@ -0,0 +1,32 @@+#pragma once++#include "Combat/VerseCombatTypes.h"+#include "CoreMinimal.h"++class UPhysicsAsset;+class USkeletalMesh;+class UPrimitiveComponent;+struct FHitResult;++/**+ * Bone to EVerseHitZone (combat-state.md 5: "the physics body hit maps to EVerseHitZone through+ * a bone table in the character's physics asset"; art-pipeline.md 12.1 bone names). The hit+ * bodies are the physics asset's bodies on the character mesh, so stance and lean move them.+ */+namespace VerseHitZones+{+ /** The zone of one bone of SKEL_Verse_Human by name; None for bones without a zone. */+ VERSEMOVEMENT_API EVerseHitZone ZoneForBoneName(FName Bone);++ /** Like ZoneForBoneName, but walks up the mesh's bone parents until a bone has a zone. */+ VERSEMOVEMENT_API EVerseHitZone ZoneForBone(const USkeletalMesh* Mesh, FName Bone);++ /**+ * The table of a physics asset: one entry per body. False (OutError names the body) when a+ * body maps to no zone, so a new rig cannot silently lose a zone.+ */+ VERSEMOVEMENT_API bool BuildTable(const UPhysicsAsset* Physics, const USkeletalMesh* Mesh, TMap<FName, EVerseHitZone>& OutTable, FString& OutError);++ /** The zone a VerseHitBody trace hit: a mesh body by bone, the prone body box as Leg. */+ VERSEMOVEMENT_API EVerseHitZone ZoneForHit(const FHitResult& Hit);+}diff --git a/unreal/Verse/Source/VerseMovement/Public/VerseInputFrameBuilder.h b/unreal/Verse/Source/VerseMovement/Public/VerseInputFrameBuilder.hnew file mode 100644index 0000000000..3656cf73fb--- /dev/null+++ b/unreal/Verse/Source/VerseMovement/Public/VerseInputFrameBuilder.h@@ -0,0 +1,87 @@+#pragma once++#include "Combat/VerseCombatTypes.h"+#include "CoreMinimal.h"+#include "InputCoreTypes.h"++class UInputComponent;++/** A key by its engine name ("W", "SpaceBar", "MouseX"): no link to InputCore's EKeys table needed. */+inline FKey VerseKey(const TCHAR* Name)+{+ return FKey(Name);+}++/** Movement keys of the person's default mapping (W, S, D, A). */+enum class EVerseMoveKey : uint8+{+ Forward,+ Back,+ Right,+ Left+};++/**+ * Collects the person's input between ticks and emits one FVerseInputFrame per tick, the same+ * struct a bot produces (bot.md B1). Buttons are "held" bits; Pressed is derived from the+ * previous frame, so a person and a bot that hold the same buttons produce the same frames.+ * Crouch and prone are toggles for the person (pressing toggles the held bit).+ */+struct VERSEMOVEMENT_API FVerseInputFrameBuilder+{+ /** Move stick, -1..1, X forward, Y right. Kept until changed; keys and the gamepad stick win over it. */+ void SetMove(const FVector2f& Move) { Move2D = Move; }+ /** A movement key went down or up. */+ void SetMoveKey(EVerseMoveKey Key, bool bHeld);+ /** Gamepad left stick, per axis (0 forward, 1 right), after the input settings' dead zone. */+ void SetStickAxis(int32 Axis, float Value);+ /** Look added this tick, degrees (pitch, yaw). Accumulates until the frame is taken. */+ void AddLook(const FVector2f& PitchYawDeg) { LookAccum += PitchYawDeg; }+ void SetButton(EVerseInputButton Button, bool bHeld);+ void ToggleButton(EVerseInputButton Button);+ /** Walk modifier: scales the move stick for quiet footsteps. */+ void SetWalkModifier(bool bHeld) { bWalk = bHeld; }+ bool IsHeld(EVerseInputButton Button) const { return (Buttons & uint32(Button)) != 0; }+ uint32 GetButtons() const { return Buttons; }++ /** The frame for this tick; clears the accumulated look and derives Pressed. */+ FVerseInputFrame Consume(uint32 ServerTimeMs);++ /** Forget everything (possession change). */+ void Reset();++ /** Move scale while the walk modifier is held. */+ float WalkScale = 0.5f;++private:+ FVector2f Move2D = FVector2f::ZeroVector;+ FVector2f Stick = FVector2f::ZeroVector;+ FVector2f LookAccum = FVector2f::ZeroVector;+ uint8 MoveKeys = 0;+ uint32 Buttons = 0;+ uint32 PrevButtons = 0;+ bool bWalk = false;+};++/**+ * The person's default key mapping (keyboard, mouse, gamepad), bound as plain key and axis+ * bindings on the pawn's input component. They work under the project's Enhanced Input player+ * input as well; moving them to Enhanced Input actions needs the module dependency (contract+ * change request for VerseMovement.Build.cs).+ */+namespace VersePersonInput+{+ /**+ * Mouse degrees per count. The input settings' MouseX/MouseY axis config already scales a+ * count by 0.07, so the bound axis value is in degrees.+ */+ inline constexpr float MouseDegPerValue = 1.f;+ /** Gamepad right stick: degrees per second at full deflection. */+ inline constexpr float StickDegPerSecond = 180.f;++ /**+ * Binds every movement key into Builder. Builder must outlive Input's bindings (the pawn owns+ * both). DeltaSeconds gives the frame time the stick look rate scales with.+ */+ VERSEMOVEMENT_API void BindDefaults(UInputComponent& Input, FVerseInputFrameBuilder& Builder, TFunction<float()> DeltaSeconds);+}diff --git a/unreal/Verse/Source/VerseMovement/Public/VerseInputFrameController.h b/unreal/Verse/Source/VerseMovement/Public/VerseInputFrameController.hnew file mode 100644index 0000000000..4d42f5d7a9--- /dev/null+++ b/unreal/Verse/Source/VerseMovement/Public/VerseInputFrameController.h@@ -0,0 +1,31 @@+#pragma once++#include "Combat/VerseCombatTypes.h"+#include "CoreMinimal.h"+#include "GameFramework/Controller.h"++#include "VerseInputFrameController.generated.h"++/**+ * A server-side controller that drives its AVerseCharacter only through FVerseInputFrame+ * (bot.md B1, 8.3; architecture.md 3.4): the bot and the harness person models produce frames,+ * this controller hands them to the pawn's one input consumer, exactly like the person's input.+ * A frame persists (held buttons, stick) until the next one; Pressed and look apply once.+ */+UCLASS()+class VERSEMOVEMENT_API AVerseInputFrameController : public AController+{+ GENERATED_BODY()++public:+ AVerseInputFrameController();++ /** The frame for the pawn's next tick. */+ void SubmitFrame(const FVerseInputFrame& Frame);++ /** Frames submitted so far. */+ int32 GetSubmittedCount() const { return SubmittedCount; }++private:+ int32 SubmittedCount = 0;+};diff --git a/unreal/Verse/Source/VerseMovement/Public/VerseMovementTuning.h b/unreal/Verse/Source/VerseMovement/Public/VerseMovementTuning.hnew file mode 100644index 0000000000..47e47f2f27--- /dev/null+++ b/unreal/Verse/Source/VerseMovement/Public/VerseMovementTuning.h@@ -0,0 +1,135 @@+#pragma once++#include "CoreMinimal.h"+#include "Engine/DataAsset.h"++#include "VerseMovementTuning.generated.h"++/**+ * Movement tuning in SI units (metres, seconds, degrees), the shape of+ * unreal/Verse/Data/movement/movement_tuning.json. The defaults are the start values of+ * work-packages.md WP01; they are tuning, not contract, and change through the harness.+ * Code reads them through the *Cm() helpers, which convert to Unreal centimetres.+ */+USTRUCT(BlueprintType)+struct VERSEMOVEMENT_API FVerseMovementTuningValues+{+ GENERATED_BODY()++ // Speeds, m/s.+ UPROPERTY(EditAnywhere, Category = "Speed") float WalkSpeed = 4.5f;+ UPROPERTY(EditAnywhere, Category = "Speed") float SprintSpeed = 6.5f;+ UPROPERTY(EditAnywhere, Category = "Speed") float CrouchSpeed = 2.2f;+ UPROPERTY(EditAnywhere, Category = "Speed") float ProneSpeed = 0.9f;+ /** Sprint needs the move input within this angle of the facing. */+ UPROPERTY(EditAnywhere, Category = "Speed") float SprintMaxAngleDeg = 45.f;+ /** Standing ground speed at or below which footsteps are "walk" (4 m) instead of "run" (10 m). */+ UPROPERTY(EditAnywhere, Category = "Speed") float QuietWalkMaxSpeed = 2.6f;++ // Slide.+ UPROPERTY(EditAnywhere, Category = "Slide") float SlideMinEntrySpeed = 5.5f;+ UPROPERTY(EditAnywhere, Category = "Slide") float SlideBoostSpeed = 7.5f;+ /** The slide has decayed to crouch speed by this time at the latest. */+ UPROPERTY(EditAnywhere, Category = "Slide") float SlideMaxDuration = 1.1f;+ UPROPERTY(EditAnywhere, Category = "Slide") float SlideCooldown = 1.0f;+ /** 1 = linear decay from boost to crouch speed; above 1 holds the speed longer. */+ UPROPERTY(EditAnywhere, Category = "Slide") float SlideDecayExponent = 1.4f;++ // Jump.+ UPROPERTY(EditAnywhere, Category = "Jump") float JumpApexHeight = 0.55f;++ // Mantle.+ UPROPERTY(EditAnywhere, Category = "Mantle") float MantleMinHeight = 0.5f;+ UPROPERTY(EditAnywhere, Category = "Mantle") float MantleLowMaxHeight = 1.2f;+ UPROPERTY(EditAnywhere, Category = "Mantle") float MantleHighMaxHeight = 2.0f;+ UPROPERTY(EditAnywhere, Category = "Mantle") float MantleLowDuration = 0.45f;+ UPROPERTY(EditAnywhere, Category = "Mantle") float MantleHighDuration = 0.85f;+ /** Horizontal reach from the capsule surface to the ledge face. */+ UPROPERTY(EditAnywhere, Category = "Mantle") float MantleReach = 0.6f;+ /** Share of the mantle spent rising; the rest moves onto the ledge. */+ UPROPERTY(EditAnywhere, Category = "Mantle") float MantleRiseFraction = 0.55f;+ /** Ledge faces more than this far off the facing are not mantled. */+ UPROPERTY(EditAnywhere, Category = "Mantle") float MantleMaxFaceAngleDeg = 55.f;++ // Lean.+ UPROPERTY(EditAnywhere, Category = "Lean") float LeanCameraOffset = 0.35f;+ UPROPERTY(EditAnywhere, Category = "Lean") float LeanRollDeg = 12.f;+ UPROPERTY(EditAnywhere, Category = "Lean") float LeanEnterTime = 0.15f;+ /** Radius kept clear around the leaned camera by the wall check. */+ UPROPERTY(EditAnywhere, Category = "Lean") float LeanCameraClearance = 0.12f;++ // Prone.+ UPROPERTY(EditAnywhere, Category = "Prone") float ProneEnterTime = 0.7f;+ UPROPERTY(EditAnywhere, Category = "Prone") float ProneExitTime = 0.6f;+ UPROPERTY(EditAnywhere, Category = "Prone") float ProneTurnCapDegPerSec = 90.f;+ /** Vertical space the whole prone body needs. */+ UPROPERTY(EditAnywhere, Category = "Prone") float ProneMinClearance = 0.4f;+ /** Length of the horizontal prone body box, feet to head. */+ UPROPERTY(EditAnywhere, Category = "Prone") float ProneBodyLength = 1.8f;+ UPROPERTY(EditAnywhere, Category = "Prone") float ProneBodyWidth = 0.5f;++ // Capsule and eyes (feet-relative heights).+ UPROPERTY(EditAnywhere, Category = "Body") float CapsuleRadius = 0.34f;+ UPROPERTY(EditAnywhere, Category = "Body") float StandHeight = 1.8f;+ UPROPERTY(EditAnywhere, Category = "Body") float CrouchHeight = 1.1f;+ UPROPERTY(EditAnywhere, Category = "Body") float ProneRadius = 0.2f;+ UPROPERTY(EditAnywhere, Category = "Body") float StandEyeHeight = 1.65f;+ UPROPERTY(EditAnywhere, Category = "Body") float CrouchEyeHeight = 0.98f;+ UPROPERTY(EditAnywhere, Category = "Body") float ProneEyeHeight = 0.3f;+ /** Seconds the camera takes to settle on a new eye height. */+ UPROPERTY(EditAnywhere, Category = "Body") float EyeBlendTime = 0.12f;++ // Noise (bot.md 3.2; ranges come from DA_Audibility, not from here).+ UPROPERTY(EditAnywhere, Category = "Noise") float WalkStride = 0.7f;+ UPROPERTY(EditAnywhere, Category = "Noise") float RunStride = 0.95f;+ UPROPERTY(EditAnywhere, Category = "Noise") float SprintStride = 1.25f;+ /** Landing raises Noise.Move.Land at or above this fall speed. */+ UPROPERTY(EditAnywhere, Category = "Noise") float LandNoiseMinFallSpeed = 3.0f;++ float WalkSpeedCm() const { return WalkSpeed * 100.f; }+ float SprintSpeedCm() const { return SprintSpeed * 100.f; }+ float CrouchSpeedCm() const { return CrouchSpeed * 100.f; }+ float ProneSpeedCm() const { return ProneSpeed * 100.f; }+ float StandHalfHeightCm() const { return StandHeight * 50.f; }+ float CrouchHalfHeightCm() const { return CrouchHeight * 50.f; }+ /** The prone capsule is a sphere-like capsule of the prone clearance. */+ float ProneHalfHeightCm() const { return FMath::Max(ProneRadius * 100.f, ProneMinClearance * 50.f); }+ float JumpZVelocityCm(float GravityZ) const { return FMath::Sqrt(2.f * FMath::Abs(GravityZ) * JumpApexHeight * 100.f); }++ /** Every value finite and in a sane range; OutError names the first that is not. */+ bool Validate(FString& OutError) const;+};++/**+ * DA_MovementTuning: the movement DataAsset (work-packages.md WP01.1). Its source of truth is+ * Data/movement/movement_tuning.json; the asset is imported from it, and code without an+ * asset loads the JSON directly (GetDefaultTuning).+ */+UCLASS(BlueprintType)+class VERSEMOVEMENT_API UVerseMovementTuning : public UPrimaryDataAsset+{+ GENERATED_BODY()++public:+ UPROPERTY(EditAnywhere, BlueprintReadOnly, Category = "Movement")+ FVerseMovementTuningValues Values;++ /** Parses JSON (field names as in FVerseMovementTuningValues; unknown fields fail). */+ static bool ParseJson(const FString& Json, FVerseMovementTuningValues& Out, FString& OutError);++ /** Replaces Values from a JSON file; false (Values unchanged) on any error. */+ bool LoadFromJsonFile(const FString& Path, FString& OutError);++ /** Editor import (Content/Verse/Test/WP01/make_content.py): Values from the JSON file. */+ UFUNCTION(BlueprintCallable, Category = "Verse|Movement")+ bool ImportJsonFile(const FString& Path, FString& OutError) { return LoadFromJsonFile(Path, OutError); }++ /** The values as JSON in the shape the file uses. */+ static FString ToJson(const FVerseMovementTuningValues& Values);++ /** unreal/Verse/Data/movement/movement_tuning.json of the running project. */+ static FString DefaultJsonPath();++ /** The process-wide default: the JSON file when it loads, else the C++ start values. */+ static const UVerseMovementTuning* GetDefaultTuning();+};