Skip to content

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.

feat(verse): add weapons, recoil, bolts, lag compensation and gadgets (#1153)

Ruben Lütke69cc21d9e02a
diff --git a/unreal/Verse/Content/Verse/Combat/Abilities/Data/DA_Gadget_BreachCharge.uasset b/unreal/Verse/Content/Verse/Combat/Abilities/Data/DA_Gadget_BreachCharge.uasset
new file mode 100644
index 0000000000..c35cb95f11
--- /dev/null
+++ b/unreal/Verse/Content/Verse/Combat/Abilities/Data/DA_Gadget_BreachCharge.uasset
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:48e3c609b7327f80948c20ec33910814d70554263bd3012e1d23379f2e5dcb0d
+size 2127
diff --git a/unreal/Verse/Content/Verse/Combat/Abilities/Data/DA_Gadget_Bulwark.uasset b/unreal/Verse/Content/Verse/Combat/Abilities/Data/DA_Gadget_Bulwark.uasset
new file mode 100644
index 0000000000..6c6d592e2c
--- /dev/null
+++ b/unreal/Verse/Content/Verse/Combat/Abilities/Data/DA_Gadget_Bulwark.uasset
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:5967d45e514c579b942063503fa023297bc9ae16de44369b4f75e5d3a8fb046e
+size 1488
diff --git a/unreal/Verse/Content/Verse/Combat/Abilities/Data/DA_Weapon_Graveline.uasset b/unreal/Verse/Content/Verse/Combat/Abilities/Data/DA_Weapon_Graveline.uasset
new file mode 100644
index 0000000000..4a4027cf15
--- /dev/null
+++ b/unreal/Verse/Content/Verse/Combat/Abilities/Data/DA_Weapon_Graveline.uasset
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:aadad492aca0791a8aee7dbd78af0b6a8a542bb16fd3073bced23f55524688f7
+size 4615
diff --git a/unreal/Verse/Content/Verse/Combat/Abilities/Data/DA_Weapon_Longsight.uasset b/unreal/Verse/Content/Verse/Combat/Abilities/Data/DA_Weapon_Longsight.uasset
new file mode 100644
index 0000000000..3e4d0a4382
--- /dev/null
+++ b/unreal/Verse/Content/Verse/Combat/Abilities/Data/DA_Weapon_Longsight.uasset
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:51e8de53f9d70514175ae5444bd3dcccdfa2cafdf4832fa0766f45eaaf8bc945
+size 5442
diff --git a/unreal/Verse/Content/Verse/Combat/Abilities/Data/DA_Weapon_Skitter.uasset b/unreal/Verse/Content/Verse/Combat/Abilities/Data/DA_Weapon_Skitter.uasset
new file mode 100644
index 0000000000..388d2a5489
--- /dev/null
+++ b/unreal/Verse/Content/Verse/Combat/Abilities/Data/DA_Weapon_Skitter.uasset
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:9c0fc4ee49472c2978050395b8a7d1d94d4f8ac45a86cde26b7c7af8d631731f
+size 5009
diff --git a/unreal/Verse/Content/Verse/Combat/Abilities/Data/DA_Weapon_Tallow.uasset b/unreal/Verse/Content/Verse/Combat/Abilities/Data/DA_Weapon_Tallow.uasset
new file mode 100644
index 0000000000..39df5cf1e4
--- /dev/null
+++ b/unreal/Verse/Content/Verse/Combat/Abilities/Data/DA_Weapon_Tallow.uasset
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:7b1b0487f8d233189f4f1afca75c17154d523cb550bdfee75bcabdc6bdf85b2f
+size 5740
diff --git a/unreal/Verse/Content/Verse/Test/WP02/M_WP02_Placeholder.uasset b/unreal/Verse/Content/Verse/Test/WP02/M_WP02_Placeholder.uasset
new file mode 100644
index 0000000000..94cd460a96
--- /dev/null
+++ b/unreal/Verse/Content/Verse/Test/WP02/M_WP02_Placeholder.uasset
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:f0fd7a79cfc5704cc8ad951f491cbb991bc1ae1efb8d99d0851d0f30668eb5f1
+size 5845
diff --git a/unreal/Verse/Data/weapons/gadgets.json b/unreal/Verse/Data/weapons/gadgets.json
new file mode 100644
index 0000000000..b7b7d45673
--- /dev/null
+++ b/unreal/Verse/Data/weapons/gadgets.json
@@ -0,0 +1,43 @@
+{
+ "$schema": "verse.gadgets/1",
+ "gadgets": [
+ {
+ "GadgetId": "bulwark",
+ "DisplayName": "Bulwark",
+ "Charges": 1,
+ "Cooldown": 20,
+ "UseTime": 0.6,
+ "Lifetime": 25,
+ "PlaceRange": 1.5,
+ "MaxHealth": 400,
+ "Size": [
+ 1.8,
+ 1.4,
+ 0.1
+ ],
+ "PawnDamage": 0,
+ "PawnRadius": 0,
+ "PieceBreachRadius": 0,
+ "bSelfDamage": false
+ },
+ {
+ "GadgetId": "breach_charge",
+ "DisplayName": "Breach Charge",
+ "Charges": 2,
+ "Cooldown": 0,
+ "UseTime": 1.0,
+ "Lifetime": 2.5,
+ "PlaceRange": 1.5,
+ "MaxHealth": 0,
+ "Size": [
+ 0.3,
+ 0.3,
+ 0.1
+ ],
+ "PawnDamage": 120,
+ "PawnRadius": 3.0,
+ "PieceBreachRadius": 150,
+ "bSelfDamage": true
+ }
+ ]
+}
diff --git a/unreal/Verse/Data/weapons/graveline.json b/unreal/Verse/Data/weapons/graveline.json
new file mode 100644
index 0000000000..dbfa76317f
--- /dev/null
+++ b/unreal/Verse/Data/weapons/graveline.json
@@ -0,0 +1,107 @@
+{
+ "$schema": "verse.weapon/1",
+ "WeaponId": "graveline",
+ "DisplayName": "Graveline",
+ "Slot": "Primary",
+ "FireMode": "Auto",
+ "BurstCount": 3,
+ "RPM": 690,
+ "MagazineSize": 30,
+ "bClosedBolt": true,
+ "ReserveRounds": 120,
+ "ReloadTactical": 2.1,
+ "ReloadEmpty": 2.8,
+ "ReloadCommitFraction": 0.6,
+ "EquipTime": 0.45,
+ "HolsterTime": 0.3,
+ "BaseDamage": 28,
+ "ZoneMultipliers": {
+ "Head": 2.5,
+ "Neck": 1.5,
+ "UpperTorso": 1.0,
+ "LowerTorso": 0.9,
+ "Arm": 0.75,
+ "Leg": 0.7
+ },
+ "FalloffStart": 25,
+ "FalloffEnd": 45,
+ "FalloffMinFraction": 0.75,
+ "ProjectileSpeed": 300,
+ "MaxRange": 150,
+ "PenetrationPower": 100,
+ "MaxPenetrations": 3,
+ "PieceDamage": 10,
+ "HoleRadiusMm": 15,
+ "RecoilPitchCurve": [
+ [
+ 0,
+ 0.45
+ ],
+ [
+ 8,
+ 0.62
+ ]
+ ],
+ "RecoilYawCurve": [
+ [
+ 0,
+ 0.1
+ ],
+ [
+ 10,
+ 0.1
+ ],
+ [
+ 11,
+ -0.15
+ ]
+ ],
+ "RecoilRandomFraction": 0.15,
+ "RecoilKickTime": 0.01,
+ "RecoilRecoveryRate": 1.8,
+ "RecoilRecoveryDelay": 0.12,
+ "PatternResetTime": 0.35,
+ "RecoilStanceMultiplier": {
+ "Stand": 1.0,
+ "Crouch": 0.85,
+ "Prone": 0.65,
+ "Slide": 1.3
+ },
+ "RecoilAdsMultiplier": 0.8,
+ "ViewPunchScale": 1.0,
+ "AdsTime": 0.25,
+ "AdsFov": 55,
+ "AdsMoveSpeedMultiplier": 0.6,
+ "SpreadBase": {
+ "Stand": [
+ 1.6,
+ 0.15
+ ],
+ "Crouch": [
+ 1.2,
+ 0.1
+ ],
+ "Prone": [
+ 0.8,
+ 0.05
+ ],
+ "Slide": [
+ 3.0,
+ 1.5
+ ]
+ },
+ "FirstShotSpread": [
+ 0.9,
+ 0.0
+ ],
+ "FirstShotRestTime": 0.35,
+ "SpreadMovePerMps": 0.25,
+ "SpreadAirborne": 3.0,
+ "BloomPerShot": 0.12,
+ "BloomMax": 1.5,
+ "BloomRecoveryRate": 4.0,
+ "BloomRecoveryDelay": 0.1,
+ "NoiseLoudness": 1.0,
+ "BoltColorOwn": "Verse.Presentation.Bolt.Amber",
+ "BoltColorFoe": "Verse.Presentation.Bolt.Red"
+}
diff --git a/unreal/Verse/Data/weapons/longsight.json b/unreal/Verse/Data/weapons/longsight.json
new file mode 100644
index 0000000000..964d5e1ad9
--- /dev/null
+++ b/unreal/Verse/Data/weapons/longsight.json
@@ -0,0 +1,147 @@
+{
+ "$schema": "verse.weapon/1",
+ "WeaponId": "longsight",
+ "DisplayName": "Longsight",
+ "Slot": "Primary",
+ "FireMode": "Semi",
+ "BurstCount": 3,
+ "RPM": 240,
+ "MagazineSize": 12,
+ "bClosedBolt": true,
+ "ReserveRounds": 48,
+ "ReloadTactical": 2.3,
+ "ReloadEmpty": 3.0,
+ "ReloadCommitFraction": 0.6,
+ "EquipTime": 0.55,
+ "HolsterTime": 0.35,
+ "BaseDamage": 52,
+ "ZoneMultipliers": {
+ "Head": 2.6,
+ "Neck": 1.5,
+ "UpperTorso": 1.0,
+ "LowerTorso": 0.9,
+ "Arm": 0.8,
+ "Leg": 0.75
+ },
+ "FalloffStart": 40,
+ "FalloffEnd": 70,
+ "FalloffMinFraction": 0.8,
+ "ProjectileSpeed": 300,
+ "MaxRange": 150,
+ "PenetrationPower": 120,
+ "MaxPenetrations": 3,
+ "PieceDamage": 14,
+ "HoleRadiusMm": 18,
+ "RecoilPitchCurve": [
+ [
+ 0,
+ 1.6
+ ]
+ ],
+ "RecoilYawCurve": [
+ [
+ 0,
+ 0.2
+ ],
+ [
+ 1,
+ -0.2
+ ],
+ [
+ 2,
+ 0.2
+ ],
+ [
+ 3,
+ -0.2
+ ],
+ [
+ 4,
+ 0.2
+ ],
+ [
+ 5,
+ -0.2
+ ],
+ [
+ 6,
+ 0.2
+ ],
+ [
+ 7,
+ -0.2
+ ],
+ [
+ 8,
+ 0.2
+ ],
+ [
+ 9,
+ -0.2
+ ],
+ [
+ 10,
+ 0.2
+ ],
+ [
+ 11,
+ -0.2
+ ],
+ [
+ 12,
+ 0.2
+ ],
+ [
+ 13,
+ -0.2
+ ]
+ ],
+ "RecoilRandomFraction": 0.15,
+ "RecoilKickTime": 0.01,
+ "RecoilRecoveryRate": 2.0,
+ "RecoilRecoveryDelay": 0.15,
+ "PatternResetTime": 0.4,
+ "RecoilStanceMultiplier": {
+ "Stand": 1.0,
+ "Crouch": 0.85,
+ "Prone": 0.65,
+ "Slide": 1.3
+ },
+ "RecoilAdsMultiplier": 0.8,
+ "ViewPunchScale": 1.0,
+ "AdsTime": 0.3,
+ "AdsFov": 40,
+ "AdsMoveSpeedMultiplier": 0.5,
+ "SpreadBase": {
+ "Stand": [
+ 2.0,
+ 0.05
+ ],
+ "Crouch": [
+ 1.6,
+ 0.04
+ ],
+ "Prone": [
+ 1.2,
+ 0.02
+ ],
+ "Slide": [
+ 3.5,
+ 2.0
+ ]
+ },
+ "FirstShotSpread": [
+ 1.5,
+ 0.0
+ ],
+ "FirstShotRestTime": 0.4,
+ "SpreadMovePerMps": 0.35,
+ "SpreadAirborne": 3.0,
+ "BloomPerShot": 0.4,
+ "BloomMax": 2.0,
+ "BloomRecoveryRate": 4.0,
+ "BloomRecoveryDelay": 0.1,
+ "NoiseLoudness": 1.0,
+ "BoltColorOwn": "Verse.Presentation.Bolt.Amber",
+ "BoltColorFoe": "Verse.Presentation.Bolt.Red"
+}
diff --git a/unreal/Verse/Data/weapons/skitter.json b/unreal/Verse/Data/weapons/skitter.json
new file mode 100644
index 0000000000..fe84c30628
--- /dev/null
+++ b/unreal/Verse/Data/weapons/skitter.json
@@ -0,0 +1,107 @@
+{
+ "$schema": "verse.weapon/1",
+ "WeaponId": "skitter",
+ "DisplayName": "Skitter",
+ "Slot": "Primary",
+ "FireMode": "Auto",
+ "BurstCount": 3,
+ "RPM": 900,
+ "MagazineSize": 32,
+ "bClosedBolt": true,
+ "ReserveRounds": 128,
+ "ReloadTactical": 1.9,
+ "ReloadEmpty": 2.4,
+ "ReloadCommitFraction": 0.6,
+ "EquipTime": 0.35,
+ "HolsterTime": 0.25,
+ "BaseDamage": 20,
+ "ZoneMultipliers": {
+ "Head": 2.0,
+ "Neck": 1.4,
+ "UpperTorso": 1.0,
+ "LowerTorso": 0.9,
+ "Arm": 0.75,
+ "Leg": 0.7
+ },
+ "FalloffStart": 10,
+ "FalloffEnd": 25,
+ "FalloffMinFraction": 0.6,
+ "ProjectileSpeed": 300,
+ "MaxRange": 100,
+ "PenetrationPower": 60,
+ "MaxPenetrations": 2,
+ "PieceDamage": 7,
+ "HoleRadiusMm": 12,
+ "RecoilPitchCurve": [
+ [
+ 0,
+ 0.3
+ ],
+ [
+ 10,
+ 0.42
+ ]
+ ],
+ "RecoilYawCurve": [
+ [
+ 0,
+ -0.12
+ ],
+ [
+ 6,
+ -0.12
+ ],
+ [
+ 7,
+ 0.14
+ ]
+ ],
+ "RecoilRandomFraction": 0.15,
+ "RecoilKickTime": 0.01,
+ "RecoilRecoveryRate": 1.3,
+ "RecoilRecoveryDelay": 0.12,
+ "PatternResetTime": 0.3,
+ "RecoilStanceMultiplier": {
+ "Stand": 1.0,
+ "Crouch": 0.85,
+ "Prone": 0.65,
+ "Slide": 1.3
+ },
+ "RecoilAdsMultiplier": 0.8,
+ "ViewPunchScale": 1.0,
+ "AdsTime": 0.2,
+ "AdsFov": 60,
+ "AdsMoveSpeedMultiplier": 0.7,
+ "SpreadBase": {
+ "Stand": [
+ 1.8,
+ 0.3
+ ],
+ "Crouch": [
+ 1.5,
+ 0.25
+ ],
+ "Prone": [
+ 1.2,
+ 0.2
+ ],
+ "Slide": [
+ 3.0,
+ 1.8
+ ]
+ },
+ "FirstShotSpread": [
+ 1.1,
+ 0.1
+ ],
+ "FirstShotRestTime": 0.3,
+ "SpreadMovePerMps": 0.15,
+ "SpreadAirborne": 3.0,
+ "BloomPerShot": 0.1,
+ "BloomMax": 1.8,
+ "BloomRecoveryRate": 4.0,
+ "BloomRecoveryDelay": 0.1,
+ "NoiseLoudness": 1.0,
+ "BoltColorOwn": "Verse.Presentation.Bolt.Amber",
+ "BoltColorFoe": "Verse.Presentation.Bolt.Red"
+}
diff --git a/unreal/Verse/Data/weapons/tallow.json b/unreal/Verse/Data/weapons/tallow.json
new file mode 100644
index 0000000000..746204cb6e
--- /dev/null
+++ b/unreal/Verse/Data/weapons/tallow.json
@@ -0,0 +1,159 @@
+{
+ "$schema": "verse.weapon/1",
+ "WeaponId": "tallow",
+ "DisplayName": "Tallow",
+ "Slot": "Secondary",
+ "FireMode": "Semi",
+ "BurstCount": 3,
+ "RPM": 380,
+ "MagazineSize": 15,
+ "bClosedBolt": true,
+ "ReserveRounds": 60,
+ "ReloadTactical": 1.5,
+ "ReloadEmpty": 1.9,
+ "ReloadCommitFraction": 0.6,
+ "EquipTime": 0.3,
+ "HolsterTime": 0.25,
+ "BaseDamage": 34,
+ "ZoneMultipliers": {
+ "Head": 2.2,
+ "Neck": 1.4,
+ "UpperTorso": 1.0,
+ "LowerTorso": 0.9,
+ "Arm": 0.75,
+ "Leg": 0.7
+ },
+ "FalloffStart": 12,
+ "FalloffEnd": 30,
+ "FalloffMinFraction": 0.6,
+ "ProjectileSpeed": 300,
+ "MaxRange": 100,
+ "PenetrationPower": 50,
+ "MaxPenetrations": 2,
+ "PieceDamage": 6,
+ "HoleRadiusMm": 12,
+ "RecoilPitchCurve": [
+ [
+ 0,
+ 1.2
+ ]
+ ],
+ "RecoilYawCurve": [
+ [
+ 0,
+ 0.15
+ ],
+ [
+ 1,
+ -0.15
+ ],
+ [
+ 2,
+ 0.15
+ ],
+ [
+ 3,
+ -0.15
+ ],
+ [
+ 4,
+ 0.15
+ ],
+ [
+ 5,
+ -0.15
+ ],
+ [
+ 6,
+ 0.15
+ ],
+ [
+ 7,
+ -0.15
+ ],
+ [
+ 8,
+ 0.15
+ ],
+ [
+ 9,
+ -0.15
+ ],
+ [
+ 10,
+ 0.15
+ ],
+ [
+ 11,
+ -0.15
+ ],
+ [
+ 12,
+ 0.15
+ ],
+ [
+ 13,
+ -0.15
+ ],
+ [
+ 14,
+ 0.15
+ ],
+ [
+ 15,
+ -0.15
+ ],
+ [
+ 16,
+ 0.15
+ ]
+ ],
+ "RecoilRandomFraction": 0.15,
+ "RecoilKickTime": 0.01,
+ "RecoilRecoveryRate": 3.0,
+ "RecoilRecoveryDelay": 0.1,
+ "PatternResetTime": 0.3,
+ "RecoilStanceMultiplier": {
+ "Stand": 1.0,
+ "Crouch": 0.85,
+ "Prone": 0.65,
+ "Slide": 1.3
+ },
+ "RecoilAdsMultiplier": 0.85,
+ "ViewPunchScale": 1.0,
+ "AdsTime": 0.18,
+ "AdsFov": 65,
+ "AdsMoveSpeedMultiplier": 0.8,
+ "SpreadBase": {
+ "Stand": [
+ 1.2,
+ 0.2
+ ],
+ "Crouch": [
+ 1.0,
+ 0.15
+ ],
+ "Prone": [
+ 0.8,
+ 0.1
+ ],
+ "Slide": [
+ 2.5,
+ 1.2
+ ]
+ },
+ "FirstShotSpread": [
+ 0.7,
+ 0.0
+ ],
+ "FirstShotRestTime": 0.3,
+ "SpreadMovePerMps": 0.2,
+ "SpreadAirborne": 3.0,
+ "BloomPerShot": 0.25,
+ "BloomMax": 1.5,
+ "BloomRecoveryRate": 4.0,
+ "BloomRecoveryDelay": 0.1,
+ "NoiseLoudness": 1.0,
+ "BoltColorOwn": "Verse.Presentation.Bolt.Amber",
+ "BoltColorFoe": "Verse.Presentation.Bolt.Red"
+}
diff --git a/unreal/Verse/Source/VerseCombat/Private/Damage/VerseCombatStateComponent.cpp b/unreal/Verse/Source/VerseCombat/Private/Damage/VerseCombatStateComponent.cpp
index d7c8fab135..e10ac394a3 100644
--- a/unreal/Verse/Source/VerseCombat/Private/Damage/VerseCombatStateComponent.cpp
+++ b/unreal/Verse/Source/VerseCombat/Private/Damage/VerseCombatStateComponent.cpp
@@ -1,5 +1,8 @@
#include "Damage/VerseCombatStateComponent.h"
+#include "Engine/World.h"
+#include "Events/VerseEventHub.h"
+#include "GameFramework/Actor.h"
#include "Net/Core/PushModel/PushModel.h"
#include "Net/UnrealNetwork.h"
@@ -19,3 +22,66 @@ void UVerseCombatStateComponent::GetLifetimeReplicatedProps(TArray<FLifetimeProp
DOREPLIFETIME_WITH_PARAMS_FAST(UVerseCombatStateComponent, bSpawnProtected, Params);
DOREPLIFETIME_WITH_PARAMS_FAST(UVerseCombatStateComponent, SpawnProtectedUntil, Params);
}
+
+UVerseCombatStateComponent* UVerseCombatStateComponent::FindOn(const AActor* Actor)
+{
+ return Actor ? Actor->FindComponentByClass<UVerseCombatStateComponent>() : nullptr;
+}
+
+void UVerseCombatStateComponent::SetPhase(EVerseCombatPhase NewPhase)
+{
+ if (Phase != NewPhase)
+ {
+ Phase = NewPhase;
+ MARK_PROPERTY_DIRTY_FROM_NAME(UVerseCombatStateComponent, Phase, this);
+ }
+}
+
+void UVerseCombatStateComponent::BeginSpawnProtection(float Now, float Duration)
+{
+ bSpawnProtected = Duration > 0.f;
+ SpawnProtectedUntil = Now + FMath::Max(0.f, Duration);
+ MARK_PROPERTY_DIRTY_FROM_NAME(UVerseCombatStateComponent, bSpawnProtected, this);
+ MARK_PROPERTY_DIRTY_FROM_NAME(UVerseCombatStateComponent, SpawnProtectedUntil, this);
+}
+
+void UVerseCombatStateComponent::NotifyOffensiveAction(float Now)
+{
+ if (bSpawnProtected)
+ {
+ bSpawnProtected = false;
+ SpawnProtectedUntil = FMath::Min(SpawnProtectedUntil, Now);
+ MARK_PROPERTY_DIRTY_FROM_NAME(UVerseCombatStateComponent, bSpawnProtected, this);
+ MARK_PROPERTY_DIRTY_FROM_NAME(UVerseCombatStateComponent, SpawnProtectedUntil, this);
+ }
+}
+
+bool UVerseCombatStateComponent::IsSpawnProtected(float Now) const
+{
+ return bSpawnProtected && Now < SpawnProtectedUntil;
+}
+
+void UVerseCombatStateComponent::ClientReceiveHit_Implementation(const FVerseHitEvent& Hit)
+{
+ // The owning client learns of the hit (direction indicator); the server already raised it.
+ const AActor* Owner = GetOwner();
+ if (Owner && !Owner->HasAuthority())
+ {
+ if (UVerseEventHub* Hub = UVerseEventHub::Get(this))
+ {
+ Hub->OnHit.Broadcast(Hit);
+ }
+ }
+}
+
+void UVerseCombatStateComponent::MulticastDeath_Implementation(const FVerseDeathEvent& Death)
+{
+ const AActor* Owner = GetOwner();
+ if (Owner && !Owner->HasAuthority())
+ {
+ if (UVerseEventHub* Hub = UVerseEventHub::Get(this))
+ {
+ Hub->OnDeath.Broadcast(Death);
+ }
+ }
+}
diff --git a/unreal/Verse/Source/VerseCombat/Private/Damage/VerseDamageMath.cpp b/unreal/Verse/Source/VerseCombat/Private/Damage/VerseDamageMath.cpp
new file mode 100644
index 0000000000..c85ca7b30b
--- /dev/null
+++ b/unreal/Verse/Source/VerseCombat/Private/Damage/VerseDamageMath.cpp
@@ -0,0 +1,56 @@
+#include "Damage/VerseDamageMath.h"
+
+#include "Combat/VerseWeaponDefinition.h"
+
+float FVerseDamageMath::Falloff(const UVerseWeaponDefinition& W, float DistanceM)
+{
+ const float D = FMath::Max(0.f, DistanceM);
+ if (D <= W.FalloffStart)
+ {
+ return 1.f;
+ }
+ if (D >= W.FalloffEnd || W.FalloffEnd <= W.FalloffStart)
+ {
+ return W.FalloffMinFraction;
+ }
+ const float T = (D - W.FalloffStart) / (W.FalloffEnd - W.FalloffStart);
+ return FMath::Lerp(1.f, W.FalloffMinFraction, T);
+}
+
+float FVerseDamageMath::ZoneMultiplier(const UVerseWeaponDefinition& W, EVerseHitZone Zone)
+{
+ if (Zone == EVerseHitZone::None)
+ {
+ return 0.f;
+ }
+ const float* Found = W.ZoneMultipliers.Find(Zone);
+ return Found ? *Found : 1.f;
+}
+
+float FVerseDamageMath::BoltDamage(const UVerseWeaponDefinition& W, EVerseHitZone Zone, float DistanceM, float PenetrationFactor)
+{
+ return W.BaseDamage * ZoneMultiplier(W, Zone) * Falloff(W, DistanceM) * FMath::Max(0.f, PenetrationFactor);
+}
+
+FVerseDamageSplit FVerseDamageMath::Split(float Damage, float Health, float Armor, float MaxArmor)
+{
+ FVerseDamageSplit Out;
+ const float D = FMath::Max(0.f, Damage);
+ Out.ToArmor = (MaxArmor > 0.f) ? FMath::Min(FMath::Max(0.f, Armor), D) : 0.f;
+ Out.ToHealth = D - Out.ToArmor;
+ Out.ArmorAfter = FMath::Max(0.f, Armor - Out.ToArmor);
+ Out.HealthAfter = FMath::Max(0.f, Health - Out.ToHealth);
+ Out.bKilled = Health > 0.f && Out.HealthAfter <= 0.f;
+ return Out;
+}
+
+int32 FVerseDamageMath::HitsToKill(const UVerseWeaponDefinition& W, EVerseHitZone Zone, float DistanceM, float MaxHealth)
+{
+ const float D = BoltDamage(W, Zone, DistanceM, 1.f);
+ if (D <= 0.f)
+ {
+ return MAX_int32;
+ }
+ // A tiny epsilon keeps exact multiples (4 x 25 = 100) at the lower count.
+ return FMath::CeilToInt((MaxHealth - 1e-4f) / D);
+}
diff --git a/unreal/Verse/Source/VerseCombat/Private/Damage/VerseDamageService.cpp b/unreal/Verse/Source/VerseCombat/Private/Damage/VerseDamageService.cpp
new file mode 100644
index 0000000000..71de6c429d
--- /dev/null
+++ b/unreal/Verse/Source/VerseCombat/Private/Damage/VerseDamageService.cpp
@@ -0,0 +1,157 @@
+#include "Damage/VerseDamageService.h"
+
+#include "AbilitySystemComponent.h"
+#include "AbilitySystemGlobals.h"
+#include "Damage/VerseCombatStateComponent.h"
+#include "Damage/VerseHealthSet.h"
+#include "Engine/World.h"
+#include "Events/VerseEventHub.h"
+#include "GameFramework/Pawn.h"
+#include "GameFramework/PlayerState.h"
+
+int32 VerseCombatIds::IdOf(const AActor* Actor)
+{
+ if (!Actor)
+ {
+ return -1;
+ }
+ if (const APawn* Pawn = Cast<APawn>(Actor))
+ {
+ if (const APlayerState* Ps = Pawn->GetPlayerState())
+ {
+ return Ps->GetPlayerId();
+ }
+ }
+ if (const APlayerState* Ps = Cast<APlayerState>(Actor))
+ {
+ return Ps->GetPlayerId();
+ }
+ // Actors without a player state (gadgets' owners in tests, targets): stable, never -1.
+ return -2 - int32(Actor->GetUniqueID() & 0x3FFFFFFF);
+}
+
+UVerseDamageService* UVerseDamageService::Get(const UObject* WorldContextObject)
+{
+ const UWorld* World = WorldContextObject ? WorldContextObject->GetWorld() : nullptr;
+ return World ? World->GetSubsystem<UVerseDamageService>() : nullptr;
+}
+
+float UVerseDamageService::Now() const
+{
+ const UWorld* World = GetWorld();
+ return World ? World->GetTimeSeconds() : 0.f;
+}
+
+UAbilitySystemComponent* UVerseDamageService::FindAsc(const AActor* Actor)
+{
+ return Actor ? UAbilitySystemGlobals::GetAbilitySystemComponentFromActor(Actor) : nullptr;
+}
+
+const UVerseHealthSet* UVerseDamageService::FindHealth(const AActor* Actor)
+{
+ const UAbilitySystemComponent* Asc = FindAsc(Actor);
+ return Asc ? Asc->GetSet<UVerseHealthSet>() : nullptr;
+}
+
+float UVerseDamageService::ApplyHit(AActor* Instigator, AActor* Victim, FVerseHitEvent& Hit)
+{
+ if (!Victim || !Victim->HasAuthority())
+ {
+ return 0.f;
+ }
+ const float T = Now();
+ Hit.ServerTime = T;
+ Hit.InstigatorId = VerseCombatIds::IdOf(Instigator);
+ Hit.VictimId = VerseCombatIds::IdOf(Victim);
+ Hit.bHeadshot = Hit.Zone == EVerseHitZone::Head ? 1 : 0;
+
+ UVerseCombatStateComponent* State = UVerseCombatStateComponent::FindOn(Victim);
+ if (State && State->Phase == EVerseCombatPhase::Dead)
+ {
+ return 0.f;
+ }
+
+ bool bBlocked = false;
+ if (State && State->IsSpawnProtected(T))
+ {
+ bBlocked = true;
+ Hit.bBlockedBySpawnProtection = 1;
+ }
+ // A finisher victim takes no other damage (combat-state.md 7.4).
+ if (State && State->Phase == EVerseCombatPhase::FinisherVictim && Hit.Source != EVerseDamageSource::Finisher)
+ {
+ bBlocked = true;
+ }
+
+ FVerseDamageQuery Query;
+ Query.Instigator = Instigator;
+ Query.Victim = Victim;
+ Query.Source = Hit.Source;
+ Query.Zone = Hit.Zone;
+ if (!bBlocked && Rules.CanDamage && !Rules.CanDamage(Query))
+ {
+ bBlocked = true;
+ }
+
+ float Damage = bBlocked ? 0.f : FMath::Max(0.f, Hit.Damage);
+ if (!bBlocked && Rules.ModifyDamage)
+ {
+ Damage = FMath::Max(0.f, Rules.ModifyDamage(Query, Damage));
+ }
+ Hit.Damage = Damage;
+
+ float Applied = 0.f;
+ bool bKilled = false;
+ if (Damage > 0.f)
+ {
+ UAbilitySystemComponent* Asc = FindAsc(Victim);
+ const UVerseHealthSet* Set = Asc ? Asc->GetSet<UVerseHealthSet>() : nullptr;
+ if (Asc && Set)
+ {
+ const float Before = Set->GetHealth();
+ FGameplayEffectContextHandle Context = Asc->MakeEffectContext();
+ Context.AddInstigator(Instigator, Instigator);
+ FGameplayEffectSpec Spec(GetDefault<UVerseDamageEffect>(), Context, 1.f);
+ Spec.SetSetByCallerMagnitude(UVerseDamageEffect::DamageName, Damage);
+ Asc->ApplyGameplayEffectSpecToSelf(Spec);
+ Applied = Set->LastToArmor + Set->LastToHealth;
+ bKilled = Before > 0.f && Set->GetHealth() <= 0.f;
+ }
+ }
+ Hit.bKillingBlow = bKilled ? 1 : 0;
+
+ UVerseEventHub* Hub = UVerseEventHub::Get(this);
+ if (Hub)
+ {
+ Hub->OnHit.Broadcast(Hit);
+ }
+ if (State)
+ {
+ State->ClientReceiveHit(Hit);
+ }
+
+ if (bKilled)
+ {
+ FVerseDeathEvent Death;
+ Death.VictimId = Hit.VictimId;
+ Death.KillerId = Hit.InstigatorId;
+ Death.Cause = Hit.Source;
+ Death.WeaponId = Hit.WeaponId;
+ Death.LastZone = Hit.Zone;
+ Death.ServerTime = T;
+ Death.RespawnAt = T + DefaultRespawnDelay;
+ if (State)
+ {
+ State->SetPhase(EVerseCombatPhase::Dead);
+ }
+ if (Hub)
+ {
+ Hub->OnDeath.Broadcast(Death);
+ }
+ if (State)
+ {
+ State->MulticastDeath(Death);
+ }
+ }
+ return Applied;
+}
diff --git a/unreal/Verse/Source/VerseCombat/Private/Damage/VerseHealthSet.cpp b/unreal/Verse/Source/VerseCombat/Private/Damage/VerseHealthSet.cpp
new file mode 100644
index 0000000000..86f25d81ea
--- /dev/null
+++ b/unreal/Verse/Source/VerseCombat/Private/Damage/VerseHealthSet.cpp
@@ -0,0 +1,88 @@
+#include "Damage/VerseHealthSet.h"
+
+#include "Damage/VerseDamageMath.h"
+#include "GameplayEffectExtension.h"
+#include "Net/UnrealNetwork.h"
+
+const FName UVerseDamageEffect::DamageName(TEXT("Verse.Damage"));
+
+UVerseHealthSet::UVerseHealthSet()
+{
+ InitHealth(StartHealth);
+ InitMaxHealth(StartHealth);
+ InitArmor(0.f);
+ InitMaxArmor(0.f);
+ InitIncomingDamage(0.f);
+}
+
+void UVerseHealthSet::GetLifetimeReplicatedProps(TArray<FLifetimeProperty>& OutLifetimeProps) const
+{
+ Super::GetLifetimeReplicatedProps(OutLifetimeProps);
+ DOREPLIFETIME_CONDITION_NOTIFY(UVerseHealthSet, Health, COND_OwnerOnly, REPNOTIFY_Always);
+ DOREPLIFETIME_CONDITION_NOTIFY(UVerseHealthSet, MaxHealth, COND_OwnerOnly, REPNOTIFY_Always);
+ DOREPLIFETIME_CONDITION_NOTIFY(UVerseHealthSet, Armor, COND_OwnerOnly, REPNOTIFY_Always);
+ DOREPLIFETIME_CONDITION_NOTIFY(UVerseHealthSet, MaxArmor, COND_OwnerOnly, REPNOTIFY_Always);
+}
+
+void UVerseHealthSet::PreAttributeChange(const FGameplayAttribute& Attribute, float& NewValue)
+{
+ Super::PreAttributeChange(Attribute, NewValue);
+ if (Attribute == GetHealthAttribute())
+ {
+ NewValue = FMath::Clamp(NewValue, 0.f, GetMaxHealth());
+ }
+ else if (Attribute == GetArmorAttribute())
+ {
+ NewValue = FMath::Clamp(NewValue, 0.f, GetMaxArmor());
+ }
+}
+
+void UVerseHealthSet::PostGameplayEffectExecute(const FGameplayEffectModCallbackData& Data)
+{
+ Super::PostGameplayEffectExecute(Data);
+ if (Data.EvaluatedData.Attribute != GetIncomingDamageAttribute())
+ {
+ return;
+ }
+ const float Damage = GetIncomingDamage();
+ SetIncomingDamage(0.f);
+ const FVerseDamageSplit Split = FVerseDamageMath::Split(Damage, GetHealth(), GetArmor(), GetMaxArmor());
+ LastToArmor = Split.ToArmor;
+ LastToHealth = Split.ToHealth;
+ SetArmor(Split.ArmorAfter);
+ SetHealth(Split.HealthAfter);
+}
+
+void UVerseHealthSet::OnRep_Health(const FGameplayAttributeData& Old)
+{
+ GAMEPLAYATTRIBUTE_REPNOTIFY(UVerseHealthSet, Health, Old);
+}
+
+void UVerseHealthSet::OnRep_MaxHealth(const FGameplayAttributeData& Old)
+{
+ GAMEPLAYATTRIBUTE_REPNOTIFY(UVerseHealthSet, MaxHealth, Old);
+}
+
+void UVerseHealthSet::OnRep_Armor(const FGameplayAttributeData& Old)
+{
+ GAMEPLAYATTRIBUTE_REPNOTIFY(UVerseHealthSet, Armor, Old);
+}
+
+void UVerseHealthSet::OnRep_MaxArmor(const FGameplayAttributeData& Old)
+{
+ GAMEPLAYATTRIBUTE_REPNOTIFY(UVerseHealthSet, MaxArmor, Old);
+}
+
+UVerseDamageEffect::UVerseDamageEffect()
+{
+ DurationPolicy = EGameplayEffectDurationType::Instant;
+
+ FSetByCallerFloat SetByCaller;
+ SetByCaller.DataName = DamageName;
+
+ FGameplayModifierInfo Modifier;
+ Modifier.Attribute = UVerseHealthSet::GetIncomingDamageAttribute();
+ Modifier.ModifierOp = EGameplayModOp::AddBase;
+ Modifier.ModifierMagnitude = FGameplayEffectModifierMagnitude(SetByCaller);
+ Modifiers.Add(Modifier);
+}
diff --git a/unreal/Verse/Source/VerseCombat/Private/Gadgets/VerseBreachCharge.cpp b/unreal/Verse/Source/VerseCombat/Private/Gadgets/VerseBreachCharge.cpp
new file mode 100644
index 0000000000..dc9bc2b84b
--- /dev/null
+++ b/unreal/Verse/Source/VerseCombat/Private/Gadgets/VerseBreachCharge.cpp
@@ -0,0 +1,220 @@
+#include "Gadgets/VerseBreachCharge.h"
+
+#include "Combat/VerseGadgetDefinition.h"
+#include "Components/SkeletalMeshComponent.h"
+#include "Components/StaticMeshComponent.h"
+#include "Damage/VerseDamageService.h"
+#include "Destruction/VerseDestructionInterfaces.h"
+#include "Engine/StaticMesh.h"
+#include "Engine/World.h"
+#include "EngineUtils.h"
+#include "GameFramework/Pawn.h"
+#include "Net/UnrealNetwork.h"
+#include "Gadgets/VerseBulwark.h"
+#include "Stubs/VerseNullStubs.h"
+#include "Projectiles/VersePlaceholderArt.h"
+#include "VerseCollision.h"
+#include "VerseGameplayTags.h"
+#include "Weapons/VerseCombatEvents.h"
+
+AVerseBreachCharge::AVerseBreachCharge()
+{
+ PrimaryActorTick.bCanEverTick = true;
+ bReplicates = true;
+ SetReplicatingMovement(false);
+
+ Look = CreateDefaultSubobject<UStaticMeshComponent>(TEXT("Look"));
+ SetRootComponent(Look);
+ Look->SetCollisionEnabled(ECollisionEnabled::NoCollision);
+ Look->SetRelativeScale3D(FVector(0.1, 0.3, 0.3));
+}
+
+void AVerseBreachCharge::BeginPlay()
+{
+ Super::BeginPlay();
+ if (UStaticMesh* Box = VersePlaceholderArt::Mesh(VersePlaceholderArt::EShape::Box))
+ {
+ Look->SetStaticMesh(Box); // placeholder look until WP14
+ }
+}
+
+void AVerseBreachCharge::GetLifetimeReplicatedProps(TArray<FLifetimeProperty>& OutLifetimeProps) const
+{
+ Super::GetLifetimeReplicatedProps(OutLifetimeProps);
+ DOREPLIFETIME_CONDITION(AVerseBreachCharge, SpawnEvent, COND_InitialOnly);
+}
+
+void AVerseBreachCharge::InitCharge(const UVerseGadgetDefinition& Def, AActor* InOwnerPawn, uint16 InPieceIndex,
+ const FVector& SurfaceNormal, double PlantCompleteTime)
+{
+ Definition = &Def;
+ OwnerPawn = InOwnerPawn;
+ OwnerId = VerseCombatIds::IdOf(InOwnerPawn);
+ PieceIndex = InPieceIndex;
+ Normal = SurfaceNormal.GetSafeNormal(UE_SMALL_NUMBER, FVector::UpVector);
+ DetonateAt = PlantCompleteTime + Def.Lifetime; // Lifetime is the fuse for a breach charge
+ bArmed = true;
+ bDetonated = false;
+ Raise(EVerseGadgetEventKind::Plant);
+ VerseCombatEvents::RaiseNoise(this, VerseTags::Noise_Gadget_BreachPlant, OwnerId, GetActorLocation());
+}
+
+void AVerseBreachCharge::Raise(EVerseGadgetEventKind Kind)
+{
+ FVerseGadgetEvent E;
+ E.Kind = Kind;
+ E.GadgetId = Definition ? Definition->GadgetId : FName(TEXT("breach_charge"));
+ E.OwnerId = OwnerId;
+ E.Location = GetActorLocation();
+ E.ServerTime = VerseCombatEvents::ServerTime(this);
+ VerseCombatEvents::RaiseGadget(this, E);
+ if (Kind == EVerseGadgetEventKind::Plant)
+ {
+ SpawnEvent = E; // reaches clients with the actor's first bunch (OnRep_SpawnEvent)
+ return;
+ }
+ MulticastGadgetEvent(E);
+}
+
+void AVerseBreachCharge::OnRep_SpawnEvent()
+{
+ if (!HasAuthority())
+ {
+ VerseCombatEvents::RaiseGadget(this, SpawnEvent);
+ }
+}
+
+void AVerseBreachCharge::MulticastGadgetEvent_Implementation(const FVerseGadgetEvent& Event)
+{
+ if (!HasAuthority())
+ {
+ VerseCombatEvents::RaiseGadget(this, Event);
+ }
+}
+
+FVector AVerseBreachCharge::PelvisOf(const AActor* Pawn)
+{
+ if (!Pawn)
+ {
+ return FVector::ZeroVector;
+ }
+ if (const USkeletalMeshComponent* Mesh = Pawn->FindComponentByClass<USkeletalMeshComponent>())
+ {
+ const int32 Bone = Mesh->GetBoneIndex(TEXT("Hips"));
+ if (Bone != INDEX_NONE)
+ {
+ return Mesh->GetBoneLocation(TEXT("Hips"));
+ }
+ }
+ return Pawn->GetActorLocation();
+}
+
+void AVerseBreachCharge::ServerAdvance(double Now)
+{
+ if (HasAuthority() && bArmed && !bDetonated && Now >= DetonateAt)
+ {
+ Detonate(Now);
+ }
+}
+
+void AVerseBreachCharge::Detonate(double Now)
+{
+ if (!HasAuthority() || bDetonated || !Definition)
+ {
+ return;
+ }
+ bDetonated = true;
+ bArmed = false;
+ DetonatedTime = Now;
+ LastVictims.Reset();
+
+ UWorld* World = GetWorld();
+ const FVector Centre = GetActorLocation();
+ AActor* OwnerActor = OwnerPawn.Get();
+
+ Raise(EVerseGadgetEventKind::Detonate);
+ VerseCombatEvents::RaiseNoise(this, VerseTags::Noise_Gadget_BreachDetonate, OwnerId, Centre);
+
+ // Pawns: pelvis within PawnRadius and in line of sight on VerseBolt from the charge.
+ const double RadiusCm = double(Definition->PawnRadius) * 100.0;
+ UVerseDamageService* DamageService = UVerseDamageService::Get(this);
+ if (World && RadiusCm > 0.0)
+ {
+ for (TActorIterator<APawn> It(World); It; ++It)
+ {
+ APawn* Pawn = *It;
+ if (!Pawn || (Pawn == OwnerActor && !Definition->bSelfDamage))
+ {
+ continue;
+ }
+ const FVector Pelvis = PelvisOf(Pawn);
+ const double R = FVector::Dist(Pelvis, Centre);
+ if (R >= RadiusCm)
+ {
+ continue;
+ }
+ // Start a hair off the surface so the planted piece itself does not count as cover.
+ const FVector From = Centre + Normal * 2.0;
+ FCollisionQueryParams Params(SCENE_QUERY_STAT(VerseBreachSight), false, this);
+ Params.AddIgnoredActor(Pawn);
+ FHitResult Hit;
+ const bool bBlocked = R > 2.0 && World->LineTraceSingleByChannel(Hit, From, Pelvis, VerseCollision::Bolt, Params);
+ if (bBlocked)
+ {
+ continue;
+ }
+ const float DistanceM = float(R / 100.0);
+ const float Damage = Definition->PawnDamageAt(DistanceM);
+ if (Damage <= 0.f)
+ {
+ continue;
+ }
+ FVerseHitEvent HitEvent;
+ HitEvent.WeaponId = Definition->GadgetId;
+ HitEvent.Source = EVerseDamageSource::Gadget;
+ HitEvent.Zone = EVerseHitZone::LowerTorso; // zone multiplier 1.0: the damage is already final
+ HitEvent.Bone = TEXT("Hips");
+ HitEvent.ImpactWorld = Pelvis;
+ HitEvent.Direction = (Pelvis - Centre).GetSafeNormal(UE_SMALL_NUMBER, Normal);
+ HitEvent.DistanceM = DistanceM;
+ HitEvent.Damage = Damage;
+ if (DamageService)
+ {
+ DamageService->ApplyHit(OwnerActor, Pawn, HitEvent);
+ }
+ FVerseBreachVictim& V = LastVictims.AddDefaulted_GetRef();
+ V.Pawn = Pawn;
+ V.DistanceM = DistanceM;
+ V.Damage = HitEvent.Damage;
+ }
+ }
+
+ // The target piece goes to its breach result (destruction.md 3.2).
+ FVersePieceDamage Piece;
+ Piece.PieceIndex = PieceIndex;
+ Piece.Amount = 0.f; // the breach result does not depend on hp; the cause decides
+ Piece.Cause = EVerseFractureCause::Breach;
+ Piece.Location = Centre;
+ Piece.Direction = -Normal;
+ Piece.InstigatorId = OwnerId;
+ Piece.BreachRadiusCm = Definition->PieceBreachRadius;
+ IVersePieceDamage* Target = PieceDamage ? PieceDamage : static_cast<IVersePieceDamage*>(GetMutableDefault<UVerseNullPieceDamage>());
+ Target->ApplyPieceDamage(Piece);
+
+ for (AVerseBulwark* Bulwark : AVerseBulwark::FindWithin(World, Centre, BulwarkClearRadiusCm))
+ {
+ Bulwark->RemoveBulwark(EVerseGadgetEventKind::Destroyed);
+ }
+
+ if (OnDetonated)
+ {
+ OnDetonated(this);
+ }
+ Destroy();
+}
+
+void AVerseBreachCharge::Tick(float DeltaSeconds)
+{
+ Super::Tick(DeltaSeconds);
+ ServerAdvance(VerseCombatEvents::ServerTime(this));
+}
diff --git a/unreal/Verse/Source/VerseCombat/Private/Gadgets/VerseBulwark.cpp b/unreal/Verse/Source/VerseCombat/Private/Gadgets/VerseBulwark.cpp
new file mode 100644
index 0000000000..b7bd37d83c
--- /dev/null
+++ b/unreal/Verse/Source/VerseCombat/Private/Gadgets/VerseBulwark.cpp
@@ -0,0 +1,223 @@
+#include "Gadgets/VerseBulwark.h"
+
+#include "Combat/VerseGadgetDefinition.h"
+#include "Components/BoxComponent.h"
+#include "Components/StaticMeshComponent.h"
+#include "Damage/VerseDamageService.h"
+#include "Engine/StaticMesh.h"
+#include "Engine/World.h"
+#include "EngineUtils.h"
+#include "Events/VerseEventHub.h"
+#include "Materials/MaterialInstanceDynamic.h"
+#include "Misc/App.h"
+#include "Net/UnrealNetwork.h"
+#include "Projectiles/VersePlaceholderArt.h"
+#include "VerseCollision.h"
+#include "VerseGameplayTags.h"
+#include "Weapons/VerseCombatEvents.h"
+
+namespace
+{
+ const FLinearColor BulwarkAmber(1.0f, 0.55f, 0.08f, 0.35f);
+}
+
+AVerseBulwark::AVerseBulwark()
+{
+ PrimaryActorTick.bCanEverTick = true;
+ bReplicates = true;
+ SetReplicatingMovement(false);
+
+ Field = CreateDefaultSubobject<UBoxComponent>(TEXT("Field"));
+ SetRootComponent(Field);
+ Field->SetBoxExtent(FVector(5.f, 90.f, 70.f));
+ Field->SetCollisionEnabled(ECollisionEnabled::QueryAndPhysics);
+ Field->SetCollisionObjectType(ECC_WorldDynamic);
+ Field->SetCollisionResponseToAllChannels(ECR_Ignore);
+ Field->SetCollisionResponseToChannel(ECC_Pawn, ECR_Block);
+ Field->SetCollisionResponseToChannel(VerseCollision::Bolt, ECR_Block);
+ Field->SetCollisionResponseToChannel(VerseCollision::Sight, ECR_Ignore);
+ Field->SetCollisionResponseToChannel(ECC_Visibility, ECR_Ignore);
+ Field->SetCollisionResponseToChannel(ECC_Camera, ECR_Ignore);
+ Field->SetGenerateOverlapEvents(false);
+
+ Look = CreateDefaultSubobject<UStaticMeshComponent>(TEXT("Look"));
+ Look->SetupAttachment(Field);
+ Look->SetCollisionEnabled(ECollisionEnabled::NoCollision);
+ Look->SetCastShadow(false);
+}
+
+void AVerseBulwark::BeginPlay()
+{
+ Super::BeginPlay();
+ // Placeholder look on every viewer (the server's InitBulwark only sizes it).
+ if (UStaticMesh* Box = VersePlaceholderArt::Mesh(VersePlaceholderArt::EShape::Box))
+ {
+ Look->SetStaticMesh(Box);
+ if (UMaterialInterface* Base = VersePlaceholderArt::Material())
+ {
+ if (UMaterialInstanceDynamic* Mid = UMaterialInstanceDynamic::Create(Base, this))
+ {
+ Mid->SetVectorParameterValue(TEXT("Color"), BulwarkAmber);
+ Look->SetMaterial(0, Mid);
+ }
+ }
+ }
+}
+
+void AVerseBulwark::GetLifetimeReplicatedProps(TArray<FLifetimeProperty>& OutLifetimeProps) const
+{
+ Super::GetLifetimeReplicatedProps(OutLifetimeProps);
+ DOREPLIFETIME(AVerseBulwark, Health);
+ DOREPLIFETIME(AVerseBulwark, MaxHealth);
+ DOREPLIFETIME_CONDITION(AVerseBulwark, SpawnEvent, COND_InitialOnly);
+}
+
+void AVerseBulwark::InitBulwark(const UVerseGadgetDefinition& Def, AActor* InOwnerPawn, double Now)
+{
+ Definition = &Def;
+ OwnerPawn = InOwnerPawn;
+ OwnerId = VerseCombatIds::IdOf(InOwnerPawn);
+ MaxHealth = Def.MaxHealth;
+ Health = Def.MaxHealth;
+ ExpireAt = Now + Def.Lifetime;
+ NextHumAt = Now + HumIntervalS;
+ bActive = true;
+
+ // Size is w x h x d in metres; the actor stands on the floor, local X faces the deployer's front.
+ const FVector Half(Def.Size.Z * 50.0, Def.Size.X * 50.0, Def.Size.Y * 50.0);
+ Field->SetBoxExtent(Half);
+ Look->SetRelativeScale3D(FVector(Def.Size.Z, Def.Size.X, Def.Size.Y));
+ Look->SetRelativeLocation(FVector::ZeroVector);
+ AddActorWorldOffset(FVector(0.0, 0.0, Half.Z));
+
+ if (UVerseEventHub* Hub = UVerseEventHub::Get(this))
+ {
+ DeathHandle = Hub->OnDeath.AddUObject(this, &AVerseBulwark::OnOwnerDeath);
+ }
+ Raise(EVerseGadgetEventKind::Deploy);
+ VerseCombatEvents::RaiseNoise(this, VerseTags::Noise_Gadget_BulwarkDeploy, OwnerId, GetActorLocation());
+}
+
+void AVerseBulwark::Raise(EVerseGadgetEventKind Kind)
+{
+ FVerseGadgetEvent E;
+ E.Kind = Kind;
+ E.GadgetId = Definition ? Definition->GadgetId : FName(TEXT("bulwark"));
+ E.OwnerId = OwnerId;
+ E.Location = GetActorLocation();
+ E.ServerTime = VerseCombatEvents::ServerTime(this);
+ VerseCombatEvents::RaiseGadget(this, E);
+ if (Kind == EVerseGadgetEventKind::Deploy)
+ {
+ SpawnEvent = E; // reaches clients with the actor's first bunch (OnRep_SpawnEvent)
+ return;
+ }
+ MulticastGadgetEvent(E);
+}
+
+void AVerseBulwark::OnRep_SpawnEvent()
+{
+ if (!HasAuthority())
+ {
+ VerseCombatEvents::RaiseGadget(this, SpawnEvent);
+ }
+}
+
+void AVerseBulwark::MulticastGadgetEvent_Implementation(const FVerseGadgetEvent& Event)
+{
+ if (!HasAuthority())
+ {
+ VerseCombatEvents::RaiseGadget(this, Event);
+ }
+}
+
+void AVerseBulwark::ApplyBoltDamage(float Damage, AActor* /*Instigator*/)
+{
+ if (!HasAuthority() || !bActive)
+ {
+ return;
+ }
+ Health = FMath::Max(0.f, Health - FMath::Max(0.f, Damage));
+ if (Health <= 0.f)
+ {
+ RemoveBulwark(EVerseGadgetEventKind::Destroyed);
+ }
+}
+
+void AVerseBulwark::ServerAdvance(double Now)
+{
+ if (!HasAuthority() || !bActive)
+ {
+ return;
+ }
+ if (Now >= ExpireAt)
+ {
+ RemoveBulwark(EVerseGadgetEventKind::Expired);
+ return;
+ }
+ if (Now >= NextHumAt)
+ {
+ NextHumAt = Now + HumIntervalS;
+ VerseCombatEvents::RaiseNoise(this, VerseTags::Noise_Gadget_BulwarkHum, OwnerId, GetActorLocation());
+ }
+}
+
+void AVerseBulwark::RemoveBulwark(EVerseGadgetEventKind Kind)
+{
+ if (!bActive)
+ {
+ return;
+ }
+ bActive = false;
+ // Gone on this tick: no bolt or pawn meets it again.
+ SetActorEnableCollision(false);
+ Raise(Kind);
+ if (OnRemoved)
+ {
+ OnRemoved(this);
+ }
+ Destroy();
+}
+
+void AVerseBulwark::OnOwnerDeath(const FVerseDeathEvent& Death)
+{
+ if (Death.VictimId == OwnerId)
+ {
+ RemoveBulwark(EVerseGadgetEventKind::Destroyed);
+ }
+}
+
+void AVerseBulwark::Tick(float DeltaSeconds)
+{
+ Super::Tick(DeltaSeconds);
+ if (HasAuthority())
+ {
+ ServerAdvance(VerseCombatEvents::ServerTime(this));
+ }
+}
+
+void AVerseBulwark::EndPlay(const EEndPlayReason::Type Reason)
+{
+ if (UVerseEventHub* Hub = UVerseEventHub::Get(this))
+ {
+ Hub->OnDeath.Remove(DeathHandle);
+ }
+ Super::EndPlay(Reason);
+}
+
+TArray<AVerseBulwark*> AVerseBulwark::FindWithin(const UWorld* World, const FVector& Location, double RadiusCm)
+{
+ TArray<AVerseBulwark*> Out;
+ if (!World)
+ {
+ return Out;
+ }
+ for (TActorIterator<AVerseBulwark> It(World); It; ++It)
+ {
+ if (It->IsActive() && FVector::Dist(It->GetActorLocation(), Location) <= RadiusCm)
+ {
+ Out.Add(*It);
+ }
+ }
+ return Out;
+}
diff --git a/unreal/Verse/Source/VerseCombat/Private/Gadgets/VerseGadgetAbilities.cpp b/unreal/Verse/Source/VerseCombat/Private/Gadgets/VerseGadgetAbilities.cpp
new file mode 100644
index 0000000000..31cbba67f7
--- /dev/null
+++ b/unreal/Verse/Source/VerseCombat/Private/Gadgets/VerseGadgetAbilities.cpp
@@ -0,0 +1,41 @@
+#include "Gadgets/VerseGadgetAbilities.h"
+
+#include "Gadgets/VerseGadgetComponent.h"
+#include "Weapons/VerseCombatEvents.h"
+
+UVerseGA_Gadget::UVerseGA_Gadget()
+{
+ NetExecutionPolicy = EGameplayAbilityNetExecutionPolicy::LocalPredicted;
+ InstancingPolicy = EGameplayAbilityInstancingPolicy::InstancedPerActor;
+}
+
+void UVerseGA_Gadget::ActivateAbility(const FGameplayAbilitySpecHandle Handle, const FGameplayAbilityActorInfo* ActorInfo,
+ const FGameplayAbilityActivationInfo ActivationInfo, const FGameplayEventData* TriggerEventData)
+{
+ bLastServerUseStarted = false;
+ if (!CommitAbility(Handle, ActorInfo, ActivationInfo))
+ {
+ EndAbility(Handle, ActorInfo, ActivationInfo, true, true);
+ return;
+ }
+ if (HasAuthority(&ActivationInfo) && ActorInfo)
+ {
+ AActor* Avatar = ActorInfo->AvatarActor.Get();
+ if (UVerseGadgetComponent* Gadgets = UVerseGadgetComponent::FindOn(Avatar))
+ {
+ bLastServerUseStarted = Gadgets->ServerBeginUse(GadgetSlot, VerseCombatEvents::ServerTime(Avatar));
+ }
+ }
+ // The use time runs in the gadget component; the predicted client side is animation only.
+ EndAbility(Handle, ActorInfo, ActivationInfo, true, false);
+}
+
+UVerseGA_Bulwark::UVerseGA_Bulwark()
+{
+ GadgetSlot = EVerseLoadoutSlot::GadgetA;
+}
+
+UVerseGA_BreachCharge::UVerseGA_BreachCharge()
+{
+ GadgetSlot = EVerseLoadoutSlot::GadgetB;
+}
diff --git a/unreal/Verse/Source/VerseCombat/Private/Gadgets/VerseGadgetComponent.cpp b/unreal/Verse/Source/VerseCombat/Private/Gadgets/VerseGadgetComponent.cpp
new file mode 100644
index 0000000000..9b8ac074b7
--- /dev/null
+++ b/unreal/Verse/Source/VerseCombat/Private/Gadgets/VerseGadgetComponent.cpp
@@ -0,0 +1,282 @@
+#include "Gadgets/VerseGadgetComponent.h"
+
+#include "Combat/VerseGadgetDefinition.h"
+#include "Damage/VerseDamageService.h"
+#include "Damage/VerseCombatStateComponent.h"
+#include "Destruction/VersePenetrationTable.h"
+#include "Engine/World.h"
+#include "Events/VerseEventHub.h"
+#include "GameFramework/Pawn.h"
+#include "Gadgets/VerseBreachCharge.h"
+#include "Gadgets/VerseBulwark.h"
+#include "Stubs/VerseNullStubs.h"
+#include "VerseCollision.h"
+#include "Weapons/VerseCombatEvents.h"
+
+UVerseGadgetComponent::UVerseGadgetComponent()
+{
+ PrimaryComponentTick.bCanEverTick = true;
+ SetIsReplicatedByDefault(false);
+}
+
+UVerseGadgetComponent* UVerseGadgetComponent::FindOn(const AActor* Actor)
+{
+ return Actor ? Actor->FindComponentByClass<UVerseGadgetComponent>() : nullptr;
+}
+
+void UVerseGadgetComponent::BeginPlay()
+{
+ Super::BeginPlay();
+ ResetForLife();
+ if (!HitHandle.IsValid())
+ {
+ if (UVerseEventHub* Hub = UVerseEventHub::Get(this))
+ {
+ HitHandle = Hub->OnHit.AddUObject(this, &UVerseGadgetComponent::OnHubHit);
+ }
+ }
+}
+
+void UVerseGadgetComponent::EndPlay(const EEndPlayReason::Type Reason)
+{
+ if (UVerseEventHub* Hub = UVerseEventHub::Get(this))
+ {
+ Hub->OnHit.Remove(HitHandle);
+ }
+ Super::EndPlay(Reason);
+}
+
+void UVerseGadgetComponent::ResetForLife()
+{
+ BulwarkCharges = Bulwark ? Bulwark->Charges : 0;
+ BreachCharges = BreachCharge ? BreachCharge->Charges : 0;
+ BulwarkCooldownEndsAt = 0.f;
+ bUsing = false;
+}
+
+const UVerseGadgetDefinition* UVerseGadgetComponent::DefinitionFor(EVerseLoadoutSlot Slot) const
+{
+ return Slot == EVerseLoadoutSlot::GadgetA ? Bulwark.Get() : (Slot == EVerseLoadoutSlot::GadgetB ? BreachCharge.Get() : nullptr);
+}
+
+int32 UVerseGadgetComponent::GetChargesLeft(EVerseLoadoutSlot Slot) const
+{
+ return Slot == EVerseLoadoutSlot::GadgetA ? BulwarkCharges : (Slot == EVerseLoadoutSlot::GadgetB ? BreachCharges : 0);
+}
+
+int32 UVerseGadgetComponent::NumPlantedCharges() const
+{
+ int32 N = 0;
+ for (const TWeakObjectPtr<AVerseBreachCharge>& C : Planted)
+ {
+ N += (C.IsValid() && C->IsArmed()) ? 1 : 0;
+ }
+ return N;
+}
+
+bool UVerseGadgetComponent::ServerBeginUse(EVerseLoadoutSlot Slot, float Now)
+{
+ AActor* Owner = GetOwner();
+ const UVerseGadgetDefinition* Def = DefinitionFor(Slot);
+ if (!Owner || !Owner->HasAuthority() || !Def || bUsing || GetChargesLeft(Slot) <= 0)
+ {
+ return false;
+ }
+ if (Slot == EVerseLoadoutSlot::GadgetA && Now < BulwarkCooldownEndsAt)
+ {
+ return false;
+ }
+ if (const UVerseCombatStateComponent* State = UVerseCombatStateComponent::FindOn(Owner))
+ {
+ if (State->Phase != EVerseCombatPhase::Alive)
+ {
+ return false;
+ }
+ }
+ if (!HitHandle.IsValid())
+ {
+ if (UVerseEventHub* Hub = UVerseEventHub::Get(this))
+ {
+ HitHandle = Hub->OnHit.AddUObject(this, &UVerseGadgetComponent::OnHubHit);
+ }
+ }
+ bUsing = true;
+ UsingSlot = Slot;
+ UseEndsAt = Now + Def->UseTime;
+
+ // A gadget activation is an offensive action: it ends spawn protection (combat-state.md 9.3).
+ if (UVerseCombatStateComponent* State = UVerseCombatStateComponent::FindOn(Owner))
+ {
+ State->NotifyOffensiveAction(Now);
+ }
+ if (UVerseDamageService* Damage = UVerseDamageService::Get(this))
+ {
+ if (Damage->Rules.OnOffensiveAction)
+ {
+ Damage->Rules.OnOffensiveAction(Owner, EVerseDamageSource::Gadget);
+ }
+ }
+ return true;
+}
+
+void UVerseGadgetComponent::Interrupt()
+{
+ bUsing = false;
+}
+
+void UVerseGadgetComponent::OnHubHit(const FVerseHitEvent& Hit)
+{
+ if (bUsing && Hit.Damage > 0.f && Hit.VictimId == VerseCombatIds::IdOf(GetOwner()))
+ {
+ Interrupt();
+ }
+}
+
+FVerseGadgetPlacement UVerseGadgetComponent::FindPlacement(EVerseLoadoutSlot Slot) const
+{
+ if (PlacementOverride)
+ {
+ return PlacementOverride(Slot);
+ }
+ FVerseGadgetPlacement Out;
+ const APawn* Pawn = Cast<APawn>(GetOwner());
+ const UWorld* World = GetWorld();
+ const UVerseGadgetDefinition* Def = DefinitionFor(Slot);
+ if (!Pawn || !World || !Def)
+ {
+ return Out;
+ }
+ const FVector Eye = Pawn->GetPawnViewLocation();
+ const FRotator View = Pawn->GetBaseAimRotation();
+ const double RangeCm = double(Def->PlaceRange) * 100.0;
+ FCollisionQueryParams Params(SCENE_QUERY_STAT(VerseGadgetPlace), false, Pawn);
+
+ if (Slot == EVerseLoadoutSlot::GadgetA)
+ {
+ // Floor in front of the eye, facing the deployer, with free width for the field.
+ const FVector Flat = FRotator(0.0, View.Yaw, 0.0).Vector();
+ const FVector Above = Eye + Flat * RangeCm;
+ FHitResult Floor;
+ if (!World->LineTraceSingleByChannel(Floor, Above, Above - FVector(0, 0, 300.0), VerseCollision::Bolt, Params))
+ {
+ return Out;
+ }
+ const FVector Right = FRotator(0.0, View.Yaw + 90.0, 0.0).Vector();
+ const FVector Probe = Floor.ImpactPoint + FVector(0, 0, 50.0);
+ const double HalfWidth = double(Def->Size.X) * 50.0;
+ FHitResult Side;
+ if (World->LineTraceSingleByChannel(Side, Probe, Probe + Right * HalfWidth, VerseCollision::Bolt, Params)
+ || World->LineTraceSingleByChannel(Side, Probe, Probe - Right * HalfWidth, VerseCollision::Bolt, Params))
+ {
+ return Out;
+ }
+ Out.bValid = true;
+ Out.Location = Floor.ImpactPoint;
+ Out.Rotation = FRotator(0.0, View.Yaw, 0.0);
+ return Out;
+ }
+
+ // Breach charge: the first piece along the view within range whose material breach can break.
+ const IVersePenetrationQuery* Query = PenetrationQuery ? PenetrationQuery : GetDefault<UVerseNullPenetrationQuery>();
+ const TArray<FVersePenetrationHit> Pieces = Query->TraceBolt(Eye, View.Vector(), float(RangeCm), 0.f, 0.f, 0, 1);
+ const UVersePenetrationTable* Table = GetDefault<UVersePenetrationTable>();
+ if (Pieces.Num() > 0)
+ {
+ const FVersePenetrationRow* Row = Table->FindRow(Pieces[0].MaterialWireId);
+ if (Row && Row->bBreakableByBreach)
+ {
+ Out.bValid = true;
+ Out.PieceIndex = Pieces[0].PieceIndex;
+ Out.Location = Pieces[0].Entry;
+ Out.Normal = -View.Vector();
+ Out.Rotation = Out.Normal.Rotation();
+ }
+ }
+ return Out;
+}
+
+void UVerseGadgetComponent::Complete(float Now)
+{
+ bUsing = false;
+ AActor* Owner = GetOwner();
+ UWorld* World = GetWorld();
+ const UVerseGadgetDefinition* Def = DefinitionFor(UsingSlot);
+ if (!Owner || !World || !Def)
+ {
+ return;
+ }
+ const FVerseGadgetPlacement Place = FindPlacement(UsingSlot);
+ if (!Place.bValid)
+ {
+ return; // nowhere to put it: the charge is kept
+ }
+ FActorSpawnParameters Spawn;
+ Spawn.Owner = Owner;
+ Spawn.Instigator = Cast<APawn>(Owner);
+ Spawn.SpawnCollisionHandlingOverride = ESpawnActorCollisionHandlingMethod::AlwaysSpawn;
+
+ if (UsingSlot == EVerseLoadoutSlot::GadgetA)
+ {
+ // One active: a second deploy removes the first.
+ if (AVerseBulwark* Old = ActiveBulwark.Get())
+ {
+ Old->RemoveBulwark(EVerseGadgetEventKind::Destroyed);
+ }
+ AVerseBulwark* B = World->SpawnActor<AVerseBulwark>(AVerseBulwark::StaticClass(), Place.Location, Place.Rotation, Spawn);
+ if (!B)
+ {
+ return;
+ }
+ B->InitBulwark(*Def, Owner, Now);
+ TWeakObjectPtr<UVerseGadgetComponent> WeakThis = this;
+ B->OnRemoved = [WeakThis](AVerseBulwark*)
+ {
+ if (UVerseGadgetComponent* Self = WeakThis.Get())
+ {
+ const UVerseGadgetDefinition* D = Self->Bulwark.Get();
+ Self->BulwarkCooldownEndsAt = VerseCombatEvents::ServerTime(Self) + (D ? D->Cooldown : 0.f);
+ }
+ };
+ ActiveBulwark = B;
+ --BulwarkCharges;
+ return;
+ }
+
+ AVerseBreachCharge* C = World->SpawnActor<AVerseBreachCharge>(AVerseBreachCharge::StaticClass(), Place.Location, Place.Rotation, Spawn);
+ if (!C)
+ {
+ return;
+ }
+ C->SetPieceDamage(PieceDamage);
+ C->InitCharge(*Def, Owner, Place.PieceIndex, Place.Normal, Now);
+ Planted.RemoveAll([](const TWeakObjectPtr<AVerseBreachCharge>& P) { return !P.IsValid(); });
+ Planted.Add(C);
+ --BreachCharges;
+}
+
+void UVerseGadgetComponent::ServerAdvance(float Now)
+{
+ const AActor* Owner = GetOwner();
+ if (!Owner || !Owner->HasAuthority())
+ {
+ return;
+ }
+ if (bUsing && Now >= UseEndsAt)
+ {
+ Complete(Now);
+ }
+ // The Bulwark's charge returns after its cooldown (Cooldown counts from the actor being gone).
+ const UVerseGadgetDefinition* B = Bulwark.Get();
+ if (B && B->Cooldown > 0.f && !ActiveBulwark.IsValid() && BulwarkCharges < B->Charges && BulwarkCooldownEndsAt > 0.f
+ && Now >= BulwarkCooldownEndsAt)
+ {
+ ++BulwarkCharges;
+ BulwarkCooldownEndsAt = 0.f;
+ }
+}
+
+void UVerseGadgetComponent::TickComponent(float DeltaTime, ELevelTick TickType, FActorComponentTickFunction* ThisTickFunction)
+{
+ Super::TickComponent(DeltaTime, TickType, ThisTickFunction);
+ ServerAdvance(VerseCombatEvents::ServerTime(this));
+}
diff --git a/unreal/Verse/Source/VerseCombat/Private/Inventory/VerseInventoryComponent.cpp b/unreal/Verse/Source/VerseCombat/Private/Inventory/VerseInventoryComponent.cpp
new file mode 100644
index 0000000000..dff58da3aa
--- /dev/null
+++ b/unreal/Verse/Source/VerseCombat/Private/Inventory/VerseInventoryComponent.cpp
@@ -0,0 +1,225 @@
+#include "Inventory/VerseInventoryComponent.h"
+
+#include "Combat/VerseWeaponDefinition.h"
+#include "Damage/VerseDamageService.h"
+#include "GameFramework/Actor.h"
+#include "Net/Core/PushModel/PushModel.h"
+#include "Net/UnrealNetwork.h"
+#include "VerseGameplayTags.h"
+#include "Weapons/VerseCombatEvents.h"
+
+UVerseInventoryComponent::UVerseInventoryComponent()
+{
+ PrimaryComponentTick.bCanEverTick = true;
+ PrimaryComponentTick.bStartWithTickEnabled = true;
+ SetIsReplicatedByDefault(true);
+}
+
+void UVerseInventoryComponent::GetLifetimeReplicatedProps(TArray<FLifetimeProperty>& OutLifetimeProps) const
+{
+ Super::GetLifetimeReplicatedProps(OutLifetimeProps);
+
+ FDoRepLifetimeParams OwnerOnly;
+ OwnerOnly.bIsPushBased = true;
+ OwnerOnly.Condition = COND_OwnerOnly;
+ DOREPLIFETIME_WITH_PARAMS_FAST(UVerseInventoryComponent, Slots, OwnerOnly);
+
+ FDoRepLifetimeParams All;
+ All.bIsPushBased = true;
+ DOREPLIFETIME_WITH_PARAMS_FAST(UVerseInventoryComponent, ActiveSlot, All);
+ DOREPLIFETIME_WITH_PARAMS_FAST(UVerseInventoryComponent, bReloading, All);
+}
+
+UVerseInventoryComponent* UVerseInventoryComponent::FindOn(const AActor* Actor)
+{
+ return Actor ? Actor->FindComponentByClass<UVerseInventoryComponent>() : nullptr;
+}
+
+float UVerseInventoryComponent::Now() const
+{
+ return VerseCombatEvents::ServerTime(this);
+}
+
+const UVerseWeaponDefinition* UVerseInventoryComponent::GetActiveWeapon() const
+{
+ const FVerseWeaponSlotState* S = GetActiveState();
+ return S ? S->Definition.Get() : nullptr;
+}
+
+void UVerseInventoryComponent::MarkSlotDirty(FVerseWeaponSlotState& S)
+{
+ Slots.MarkItemDirty(S);
+ MARK_PROPERTY_DIRTY_FROM_NAME(UVerseInventoryComponent, Slots, this);
+}
+
+void UVerseInventoryComponent::SetReloading(bool bNew)
+{
+ if (bReloading != bNew)
+ {
+ bReloading = bNew;
+ MARK_PROPERTY_DIRTY_FROM_NAME(UVerseInventoryComponent, bReloading, this);
+ }
+}
+
+void UVerseInventoryComponent::GiveLoadout(const TMap<EVerseLoadoutSlot, const UVerseWeaponDefinition*>& Weapons, float InNow)
+{
+ Slots.Items.Reset();
+ for (const TPair<EVerseLoadoutSlot, const UVerseWeaponDefinition*>& Pair : Weapons)
+ {
+ if (!Pair.Value)
+ {
+ continue;
+ }
+ FVerseWeaponSlotState& S = Slots.Items.AddDefaulted_GetRef();
+ S.Slot = Pair.Key;
+ S.Definition = Pair.Value;
+ FVerseMagazine::InitFull(S, *Pair.Value);
+ }
+ Slots.MarkArrayDirty();
+ MARK_PROPERTY_DIRTY_FROM_NAME(UVerseInventoryComponent, Slots, this);
+ ActiveSlot = EVerseLoadoutSlot::Primary;
+ MARK_PROPERTY_DIRTY_FROM_NAME(UVerseInventoryComponent, ActiveSlot, this);
+ SetReloading(false);
+ ReadyAt = InNow;
+}
+
+void UVerseInventoryComponent::RefillAll()
+{
+ for (FVerseWeaponSlotState& S : Slots.Items)
+ {
+ if (const UVerseWeaponDefinition* W = S.Definition.Get())
+ {
+ FVerseMagazine::InitFull(S, *W);
+ Slots.MarkItemDirty(S);
+ }
+ }
+ MARK_PROPERTY_DIRTY_FROM_NAME(UVerseInventoryComponent, Slots, this);
+ SetReloading(false);
+}
+
+bool UVerseInventoryComponent::ServerConsumeRound(float InNow)
+{
+ FVerseWeaponSlotState* S = Slots.Find(ActiveSlot);
+ const UVerseWeaponDefinition* W = S ? S->Definition.Get() : nullptr;
+ if (!W || !IsReady(InNow) || !FVerseMagazine::ConsumeRound(*S, *W))
+ {
+ return false;
+ }
+ MarkSlotDirty(*S);
+ return true;
+}
+
+void UVerseInventoryComponent::RaiseReload(const FVerseWeaponSlotState& S, bool bCancelled)
+{
+ const UVerseWeaponDefinition* W = S.Definition.Get();
+ FVerseReloadEvent E;
+ E.PlayerId = VerseCombatIds::IdOf(GetOwner());
+ E.WeaponId = W ? W->WeaponId : NAME_None;
+ E.bTactical = S.Reload != EVerseReloadPhase::Empty;
+ E.StartServerTime = S.ReloadStartedAt;
+ E.EndServerTime = S.ReloadEndsAt;
+ E.bCancelled = bCancelled;
+
+ VerseCombatEvents::RaiseReload(this, E);
+ OnReloadEvent.Broadcast(E);
+ ClientReloadEvent(E);
+ if (!bCancelled)
+ {
+ const AActor* Owner = GetOwner();
+ VerseCombatEvents::RaiseNoise(this, VerseTags::Noise_Reload, E.PlayerId, Owner ? Owner->GetActorLocation() : FVector::ZeroVector);
+ }
+}
+
+bool UVerseInventoryComponent::ServerStartReload(float InNow)
+{
+ FVerseWeaponSlotState* S = Slots.Find(ActiveSlot);
+ const UVerseWeaponDefinition* W = S ? S->Definition.Get() : nullptr;
+ if (!W || !IsReady(InNow) || !FVerseMagazine::StartReload(*S, *W, InNow))
+ {
+ return false;
+ }
+ MarkSlotDirty(*S);
+ SetReloading(true);
+ RaiseReload(*S, false);
+ return true;
+}
+
+void UVerseInventoryComponent::ServerCancelReload(float InNow)
+{
+ for (FVerseWeaponSlotState& S : Slots.Items)
+ {
+ if (FVerseMagazine::IsReloading(S))
+ {
+ const FVerseWeaponSlotState Before = S;
+ FVerseMagazine::Cancel(S);
+ MarkSlotDirty(S);
+ FVerseWeaponSlotState Report = Before;
+ Report.ReloadEndsAt = InNow;
+ RaiseReload(Report, true);
+ }
+ }
+ SetReloading(false);
+}
+
+void UVerseInventoryComponent::ServerSwitch(EVerseLoadoutSlot NewSlot, float InNow)
+{
+ if (NewSlot == ActiveSlot)
+ {
+ return;
+ }
+ ServerCancelReload(InNow);
+ const UVerseWeaponDefinition* Old = GetActiveWeapon();
+ ActiveSlot = NewSlot;
+ MARK_PROPERTY_DIRTY_FROM_NAME(UVerseInventoryComponent, ActiveSlot, this);
+ const UVerseWeaponDefinition* New = GetActiveWeapon();
+ ReadyAt = InNow + (Old ? Old->HolsterTime : 0.f) + (New ? New->EquipTime : 0.f);
+}
+
+void UVerseInventoryComponent::ServerAdvance(float InNow)
+{
+ bool bAnyReloading = false;
+ for (FVerseWeaponSlotState& S : Slots.Items)
+ {
+ const UVerseWeaponDefinition* W = S.Definition.Get();
+ if (!W)
+ {
+ continue;
+ }
+ const EVerseMagazineChange Change = FVerseMagazine::Tick(S, *W, InNow);
+ if (Change != EVerseMagazineChange::None)
+ {
+ MarkSlotDirty(S);
+ }
+ bAnyReloading |= FVerseMagazine::IsReloading(S);
+ }
+ SetReloading(bAnyReloading);
+}
+
+void UVerseInventoryComponent::TickComponent(float DeltaTime, ELevelTick TickType, FActorComponentTickFunction* ThisTickFunction)
+{
+ Super::TickComponent(DeltaTime, TickType, ThisTickFunction);
+ if (GetOwner() && GetOwner()->HasAuthority())
+ {
+ ServerAdvance(Now());
+ }
+}
+
+void UVerseInventoryComponent::ServerReload_Implementation(uint16 /*ClientCounter*/)
+{
+ ServerStartReload(Now());
+}
+
+void UVerseInventoryComponent::ServerSwitchSlot_Implementation(EVerseLoadoutSlot NewSlot)
+{
+ ServerSwitch(NewSlot, Now());
+}
+
+void UVerseInventoryComponent::ClientReloadEvent_Implementation(const FVerseReloadEvent& Event)
+{
+ const AActor* Owner = GetOwner();
+ if (Owner && !Owner->HasAuthority())
+ {
+ VerseCombatEvents::RaiseReload(this, Event);
+ OnReloadEvent.Broadcast(Event);
+ }
+}
diff --git a/unreal/Verse/Source/VerseCombat/Private/Inventory/VerseWeaponSlot.cpp b/unreal/Verse/Source/VerseCombat/Private/Inventory/VerseWeaponSlot.cpp
new file mode 100644
index 0000000000..ee30b78334
--- /dev/null
+++ b/unreal/Verse/Source/VerseCombat/Private/Inventory/VerseWeaponSlot.cpp
@@ -0,0 +1,172 @@
+#include "Inventory/VerseWeaponSlot.h"
+
+#include "Combat/VerseWeaponDefinition.h"
+
+FVerseWeaponSlotState* FVerseWeaponSlotArray::Find(EVerseLoadoutSlot Slot)
+{
+ return Items.FindByPredicate([Slot](const FVerseWeaponSlotState& S) { return S.Slot == Slot; });
+}
+
+const FVerseWeaponSlotState* FVerseWeaponSlotArray::Find(EVerseLoadoutSlot Slot) const
+{
+ return Items.FindByPredicate([Slot](const FVerseWeaponSlotState& S) { return S.Slot == Slot; });
+}
+
+void FVerseMagazine::InitFull(FVerseWeaponSlotState& S, const UVerseWeaponDefinition& W)
+{
+ const int32 Size = FMath::Clamp(W.MagazineSize, 0, 255);
+ if (W.bClosedBolt && Size > 0)
+ {
+ S.bChambered = true;
+ S.Magazine = uint8(Size - 1);
+ }
+ else
+ {
+ S.bChambered = false;
+ S.Magazine = uint8(Size);
+ }
+ S.Reserve = uint16(FMath::Clamp(W.ReserveRounds, 0, 65535));
+ S.Reload = EVerseReloadPhase::None;
+ S.ReloadEndsAt = 0.f;
+ S.ReloadStartedAt = 0.f;
+ S.bReloadCommitted = false;
+}
+
+int32 FVerseMagazine::RoundsReady(const FVerseWeaponSlotState& S, const UVerseWeaponDefinition& W)
+{
+ return int32(S.Magazine) + ((W.bClosedBolt && S.bChambered) ? 1 : 0);
+}
+
+bool FVerseMagazine::WouldBeTactical(const FVerseWeaponSlotState& S, const UVerseWeaponDefinition& W)
+{
+ return W.bClosedBolt ? S.bChambered : S.Magazine > 0;
+}
+
+bool FVerseMagazine::CanFire(const FVerseWeaponSlotState& S, const UVerseWeaponDefinition& W)
+{
+ return !IsReloading(S) && RoundsReady(S, W) > 0;
+}
+
+bool FVerseMagazine::ConsumeRound(FVerseWeaponSlotState& S, const UVerseWeaponDefinition& W)
+{
+ if (!CanFire(S, W))
+ {
+ return false;
+ }
+ if (W.bClosedBolt)
+ {
+ // The chambered round goes; the next one is fed from the magazine.
+ S.bChambered = S.Magazine > 0;
+ if (S.Magazine > 0)
+ {
+ --S.Magazine;
+ }
+ }
+ else
+ {
+ --S.Magazine;
+ }
+ return true;
+}
+
+void FVerseMagazine::RefundRound(FVerseWeaponSlotState& S, const UVerseWeaponDefinition& W)
+{
+ if (W.bClosedBolt)
+ {
+ if (S.bChambered)
+ {
+ S.Magazine = uint8(FMath::Min(255, int32(S.Magazine) + 1));
+ }
+ else
+ {
+ S.bChambered = true;
+ }
+ }
+ else
+ {
+ S.Magazine = uint8(FMath::Min(255, int32(S.Magazine) + 1));
+ }
+}
+
+bool FVerseMagazine::CanReload(const FVerseWeaponSlotState& S, const UVerseWeaponDefinition& W)
+{
+ return !IsReloading(S) && S.Reserve > 0 && int32(S.Magazine) < W.MagazineSize;
+}
+
+bool FVerseMagazine::StartReload(FVerseWeaponSlotState& S, const UVerseWeaponDefinition& W, float Now)
+{
+ if (!CanReload(S, W))
+ {
+ return false;
+ }
+ const bool bTactical = WouldBeTactical(S, W);
+ S.Reload = bTactical ? EVerseReloadPhase::Tactical : EVerseReloadPhase::Empty;
+ S.ReloadStartedAt = Now;
+ S.ReloadEndsAt = Now + (bTactical ? W.ReloadTactical : W.ReloadEmpty);
+ S.bReloadCommitted = false;
+ return true;
+}
+
+float FVerseMagazine::CommitTime(const FVerseWeaponSlotState& S, const UVerseWeaponDefinition& W)
+{
+ const float Fraction = FMath::Clamp(W.ReloadCommitFraction, 0.f, 1.f);
+ return S.ReloadStartedAt + (S.ReloadEndsAt - S.ReloadStartedAt) * Fraction;
+}
+
+void FVerseMagazine::Commit(FVerseWeaponSlotState& S, const UVerseWeaponDefinition& W)
+{
+ const int32 Size = FMath::Clamp(W.MagazineSize, 0, 255);
+ // The rounds left in the old magazine go back to the reserve; a full magazine is taken from it.
+ int32 Pool = int32(S.Reserve) + int32(S.Magazine);
+ const int32 Take = FMath::Min(Size, Pool);
+ Pool -= Take;
+ if (W.bClosedBolt && !S.bChambered)
+ {
+ // Empty reload: chambering takes one round from the new magazine.
+ S.bChambered = Take > 0;
+ S.Magazine = uint8(FMath::Max(0, Take - 1));
+ }
+ else
+ {
+ // Tactical: the chambered round stays, so the weapon holds magazine + 1.
+ S.Magazine = uint8(Take);
+ }
+ S.Reserve = uint16(FMath::Clamp(Pool, 0, 65535));
+ S.bReloadCommitted = true;
+}
+
+EVerseMagazineChange FVerseMagazine::Tick(FVerseWeaponSlotState& S, const UVerseWeaponDefinition& W, float Now)
+{
+ if (!IsReloading(S))
+ {
+ return EVerseMagazineChange::None;
+ }
+ EVerseMagazineChange Change = EVerseMagazineChange::None;
+ if (!S.bReloadCommitted && Now >= CommitTime(S, W))
+ {
+ Commit(S, W);
+ Change = EVerseMagazineChange::ReloadCommitted;
+ }
+ if (Now >= S.ReloadEndsAt)
+ {
+ if (!S.bReloadCommitted)
+ {
+ Commit(S, W);
+ }
+ S.Reload = EVerseReloadPhase::None;
+ S.bReloadCommitted = false;
+ Change = EVerseMagazineChange::ReloadFinished;
+ }
+ return Change;
+}
+
+EVerseMagazineChange FVerseMagazine::Cancel(FVerseWeaponSlotState& S)
+{
+ if (!IsReloading(S))
+ {
+ return EVerseMagazineChange::None;
+ }
+ S.Reload = EVerseReloadPhase::None;
+ S.bReloadCommitted = false;
+ return EVerseMagazineChange::ReloadCancelled;
+}
diff --git a/unreal/Verse/Source/VerseCombat/Private/LagComp/VerseLagCompensation.cpp b/unreal/Verse/Source/VerseCombat/Private/LagComp/VerseLagCompensation.cpp
new file mode 100644
index 0000000000..cd9bd36f39
--- /dev/null
+++ b/unreal/Verse/Source/VerseCombat/Private/LagComp/VerseLagCompensation.cpp
@@ -0,0 +1,392 @@
+#include "LagComp/VerseLagCompensation.h"
+
+#include "Components/SkeletalMeshComponent.h"
+#include "Engine/World.h"
+#include "GameFramework/Actor.h"
+#include "PhysicsEngine/PhysicsAsset.h"
+#include "PhysicsEngine/SkeletalBodySetup.h"
+
+// ---------------------------------------------------------------------------------------------
+// History
+
+FVerseHitBodyHistory::FVerseHitBodyHistory(int32 InCapacity)
+ : Capacity(FMath::Max(2, InCapacity))
+{
+ Ring.SetNum(Capacity);
+}
+
+const FVerseHitBodyPose& FVerseHitBodyHistory::At(int32 IndexFromOldest) const
+{
+ const int32 Oldest = (Head - Count + Capacity) % Capacity;
+ return Ring[(Oldest + IndexFromOldest) % Capacity];
+}
+
+void FVerseHitBodyHistory::Push(FVerseHitBodyPose&& Pose)
+{
+ Ring[Head] = MoveTemp(Pose);
+ Head = (Head + 1) % Capacity;
+ Count = FMath::Min(Count + 1, Capacity);
+}
+
+double FVerseHitBodyHistory::OldestTime() const
+{
+ return Count > 0 ? At(0).Time : 0.0;
+}
+
+double FVerseHitBodyHistory::NewestTime() const
+{
+ return Count > 0 ? At(Count - 1).Time : 0.0;
+}
+
+bool FVerseHitBodyHistory::Sample(double Time, FVerseHitBodyPose& Out) const
+{
+ if (Count == 0)
+ {
+ return false;
+ }
+ if (Count == 1 || Time <= At(0).Time)
+ {
+ Out = At(0);
+ return true;
+ }
+ if (Time >= At(Count - 1).Time)
+ {
+ Out = At(Count - 1);
+ return true;
+ }
+ // Binary search for the pair around Time.
+ int32 Lo = 0;
+ int32 Hi = Count - 1;
+ while (Hi - Lo > 1)
+ {
+ const int32 Mid = (Lo + Hi) / 2;
+ if (At(Mid).Time <= Time)
+ {
+ Lo = Mid;
+ }
+ else
+ {
+ Hi = Mid;
+ }
+ }
+ const FVerseHitBodyPose& P0 = At(Lo);
+ const FVerseHitBodyPose& P1 = At(Hi);
+ const double Span = P1.Time - P0.Time;
+ const float Alpha = Span > 0.0 ? float((Time - P0.Time) / Span) : 0.f;
+
+ Out.Time = Time;
+ Out.Root.Blend(P0.Root, P1.Root, Alpha);
+ Out.Capsules.Reset(P0.Capsules.Num());
+ for (int32 I = 0; I < P0.Capsules.Num(); ++I)
+ {
+ const FVerseHitCapsule& C0 = P0.Capsules[I];
+ // Bodies are matched by bone; a body missing in the later pose holds its earlier place.
+ const FVerseHitCapsule* C1 = P1.Capsules.IsValidIndex(I) && P1.Capsules[I].Bone == C0.Bone
+ ? &P1.Capsules[I]
+ : P1.Capsules.FindByPredicate([&C0](const FVerseHitCapsule& C) { return C.Bone == C0.Bone; });
+ FVerseHitCapsule& C = Out.Capsules.Add_GetRef(C0);
+ if (C1)
+ {
+ C.A = FMath::Lerp(C0.A, C1->A, double(Alpha));
+ C.B = FMath::Lerp(C0.B, C1->B, double(Alpha));
+ C.Radius = FMath::Lerp(C0.Radius, C1->Radius, Alpha);
+ C.BoneTransform.Blend(C0.BoneTransform, C1->BoneTransform, Alpha);
+ }
+ }
+ return true;
+}
+
+// ---------------------------------------------------------------------------------------------
+// Subsystem
+
+UVerseLagCompSubsystem* UVerseLagCompSubsystem::Get(const UObject* WorldContextObject)
+{
+ const UWorld* World = WorldContextObject ? WorldContextObject->GetWorld() : nullptr;
+ return World ? World->GetSubsystem<UVerseLagCompSubsystem>() : nullptr;
+}
+
+void UVerseLagCompSubsystem::Initialize(FSubsystemCollectionBase& Collection)
+{
+ Super::Initialize(Collection);
+ PostTickHandle = FWorldDelegates::OnWorldPostActorTick.AddUObject(this, &UVerseLagCompSubsystem::OnPostActorTick);
+}
+
+void UVerseLagCompSubsystem::Deinitialize()
+{
+ FWorldDelegates::OnWorldPostActorTick.Remove(PostTickHandle);
+ Targets.Reset();
+ Super::Deinitialize();
+}
+
+void UVerseLagCompSubsystem::OnPostActorTick(UWorld* World, ELevelTick, float)
+{
+ if (World != GetWorld() || !World || World->GetNetMode() == NM_Client)
+ {
+ return;
+ }
+ Record(World->GetTimeSeconds());
+}
+
+void UVerseLagCompSubsystem::RegisterTarget(AActor* Target, FVerseHitBodyProvider Provider)
+{
+ if (!Target || !Provider)
+ {
+ return;
+ }
+ UnregisterTarget(Target);
+ FTarget& T = Targets.AddDefaulted_GetRef();
+ T.Actor = Target;
+ T.Provider = MoveTemp(Provider);
+}
+
+void UVerseLagCompSubsystem::RegisterSkeletalTarget(AActor* Target, USkeletalMeshComponent* Mesh)
+{
+ if (!Target || !Mesh)
+ {
+ return;
+ }
+ TWeakObjectPtr<USkeletalMeshComponent> WeakMesh = Mesh;
+ TWeakObjectPtr<AActor> WeakActor = Target;
+ RegisterTarget(Target, [WeakMesh, WeakActor](FTransform& OutRoot, TArray<FVerseHitCapsule>& Out)
+ {
+ const USkeletalMeshComponent* M = WeakMesh.Get();
+ const AActor* A = WeakActor.Get();
+ if (!M || !A)
+ {
+ return;
+ }
+ OutRoot = A->GetActorTransform();
+ const UPhysicsAsset* Phys = M->GetPhysicsAsset();
+ if (!Phys)
+ {
+ return;
+ }
+ for (const TObjectPtr<USkeletalBodySetup>& Body : Phys->SkeletalBodySetups)
+ {
+ if (!Body)
+ {
+ continue;
+ }
+ const int32 BoneIndex = M->GetBoneIndex(Body->BoneName);
+ if (BoneIndex == INDEX_NONE)
+ {
+ continue;
+ }
+ const FTransform BoneWorld = M->GetBoneTransform(BoneIndex);
+ const EVerseHitZone Zone = ZoneForBone(Body->BoneName);
+ const float Scale = float(BoneWorld.GetScale3D().GetAbsMax());
+ for (const FKSphylElem& Sphyl : Body->AggGeom.SphylElems)
+ {
+ const FTransform Elem = Sphyl.GetTransform() * BoneWorld;
+ const FVector Axis = Elem.GetUnitAxis(EAxis::Z) * (0.5 * Sphyl.Length * Scale);
+ FVerseHitCapsule& C = Out.AddDefaulted_GetRef();
+ C.Bone = Body->BoneName;
+ C.Zone = Zone;
+ C.A = Elem.GetLocation() - Axis;
+ C.B = Elem.GetLocation() + Axis;
+ C.Radius = Sphyl.Radius * Scale;
+ C.BoneTransform = BoneWorld;
+ }
+ for (const FKSphereElem& Sphere : Body->AggGeom.SphereElems)
+ {
+ const FVector Centre = BoneWorld.TransformPosition(Sphere.Center);
+ FVerseHitCapsule& C = Out.AddDefaulted_GetRef();
+ C.Bone = Body->BoneName;
+ C.Zone = Zone;
+ C.A = Centre;
+ C.B = Centre;
+ C.Radius = Sphere.Radius * Scale;
+ C.BoneTransform = BoneWorld;
+ }
+ }
+ });
+}
+
+void UVerseLagCompSubsystem::UnregisterTarget(AActor* Target)
+{
+ Targets.RemoveAll([Target](const FTarget& T) { return !T.Actor.IsValid() || T.Actor.Get() == Target; });
+}
+
+void UVerseLagCompSubsystem::Record(double Now)
+{
+ Targets.RemoveAll([](const FTarget& T) { return !T.Actor.IsValid(); });
+ for (FTarget& T : Targets)
+ {
+ if (T.History.Num() > 0 && T.History.NewestTime() >= Now)
+ {
+ continue; // one snapshot per server time
+ }
+ FVerseHitBodyPose Pose;
+ Pose.Time = Now;
+ T.Provider(Pose.Root, Pose.Capsules);
+ T.History.Push(MoveTemp(Pose));
+ }
+}
+
+double UVerseLagCompSubsystem::ClampRewindTime(double Now, double ViewTime)
+{
+ return FMath::Clamp(ViewTime, Now - MaxRewindS, Now);
+}
+
+bool UVerseLagCompSubsystem::GetPoseAt(const AActor* Target, double Time, FVerseHitBodyPose& Out) const
+{
+ for (const FTarget& T : Targets)
+ {
+ if (T.Actor.Get() == Target)
+ {
+ return T.History.Sample(Time, Out);
+ }
+ }
+ return false;
+}
+
+bool UVerseLagCompSubsystem::TraceRewound(const FVector& Start, const FVector& End, double Now, double ViewTime,
+ const AActor* Ignore, FVerseRewindHit& Out) const
+{
+ return TraceAt(Start, End, ClampRewindTime(Now, ViewTime), Ignore, Out);
+}
+
+bool UVerseLagCompSubsystem::TraceAt(const FVector& Start, const FVector& End, double Time, const AActor* Ignore,
+ FVerseRewindHit& Out) const
+{
+ bool bHit = false;
+ FVerseHitBodyPose Pose;
+ for (const FTarget& T : Targets)
+ {
+ AActor* Actor = T.Actor.Get();
+ if (!Actor || Actor == Ignore || !T.History.Sample(Time, Pose))
+ {
+ continue;
+ }
+ FVerseRewindHit Candidate;
+ if (TracePose(Pose, Start, End, Candidate) && (!bHit || Candidate.Distance < Out.Distance))
+ {
+ Out = Candidate;
+ Out.Actor = Actor;
+ Out.PoseTime = Time;
+ bHit = true;
+ }
+ }
+ return bHit;
+}
+
+bool UVerseLagCompSubsystem::TracePose(const FVerseHitBodyPose& Pose, const FVector& Start, const FVector& End, FVerseRewindHit& Out)
+{
+ const FVector Delta = End - Start;
+ const double Len = Delta.Size();
+ if (Len <= UE_DOUBLE_SMALL_NUMBER)
+ {
+ return false;
+ }
+ const FVector Dir = Delta / Len;
+ bool bHit = false;
+ for (const FVerseHitCapsule& C : Pose.Capsules)
+ {
+ const double T = RayCapsule(Start, Dir, C.A, C.B, C.Radius);
+ if (T >= 0.0 && T <= Len && (!bHit || T < Out.Distance))
+ {
+ bHit = true;
+ Out.Distance = T;
+ Out.Bone = C.Bone;
+ Out.Zone = C.Zone;
+ Out.ImpactWorld = Start + Dir * T;
+ Out.ImpactBoneLocal = C.BoneTransform.InverseTransformPosition(Out.ImpactWorld);
+ }
+ }
+ return bHit;
+}
+
+double UVerseLagCompSubsystem::RayCapsule(const FVector& Ro, const FVector& Rd, const FVector& Pa, const FVector& Pb, double R)
+{
+ // Start inside the capsule: hit at 0.
+ const FVector Ba = Pb - Pa;
+ const double Baba = FVector::DotProduct(Ba, Ba);
+ {
+ const double Along = Baba > 0.0 ? FMath::Clamp(FVector::DotProduct(Ro - Pa, Ba) / Baba, 0.0, 1.0) : 0.0;
+ if (FVector::DistSquared(Ro, Pa + Ba * Along) <= R * R)
+ {
+ return 0.0;
+ }
+ }
+ auto Sphere = [&Ro, &Rd, R](const FVector& C) -> double
+ {
+ const FVector Oc = Ro - C;
+ const double B = FVector::DotProduct(Rd, Oc);
+ const double Cc = FVector::DotProduct(Oc, Oc) - R * R;
+ const double H = B * B - Cc;
+ if (H < 0.0)
+ {
+ return -1.0;
+ }
+ const double T = -B - FMath::Sqrt(H);
+ return T >= 0.0 ? T : -1.0;
+ };
+ if (Baba <= UE_DOUBLE_SMALL_NUMBER)
+ {
+ return Sphere(Pa);
+ }
+ const FVector Oa = Ro - Pa;
+ const double Bard = FVector::DotProduct(Ba, Rd);
+ const double Baoa = FVector::DotProduct(Ba, Oa);
+ const double Rdoa = FVector::DotProduct(Rd, Oa);
+ const double Oaoa = FVector::DotProduct(Oa, Oa);
+ const double A = Baba - Bard * Bard;
+ double Best = -1.0;
+ if (A > UE_DOUBLE_SMALL_NUMBER)
+ {
+ const double B = Baba * Rdoa - Baoa * Bard;
+ const double C = Baba * Oaoa - Baoa * Baoa - R * R * Baba;
+ const double H = B * B - A * C;
+ if (H >= 0.0)
+ {
+ const double T = (-B - FMath::Sqrt(H)) / A;
+ const double Y = Baoa + T * Bard;
+ if (T >= 0.0 && Y > 0.0 && Y < Baba)
+ {
+ return T; // cylinder body
+ }
+ }
+ }
+ // End caps.
+ const double Ta = Sphere(Pa);
+ const double Tb = Sphere(Pb);
+ if (Ta >= 0.0)
+ {
+ Best = Ta;
+ }
+ if (Tb >= 0.0 && (Best < 0.0 || Tb < Best))
+ {
+ Best = Tb;
+ }
+ return Best;
+}
+
+EVerseHitZone UVerseLagCompSubsystem::ZoneForBone(FName Bone)
+{
+ const FString S = Bone.ToString();
+ if (S == TEXT("Head") || S == TEXT("Camera"))
+ {
+ return EVerseHitZone::Head;
+ }
+ if (S == TEXT("Neck"))
+ {
+ return EVerseHitZone::Neck;
+ }
+ if (S == TEXT("Spine_02") || S == TEXT("Spine_03") || S.StartsWith(TEXT("Clavicle")))
+ {
+ return EVerseHitZone::UpperTorso;
+ }
+ if (S == TEXT("Spine_01") || S == TEXT("Hips") || S == TEXT("Pelvis"))
+ {
+ return EVerseHitZone::LowerTorso;
+ }
+ if (S.StartsWith(TEXT("UpperArm")) || S.StartsWith(TEXT("LowerArm")) || S.StartsWith(TEXT("Hand")))
+ {
+ return EVerseHitZone::Arm;
+ }
+ if (S.StartsWith(TEXT("Thigh")) || S.StartsWith(TEXT("Calf")) || S.StartsWith(TEXT("Foot")) || S.StartsWith(TEXT("Ball")))
+ {
+ return EVerseHitZone::Leg;
+ }
+ return EVerseHitZone::UpperTorso;
+}
diff --git a/unreal/Verse/Source/VerseCombat/Private/Projectiles/VerseBoltPresentation.cpp b/unreal/Verse/Source/VerseCombat/Private/Projectiles/VerseBoltPresentation.cpp
new file mode 100644
index 0000000000..133373891f
--- /dev/null
+++ b/unreal/Verse/Source/VerseCombat/Private/Projectiles/VerseBoltPresentation.cpp
@@ -0,0 +1,250 @@
+#include "Projectiles/VerseBoltPresentation.h"
+
+#include "Combat/VerseWeaponDefinition.h"
+#include "Components/InstancedStaticMeshComponent.h"
+#include "Damage/VerseDamageService.h"
+#include "Engine/StaticMesh.h"
+#include "Engine/World.h"
+#include "Events/VerseEventHub.h"
+#include "GameFramework/PlayerController.h"
+#include "Materials/MaterialInstanceDynamic.h"
+#include "Misc/App.h"
+#include "Projectiles/VersePlaceholderArt.h"
+#include "Subsystems/SubsystemCollection.h"
+#include "Weapons/VerseCombatTags.h"
+#include "Weapons/VerseWeaponComponent.h"
+#include "Weapons/VerseWeaponRegistry.h"
+
+UVerseBoltPresentation* UVerseBoltPresentation::Get(const UObject* WorldContextObject)
+{
+ const UWorld* World = WorldContextObject ? WorldContextObject->GetWorld() : nullptr;
+ return World ? World->GetSubsystem<UVerseBoltPresentation>() : nullptr;
+}
+
+bool UVerseBoltPresentation::ShouldCreateSubsystem(UObject* Outer) const
+{
+ const UWorld* World = Cast<UWorld>(Outer);
+ return Super::ShouldCreateSubsystem(Outer) && (!World || World->GetNetMode() != NM_DedicatedServer);
+}
+
+void UVerseBoltPresentation::Initialize(FSubsystemCollectionBase& Collection)
+{
+ Super::Initialize(Collection);
+ Collection.InitializeDependency<UVerseEventHub>();
+ Subscribe();
+}
+
+void UVerseBoltPresentation::Subscribe()
+{
+ if (bSubscribed)
+ {
+ return;
+ }
+ if (UVerseEventHub* Hub = UVerseEventHub::Get(this))
+ {
+ FireHandle = Hub->OnFire.AddUObject(this, &UVerseBoltPresentation::HandleFire);
+ HitHandle = Hub->OnHit.AddUObject(this, &UVerseBoltPresentation::HandleHit);
+ RejectHandle = UVerseWeaponComponent::OnAnyShotRejected.AddUObject(this, &UVerseBoltPresentation::HandleRejected);
+ bSubscribed = true;
+ }
+}
+
+void UVerseBoltPresentation::Deinitialize()
+{
+ if (UVerseEventHub* Hub = UVerseEventHub::Get(this))
+ {
+ Hub->OnFire.Remove(FireHandle);
+ Hub->OnHit.Remove(HitHandle);
+ }
+ UVerseWeaponComponent::OnAnyShotRejected.Remove(RejectHandle);
+ bSubscribed = false;
+ Bolts.Reset();
+ Impacts.Reset();
+ Super::Deinitialize();
+}
+
+TStatId UVerseBoltPresentation::GetStatId() const
+{
+ RETURN_QUICK_DECLARE_CYCLE_STAT(UVerseBoltPresentation, STATGROUP_Tickables);
+}
+
+double UVerseBoltPresentation::WorldNow() const
+{
+ if (ClockOverride)
+ {
+ return ClockOverride();
+ }
+ const UWorld* World = GetWorld();
+ return World ? World->GetTimeSeconds() : 0.0;
+}
+
+int32 UVerseBoltPresentation::GetLocalPlayerId() const
+{
+ if (LocalPlayerIdOverride.IsSet())
+ {
+ return LocalPlayerIdOverride.GetValue();
+ }
+ if (const UWorld* World = GetWorld())
+ {
+ if (const APlayerController* Pc = World->GetFirstPlayerController())
+ {
+ if (Pc->IsLocalController() && Pc->GetPawn())
+ {
+ return VerseCombatIds::IdOf(Pc->GetPawn());
+ }
+ }
+ }
+ return MIN_int32;
+}
+
+void UVerseBoltPresentation::HandleFire(const FVerseFireEvent& E)
+{
+ FVerseVisualBolt B;
+ B.ShooterId = E.ShooterId;
+ B.ShotCounter = E.ShotCounter;
+ B.WeaponId = E.WeaponId;
+ B.Origin = E.Origin;
+ B.Dir = FVector(E.Direction).GetSafeNormal(UE_SMALL_NUMBER, FVector::ForwardVector);
+ B.SpawnTime = WorldNow();
+ B.bOwn = E.ShooterId == GetLocalPlayerId();
+ FGameplayTag Tag;
+ if (const UVerseWeaponDefinition* W = FVerseWeaponRegistry::FindWeapon(E.WeaponId))
+ {
+ B.SpeedCmS = W->ProjectileSpeed * 100.0;
+ B.MaxRangeCm = W->MaxRange * 100.0;
+ Tag = B.bOwn ? W->BoltColorOwn : W->BoltColorFoe;
+ }
+ B.Color = VerseCombatTags::BoltColor(Tag, B.bOwn);
+ // A bolt is drawn once: shooter and counter identify it.
+ Bolts.RemoveAll([&B](const FVerseVisualBolt& X) { return X.ShooterId == B.ShooterId && X.ShotCounter == B.ShotCounter; });
+ Bolts.Add(B);
+}
+
+void UVerseBoltPresentation::HandleHit(const FVerseHitEvent& E)
+{
+ if (E.Source != EVerseDamageSource::Bolt)
+ {
+ return;
+ }
+ const int32 Before = Bolts.Num();
+ Bolts.RemoveAll([&E](const FVerseVisualBolt& X) { return X.ShooterId == E.InstigatorId && X.ShotCounter == E.ShotCounter; });
+ if (Bolts.Num() != Before || E.VictimId == -1)
+ {
+ FVerseVisualImpact& I = Impacts.AddDefaulted_GetRef();
+ I.Location = E.ImpactWorld;
+ I.SpawnTime = WorldNow();
+ }
+}
+
+void UVerseBoltPresentation::HandleRejected(int32 ShooterId, uint16 ShotCounter)
+{
+ Bolts.RemoveAll([ShooterId, ShotCounter](const FVerseVisualBolt& X) { return X.ShooterId == ShooterId && X.ShotCounter == ShotCounter; });
+}
+
+FVector UVerseBoltPresentation::HeadAt(const FVerseVisualBolt& B, double Now)
+{
+ const double D = FMath::Clamp((Now - B.SpawnTime) * B.SpeedCmS, 0.0, B.MaxRangeCm);
+ return B.Origin + B.Dir * D;
+}
+
+int32 UVerseBoltPresentation::NumOwn() const
+{
+ int32 N = 0;
+ for (const FVerseVisualBolt& B : Bolts)
+ {
+ N += B.bOwn ? 1 : 0;
+ }
+ return N;
+}
+
+int32 UVerseBoltPresentation::NumFoe() const
+{
+ return Bolts.Num() - NumOwn();
+}
+
+void UVerseBoltPresentation::Advance(double Now)
+{
+ Bolts.RemoveAll([Now](const FVerseVisualBolt& B) { return (Now - B.SpawnTime) * B.SpeedCmS >= B.MaxRangeCm; });
+ Impacts.RemoveAll([Now](const FVerseVisualImpact& I) { return Now - I.SpawnTime > ImpactLifeS; });
+ UpdateRender(Now);
+}
+
+void UVerseBoltPresentation::Tick(float DeltaTime)
+{
+ Super::Tick(DeltaTime);
+ Advance(WorldNow());
+}
+
+void UVerseBoltPresentation::EnsureRender()
+{
+ UWorld* World = GetWorld();
+ if (RenderActor || !World || !FApp::CanEverRender() || !World->IsGameWorld())
+ {
+ return;
+ }
+ UStaticMesh* Cylinder = VersePlaceholderArt::Mesh(VersePlaceholderArt::EShape::Cylinder);
+ UStaticMesh* Sphere = VersePlaceholderArt::Mesh(VersePlaceholderArt::EShape::Sphere);
+ // Placeholder look (own WP02 test material, colour parameter); the glowing bolt material is WP14.9.
+ UMaterialInterface* Base = VersePlaceholderArt::Material();
+ if (!Cylinder || !Sphere || !Base)
+ {
+ return;
+ }
+ FActorSpawnParameters Params;
+ Params.ObjectFlags |= RF_Transient;
+ RenderActor = World->SpawnActor<AActor>(AActor::StaticClass(), FTransform::Identity, Params);
+ if (!RenderActor)
+ {
+ return;
+ }
+ auto Make = [this, Base](UStaticMesh* Mesh, const FLinearColor& Color, const TCHAR* Name)
+ {
+ UInstancedStaticMeshComponent* C = NewObject<UInstancedStaticMeshComponent>(RenderActor, Name);
+ C->SetStaticMesh(Mesh);
+ C->SetCollisionEnabled(ECollisionEnabled::NoCollision);
+ C->SetCastShadow(false);
+ UMaterialInstanceDynamic* Mid = UMaterialInstanceDynamic::Create(Base, C);
+ Mid->SetVectorParameterValue(TEXT("Color"), Color);
+ C->SetMaterial(0, Mid);
+ RenderActor->SetRootComponent(RenderActor->GetRootComponent() ? RenderActor->GetRootComponent() : C);
+ C->RegisterComponent();
+ RenderActor->AddInstanceComponent(C);
+ return C;
+ };
+ OwnMeshes = Make(Cylinder, VerseCombatTags::BoltColor(VerseCombatTags::Presentation_Bolt_Amber, true), TEXT("OwnBolts"));
+ FoeMeshes = Make(Cylinder, VerseCombatTags::BoltColor(VerseCombatTags::Presentation_Bolt_Red, false), TEXT("FoeBolts"));
+ ImpactMeshes = Make(Sphere, FLinearColor(1.f, 0.8f, 0.5f), TEXT("Impacts"));
+}
+
+void UVerseBoltPresentation::UpdateRender(double Now)
+{
+ if (Bolts.Num() == 0 && Impacts.Num() == 0 && !RenderActor)
+ {
+ return;
+ }
+ EnsureRender();
+ if (!OwnMeshes || !FoeMeshes || !ImpactMeshes)
+ {
+ return;
+ }
+ OwnMeshes->ClearInstances();
+ FoeMeshes->ClearInstances();
+ ImpactMeshes->ClearInstances();
+ for (const FVerseVisualBolt& B : Bolts)
+ {
+ const FVector Head = HeadAt(B, Now);
+ const double Length = FMath::Min(StreakLengthCm, FVector::Dist(Head, B.Origin));
+ if (Length <= 1.0)
+ {
+ continue;
+ }
+ const FVector Mid = Head - B.Dir * (0.5 * Length);
+ const FRotator Rot = FRotationMatrix::MakeFromZ(B.Dir).Rotator();
+ const FVector Scale(StreakRadiusCm * 2.0 / 100.0, StreakRadiusCm * 2.0 / 100.0, Length / 100.0);
+ (B.bOwn ? OwnMeshes : FoeMeshes)->AddInstance(FTransform(Rot, Mid, Scale), true);
+ }
+ for (const FVerseVisualImpact& I : Impacts)
+ {
+ ImpactMeshes->AddInstance(FTransform(FRotator::ZeroRotator, I.Location, FVector(0.12)), true);
+ }
+}
diff --git a/unreal/Verse/Source/VerseCombat/Private/Projectiles/VersePlaceholderArt.cpp b/unreal/Verse/Source/VerseCombat/Private/Projectiles/VersePlaceholderArt.cpp
new file mode 100644
index 0000000000..6bfdff7d24
--- /dev/null
+++ b/unreal/Verse/Source/VerseCombat/Private/Projectiles/VersePlaceholderArt.cpp
@@ -0,0 +1,167 @@
+#include "Projectiles/VersePlaceholderArt.h"
+
+#include "Engine/StaticMesh.h"
+#include "Materials/MaterialInterface.h"
+#include "MeshDescription.h"
+#include "Misc/App.h"
+#include "StaticMeshAttributes.h"
+
+namespace
+{
+ const TCHAR* MaterialPath = TEXT("/Game/Verse/Test/WP02/M_WP02_Placeholder.M_WP02_Placeholder");
+ const FName SlotName(TEXT("Placeholder"));
+
+ struct FBuilder
+ {
+ FMeshDescription Desc;
+ FStaticMeshAttributes Attr;
+ FPolygonGroupID Group;
+
+ FBuilder()
+ : Attr(Desc)
+ {
+ Attr.Register();
+ Group = Desc.CreatePolygonGroup();
+ Attr.GetPolygonGroupMaterialSlotNames()[Group] = SlotName;
+ }
+
+ /** One triangle; A, B, C wind clockwise seen from the side the normal N points to. */
+ void Tri(const FVector3f& A, const FVector3f& B, const FVector3f& C, const FVector3f& NA, const FVector3f& NB, const FVector3f& NC)
+ {
+ const FVector3f P[3] = {A, B, C};
+ const FVector3f N[3] = {NA, NB, NC};
+ TArray<FVertexInstanceID, TFixedAllocator<3>> Corners;
+ for (int32 I = 0; I < 3; ++I)
+ {
+ const FVertexID V = Desc.CreateVertex();
+ Attr.GetVertexPositions()[V] = P[I];
+ const FVertexInstanceID Inst = Desc.CreateVertexInstance(V);
+ Attr.GetVertexInstanceNormals()[Inst] = N[I];
+ Attr.GetVertexInstanceUVs()[Inst] = FVector2f(P[I].X / 100.f + 0.5f, P[I].Y / 100.f + 0.5f);
+ Corners.Add(Inst);
+ }
+ Desc.CreateTriangle(Group, Corners);
+ }
+
+ void FlatTri(const FVector3f& A, const FVector3f& B, const FVector3f& C)
+ {
+ const FVector3f N = FVector3f::CrossProduct(C - A, B - A).GetSafeNormal();
+ Tri(A, B, C, N, N, N);
+ }
+
+ void Quad(const FVector3f& A, const FVector3f& B, const FVector3f& C, const FVector3f& D)
+ {
+ FlatTri(A, B, C);
+ FlatTri(A, C, D);
+ }
+ };
+
+ void BuildBox(FBuilder& B)
+ {
+ const float H = 50.f;
+ auto P = [H](int32 X, int32 Y, int32 Z) { return FVector3f(X ? H : -H, Y ? H : -H, Z ? H : -H); };
+ B.Quad(P(1, 0, 0), P(1, 0, 1), P(1, 1, 1), P(1, 1, 0)); // +X
+ B.Quad(P(0, 1, 0), P(0, 1, 1), P(0, 0, 1), P(0, 0, 0)); // -X
+ B.Quad(P(1, 1, 0), P(1, 1, 1), P(0, 1, 1), P(0, 1, 0)); // +Y
+ B.Quad(P(0, 0, 0), P(0, 0, 1), P(1, 0, 1), P(1, 0, 0)); // -Y
+ B.Quad(P(0, 0, 1), P(0, 1, 1), P(1, 1, 1), P(1, 0, 1)); // +Z
+ B.Quad(P(0, 1, 0), P(0, 0, 0), P(1, 0, 0), P(1, 1, 0)); // -Z
+ }
+
+ void BuildCylinder(FBuilder& B)
+ {
+ const int32 N = 16;
+ const float R = 50.f, H = 50.f;
+ for (int32 I = 0; I < N; ++I)
+ {
+ const float A0 = 2.f * PI * I / N, A1 = 2.f * PI * (I + 1) / N;
+ const FVector3f D0(FMath::Cos(A0), FMath::Sin(A0), 0.f), D1(FMath::Cos(A1), FMath::Sin(A1), 0.f);
+ const FVector3f B0 = D0 * R - FVector3f(0, 0, H), B1 = D1 * R - FVector3f(0, 0, H);
+ const FVector3f T0 = D0 * R + FVector3f(0, 0, H), T1 = D1 * R + FVector3f(0, 0, H);
+ B.Tri(B0, T0, T1, D0, D0, D1);
+ B.Tri(B0, T1, B1, D0, D1, D1);
+ B.FlatTri(FVector3f(0, 0, H), T1, T0);
+ B.FlatTri(FVector3f(0, 0, -H), B0, B1);
+ }
+ }
+
+ void BuildSphere(FBuilder& B)
+ {
+ const int32 Rings = 8, Segments = 12;
+ const float R = 50.f;
+ auto P = [R, Rings, Segments](int32 J, int32 I)
+ {
+ const float T = PI * J / Rings, A = 2.f * PI * I / Segments;
+ return FVector3f(FMath::Sin(T) * FMath::Cos(A), FMath::Sin(T) * FMath::Sin(A), FMath::Cos(T)) * R;
+ };
+ for (int32 J = 0; J < Rings; ++J)
+ {
+ for (int32 I = 0; I < Segments; ++I)
+ {
+ const FVector3f A = P(J, I), Bv = P(J + 1, I), C = P(J + 1, I + 1), D = P(J, I + 1);
+ if (J > 0)
+ {
+ B.Tri(A, D, C, A / R, D / R, C / R);
+ }
+ if (J < Rings - 1)
+ {
+ B.Tri(A, C, Bv, A / R, C / R, Bv / R);
+ }
+ }
+ }
+ }
+
+ void BuildPlane(FBuilder& B)
+ {
+ B.Quad(FVector3f(-50, -50, 0), FVector3f(-50, 50, 0), FVector3f(50, 50, 0), FVector3f(50, -50, 0));
+ }
+
+ UStaticMesh* Build(VersePlaceholderArt::EShape Shape)
+ {
+ FBuilder B;
+ const TCHAR* Name = TEXT("WP02_Placeholder");
+ switch (Shape)
+ {
+ case VersePlaceholderArt::EShape::Box: BuildBox(B); Name = TEXT("WP02_PlaceholderBox"); break;
+ case VersePlaceholderArt::EShape::Cylinder: BuildCylinder(B); Name = TEXT("WP02_PlaceholderCylinder"); break;
+ case VersePlaceholderArt::EShape::Sphere: BuildSphere(B); Name = TEXT("WP02_PlaceholderSphere"); break;
+ case VersePlaceholderArt::EShape::Plane: BuildPlane(B); Name = TEXT("WP02_PlaceholderPlane"); break;
+ }
+ UStaticMesh* Mesh = NewObject<UStaticMesh>(GetTransientPackage(), MakeUniqueObjectName(GetTransientPackage(), UStaticMesh::StaticClass(), Name),
+ RF_Transient);
+ Mesh->GetStaticMaterials().Add(FStaticMaterial(VersePlaceholderArt::Material(), SlotName));
+ UStaticMesh::FBuildMeshDescriptionsParams Params;
+ Params.bFastBuild = true;
+ Params.bBuildSimpleCollision = false;
+ Params.bCommitMeshDescription = false;
+ Params.bMarkPackageDirty = false;
+ Mesh->BuildFromMeshDescriptions({&B.Desc}, Params);
+ return Mesh;
+ }
+}
+
+namespace VersePlaceholderArt
+{
+ UStaticMesh* Mesh(EShape Shape)
+ {
+ if (!FApp::CanEverRender())
+ {
+ return nullptr;
+ }
+ // Rooted for the process: shared by every world, never saved.
+ static TWeakObjectPtr<UStaticMesh> Cache[4];
+ TWeakObjectPtr<UStaticMesh>& Slot = Cache[int32(Shape)];
+ if (!Slot.IsValid())
+ {
+ UStaticMesh* Built = Build(Shape);
+ Built->AddToRoot();
+ Slot = Built;
+ }
+ return Slot.Get();
+ }
+
+ UMaterialInterface* Material()
+ {
+ return LoadObject<UMaterialInterface>(nullptr, MaterialPath);
+ }
+}
diff --git a/unreal/Verse/Source/VerseCombat/Private/Projectiles/VersePlaceholderArt.h b/unreal/Verse/Source/VerseCombat/Private/Projectiles/VersePlaceholderArt.h
new file mode 100644
index 0000000000..6cac73f810
--- /dev/null
+++ b/unreal/Verse/Source/VerseCombat/Private/Projectiles/VersePlaceholderArt.h
@@ -0,0 +1,30 @@
+#pragma once
+
+#include "CoreMinimal.h"
+
+class UMaterialInterface;
+class UStaticMesh;
+
+/**
+ * WP02 placeholder look until WP14 (bolts, impacts, Bulwark slab, breach charge, test floor).
+ * The shapes are built in code at first use (transient meshes, own geometry, no imported or
+ * engine sample content); the material is the WP02 test material with a "Color" vector
+ * parameter. Unit sizes: box 100 cm, cylinder 100 cm across and 100 cm tall along Z, sphere
+ * 100 cm across, plane 100 x 100 cm facing +Z; all centred on the origin.
+ */
+namespace VersePlaceholderArt
+{
+ enum class EShape : uint8
+ {
+ Box,
+ Cylinder,
+ Sphere,
+ Plane,
+ };
+
+ /** The shared transient mesh of a shape; null when the world cannot render. */
+ UStaticMesh* Mesh(EShape Shape);
+
+ /** /Game/Verse/Test/WP02/M_WP02_Placeholder (vector parameter "Color"). */
+ UMaterialInterface* Material();
+}
diff --git a/unreal/Verse/Source/VerseCombat/Private/Projectiles/VerseProjectileManager.cpp b/unreal/Verse/Source/VerseCombat/Private/Projectiles/VerseProjectileManager.cpp
new file mode 100644
index 0000000000..94fea27f05
--- /dev/null
+++ b/unreal/Verse/Source/VerseCombat/Private/Projectiles/VerseProjectileManager.cpp
@@ -0,0 +1,367 @@
+#include "Projectiles/VerseProjectileManager.h"
+
+#include "Combat/VerseWeaponDefinition.h"
+#include "Damage/VerseDamageMath.h"
+#include "Damage/VerseDamageService.h"
+#include "Destruction/VerseDestructionInterfaces.h"
+#include "Destruction/VersePenetrationTable.h"
+#include "Engine/World.h"
+#include "Gadgets/VerseBulwark.h"
+#include "HAL/PlatformTime.h"
+#include "LagComp/VerseLagCompensation.h"
+#include "Stubs/VerseNullStubs.h"
+#include "VerseCollision.h"
+#include "Weapons/VerseCombatEvents.h"
+#include "Weapons/VerseWeaponComponent.h"
+
+UVerseProjectileManager* UVerseProjectileManager::Get(const UObject* WorldContextObject)
+{
+ const UWorld* World = WorldContextObject ? WorldContextObject->GetWorld() : nullptr;
+ return World ? World->GetSubsystem<UVerseProjectileManager>() : nullptr;
+}
+
+void UVerseProjectileManager::Initialize(FSubsystemCollectionBase& Collection)
+{
+ Super::Initialize(Collection);
+}
+
+void UVerseProjectileManager::Deinitialize()
+{
+ Bolts.Reset();
+ Super::Deinitialize();
+}
+
+TStatId UVerseProjectileManager::GetStatId() const
+{
+ RETURN_QUICK_DECLARE_CYCLE_STAT(UVerseProjectileManager, STATGROUP_Tickables);
+}
+
+double UVerseProjectileManager::Now() const
+{
+ return ClockOverride ? ClockOverride() : double(VerseCombatEvents::ServerTime(this));
+}
+
+void UVerseProjectileManager::Tick(float DeltaTime)
+{
+ Super::Tick(DeltaTime);
+ const UWorld* World = GetWorld();
+ if (bManualStepping || !World || World->GetNetMode() == NM_Client || Bolts.Num() == 0)
+ {
+ return;
+ }
+ StepAll(DeltaTime, Now());
+}
+
+bool UVerseProjectileManager::TraceWorld(const FVector& Start, const FVector& End, const AActor* Ignore, FHitResult& Out) const
+{
+ if (WorldTrace)
+ {
+ return WorldTrace(Start, End, Ignore, Out);
+ }
+ const UWorld* World = GetWorld();
+ if (!World)
+ {
+ return false;
+ }
+ FCollisionQueryParams Params(SCENE_QUERY_STAT(VerseBolt), false, Ignore);
+ return World->LineTraceSingleByChannel(Out, Start, End, VerseCollision::Bolt, Params);
+}
+
+void UVerseProjectileManager::SpawnBolt(const FVerseFireEvent& Fire, const UVerseWeaponDefinition& Weapon, float LatencyS)
+{
+ SpawnBoltFrom(Fire, Weapon, LatencyS, nullptr);
+}
+
+void UVerseProjectileManager::SpawnBoltFrom(const FVerseFireEvent& Fire, const UVerseWeaponDefinition& Weapon, float LatencyS,
+ AActor* Shooter)
+{
+ const UWorld* World = GetWorld();
+ if (World && World->GetNetMode() == NM_Client)
+ {
+ return;
+ }
+ FVerseBolt Bolt;
+ Bolt.Fire = Fire;
+ Bolt.Weapon = &Weapon;
+ Bolt.Shooter = Shooter;
+ Bolt.Position = Fire.Origin;
+ Bolt.Dir = FVector(Fire.Direction).GetSafeNormal(UE_SMALL_NUMBER, FVector::ForwardVector);
+ Bolt.Power = Weapon.PenetrationPower;
+
+ // The first step covers the shooter's latency (capped), against bodies rewound to the time the
+ // bolt was at each point of it: one tick-sized segment at a time.
+ const double Latency = FMath::Clamp(double(LatencyS), 0.0, double(MaxLatencyS));
+ const double Speed = Weapon.ProjectileSpeed * 100.0;
+ const double Clock = Now();
+ Bolt.Time = Clock - Latency;
+ double Remaining = Latency;
+ while (Bolt.bAlive && Remaining > 1e-6)
+ {
+ const double Dt = FMath::Min(double(ServerStepS), Remaining);
+ const double PoseTime = Bolt.Time + Dt;
+ StepBolt(Bolt, Speed * Dt, PoseTime, Bolt.Time + Dt);
+ Remaining -= Dt;
+ }
+ if (Bolt.bAlive)
+ {
+ Bolt.Time = Clock;
+ Bolts.Add(MoveTemp(Bolt));
+ }
+}
+
+void UVerseProjectileManager::StepAll(float Dt, double InNow)
+{
+ const double T0 = FPlatformTime::Seconds();
+ for (FVerseBolt& Bolt : Bolts)
+ {
+ if (!Bolt.bAlive)
+ {
+ continue;
+ }
+ const UVerseWeaponDefinition* W = Bolt.Weapon.Get();
+ if (!W)
+ {
+ Bolt.bAlive = false;
+ continue;
+ }
+ StepBolt(Bolt, W->ProjectileSpeed * 100.0 * Dt, -1.0, InNow);
+ }
+ Bolts.RemoveAll([](const FVerseBolt& B) { return !B.bAlive; });
+ LastStepSeconds = FPlatformTime::Seconds() - T0;
+}
+
+void UVerseProjectileManager::Resolve(FVerseBolt& Bolt, EVerseShotResult Result, EVerseHitZone Zone, bool bKillingBlow,
+ AActor* HitActor, const FVector& Where)
+{
+ Bolt.bAlive = false;
+ FVerseBoltResult R;
+ R.Shooter = Bolt.Shooter;
+ R.WeaponId = Bolt.Fire.WeaponId;
+ R.ShotCounter = Bolt.Fire.ShotCounter;
+ R.Result = Result;
+ R.Zone = Zone;
+ R.bKillingBlow = bKillingBlow;
+ R.HitActor = HitActor;
+ R.Location = Where;
+ R.Travelled = Bolt.Travelled + FVector::Dist(Bolt.Position, Where);
+ R.Time = Bolt.Time;
+ if (UVerseWeaponComponent* Weapon = UVerseWeaponComponent::FindOn(Bolt.Shooter.Get()))
+ {
+ Weapon->HandleBoltResolved(R);
+ }
+ OnBoltResolved.Broadcast(R);
+}
+
+void UVerseProjectileManager::StepBolt(FVerseBolt& Bolt, double Len, double PoseTime, double EndTime)
+{
+ const UVerseWeaponDefinition* W = Bolt.Weapon.Get();
+ if (!W)
+ {
+ Bolt.bAlive = false;
+ return;
+ }
+ const double MaxRangeCm = double(W->MaxRange) * 100.0;
+ Len = FMath::Min(Len, MaxRangeCm - Bolt.Travelled);
+ if (Len <= 0.0)
+ {
+ Resolve(Bolt, EVerseShotResult::Miss, EVerseHitZone::None, false, nullptr, Bolt.Position);
+ return;
+ }
+
+ AActor* Shooter = Bolt.Shooter.Get();
+ const FVector P0 = Bolt.Position;
+ const FVector P1 = P0 + Bolt.Dir * Len;
+
+ // Hit bodies: rewound for the latency segments, current otherwise.
+ FVerseRewindHit Body;
+ bool bBody = false;
+ if (const UVerseLagCompSubsystem* Lag = UVerseLagCompSubsystem::Get(this))
+ {
+ bBody = Lag->TraceAt(P0, P1, PoseTime >= 0.0 ? PoseTime : EndTime, Shooter, Body);
+ }
+
+ // World and Bulwarks on VerseBolt.
+ FHitResult WorldHit;
+ bool bWorld = TraceWorld(P0, P1, Shooter, WorldHit);
+ double WorldDist = bWorld ? WorldHit.Distance : 0.0;
+ if (bWorld && WorldDist <= 0.0)
+ {
+ WorldDist = FVector::Dist(P0, FVector(WorldHit.ImpactPoint));
+ }
+
+ // Pieces (current-state proxies), in order.
+ const IVersePenetrationQuery* Query = PenetrationQuery ? PenetrationQuery : GetDefault<UVerseNullPenetrationQuery>();
+ const int32 MaxPasses = W->GetEffectiveMaxPenetrations();
+ const float DistanceSoFarM = float(Bolt.Travelled / 100.0);
+ const float DamageNow = FVerseDamageMath::BoltDamage(*W, EVerseHitZone::UpperTorso, DistanceSoFarM, Bolt.Factor);
+ const TArray<FVersePenetrationHit> Pieces =
+ Query->TraceBolt(P0, Bolt.Dir, float(Len), Bolt.Power, DamageNow, W->HoleRadiusMm, FMath::Max(1, MaxPasses - Bolt.Passes + 1));
+ const UVersePenetrationTable* Table = PenetrationTable ? PenetrationTable : GetDefault<UVersePenetrationTable>();
+ IVersePieceDamage* Damage = PieceDamage ? PieceDamage : static_cast<IVersePieceDamage*>(GetMutableDefault<UVerseNullPieceDamage>());
+ UVerseWeaponComponent* ShooterWeapon = UVerseWeaponComponent::FindOn(Shooter);
+ UVerseDamageService* DamageService = UVerseDamageService::Get(this);
+
+ auto HitBody = [&]()
+ {
+ AActor* Victim = Body.Actor.Get();
+ const float DistanceM = float((Bolt.Travelled + Body.Distance) / 100.0);
+ FVerseHitEvent Hit;
+ Hit.WeaponId = W->WeaponId;
+ Hit.Source = EVerseDamageSource::Bolt;
+ Hit.ShotCounter = Bolt.Fire.ShotCounter;
+ Hit.Zone = Body.Zone;
+ Hit.Bone = Body.Bone;
+ Hit.ImpactWorld = Body.ImpactWorld;
+ Hit.ImpactBoneLocal = Body.ImpactBoneLocal;
+ Hit.Direction = Bolt.Dir;
+ Hit.DistanceM = DistanceM;
+ Hit.Damage = FVerseDamageMath::BoltDamage(*W, Body.Zone, DistanceM, Bolt.Factor);
+ Hit.PenetrationCount = uint8(FMath::Clamp(Bolt.Passes, 0, 255));
+ if (DamageService)
+ {
+ DamageService->ApplyHit(Shooter, Victim, Hit);
+ }
+ else
+ {
+ Hit.InstigatorId = VerseCombatIds::IdOf(Shooter);
+ Hit.VictimId = VerseCombatIds::IdOf(Victim);
+ }
+ if (ShooterWeapon)
+ {
+ ShooterWeapon->MulticastHitCosmetic(Hit);
+ }
+ const EVerseShotResult Result = Hit.bBlockedBySpawnProtection ? EVerseShotResult::Blocked : EVerseShotResult::HitBody;
+ Resolve(Bolt, Result, Body.Zone, Hit.bKillingBlow != 0, Victim, Body.ImpactWorld);
+ };
+
+ // Every bolt that ends without a body hit sends a cosmetic impact (victim -1, zone None, no
+ // damage): presentation ends the drawn bolt there and places the impact (WP02.11).
+ auto SendImpact = [&](const FVector& Where, float DistanceM)
+ {
+ FVerseHitEvent Impact;
+ Impact.InstigatorId = VerseCombatIds::IdOf(Shooter);
+ Impact.VictimId = -1;
+ Impact.WeaponId = W->WeaponId;
+ Impact.ShotCounter = Bolt.Fire.ShotCounter;
+ Impact.ImpactWorld = Where;
+ Impact.Direction = Bolt.Dir;
+ Impact.DistanceM = DistanceM;
+ Impact.ServerTime = float(EndTime);
+ if (ShooterWeapon)
+ {
+ ShooterWeapon->MulticastHitCosmetic(Impact);
+ }
+ else
+ {
+ UVerseWeaponComponent::RaiseLocalImpact(this, Impact); // no shooter component: local viewers only
+ }
+ };
+
+ auto HitWorld = [&]()
+ {
+ const FVector Where = FVector(WorldHit.ImpactPoint);
+ const float DistanceM = float((Bolt.Travelled + WorldDist) / 100.0);
+ SendImpact(Where, DistanceM);
+ if (AVerseBulwark* Bulwark = Cast<AVerseBulwark>(WorldHit.GetActor()))
+ {
+ // The damage after all factors goes to the field; a Bulwark never lets a bolt through.
+ Bulwark->ApplyBoltDamage(W->BaseDamage * FVerseDamageMath::Falloff(*W, DistanceM) * Bolt.Factor, Shooter);
+ Resolve(Bolt, EVerseShotResult::Blocked, EVerseHitZone::None, false, Bulwark, Where);
+ return;
+ }
+ Resolve(Bolt, EVerseShotResult::Miss, EVerseHitZone::None, false, WorldHit.GetActor(), Where);
+ };
+
+ for (const FVersePenetrationHit& Piece : Pieces)
+ {
+ if (Bolt.PassedPieces.Contains(Piece.PieceIndex))
+ {
+ continue;
+ }
+ const double PieceDist = FVector::Dist(P0, Piece.Entry);
+ // The nearest of world (Bulwarks included), body and piece wins. The world trace may stop on
+ // this piece's own proxy, so a world hit counts as nearer only 1 cm before the entry.
+ const bool bWorldFirst = bWorld && WorldDist < PieceDist - 1.0;
+ const bool bBodyFirst = bBody && Body.Distance < PieceDist;
+ if (bWorldFirst || bBodyFirst)
+ {
+ if (bBodyFirst && (!bWorldFirst || Body.Distance <= WorldDist))
+ {
+ HitBody();
+ }
+ else
+ {
+ HitWorld();
+ }
+ return;
+ }
+
+ // Piece damage always, pass or not (server).
+ FVersePieceDamage PieceHit;
+ PieceHit.PieceIndex = Piece.PieceIndex;
+ PieceHit.Amount = W->PieceDamage;
+ PieceHit.Cause = EVerseFractureCause::Bolt;
+ PieceHit.Location = Piece.Entry;
+ PieceHit.Direction = Bolt.Dir;
+ PieceHit.InstigatorId = VerseCombatIds::IdOf(Shooter);
+ Damage->ApplyPieceDamage(PieceHit);
+
+ const FVersePenetrationRow* Row = Table->FindRow(Piece.MaterialWireId);
+ const float Cost = Row ? UVersePenetrationTable::PassCost(*Row, Piece.TracedThicknessCm) : TNumericLimits<float>::Max();
+ if (Bolt.Power < Cost || Bolt.Passes >= MaxPasses)
+ {
+ SendImpact(Piece.Entry, float((Bolt.Travelled + PieceDist) / 100.0));
+ Resolve(Bolt, EVerseShotResult::HitPiece, EVerseHitZone::None, false, nullptr, Piece.Entry);
+ return;
+ }
+ FVersePenetrationEvent Pen;
+ Pen.ShooterId = VerseCombatIds::IdOf(Shooter);
+ Pen.ShotCounter = Bolt.Fire.ShotCounter;
+ Pen.PieceIndex = Piece.PieceIndex;
+ Pen.MaterialWireId = Piece.MaterialWireId;
+ Pen.Entry = Piece.Entry;
+ Pen.Exit = Piece.Exit;
+ Pen.ThicknessCm = Piece.TracedThicknessCm;
+ Pen.PowerBefore = Bolt.Power;
+ Bolt.Power -= Cost;
+ Bolt.Factor *= Row->DamageMultiplier;
+ Bolt.Passes += 1;
+ Bolt.PassedPieces.Add(Piece.PieceIndex);
+ Pen.PowerAfter = Bolt.Power;
+ Pen.DamageFactorAfter = Bolt.Factor;
+ Pen.bPassed = true;
+ VerseCombatEvents::RaisePenetration(this, Pen);
+ if (ShooterWeapon)
+ {
+ ShooterWeapon->MulticastPenetration(Pen);
+ }
+
+ // The world trace may have stopped on this piece's own proxy: look again behind its exit.
+ const double ExitDist = FVector::Dist(P0, Piece.Exit);
+ if (bWorld && WorldDist <= ExitDist + 1.0)
+ {
+ const FVector Behind = Piece.Exit + Bolt.Dir * 0.5;
+ bWorld = ExitDist + 0.5 < Len && TraceWorld(Behind, P1, Shooter, WorldHit);
+ WorldDist = bWorld ? ExitDist + 0.5 + FVector::Dist(Behind, FVector(WorldHit.ImpactPoint)) : 0.0;
+ }
+ }
+
+ if (bBody && (!bWorld || Body.Distance <= WorldDist))
+ {
+ HitBody();
+ return;
+ }
+ if (bWorld)
+ {
+ HitWorld();
+ return;
+ }
+
+ Bolt.Position = P1;
+ Bolt.Travelled += Len;
+ Bolt.Time = EndTime;
+ if (Bolt.Travelled >= MaxRangeCm - 0.01)
+ {
+ Resolve(Bolt, EVerseShotResult::Miss, EVerseHitZone::None, false, nullptr, Bolt.Position);
+ }
+}
diff --git a/unreal/Verse/Source/VerseCombat/Private/Tests/Damage/VerseDamageTest.cpp b/unreal/Verse/Source/VerseCombat/Private/Tests/Damage/VerseDamageTest.cpp
new file mode 100644
index 0000000000..c899cae2ae
--- /dev/null
+++ b/unreal/Verse/Source/VerseCombat/Private/Tests/Damage/VerseDamageTest.cpp
@@ -0,0 +1,186 @@
+#include "Damage/VerseDamageMath.h"
+#include "Damage/VerseDamageService.h"
+#include "Events/VerseEventHub.h"
+#include "Misc/AutomationTest.h"
+#include "Tests/Weapons/VerseWp02TestUtils.h"
+
+#if WITH_DEV_AUTOMATION_TESTS
+
+// Verse.Combat.Damage.*: the damage formula of combat-state.md 5 (A2.2) and the server damage path
+// (WP02.9): GAS effect, armor first, spawn protection, finisher immunity, ruleset hooks, death.
+
+namespace VerseDamageTest
+{
+ const EVerseHitZone Zones[] = {EVerseHitZone::Head, EVerseHitZone::Neck, EVerseHitZone::UpperTorso, EVerseHitZone::LowerTorso,
+ EVerseHitZone::Arm, EVerseHitZone::Leg};
+
+ /** The formula written out independently of FVerseDamageMath. */
+ double Expected(const UVerseWeaponDefinition& W, EVerseHitZone Zone, double D)
+ {
+ double F = 1.0;
+ if (D > W.FalloffStart)
+ {
+ F = D >= W.FalloffEnd ? W.FalloffMinFraction
+ : 1.0 + (W.FalloffMinFraction - 1.0) * (D - W.FalloffStart) / (W.FalloffEnd - W.FalloffStart);
+ }
+ const float* Z = W.ZoneMultipliers.Find(Zone);
+ return double(W.BaseDamage) * double(Z ? *Z : 1.f) * F;
+ }
+
+ FVerseHitEvent BoltHit(const UVerseWeaponDefinition& W, EVerseHitZone Zone, float DistanceM)
+ {
+ FVerseHitEvent H;
+ H.WeaponId = W.WeaponId;
+ H.Source = EVerseDamageSource::Bolt;
+ H.Zone = Zone;
+ H.DistanceM = DistanceM;
+ H.Damage = FVerseDamageMath::BoltDamage(W, Zone, DistanceM, 1.f);
+ return H;
+ }
+}
+
+IMPLEMENT_SIMPLE_AUTOMATION_TEST(FVerseDamageZonesAndFalloff, "Verse.Combat.Damage.ZonesAndFalloff", VERSE_WP02_TEST_FLAGS)
+bool FVerseDamageZonesAndFalloff::RunTest(const FString&)
+{
+ for (const UVerseWeaponDefinition* W : VerseWp02Test::AllWeapons(*this))
+ {
+ const double Mid = 0.5 * (W->FalloffStart + W->FalloffEnd);
+ const double Distances[] = {0.0, W->FalloffStart, Mid, W->FalloffEnd, W->FalloffEnd + 20.0};
+ for (const EVerseHitZone Zone : VerseDamageTest::Zones)
+ {
+ TestTrue(FString::Printf(TEXT("%s has every zone"), *W->WeaponId.ToString()), W->ZoneMultipliers.Contains(Zone));
+ for (const double D : Distances)
+ {
+ const double Got = FVerseDamageMath::BoltDamage(*W, Zone, float(D), 1.f);
+ const double Want = VerseDamageTest::Expected(*W, Zone, D);
+ if (FMath::Abs(Got - Want) > 1e-4)
+ {
+ AddError(FString::Printf(TEXT("%s zone %d at %.1f m: %.6f != %.6f"), *W->WeaponId.ToString(), int32(Zone), D, Got, Want));
+ }
+ }
+ }
+ TestEqual(TEXT("penetration factor multiplies"), FVerseDamageMath::BoltDamage(*W, EVerseHitZone::UpperTorso, 0.f, 0.5625f),
+ W->BaseDamage * 0.5625f, 1e-4f);
+ TestEqual(TEXT("zone None does nothing"), FVerseDamageMath::BoltDamage(*W, EVerseHitZone::None, 0.f, 1.f), 0.f);
+ }
+
+ const UVerseWeaponDefinition* G = VerseWp02Test::Weapon(*this, TEXT("graveline"));
+ if (!G)
+ {
+ return false;
+ }
+ for (const float D : {0.f, 10.f, 25.f})
+ {
+ TestEqual(FString::Printf(TEXT("Graveline: 4 upper-torso hits kill at %.0f m"), D),
+ FVerseDamageMath::HitsToKill(*G, EVerseHitZone::UpperTorso, D, 100.f), 4);
+ }
+ TestTrue(TEXT("Graveline: 2 head hits kill at any range"), FVerseDamageMath::HitsToKill(*G, EVerseHitZone::Head, 150.f, 100.f) <= 2);
+
+ // Through GAS on a real victim: exact to 1e-4 hp.
+ VerseWp02Test::FTestWorld World;
+ UVerseDamageService* Service = UVerseDamageService::Get(World.World);
+ APawn* Shooter = VerseWp02Test::SpawnTarget(World.World, FVector(-1000, 0, 0));
+ for (const EVerseHitZone Zone : VerseDamageTest::Zones)
+ {
+ APawn* Victim = VerseWp02Test::SpawnTarget(World.World, FVector(0, 0, 0), 1000.f);
+ FVerseHitEvent Hit = VerseDamageTest::BoltHit(*G, Zone, 35.f);
+ Service->ApplyHit(Shooter, Victim, Hit);
+ TestEqual(FString::Printf(TEXT("GAS applies zone %d exactly"), int32(Zone)), double(VerseWp02Test::HealthOf(Victim)),
+ 1000.0 - VerseDamageTest::Expected(*G, Zone, 35.0), 1e-3);
+ }
+ APawn* Victim = VerseWp02Test::SpawnTarget(World.World, FVector(0, 0, 0));
+ int32 Hits = 0;
+ while (VerseWp02Test::HealthOf(Victim) > 0.f && Hits < 10)
+ {
+ FVerseHitEvent Hit = VerseDamageTest::BoltHit(*G, EVerseHitZone::UpperTorso, 25.f);
+ Service->ApplyHit(Shooter, Victim, Hit);
+ ++Hits;
+ TestEqual(TEXT("killing blow only on the last hit"), Hit.bKillingBlow != 0, VerseWp02Test::HealthOf(Victim) <= 0.f);
+ }
+ TestEqual(TEXT("4 upper-torso hits at 25 m through the damage path"), Hits, 4);
+ return true;
+}
+
+IMPLEMENT_SIMPLE_AUTOMATION_TEST(FVerseDamageRulesAndDeath, "Verse.Combat.Damage.RulesAndDeath", VERSE_WP02_TEST_FLAGS)
+bool FVerseDamageRulesAndDeath::RunTest(const FString&)
+{
+ const UVerseWeaponDefinition* G = VerseWp02Test::Weapon(*this, TEXT("graveline"));
+ if (!G)
+ {
+ return false;
+ }
+ // Armor first (inert at MaxArmor 0).
+ const FVerseDamageSplit Inert = FVerseDamageMath::Split(30.f, 100.f, 50.f, 0.f);
+ TestEqual(TEXT("MaxArmor 0: all to health"), Inert.ToHealth, 30.f);
+ const FVerseDamageSplit Armored = FVerseDamageMath::Split(30.f, 100.f, 20.f, 50.f);
+ TestEqual(TEXT("armor absorbs first"), Armored.ToArmor, 20.f);
+ TestEqual(TEXT("rest to health"), Armored.HealthAfter, 90.f);
+
+ VerseWp02Test::FTestWorld World;
+ UVerseDamageService* Service = UVerseDamageService::Get(World.World);
+ UVerseEventHub* Hub = UVerseEventHub::Get(World.World);
+ TArray<FVerseHitEvent> Hits;
+ TArray<FVerseDeathEvent> Deaths;
+ Hub->OnHit.AddLambda([&Hits](const FVerseHitEvent& E) { Hits.Add(E); });
+ Hub->OnDeath.AddLambda([&Deaths](const FVerseDeathEvent& E) { Deaths.Add(E); });
+
+ APawn* Shooter = VerseWp02Test::SpawnTarget(World.World, FVector(-1000, 0, 0));
+ APawn* Victim = VerseWp02Test::SpawnTarget(World.World, FVector::ZeroVector);
+ UVerseCombatStateComponent* State = UVerseCombatStateComponent::FindOn(Victim);
+ const float Now = Service->Now();
+
+ // Spawn protection: no damage, the hit still raised with the marker.
+ State->BeginSpawnProtection(Now, 2.f);
+ FVerseHitEvent Protected = VerseDamageTest::BoltHit(*G, EVerseHitZone::Head, 5.f);
+ Service->ApplyHit(Shooter, Victim, Protected);
+ TestEqual(TEXT("protected: full health"), VerseWp02Test::HealthOf(Victim), 100.f);
+ TestTrue(TEXT("protected: marker set"), Protected.bBlockedBySpawnProtection != 0);
+ TestEqual(TEXT("protected: hit event raised"), Hits.Num(), 1);
+ State->NotifyOffensiveAction(Now);
+ TestFalse(TEXT("own action ends protection"), State->IsSpawnProtected(Now));
+
+ // Finisher victim: only the finisher's own damage.
+ State->SetPhase(EVerseCombatPhase::FinisherVictim);
+ FVerseHitEvent Bolt = VerseDamageTest::BoltHit(*G, EVerseHitZone::Head, 5.f);
+ Service->ApplyHit(Shooter, Victim, Bolt);
+ TestEqual(TEXT("finisher victim ignores bolts"), VerseWp02Test::HealthOf(Victim), 100.f);
+ State->SetPhase(EVerseCombatPhase::Alive);
+
+ // Ruleset hooks (the WP11 fake allows all; here they refuse, then scale).
+ Service->Rules.CanDamage = [](const FVerseDamageQuery& Q) { return Q.Source != EVerseDamageSource::Bolt; };
+ FVerseHitEvent Refused = VerseDamageTest::BoltHit(*G, EVerseHitZone::UpperTorso, 5.f);
+ Service->ApplyHit(Shooter, Victim, Refused);
+ TestEqual(TEXT("CanDamage false: no damage"), VerseWp02Test::HealthOf(Victim), 100.f);
+ Service->Rules.CanDamage = nullptr;
+ Service->Rules.ModifyDamage = [](const FVerseDamageQuery&, float D) { return D * 0.5f; };
+ FVerseHitEvent Halved = VerseDamageTest::BoltHit(*G, EVerseHitZone::UpperTorso, 5.f);
+ Service->ApplyHit(Shooter, Victim, Halved);
+ TestEqual(TEXT("ModifyDamage applied"), VerseWp02Test::HealthOf(Victim), 100.f - 14.f, 1e-4f);
+ Service->Rules.ModifyDamage = nullptr;
+
+ // Death: one event, killer and cause, phase Dead, nothing after.
+ FVerseHitEvent Head1 = VerseDamageTest::BoltHit(*G, EVerseHitZone::Head, 5.f);
+ FVerseHitEvent Head2 = VerseDamageTest::BoltHit(*G, EVerseHitZone::Head, 5.f);
+ Service->ApplyHit(Shooter, Victim, Head1);
+ Service->ApplyHit(Shooter, Victim, Head2);
+ TestEqual(TEXT("one death"), Deaths.Num(), 1);
+ TestTrue(TEXT("killing blow flagged"), Head2.bKillingBlow != 0);
+ TestTrue(TEXT("headshot flagged"), Head2.bHeadshot != 0);
+ TestEqual(TEXT("phase Dead"), State->Phase, EVerseCombatPhase::Dead);
+ if (Deaths.Num() == 1)
+ {
+ TestEqual(TEXT("killer id"), Deaths[0].KillerId, VerseCombatIds::IdOf(Shooter));
+ TestEqual(TEXT("victim id"), Deaths[0].VictimId, VerseCombatIds::IdOf(Victim));
+ TestEqual(TEXT("cause"), Deaths[0].Cause, EVerseDamageSource::Bolt);
+ TestEqual(TEXT("last zone"), Deaths[0].LastZone, EVerseHitZone::Head);
+ TestEqual(TEXT("respawn at +3 s"), Deaths[0].RespawnAt, Deaths[0].ServerTime + 3.f, 1e-5f);
+ }
+ const int32 HitsBefore = Hits.Num();
+ FVerseHitEvent Late = VerseDamageTest::BoltHit(*G, EVerseHitZone::Head, 5.f);
+ Service->ApplyHit(Shooter, Victim, Late);
+ TestEqual(TEXT("dead victims take no more hits"), Hits.Num(), HitsBefore);
+ TestEqual(TEXT("still one death"), Deaths.Num(), 1);
+ return true;
+}
+
+#endif // WITH_DEV_AUTOMATION_TESTS
diff --git a/unreal/Verse/Source/VerseCombat/Private/Tests/Gadgets/VerseGadgetTest.cpp b/unreal/Verse/Source/VerseCombat/Private/Tests/Gadgets/VerseGadgetTest.cpp
new file mode 100644
index 0000000000..0f35e757dc
--- /dev/null
+++ b/unreal/Verse/Source/VerseCombat/Private/Tests/Gadgets/VerseGadgetTest.cpp
@@ -0,0 +1,409 @@
+#include "Components/BoxComponent.h"
+#include "Events/VerseEventHub.h"
+#include "Gadgets/VerseBreachCharge.h"
+#include "Gadgets/VerseBulwark.h"
+#include "Gadgets/VerseGadgetAbilities.h"
+#include "Gadgets/VerseGadgetComponent.h"
+#include "Misc/AutomationTest.h"
+#include "Projectiles/VerseProjectileManager.h"
+#include "Tests/Projectiles/Fakes/VerseFakeDestruction.h"
+#include "Tests/Weapons/VerseWp02TestUtils.h"
+#include "VerseCollision.h"
+#include "VerseGameplayTags.h"
+#include "VerseRng.h"
+
+#if WITH_DEV_AUTOMATION_TESTS
+
+// Verse.Combat.Gadget.*: the Bulwark (GD1, A2.10), the breach charge (GD2-GD4, A2.11) and the gadget
+// component behind the two GAS abilities (WP02.12, WP02.13).
+
+namespace VerseGadgetTest
+{
+ UVerseGadgetDefinition* Copy(const UVerseGadgetDefinition* Src)
+ {
+ UVerseGadgetDefinition* D = DuplicateObject<UVerseGadgetDefinition>(Src, GetTransientPackage());
+ D->AddToRoot();
+ return D;
+ }
+
+ AVerseBulwark* SpawnBulwark(UWorld* World, const UVerseGadgetDefinition& Def, const FVector& Floor, AActor* Owner)
+ {
+ FActorSpawnParameters P;
+ P.SpawnCollisionHandlingOverride = ESpawnActorCollisionHandlingMethod::AlwaysSpawn;
+ AVerseBulwark* B = World->SpawnActor<AVerseBulwark>(AVerseBulwark::StaticClass(), Floor, FRotator(0, 180, 0), P);
+ B->InitBulwark(Def, Owner, World->GetTimeSeconds());
+ return B;
+ }
+
+ struct FScene
+ {
+ VerseWp02Test::FTestWorld World;
+ UVerseProjectileManager* Manager = nullptr;
+ UVerseLagCompSubsystem* Lag = nullptr;
+ TArray<FVerseBoltResult> Results;
+
+ FScene()
+ {
+ Manager = UVerseProjectileManager::Get(World.World);
+ Lag = UVerseLagCompSubsystem::Get(World.World);
+ Manager->SetManualStepping(true);
+ Manager->OnBoltResolved.AddLambda([this](const FVerseBoltResult& R) { Results.Add(R); });
+ }
+
+ void Step(int32 Ticks)
+ {
+ for (int32 I = 0; I < Ticks; ++I)
+ {
+ World.TickFrames(1);
+ Manager->StepAll(VerseWp02Test::Tick, World.World->GetTimeSeconds());
+ }
+ }
+
+ APawn* TargetBehind(const FVector& Root)
+ {
+ APawn* T = VerseWp02Test::SpawnTarget(World.World, Root, 1e6f);
+ Lag->RegisterTarget(T, [T](FTransform& R, TArray<FVerseHitCapsule>& Out)
+ {
+ R = T->GetActorTransform();
+ VerseWp02Test::HumanCapsules(T->GetActorLocation(), Out);
+ });
+ return T;
+ }
+
+ void FireAt(const UVerseWeaponDefinition& W, const FVector& From, const FVector& To, uint16 Counter)
+ {
+ FVerseFireEvent E;
+ E.WeaponId = W.WeaponId;
+ E.ShotCounter = Counter;
+ E.Origin = From;
+ E.Direction = (To - From).GetSafeNormal();
+ Manager->SpawnBoltFrom(E, W, 0.f, nullptr);
+ }
+ };
+}
+
+IMPLEMENT_SIMPLE_AUTOMATION_TEST(FVerseGadgetBulwark, "Verse.Combat.Gadget.Bulwark", VERSE_WP02_TEST_FLAGS)
+bool FVerseGadgetBulwark::RunTest(const FString&)
+{
+ const UVerseGadgetDefinition* Def = VerseWp02Test::Gadget(*this, TEXT("bulwark"));
+ const UVerseWeaponDefinition* G = VerseWp02Test::Weapon(*this, TEXT("graveline"));
+ if (!Def || !G)
+ {
+ return false;
+ }
+
+ // GD1: 1,000 seeded bolts at an intact Bulwark, 0 pass; 1,000 sight traces, all pass.
+ {
+ VerseGadgetTest::FScene Scene;
+ UVerseGadgetDefinition* Tough = VerseGadgetTest::Copy(Def);
+ Tough->MaxHealth = 1e6f; // intact for the whole volley
+ AVerseBulwark* B = VerseGadgetTest::SpawnBulwark(Scene.World.World, *Tough, FVector(1000, 0, 0), nullptr);
+ APawn* Behind = Scene.TargetBehind(FVector(1400, 0, 0));
+ Scene.World.TickFrames(2);
+ TArray<FVerseGadgetEvent> Gadgets;
+ UVerseEventHub::Get(Scene.World.World)->OnGadget.AddLambda([&Gadgets](const FVerseGadgetEvent& E) { Gadgets.Add(E); });
+
+ FVerseRng Rng(2026);
+ int32 Fired = 0;
+ for (int32 Volley = 0; Volley < 20; ++Volley)
+ {
+ for (int32 I = 0; I < 50; ++I)
+ {
+ const FVector From(0, Rng.Range(-60.0, 60.0), Rng.Range(20.0, 130.0));
+ const FVector To(1000, Rng.Range(-85.0, 85.0), Rng.Range(5.0, 135.0));
+ Scene.FireAt(*G, From, To, uint16(++Fired));
+ }
+ Scene.Step(4);
+ }
+ Scene.Step(10);
+ TestEqual(TEXT("1,000 bolts resolved"), Scene.Results.Num(), 1000);
+ const int32 Blocked = Scene.Results.FilterByPredicate([](const FVerseBoltResult& R) { return R.Result == EVerseShotResult::Blocked; }).Num();
+ TestEqual(TEXT("GD1: every bolt stopped by the field"), Blocked, 1000);
+ TestEqual(TEXT("nothing reached the pawn behind"), double(VerseWp02Test::HealthOf(Behind)), 1e6, 1e-3);
+ TestTrue(TEXT("field took the damage"), B->GetHealth() < Tough->MaxHealth);
+
+ int32 SightBlocked = 0;
+ for (int32 I = 0; I < 1000; ++I)
+ {
+ const FVector From(0, Rng.Range(-60.0, 60.0), Rng.Range(20.0, 130.0));
+ const FVector To(1400, Rng.Range(-85.0, 85.0), Rng.Range(5.0, 135.0));
+ FHitResult Hit;
+ FCollisionQueryParams Params(SCENE_QUERY_STAT(VerseTestSight), false);
+ if (Scene.World.World->LineTraceSingleByChannel(Hit, From, To, VerseCollision::Sight, Params) && Hit.GetActor() == B)
+ {
+ ++SightBlocked;
+ }
+ }
+ TestEqual(TEXT("GD1: every sight trace passes the field"), SightBlocked, 0);
+ FHitResult BoltHit;
+ TestTrue(TEXT("the field blocks the VerseBolt channel"),
+ Scene.World.World->LineTraceSingleByChannel(BoltHit, FVector(0, 0, 70), FVector(1400, 0, 70), VerseCollision::Bolt) && BoltHit.GetActor() == B);
+ TestEqual(TEXT("field blocks pawns"), B->Field->GetCollisionResponseToChannel(ECC_Pawn), ECR_Block);
+ }
+
+ // GD1 / trace order inside one 5 m step: a Bulwark, then a pawn, then a piece. The field is the
+ // nearest hit; neither the pawn nor the piece is touched.
+ {
+ VerseGadgetTest::FScene Scene;
+ FFakeVersePenetrationQuery Query;
+ FFakeVersePieceDamage PieceDamage;
+ FFakeVersePiece Wall;
+ Wall.PieceIndex = 9;
+ Wall.Material = EVersePenetrationMaterial::ContainerWall;
+ Wall.Bounds = FBox(FVector(420, -200, -100), FVector(425, 200, 300));
+ Query.Pieces.Add(Wall);
+ Scene.Manager->SetPenetrationQuery(&Query);
+ Scene.Manager->SetPieceDamage(&PieceDamage);
+ UVerseGadgetDefinition* Tough = VerseGadgetTest::Copy(Def);
+ Tough->MaxHealth = 1e6f;
+ AVerseBulwark* B = VerseGadgetTest::SpawnBulwark(Scene.World.World, *Tough, FVector(200, 0, 0), nullptr);
+ APawn* Between = Scene.TargetBehind(FVector(330, 0, 0));
+ Scene.World.TickFrames(2);
+ TArray<FVerseHitEvent> Impacts;
+ UVerseEventHub::Get(Scene.World.World)->OnHit.AddLambda([&Impacts](const FVerseHitEvent& E) { Impacts.Add(E); });
+ for (int32 I = 0; I < 20; ++I)
+ {
+ Scene.FireAt(*G, FVector(0, 0, 40 + 4 * I), FVector(500, 0, 40 + 4 * I), uint16(I + 1));
+ }
+ Scene.Step(2);
+ const int32 Blocked = Scene.Results.FilterByPredicate([B](const FVerseBoltResult& R)
+ {
+ return R.Result == EVerseShotResult::Blocked && R.HitActor.Get() == B;
+ }).Num();
+ TestEqual(TEXT("GD1 one segment: every bolt stops at the Bulwark first"), Blocked, 20);
+ TestEqual(TEXT("the pawn behind the field in the same segment is untouched"), double(VerseWp02Test::HealthOf(Between)), 1e6, 1e-3);
+ TestEqual(TEXT("the piece behind is untouched"), PieceDamage.Calls.Num(), 0);
+ TestEqual(TEXT("a cosmetic impact for every stop at the field"),
+ Impacts.FilterByPredicate([](const FVerseHitEvent& E) { return E.VictimId == -1; }).Num(), 20);
+ }
+
+ // It disappears on the tick its health reaches 0; the next bolt goes through.
+ {
+ VerseGadgetTest::FScene Scene;
+ TArray<FVerseGadgetEvent> Gadgets;
+ TArray<FVerseNoiseEvent> Noises;
+ UVerseEventHub::Get(Scene.World.World)->OnGadget.AddLambda([&Gadgets](const FVerseGadgetEvent& E) { Gadgets.Add(E); });
+ UVerseEventHub::Get(Scene.World.World)->OnNoise.AddLambda([&Noises](const FVerseNoiseEvent& E) { Noises.Add(E); });
+ AVerseBulwark* B = VerseGadgetTest::SpawnBulwark(Scene.World.World, *Def, FVector(1000, 0, 0), nullptr);
+ TestTrue(TEXT("deploy event"), Gadgets.Num() == 1 && Gadgets[0].Kind == EVerseGadgetEventKind::Deploy);
+ TestTrue(TEXT("deploy noise"), Noises.Num() == 1 && Noises[0].Noise == VerseTags::Noise_Gadget_BulwarkDeploy);
+ APawn* Behind = Scene.TargetBehind(FVector(1400, 0, -100));
+ Scene.World.TickFrames(2);
+ const int32 BoltsToBreak = FMath::CeilToInt(Def->MaxHealth / G->BaseDamage);
+ uint16 Counter = 0;
+ for (int32 I = 0; I < BoltsToBreak; ++I)
+ {
+ TestTrue(FString::Printf(TEXT("intact before bolt %d"), I + 1), B->IsActive());
+ Scene.FireAt(*G, FVector(0, 0, 50), FVector(1400, 0, 50), ++Counter);
+ Scene.Step(3);
+ }
+ TestFalse(TEXT("gone on the tick its health reached 0"), B->IsActive());
+ TestTrue(TEXT("destroyed event"), Gadgets.Num() >= 2 && Gadgets.Last().Kind == EVerseGadgetEventKind::Destroyed);
+ const int32 Before = Scene.Results.Num();
+ Scene.FireAt(*G, FVector(0, 0, 50), FVector(1400, 0, 50), ++Counter);
+ Scene.Step(8);
+ TestTrue(TEXT("the next bolt passes where the field was"),
+ Scene.Results.Num() == Before + 1 && Scene.Results.Last().Result == EVerseShotResult::HitBody && Scene.Results.Last().HitActor.Get() == Behind);
+ }
+
+ // Lifetime: 25 s after deploy.
+ {
+ VerseGadgetTest::FScene Scene;
+ AVerseBulwark* B = VerseGadgetTest::SpawnBulwark(Scene.World.World, *Def, FVector(1000, 0, 0), nullptr);
+ const double Deployed = Scene.World.World->GetTimeSeconds();
+ TArray<FVerseGadgetEvent> Gadgets;
+ UVerseEventHub::Get(Scene.World.World)->OnGadget.AddLambda([&Gadgets](const FVerseGadgetEvent& E) { Gadgets.Add(E); });
+ B->ServerAdvance(Deployed + Def->Lifetime - 0.001);
+ TestTrue(TEXT("alive just before its lifetime"), B->IsActive());
+ B->ServerAdvance(Deployed + Def->Lifetime);
+ TestFalse(TEXT("gone at its lifetime"), B->IsActive());
+ TestTrue(TEXT("expired event"), Gadgets.Num() == 1 && Gadgets[0].Kind == EVerseGadgetEventKind::Expired);
+ }
+
+ // Owner death removes it.
+ {
+ VerseGadgetTest::FScene Scene;
+ APawn* Owner = VerseWp02Test::SpawnTarget(Scene.World.World, FVector::ZeroVector);
+ AVerseBulwark* B = VerseGadgetTest::SpawnBulwark(Scene.World.World, *Def, FVector(1000, 0, 0), Owner);
+ FVerseDeathEvent Death;
+ Death.VictimId = VerseCombatIds::IdOf(Owner);
+ UVerseEventHub::Get(Scene.World.World)->OnDeath.Broadcast(Death);
+ TestFalse(TEXT("owner death removes the field"), B->IsActive());
+ }
+ return true;
+}
+
+IMPLEMENT_SIMPLE_AUTOMATION_TEST(FVerseGadgetBreach, "Verse.Combat.Gadget.Breach", VERSE_WP02_TEST_FLAGS)
+bool FVerseGadgetBreach::RunTest(const FString&)
+{
+ const UVerseGadgetDefinition* Def = VerseWp02Test::Gadget(*this, TEXT("breach_charge"));
+ const UVerseGadgetDefinition* BulwarkDef = VerseWp02Test::Gadget(*this, TEXT("bulwark"));
+ if (!Def || !BulwarkDef)
+ {
+ return false;
+ }
+ auto Spawn = [](UWorld* World, const FVector& At)
+ {
+ FActorSpawnParameters P;
+ P.SpawnCollisionHandlingOverride = ESpawnActorCollisionHandlingMethod::AlwaysSpawn;
+ return World->SpawnActor<AVerseBreachCharge>(AVerseBreachCharge::StaticClass(), At, FRotator::ZeroRotator, P);
+ };
+
+ // GD2: detonation FuseTime after the plant, within one tick.
+ {
+ VerseWp02Test::FTestWorld World;
+ FFakeVersePieceDamage Pieces;
+ AVerseBreachCharge* C = Spawn(World.World, FVector(0, 0, 100));
+ C->SetPieceDamage(&Pieces);
+ const double Plant = 10.0;
+ C->InitCharge(*Def, nullptr, 3, FVector(-1, 0, 0), Plant);
+ double T = Plant;
+ while (!C->HasDetonated() && T < Plant + 10.0)
+ {
+ T += VerseWp02Test::Tick;
+ C->ServerAdvance(T);
+ }
+ TestTrue(TEXT("detonated"), C->HasDetonated());
+ TestTrue(FString::Printf(TEXT("GD2: %.4f s after the plant, within one tick of %.2f"), C->GetDetonatedTime() - Plant, Def->Lifetime),
+ FMath::Abs(C->GetDetonatedTime() - Plant - Def->Lifetime) <= VerseWp02Test::Tick + 1e-6);
+ }
+
+ // GD3: pawn damage at 0, 1.5 and 3.0 m: 120, 60, 0 to 1e-4 hp, owner included.
+ {
+ VerseWp02Test::FTestWorld World;
+ const FVector At(0, 0, 100);
+ APawn* Owner = VerseWp02Test::SpawnTarget(World.World, At + FVector(0, 150, 0), 1000.f);
+ APawn* Zero = VerseWp02Test::SpawnTarget(World.World, At, 1000.f);
+ APawn* Mid = VerseWp02Test::SpawnTarget(World.World, At + FVector(-150, 0, 0), 1000.f);
+ APawn* Edge = VerseWp02Test::SpawnTarget(World.World, At + FVector(300, 0, 0), 1000.f);
+ AVerseBulwark* Near = VerseGadgetTest::SpawnBulwark(World.World, *BulwarkDef, At + FVector(0, -250, -100), nullptr);
+ AVerseBulwark* Far = VerseGadgetTest::SpawnBulwark(World.World, *BulwarkDef, At + FVector(0, -600, -100), nullptr);
+ FFakeVersePieceDamage Pieces;
+ AVerseBreachCharge* C = Spawn(World.World, At);
+ C->SetPieceDamage(&Pieces);
+ C->InitCharge(*Def, Owner, 7, FVector(0, 0, 1), 0.0);
+ C->Detonate(2.5);
+ TestEqual(TEXT("GD3: 0 m takes 120"), double(1000.f - VerseWp02Test::HealthOf(Zero)), 120.0, 1e-4);
+ TestEqual(TEXT("GD3: 1.5 m takes 60"), double(1000.f - VerseWp02Test::HealthOf(Mid)), 60.0, 1e-4);
+ TestEqual(TEXT("GD3: owner at 1.5 m takes 60"), double(1000.f - VerseWp02Test::HealthOf(Owner)), 60.0, 1e-4);
+ TestEqual(TEXT("GD3: 3.0 m takes 0"), double(1000.f - VerseWp02Test::HealthOf(Edge)), 0.0, 1e-4);
+ TestFalse(TEXT("a Bulwark within 3 m goes"), Near->IsActive());
+ TestTrue(TEXT("a Bulwark beyond 3 m stays"), Far->IsActive());
+ if (TestEqual(TEXT("one piece damage call"), Pieces.Calls.Num(), 1))
+ {
+ TestEqual(TEXT("breach cause"), Pieces.Calls[0].Cause, EVerseFractureCause::Breach);
+ TestEqual(TEXT("target piece"), int32(Pieces.Calls[0].PieceIndex), 7);
+ TestEqual(TEXT("breach radius"), Pieces.Calls[0].BreachRadiusCm, Def->PieceBreachRadius);
+ }
+ }
+
+ // GD4: 100 of 100 plants drive their target piece to its breach result (the request reaches
+ // destruction with Cause = Breach; WP06 maps it to the breach state, its own GD4 half).
+ {
+ VerseWp02Test::FTestWorld World;
+ FFakeVersePieceDamage Pieces;
+ for (uint16 I = 0; I < 100; ++I)
+ {
+ AVerseBreachCharge* C = Spawn(World.World, FVector(I * 1000.0, 0, 100));
+ C->SetPieceDamage(&Pieces);
+ C->InitCharge(*Def, nullptr, uint16(100 + I), FVector(1, 0, 0), 0.0);
+ C->ServerAdvance(Def->Lifetime);
+ }
+ int32 Good = 0;
+ for (int32 I = 0; I < Pieces.Calls.Num(); ++I)
+ {
+ const FVersePieceDamage& D = Pieces.Calls[I];
+ Good += (D.Cause == EVerseFractureCause::Breach && D.PieceIndex == 100 + I && D.BreachRadiusCm == Def->PieceBreachRadius) ? 1 : 0;
+ }
+ TestEqual(TEXT("GD4: 100 of 100 plants reach their piece"), Good, 100);
+ }
+ return true;
+}
+
+IMPLEMENT_SIMPLE_AUTOMATION_TEST(FVerseGadgetComponent, "Verse.Combat.Gadget.Component", VERSE_WP02_TEST_FLAGS)
+bool FVerseGadgetComponent::RunTest(const FString&)
+{
+ const UVerseGadgetDefinition* BulwarkDef = VerseWp02Test::Gadget(*this, TEXT("bulwark"));
+ const UVerseGadgetDefinition* BreachDef = VerseWp02Test::Gadget(*this, TEXT("breach_charge"));
+ if (!BulwarkDef || !BreachDef)
+ {
+ return false;
+ }
+ VerseWp02Test::FTestWorld World;
+ APawn* Pawn = VerseWp02Test::SpawnTarget(World.World, FVector::ZeroVector);
+ UVerseGadgetComponent* Gadgets = NewObject<UVerseGadgetComponent>(Pawn, TEXT("Gadgets"));
+ UVerseGadgetDefinition* TwoBulwarks = VerseGadgetTest::Copy(BulwarkDef);
+ TwoBulwarks->Charges = 2;
+ Gadgets->Bulwark = TwoBulwarks;
+ Gadgets->BreachCharge = BreachDef;
+ Gadgets->PlacementOverride = [](EVerseLoadoutSlot Slot)
+ {
+ FVerseGadgetPlacement P;
+ P.bValid = true;
+ P.Location = Slot == EVerseLoadoutSlot::GadgetA ? FVector(150, 0, 0) : FVector(150, 0, 100);
+ P.PieceIndex = 4;
+ P.Normal = FVector(-1, 0, 0);
+ return P;
+ };
+ FFakeVersePieceDamage Pieces;
+ Gadgets->SetPieceDamage(&Pieces);
+ Gadgets->RegisterComponent();
+ Gadgets->ResetForLife(); // as on spawn; BeginPlay does the same when the pawn begins play
+ TestEqual(TEXT("charges per life"), Gadgets->GetChargesLeft(EVerseLoadoutSlot::GadgetA), 2);
+ TestEqual(TEXT("breach charges per life"), Gadgets->GetChargesLeft(EVerseLoadoutSlot::GadgetB), 2);
+
+ UVerseCombatStateComponent* State = UVerseCombatStateComponent::FindOn(Pawn);
+ State->BeginSpawnProtection(0.f, 100.f);
+ TestTrue(TEXT("deploy starts"), Gadgets->ServerBeginUse(EVerseLoadoutSlot::GadgetA, 1.f));
+ TestFalse(TEXT("gadget use ends spawn protection"), State->bSpawnProtected);
+ TestFalse(TEXT("busy while deploying"), Gadgets->ServerBeginUse(EVerseLoadoutSlot::GadgetB, 1.1f));
+ Gadgets->ServerAdvance(1.f + TwoBulwarks->UseTime - 0.01f);
+ TestNull(TEXT("not yet deployed"), Gadgets->GetActiveBulwark());
+ Gadgets->ServerAdvance(1.f + TwoBulwarks->UseTime);
+ AVerseBulwark* First = Gadgets->GetActiveBulwark();
+ TestNotNull(TEXT("deployed after the use time"), First);
+ TestEqual(TEXT("one charge left"), Gadgets->GetChargesLeft(EVerseLoadoutSlot::GadgetA), 1);
+
+ TestTrue(TEXT("second deploy"), Gadgets->ServerBeginUse(EVerseLoadoutSlot::GadgetA, 2.f));
+ Gadgets->ServerAdvance(2.f + TwoBulwarks->UseTime);
+ TestFalse(TEXT("a second deploy removes the first"), First && First->IsActive());
+ TestNotNull(TEXT("the second stands"), Gadgets->GetActiveBulwark());
+ TestFalse(TEXT("out of charges"), Gadgets->ServerBeginUse(EVerseLoadoutSlot::GadgetA, 3.f));
+
+ // Damage interrupts a plant and keeps the charge.
+ TestTrue(TEXT("plant starts"), Gadgets->ServerBeginUse(EVerseLoadoutSlot::GadgetB, 4.f));
+ FVerseHitEvent Hit;
+ Hit.VictimId = VerseCombatIds::IdOf(Pawn);
+ Hit.Damage = 10.f;
+ UVerseEventHub::Get(World.World)->OnHit.Broadcast(Hit);
+ TestFalse(TEXT("damage interrupts"), Gadgets->IsUsing());
+ Gadgets->ServerAdvance(10.f);
+ TestEqual(TEXT("charge kept"), Gadgets->GetChargesLeft(EVerseLoadoutSlot::GadgetB), 2);
+ TestTrue(TEXT("plant again"), Gadgets->ServerBeginUse(EVerseLoadoutSlot::GadgetB, 11.f));
+ Gadgets->ServerAdvance(11.f + BreachDef->UseTime);
+ TestEqual(TEXT("one charge planted"), Gadgets->NumPlantedCharges(), 1);
+ TestEqual(TEXT("one breach charge left"), Gadgets->GetChargesLeft(EVerseLoadoutSlot::GadgetB), 1);
+
+ // The Bulwark's charge returns Cooldown after the field is gone.
+ AVerseBulwark* Second = Gadgets->GetActiveBulwark();
+ if (!TestNotNull(TEXT("second Bulwark still up"), Second))
+ {
+ return false;
+ }
+ Second->RemoveBulwark(EVerseGadgetEventKind::Destroyed);
+ const float CooldownEnd = Gadgets->GetCooldownEndsAt();
+ TestTrue(TEXT("cooldown counts from the field being gone"), CooldownEnd >= TwoBulwarks->Cooldown - 1e-3f);
+ Gadgets->ServerAdvance(CooldownEnd - 0.01f);
+ TestEqual(TEXT("cooling down"), Gadgets->GetChargesLeft(EVerseLoadoutSlot::GadgetA), 0);
+ Gadgets->ServerAdvance(CooldownEnd);
+ TestEqual(TEXT("charge back after the cooldown"), Gadgets->GetChargesLeft(EVerseLoadoutSlot::GadgetA), 1);
+
+ // The abilities are local-predicted.
+ const UVerseGA_Bulwark* Ga = GetDefault<UVerseGA_Bulwark>();
+ TestEqual(TEXT("Bulwark ability slot"), Ga->GadgetSlot, EVerseLoadoutSlot::GadgetA);
+ TestTrue(TEXT("local predicted"), Ga->GetNetExecutionPolicy() == EGameplayAbilityNetExecutionPolicy::LocalPredicted);
+ TestEqual(TEXT("breach ability slot"), GetDefault<UVerseGA_BreachCharge>()->GadgetSlot, EVerseLoadoutSlot::GadgetB);
+ return true;
+}
+
+#endif // WITH_DEV_AUTOMATION_TESTS
diff --git a/unreal/Verse/Source/VerseCombat/Private/Tests/Inventory/VerseInventoryTest.cpp b/unreal/Verse/Source/VerseCombat/Private/Tests/Inventory/VerseInventoryTest.cpp
new file mode 100644
index 0000000000..8abc9d65ca
--- /dev/null
+++ b/unreal/Verse/Source/VerseCombat/Private/Tests/Inventory/VerseInventoryTest.cpp
@@ -0,0 +1,186 @@
+#include "Events/VerseEventHub.h"
+#include "Inventory/VerseInventoryComponent.h"
+#include "Misc/AutomationTest.h"
+#include "Net/UnrealNetwork.h"
+#include "Tests/Weapons/VerseWp02TestUtils.h"
+#include "VerseGameplayTags.h"
+
+#if WITH_DEV_AUTOMATION_TESTS
+
+// Verse.Combat.Reload.Times (A2.4) and Verse.Combat.Inventory.*: the magazine and reload state
+// machine (WP02.3) and the inventory component (WP02.2).
+
+namespace VerseInventoryTest
+{
+ /** Ticks a reload at 60 Hz from Start until it ends; returns the server time it ended. */
+ float RunReload(FVerseWeaponSlotState& S, const UVerseWeaponDefinition& W, float Start)
+ {
+ float Now = Start;
+ for (int32 I = 0; I < 1000 && FVerseMagazine::IsReloading(S); ++I)
+ {
+ Now += VerseWp02Test::Tick;
+ FVerseMagazine::Tick(S, W, Now);
+ }
+ return Now;
+ }
+
+ UVerseInventoryComponent* AddInventory(APawn* Pawn, const UVerseWeaponDefinition* Primary, const UVerseWeaponDefinition* Secondary, float Now)
+ {
+ UVerseInventoryComponent* Inv = NewObject<UVerseInventoryComponent>(Pawn, TEXT("Inventory"));
+ Inv->RegisterComponent();
+ TMap<EVerseLoadoutSlot, const UVerseWeaponDefinition*> Loadout;
+ Loadout.Add(EVerseLoadoutSlot::Primary, Primary);
+ Loadout.Add(EVerseLoadoutSlot::Secondary, Secondary);
+ Inv->GiveLoadout(Loadout, Now);
+ return Inv;
+ }
+}
+
+IMPLEMENT_SIMPLE_AUTOMATION_TEST(FVerseReloadTimes, "Verse.Combat.Reload.Times", VERSE_WP02_TEST_FLAGS)
+bool FVerseReloadTimes::RunTest(const FString&)
+{
+ for (const UVerseWeaponDefinition* W : VerseWp02Test::AllWeapons(*this))
+ {
+ const FString Id = W->WeaponId.ToString();
+ FVerseWeaponSlotState S;
+ FVerseMagazine::InitFull(S, *W);
+ TestEqual(FString::Printf(TEXT("%s: spawn holds a full magazine"), *Id), FVerseMagazine::RoundsReady(S, *W), W->MagazineSize);
+
+ // Tactical: fire a few, reload with a round chambered.
+ for (int32 I = 0; I < 5; ++I)
+ {
+ FVerseMagazine::ConsumeRound(S, *W);
+ }
+ const int32 ReserveBefore = S.Reserve;
+ TestTrue(TEXT("tactical reload starts"), FVerseMagazine::StartReload(S, *W, 10.f));
+ TestEqual(TEXT("phase tactical"), S.Reload, EVerseReloadPhase::Tactical);
+ TestFalse(TEXT("cannot fire while reloading"), FVerseMagazine::CanFire(S, *W));
+ const float TacticalEnd = VerseInventoryTest::RunReload(S, *W, 10.f);
+ TestTrue(FString::Printf(TEXT("%s: tactical reload within one tick (%.4f vs %.4f)"), *Id, TacticalEnd - 10.f, W->ReloadTactical),
+ FMath::Abs((TacticalEnd - 10.f) - W->ReloadTactical) <= VerseWp02Test::Tick + 1e-4f);
+ const int32 WantTactical = W->bClosedBolt ? W->MagazineSize + 1 : W->MagazineSize;
+ TestEqual(FString::Printf(TEXT("%s: tactical leaves magazine + 1"), *Id), FVerseMagazine::RoundsReady(S, *W), WantTactical);
+ TestEqual(TEXT("reserve pays only what was spent"), int32(S.Reserve), ReserveBefore - (W->bClosedBolt ? 6 : 5));
+
+ // Empty: fire everything, reload from empty.
+ while (FVerseMagazine::ConsumeRound(S, *W))
+ {
+ }
+ TestEqual(TEXT("empty"), FVerseMagazine::RoundsReady(S, *W), 0);
+ TestTrue(TEXT("empty reload starts"), FVerseMagazine::StartReload(S, *W, 20.f));
+ TestEqual(TEXT("phase empty"), S.Reload, EVerseReloadPhase::Empty);
+ const float EmptyEnd = VerseInventoryTest::RunReload(S, *W, 20.f);
+ TestTrue(FString::Printf(TEXT("%s: empty reload within one tick"), *Id),
+ FMath::Abs((EmptyEnd - 20.f) - W->ReloadEmpty) <= VerseWp02Test::Tick + 1e-4f);
+ TestEqual(FString::Printf(TEXT("%s: empty reload gives a full magazine"), *Id), FVerseMagazine::RoundsReady(S, *W), W->MagazineSize);
+ TestTrue(TEXT("tactical is faster than empty"), W->ReloadTactical < W->ReloadEmpty);
+
+ // Cancel before the commit keeps the old magazine; after it the new one is in.
+ FVerseMagazine::ConsumeRound(S, *W);
+ FVerseMagazine::ConsumeRound(S, *W);
+ const FVerseWeaponSlotState Before = S;
+ FVerseMagazine::StartReload(S, *W, 30.f);
+ const float Commit = FVerseMagazine::CommitTime(S, *W);
+ FVerseMagazine::Tick(S, *W, Commit - 0.01f);
+ TestEqual(TEXT("cancel before commit"), FVerseMagazine::Cancel(S), EVerseMagazineChange::ReloadCancelled);
+ TestEqual(TEXT("old magazine kept"), int32(S.Magazine), int32(Before.Magazine));
+ TestEqual(TEXT("old chamber kept"), S.bChambered, Before.bChambered);
+ TestEqual(TEXT("reserve untouched"), int32(S.Reserve), int32(Before.Reserve));
+ FVerseMagazine::StartReload(S, *W, 40.f);
+ FVerseMagazine::Tick(S, *W, FVerseMagazine::CommitTime(S, *W) + 0.001f);
+ FVerseMagazine::Cancel(S);
+ TestEqual(TEXT("cancel after commit keeps the new magazine"), FVerseMagazine::RoundsReady(S, *W), WantTactical);
+
+ // No reserve, no reload.
+ FVerseWeaponSlotState Dry = S;
+ Dry.Reserve = 0;
+ FVerseMagazine::ConsumeRound(Dry, *W);
+ TestFalse(TEXT("no reload without reserve"), FVerseMagazine::StartReload(Dry, *W, 50.f));
+ }
+ return true;
+}
+
+IMPLEMENT_SIMPLE_AUTOMATION_TEST(FVerseInventorySlots, "Verse.Combat.Inventory.SlotsAndEquip", VERSE_WP02_TEST_FLAGS)
+bool FVerseInventorySlots::RunTest(const FString&)
+{
+ const UVerseWeaponDefinition* G = VerseWp02Test::Weapon(*this, TEXT("graveline"));
+ const UVerseWeaponDefinition* T = VerseWp02Test::Weapon(*this, TEXT("tallow"));
+ if (!G || !T)
+ {
+ return false;
+ }
+
+ // Replication conditions of combat-state.md 2.1: slots owner only, active slot and reloading to all.
+ UVerseInventoryComponent::StaticClass()->SetUpRuntimeReplicationData(); // assigns RepIndex
+ TArray<FLifetimeProperty> Props;
+ GetDefault<UVerseInventoryComponent>()->GetLifetimeReplicatedProps(Props);
+ for (const FLifetimeProperty& L : Props)
+ {
+ AddInfo(FString::Printf(TEXT("lifetime rep index %d condition %d"), int32(L.RepIndex), int32(L.Condition)));
+ }
+ for (const TCHAR* Name : {TEXT("Slots"), TEXT("ActiveSlot"), TEXT("bReloading")})
+ {
+ const FProperty* P = UVerseInventoryComponent::StaticClass()->FindPropertyByName(Name);
+ AddInfo(FString::Printf(TEXT("%s rep index %d"), Name, P ? int32(P->RepIndex) : -1));
+ }
+ auto ConditionOf = [&Props](const TCHAR* Name) -> int32
+ {
+ const FProperty* P = UVerseInventoryComponent::StaticClass()->FindPropertyByName(Name);
+ for (const FLifetimeProperty& L : Props)
+ {
+ if (P && L.RepIndex == P->RepIndex)
+ {
+ return int32(L.Condition);
+ }
+ }
+ return -1;
+ };
+ TestEqual(TEXT("Slots owner only"), ConditionOf(TEXT("Slots")), int32(COND_OwnerOnly));
+ TestEqual(TEXT("ActiveSlot to all"), ConditionOf(TEXT("ActiveSlot")), int32(COND_None));
+ TestEqual(TEXT("bReloading to all"), ConditionOf(TEXT("bReloading")), int32(COND_None));
+
+ VerseWp02Test::FTestWorld W;
+ APawn* Pawn = VerseWp02Test::SpawnTarget(W.World, FVector::ZeroVector);
+ UVerseInventoryComponent* Inv = VerseInventoryTest::AddInventory(Pawn, G, T, 1.f);
+ TestEqual(TEXT("primary drawn"), Inv->ActiveSlot, EVerseLoadoutSlot::Primary);
+ TestTrue(TEXT("weapon ready"), Inv->IsReady(1.f));
+ TestEqual(TEXT("two slots"), Inv->Slots.Items.Num(), 2);
+ TestTrue(TEXT("primary is the Graveline"), Inv->GetActiveWeapon() == G);
+
+ TArray<FVerseReloadEvent> Reloads;
+ TArray<FVerseNoiseEvent> Noises;
+ UVerseEventHub* Hub = UVerseEventHub::Get(W.World);
+ Hub->OnReload.AddLambda([&Reloads](const FVerseReloadEvent& E) { Reloads.Add(E); });
+ Hub->OnNoise.AddLambda([&Noises](const FVerseNoiseEvent& E) { Noises.Add(E); });
+
+ TestTrue(TEXT("consume"), Inv->ServerConsumeRound(1.f));
+ TestTrue(TEXT("reload starts"), Inv->ServerStartReload(1.1f));
+ TestTrue(TEXT("reloading flag"), Inv->bReloading);
+ TestEqual(TEXT("one reload event"), Reloads.Num(), 1);
+ TestTrue(TEXT("tactical event"), Reloads.Num() == 1 && Reloads[0].bTactical);
+ TestTrue(TEXT("reload noise raised"), Noises.Num() == 1 && Noises[0].Noise == VerseTags::Noise_Reload);
+
+ // Switching cancels the reload and readies the new weapon after holster + equip.
+ Inv->ServerSwitch(EVerseLoadoutSlot::Secondary, 1.2f);
+ TestEqual(TEXT("cancel event"), Reloads.Num(), 2);
+ TestTrue(TEXT("cancel flagged"), Reloads.Num() == 2 && Reloads[1].bCancelled);
+ TestFalse(TEXT("not reloading"), Inv->bReloading);
+ TestEqual(TEXT("active is secondary"), Inv->ActiveSlot, EVerseLoadoutSlot::Secondary);
+ TestEqual(TEXT("ready after holster + equip"), Inv->GetReadyAt(), 1.2f + G->HolsterTime + T->EquipTime, 1e-5f);
+ TestFalse(TEXT("cannot fire while equipping"), Inv->ServerConsumeRound(1.25f));
+ TestTrue(TEXT("fires once equipped"), Inv->ServerConsumeRound(Inv->GetReadyAt()));
+
+ // The server tick finishes a reload on its own.
+ Inv->ServerSwitch(EVerseLoadoutSlot::Primary, 5.f);
+ const float Ready = Inv->GetReadyAt();
+ TestTrue(TEXT("reload after equip"), Inv->ServerStartReload(Ready));
+ Inv->ServerAdvance(Ready + G->ReloadTactical + 0.001f);
+ TestFalse(TEXT("reload done"), Inv->bReloading);
+ TestEqual(TEXT("magazine + 1"), FVerseMagazine::RoundsReady(*Inv->GetActiveState(), *G), G->MagazineSize + 1);
+
+ Inv->RefillAll();
+ TestEqual(TEXT("refill"), FVerseMagazine::RoundsReady(*Inv->GetActiveState(), *G), G->MagazineSize);
+ return true;
+}
+
+#endif // WITH_DEV_AUTOMATION_TESTS
diff --git a/unreal/Verse/Source/VerseCombat/Private/Tests/LagComp/VerseLagCompTest.cpp b/unreal/Verse/Source/VerseCombat/Private/Tests/LagComp/VerseLagCompTest.cpp
new file mode 100644
index 0000000000..86b3ded60c
--- /dev/null
+++ b/unreal/Verse/Source/VerseCombat/Private/Tests/LagComp/VerseLagCompTest.cpp
@@ -0,0 +1,170 @@
+#include "Misc/AutomationTest.h"
+#include "Projectiles/VerseProjectileManager.h"
+#include "Tests/Weapons/VerseWp02TestUtils.h"
+
+#if WITH_DEV_AUTOMATION_TESTS
+
+// Verse.Combat.LagComp.*: the 1 s per-bone ring buffer, the 250 ms rewind cap and lag-compensated
+// bolt hits on a strafing target (A2.7).
+
+IMPLEMENT_SIMPLE_AUTOMATION_TEST(FVerseLagCompRingBuffer, "Verse.Combat.LagComp.RingBuffer", VERSE_WP02_TEST_FLAGS)
+bool FVerseLagCompRingBuffer::RunTest(const FString&)
+{
+ FVerseHitBodyHistory H;
+ for (int32 I = 0; I < 200; ++I)
+ {
+ FVerseHitBodyPose P;
+ P.Time = I / 60.0;
+ P.Root.SetLocation(FVector(I * 10.0, 0, 0));
+ FVerseHitCapsule& C = P.Capsules.AddDefaulted_GetRef();
+ C.Bone = TEXT("Head");
+ C.A = C.B = FVector(I * 10.0, 0, 170);
+ C.Radius = 10.f;
+ H.Push(MoveTemp(P));
+ }
+ TestTrue(TEXT("holds at least 1 s"), H.NewestTime() - H.OldestTime() >= 1.0);
+ TestTrue(TEXT("holds no more than 1.2 s"), H.NewestTime() - H.OldestTime() <= 1.2);
+ FVerseHitBodyPose Mid;
+ TestTrue(TEXT("sample"), H.Sample(H.NewestTime() - 0.5 / 60.0, Mid));
+ TestEqual(TEXT("interpolated between ticks"), Mid.Capsules[0].A.X, 199 * 10.0 - 5.0, 1e-6);
+ FVerseHitBodyPose Old;
+ H.Sample(-100.0, Old);
+ TestEqual(TEXT("clamped to the oldest"), Old.Time, H.OldestTime());
+
+ TestEqual(TEXT("rewind clamps to 250 ms"), UVerseLagCompSubsystem::ClampRewindTime(10.0, 9.7), 9.75, 1e-9);
+ TestEqual(TEXT("rewind never into the future"), UVerseLagCompSubsystem::ClampRewindTime(10.0, 10.5), 10.0, 1e-9);
+ TestEqual(TEXT("60 ms kept"), UVerseLagCompSubsystem::ClampRewindTime(10.0, 9.94), 9.94, 1e-9);
+
+ // Ray against capsule: side, cap, miss, start inside.
+ const FVector A(0, 0, 0), B(0, 0, 100);
+ TestEqual(TEXT("side hit"), UVerseLagCompSubsystem::RayCapsule(FVector(-100, 0, 50), FVector(1, 0, 0), A, B, 10.0), 90.0, 1e-6);
+ TestEqual(TEXT("cap hit"), UVerseLagCompSubsystem::RayCapsule(FVector(0, 0, 300), FVector(0, 0, -1), A, B, 10.0), 190.0, 1e-6);
+ TestTrue(TEXT("miss"), UVerseLagCompSubsystem::RayCapsule(FVector(-100, 50, 50), FVector(1, 0, 0), A, B, 10.0) < 0.0);
+ TestEqual(TEXT("inside"), UVerseLagCompSubsystem::RayCapsule(FVector(0, 0, 50), FVector(1, 0, 0), A, B, 10.0), 0.0);
+
+ TestEqual(TEXT("Head zone"), UVerseLagCompSubsystem::ZoneForBone(TEXT("Head")), EVerseHitZone::Head);
+ TestEqual(TEXT("Neck zone"), UVerseLagCompSubsystem::ZoneForBone(TEXT("Neck")), EVerseHitZone::Neck);
+ TestEqual(TEXT("Spine_03 zone"), UVerseLagCompSubsystem::ZoneForBone(TEXT("Spine_03")), EVerseHitZone::UpperTorso);
+ TestEqual(TEXT("Hips zone"), UVerseLagCompSubsystem::ZoneForBone(TEXT("Hips")), EVerseHitZone::LowerTorso);
+ TestEqual(TEXT("LowerArm_L zone"), UVerseLagCompSubsystem::ZoneForBone(TEXT("LowerArm_L")), EVerseHitZone::Arm);
+ TestEqual(TEXT("Calf_R zone"), UVerseLagCompSubsystem::ZoneForBone(TEXT("Calf_R")), EVerseHitZone::Leg);
+ return true;
+}
+
+namespace VerseLagCompTest
+{
+ constexpr double StrafeCmS = 650.0; // 6.5 m/s
+ constexpr double T0 = 100.0;
+ const FVector Muzzle(0, 0, 135);
+
+ struct FScene
+ {
+ VerseWp02Test::FTestWorld World;
+ UVerseProjectileManager* Manager = nullptr;
+ UVerseLagCompSubsystem* Lag = nullptr;
+ APawn* Target = nullptr;
+ double Now = T0;
+ TArray<FVerseBoltResult> Results;
+
+ FScene()
+ {
+ Manager = UVerseProjectileManager::Get(World.World);
+ Lag = UVerseLagCompSubsystem::Get(World.World);
+ Manager->SetManualStepping(true);
+ Manager->SetClock([this]() { return Now; });
+ Manager->OnBoltResolved.AddLambda([this](const FVerseBoltResult& R) { Results.Add(R); });
+ Target = VerseWp02Test::SpawnTarget(World.World, RootAt(T0), 10000.f);
+ Lag->RegisterTarget(Target, [this](FTransform& Root, TArray<FVerseHitCapsule>& Out)
+ {
+ Root = FTransform(RootAt(Now));
+ VerseWp02Test::HumanCapsules(RootAt(Now), Out);
+ });
+ }
+
+ static FVector RootAt(double T)
+ {
+ // 20 m downrange, strafing along Y (a back-and-forth every 2 s).
+ const double Phase = FMath::Fmod(T - T0, 4.0);
+ const double Y = Phase < 2.0 ? StrafeCmS * Phase : StrafeCmS * (4.0 - Phase);
+ return FVector(2000.0, Y - 650.0, 0.0);
+ }
+
+ void Advance(double To)
+ {
+ while (Now + 1e-9 < To)
+ {
+ Now += VerseWp02Test::Tick;
+ Lag->Record(Now);
+ Manager->StepAll(VerseWp02Test::Tick, Now);
+ }
+ }
+
+ /** The client's aim: lead the target as it shows it (pose at view time V) to where bolt and target meet. */
+ static FVector AimFor(double ViewTime)
+ {
+ double Tau = 0.06;
+ for (int32 I = 0; I < 20; ++I)
+ {
+ const FVector Chest = RootAt(ViewTime + Tau) + FVector(0, 0, 135);
+ Tau = FVector::Dist(Chest, Muzzle) / 30000.0;
+ }
+ return (RootAt(ViewTime + Tau) + FVector(0, 0, 135) - Muzzle).GetSafeNormal();
+ }
+
+ /** Fires at server time S with lag L, aiming from the client's picture at ViewLag. */
+ EVerseShotResult Shoot(const UVerseWeaponDefinition& W, double Lag_, double AimLag)
+ {
+ Results.Reset();
+ FVerseFireEvent E;
+ E.WeaponId = W.WeaponId;
+ E.ShotCounter = 1;
+ E.Origin = Muzzle;
+ E.Direction = AimFor(Now - AimLag);
+ Manager->SpawnBoltFrom(E, W, float(Lag_), nullptr);
+ Advance(Now + 0.5);
+ return Results.Num() == 1 ? Results[0].Result : EVerseShotResult::Rejected;
+ }
+ };
+}
+
+IMPLEMENT_SIMPLE_AUTOMATION_TEST(FVerseLagCompRewind, "Verse.Combat.LagComp.Rewind", VERSE_WP02_TEST_FLAGS)
+bool FVerseLagCompRewind::RunTest(const FString&)
+{
+ const UVerseWeaponDefinition* G = VerseWp02Test::Weapon(*this, TEXT("graveline"));
+ if (!G)
+ {
+ return false;
+ }
+ TSharedRef<FJsonObject> Proof = MakeShared<FJsonObject>();
+ for (const double Lag : {0.06, 0.12, 0.25})
+ {
+ int32 HitsCount = 0;
+ const int32 Shots = 12;
+ VerseLagCompTest::FScene Scene;
+ Scene.Advance(VerseLagCompTest::T0 + 1.2); // fill the ring buffer
+ for (int32 I = 0; I < Shots; ++I)
+ {
+ // Shots across the strafe, including the turn-around points.
+ Scene.Advance(Scene.Now + 0.31);
+ HitsCount += Scene.Shoot(*G, Lag, Lag) == EVerseShotResult::HitBody ? 1 : 0;
+ }
+ TestEqual(FString::Printf(TEXT("strafing target hit at %.0f ms lag"), Lag * 1000.0), HitsCount, Shots);
+ Proof->SetNumberField(FString::Printf(TEXT("hits_at_%d_ms"), int32(Lag * 1000.0 + 0.5)), HitsCount);
+ }
+
+ // 300 ms: the rewind clamps to 250 ms. Aim from the clamped picture hits; aim from the true
+ // 300 ms picture lands 32.5 cm behind a 6.5 m/s target and misses the 18 cm torso.
+ {
+ VerseLagCompTest::FScene Scene;
+ Scene.Advance(VerseLagCompTest::T0 + 0.5);
+ TestEqual(TEXT("300 ms clamps to 250 ms"), UVerseLagCompSubsystem::ClampRewindTime(Scene.Now, Scene.Now - 0.3), Scene.Now - 0.25, 1e-9);
+ TestEqual(TEXT("300 ms with the clamped picture hits"), Scene.Shoot(*G, 0.3, 0.25), EVerseShotResult::HitBody);
+ Scene.Advance(Scene.Now + 0.1);
+ TestNotEqual(TEXT("300 ms picture is not rewound past the cap"), Scene.Shoot(*G, 0.3, 0.3), EVerseShotResult::HitBody);
+ Proof->SetNumberField(TEXT("clamp_ms"), 250);
+ }
+ VerseWp02Test::WriteProof(TEXT("2.8"), TEXT("lagcomp_rewind.json"), Proof);
+ return true;
+}
+
+#endif // WITH_DEV_AUTOMATION_TESTS
diff --git a/unreal/Verse/Source/VerseCombat/Private/Tests/Projectiles/Fakes/VerseFakeDestruction.h b/unreal/Verse/Source/VerseCombat/Private/Tests/Projectiles/Fakes/VerseFakeDestruction.h
new file mode 100644
index 0000000000..8ddd946214
--- /dev/null
+++ b/unreal/Verse/Source/VerseCombat/Private/Tests/Projectiles/Fakes/VerseFakeDestruction.h
@@ -0,0 +1,86 @@
+#pragma once
+
+#include "CoreMinimal.h"
+#include "Destruction/VerseDestructionInterfaces.h"
+#include "Destruction/VerseDestructionTypes.h"
+
+#if WITH_DEV_AUTOMATION_TESTS
+
+/** One fake piece: an axis-aligned slab of one penetration material. */
+struct FFakeVersePiece
+{
+ uint16 PieceIndex = 0;
+ EVersePenetrationMaterial Material = EVersePenetrationMaterial::ContainerWall;
+ FBox Bounds = FBox(ForceInit);
+};
+
+/**
+ * WP03 fake (work-packages.md 0.3): IVersePenetrationQuery over a list of slabs. TraceBolt returns
+ * every slab the segment enters, in order, with entry, exit and traced thickness; it never decides
+ * a pass itself (the combat loop does). TestSight is always clear. A plain C++ object, compiled
+ * only with the automation tests.
+ */
+class FFakeVersePenetrationQuery : public IVersePenetrationQuery
+{
+public:
+ TArray<FFakeVersePiece> Pieces;
+ mutable int32 Calls = 0;
+
+ virtual TArray<FVersePenetrationHit> TraceBolt(const FVector& Origin, const FVector& Dir, float MaxDist, float Power, float Damage,
+ uint8 RadiusMm, int32 MaxPieces) const override
+ {
+ ++Calls;
+ TArray<TPair<double, FVersePenetrationHit>> Found;
+ const FVector End = Origin + Dir * MaxDist;
+ for (const FFakeVersePiece& P : Pieces)
+ {
+ FVector HitLoc, HitNormal;
+ float HitTime = 0.f;
+ if (!FMath::LineExtentBoxIntersection(P.Bounds, Origin, End, FVector::ZeroVector, HitLoc, HitNormal, HitTime))
+ {
+ continue;
+ }
+ // Exit: the same test from the far side.
+ FVector ExitLoc, ExitNormal;
+ float ExitTime = 0.f;
+ const bool bExit = FMath::LineExtentBoxIntersection(P.Bounds, End, Origin, FVector::ZeroVector, ExitLoc, ExitNormal, ExitTime);
+ FVersePenetrationHit H;
+ H.PieceIndex = P.PieceIndex;
+ H.MaterialWireId = uint8(P.Material);
+ H.Entry = HitLoc;
+ H.Exit = bExit ? ExitLoc : End;
+ H.TracedThicknessCm = float(FVector::Dist(H.Entry, H.Exit));
+ Found.Add({double(HitTime), H});
+ }
+ Found.Sort([](const TPair<double, FVersePenetrationHit>& A, const TPair<double, FVersePenetrationHit>& B) { return A.Key < B.Key; });
+ TArray<FVersePenetrationHit> Out;
+ for (const TPair<double, FVersePenetrationHit>& F : Found)
+ {
+ if (Out.Num() >= MaxPieces)
+ {
+ break;
+ }
+ Out.Add(F.Value);
+ }
+ return Out;
+ }
+
+ virtual bool TestSight(const FVector&, const FVector&) const override
+ {
+ return true;
+ }
+};
+
+/** Records every piece damage request (WP06 fake). */
+class FFakeVersePieceDamage : public IVersePieceDamage
+{
+public:
+ TArray<FVersePieceDamage> Calls;
+
+ virtual void ApplyPieceDamage(const FVersePieceDamage& Damage) override
+ {
+ Calls.Add(Damage);
+ }
+};
+
+#endif // WITH_DEV_AUTOMATION_TESTS
diff --git a/unreal/Verse/Source/VerseCombat/Private/Tests/Projectiles/VerseBoltVisualTest.cpp b/unreal/Verse/Source/VerseCombat/Private/Tests/Projectiles/VerseBoltVisualTest.cpp
new file mode 100644
index 0000000000..2e30d2916c
--- /dev/null
+++ b/unreal/Verse/Source/VerseCombat/Private/Tests/Projectiles/VerseBoltVisualTest.cpp
@@ -0,0 +1,187 @@
+#include "Camera/CameraActor.h"
+#include "Camera/CameraComponent.h"
+#include "Components/DirectionalLightComponent.h"
+#include "Components/StaticMeshComponent.h"
+#include "Engine/DirectionalLight.h"
+#include "Engine/Engine.h"
+#include "Engine/StaticMesh.h"
+#include "Engine/StaticMeshActor.h"
+#include "Events/VerseEventHub.h"
+#include "GameFramework/PlayerController.h"
+#include "HAL/FileManager.h"
+#include "Materials/MaterialInstanceDynamic.h"
+#include "Misc/AutomationTest.h"
+#include "Projectiles/VerseBoltPresentation.h"
+#include "Projectiles/VersePlaceholderArt.h"
+#include "ShaderCompiler.h"
+#include "Tests/AutomationCommon.h"
+#include "Tests/Weapons/VerseWp02TestUtils.h"
+#include "UnrealClient.h"
+
+#if WITH_DEV_AUTOMATION_TESTS
+
+// Verse.Visual.Combat.Bolts (WP02.11 evidence, rendered lane only: scripts/unreal/screenshot.py):
+// a first-person view with the viewer's own bolts in amber and the opponent's in red, frozen mid
+// flight. Synthetic scene (dark floor, one work light); the PNG goes to the proof folder.
+
+namespace VerseBoltVisual
+{
+ struct FState
+ {
+ TWeakObjectPtr<UWorld> World;
+ TArray<TWeakObjectPtr<AActor>> Spawned;
+ FString Path;
+ };
+
+ UWorld* GameWorld()
+ {
+ for (const FWorldContext& C : GEngine->GetWorldContexts())
+ {
+ if (C.WorldType == EWorldType::Game && C.World())
+ {
+ return C.World();
+ }
+ }
+ return nullptr;
+ }
+
+ void Setup(const TSharedRef<FState>& S)
+ {
+ UWorld* World = GameWorld();
+ S->World = World;
+ if (!World)
+ {
+ return;
+ }
+ FActorSpawnParameters P;
+ P.SpawnCollisionHandlingOverride = ESpawnActorCollisionHandlingMethod::AlwaysSpawn;
+
+ UStaticMesh* Plane = VersePlaceholderArt::Mesh(VersePlaceholderArt::EShape::Plane);
+ UMaterialInterface* Base = VersePlaceholderArt::Material();
+ if (AStaticMeshActor* Floor = World->SpawnActor<AStaticMeshActor>(FVector(3000, 0, 0), FRotator::ZeroRotator, P))
+ {
+ Floor->SetMobility(EComponentMobility::Movable);
+ Floor->GetStaticMeshComponent()->SetStaticMesh(Plane);
+ Floor->SetActorScale3D(FVector(100, 100, 1));
+ if (UMaterialInstanceDynamic* Mid = UMaterialInstanceDynamic::Create(Base, Floor))
+ {
+ Mid->SetVectorParameterValue(TEXT("Color"), FLinearColor(0.02f, 0.02f, 0.022f));
+ Floor->GetStaticMeshComponent()->SetMaterial(0, Mid);
+ }
+ S->Spawned.Add(Floor);
+ }
+ if (ADirectionalLight* Light = World->SpawnActor<ADirectionalLight>(FVector::ZeroVector, FRotator(-35, 30, 0), P))
+ {
+ Light->SetMobility(EComponentMobility::Movable);
+ Light->GetLightComponent()->SetIntensity(6.f);
+ S->Spawned.Add(Light);
+ }
+ if (ACameraActor* Camera = World->SpawnActor<ACameraActor>(FVector(0, 0, 160), FRotator(-4, 0, 0), P))
+ {
+ UCameraComponent* Cam = Camera->GetCameraComponent();
+ Cam->SetFieldOfView(90.f);
+ // Fixed exposure, so the frame does not depend on eye adaptation timing.
+ Cam->PostProcessSettings.bOverride_AutoExposureMinBrightness = true;
+ Cam->PostProcessSettings.bOverride_AutoExposureMaxBrightness = true;
+ Cam->PostProcessSettings.AutoExposureMinBrightness = 1.f;
+ Cam->PostProcessSettings.AutoExposureMaxBrightness = 1.f;
+ Cam->PostProcessBlendWeight = 1.f;
+ if (APlayerController* Pc = World->GetFirstPlayerController())
+ {
+ Pc->SetViewTarget(Camera);
+ }
+ S->Spawned.Add(Camera);
+ }
+
+ UVerseBoltPresentation* Present = UVerseBoltPresentation::Get(World);
+ if (!Present)
+ {
+ return;
+ }
+ Present->LocalPlayerIdOverride = 1;
+ double Clock = 100.0;
+ Present->ClockOverride = [&Clock]() { return Clock; };
+ UVerseEventHub* Hub = UVerseEventHub::Get(World);
+ // Own volley from the muzzle (right of the eye), staggered in time like a spray.
+ for (int32 I = 0; I < 6; ++I)
+ {
+ FVerseFireEvent E;
+ E.ShooterId = 1;
+ E.WeaponId = TEXT("graveline");
+ E.ShotCounter = uint16(I + 1);
+ E.Origin = FVector(30, 18, 148);
+ E.Direction = FRotator(1.f + 0.8f * I, -12.f + 4.5f * I, 0).Vector();
+ Clock = 100.0 - 0.008 * I;
+ Hub->OnFire.Broadcast(E);
+ }
+ // The opponent's bolts coming in from the far side.
+ for (int32 I = 0; I < 4; ++I)
+ {
+ FVerseFireEvent E;
+ E.ShooterId = 2;
+ E.WeaponId = TEXT("graveline");
+ E.ShotCounter = uint16(I + 1);
+ // Crossing the view from the left at 12-18 m, aimed past the viewer.
+ E.Origin = FVector(1500 + 150 * I, -2200, 140 + 25 * I);
+ E.Direction = (FVector(900 + 100 * I, 1200, 170) - FVector(E.Origin)).GetSafeNormal();
+ Clock = 100.0 - 0.02 * I;
+ Hub->OnFire.Broadcast(E);
+ }
+ // Freeze the flight mid-way so the shot holds still while shaders and streaming settle.
+ Present->ClockOverride = []() { return 100.03; };
+ Present->Advance(100.03);
+ }
+}
+
+IMPLEMENT_SIMPLE_AUTOMATION_TEST(FVerseVisualBolts, "Verse.Visual.Combat.Bolts",
+ EAutomationTestFlags::ClientContext | EAutomationTestFlags::EngineFilter)
+bool FVerseVisualBolts::RunTest(const FString&)
+{
+ TSharedRef<VerseBoltVisual::FState> S = MakeShared<VerseBoltVisual::FState>();
+ S->Path = VerseWp02Test::ProofPath(TEXT("2.11"), TEXT("bolts_first_person.png"));
+ IFileManager::Get().Delete(*S->Path, false, true, true);
+ IFileManager::Get().MakeDirectory(*FPaths::GetPath(S->Path), true);
+
+ ADD_LATENT_AUTOMATION_COMMAND(FFunctionLatentCommand([this, S]()
+ {
+ VerseBoltVisual::Setup(S);
+ TestTrue(TEXT("a game world to draw in"), S->World.IsValid());
+ const UVerseBoltPresentation* P = UVerseBoltPresentation::Get(S->World.Get());
+ TestTrue(TEXT("own bolts in flight"), P && P->NumOwn() == 6);
+ TestTrue(TEXT("opponent bolts in flight"), P && P->NumFoe() == 4);
+ return true;
+ }));
+ ADD_LATENT_AUTOMATION_COMMAND(FWaitLatentCommand(2.0f));
+ ADD_LATENT_AUTOMATION_COMMAND(FFunctionLatentCommand([]()
+ {
+ // An uncooked run compiles the placeholder material on first use; until then it draws the
+ // default material. Wait for it, then give the renderer a moment.
+ if (GShaderCompilingManager)
+ {
+ GShaderCompilingManager->FinishAllCompilation();
+ }
+ return true;
+ }));
+ ADD_LATENT_AUTOMATION_COMMAND(FWaitLatentCommand(1.0f));
+ ADD_LATENT_AUTOMATION_COMMAND(FFunctionLatentCommand([S]()
+ {
+ FScreenshotRequest::RequestScreenshot(S->Path, false, false);
+ return true;
+ }));
+ ADD_LATENT_AUTOMATION_COMMAND(FWaitLatentCommand(1.5f));
+ ADD_LATENT_AUTOMATION_COMMAND(FFunctionLatentCommand([this, S]()
+ {
+ TestTrue(FString::Printf(TEXT("screenshot written to %s"), *S->Path), IFileManager::Get().FileExists(*S->Path));
+ for (const TWeakObjectPtr<AActor>& A : S->Spawned)
+ {
+ if (A.IsValid())
+ {
+ A->Destroy();
+ }
+ }
+ return true;
+ }));
+ return true;
+}
+
+#endif // WITH_DEV_AUTOMATION_TESTS
diff --git a/unreal/Verse/Source/VerseCombat/Private/Tests/Projectiles/VerseProjectileTest.cpp b/unreal/Verse/Source/VerseCombat/Private/Tests/Projectiles/VerseProjectileTest.cpp
new file mode 100644
index 0000000000..7512cbd509
--- /dev/null
+++ b/unreal/Verse/Source/VerseCombat/Private/Tests/Projectiles/VerseProjectileTest.cpp
@@ -0,0 +1,372 @@
+#include "Components/BoxComponent.h"
+#include "Damage/VerseDamageMath.h"
+#include "Destruction/VersePenetrationTable.h"
+#include "Events/VerseEventHub.h"
+#include "HAL/PlatformTime.h"
+#include "Misc/AutomationTest.h"
+#include "Projectiles/VerseProjectileManager.h"
+#include "Tests/Projectiles/Fakes/VerseFakeDestruction.h"
+#include "Tests/Weapons/VerseWp02TestUtils.h"
+
+#if WITH_DEV_AUTOMATION_TESTS
+
+// Verse.Combat.Projectile.*: bolt flight (A2.5), the trace order and penetration loop of
+// combat-state.md 5 and 6, the latency advance, and the cost gate (A2.8).
+
+namespace VerseProjectileTest
+{
+ FVerseFireEvent Fire(const FVector& Origin, const FVector& Dir, uint16 Counter = 1, FName Weapon = TEXT("graveline"))
+ {
+ FVerseFireEvent E;
+ E.WeaponId = Weapon;
+ E.ShotCounter = Counter;
+ E.Origin = Origin;
+ E.Direction = Dir;
+ return E;
+ }
+
+ /** Manager on a test world with a manual clock. */
+ struct FRig
+ {
+ VerseWp02Test::FTestWorld World;
+ UVerseProjectileManager* Manager = nullptr;
+ UVerseLagCompSubsystem* Lag = nullptr;
+ double Now = 100.0;
+ TArray<FVerseBoltResult> Results;
+
+ FRig()
+ {
+ Manager = UVerseProjectileManager::Get(World.World);
+ Lag = UVerseLagCompSubsystem::Get(World.World);
+ Manager->SetManualStepping(true);
+ Manager->SetClock([this]() { return Now; });
+ Manager->OnBoltResolved.AddLambda([this](const FVerseBoltResult& R) { Results.Add(R); });
+ }
+
+ void Step(int32 Ticks = 1)
+ {
+ for (int32 I = 0; I < Ticks; ++I)
+ {
+ Now += VerseWp02Test::Tick;
+ Lag->Record(Now);
+ Manager->StepAll(VerseWp02Test::Tick, Now);
+ }
+ }
+ };
+}
+
+IMPLEMENT_SIMPLE_AUTOMATION_TEST(FVerseProjectileFlight, "Verse.Combat.Projectile.Flight", VERSE_WP02_TEST_FLAGS)
+bool FVerseProjectileFlight::RunTest(const FString&)
+{
+ for (const UVerseWeaponDefinition* W : VerseWp02Test::AllWeapons(*this))
+ {
+ VerseProjectileTest::FRig Rig;
+ const FVector Origin(0, 0, 5000); // far above the empty world
+ const FVector Dir = FVector(1, 0.2, 0).GetSafeNormal();
+ Rig.Manager->SpawnBoltFrom(VerseProjectileTest::Fire(Origin, Dir, 1, W->WeaponId), *W, 0.f, nullptr);
+ TestEqual(TEXT("one bolt in flight"), Rig.Manager->NumActive(), 1);
+ const double Start = Rig.Now;
+ double MaxDrop = 0.0;
+ int32 Ticks = 0;
+ double SpeedErr = 0.0;
+ while (Rig.Manager->NumActive() > 0 && Ticks < 10000)
+ {
+ const FVector Before = Rig.Manager->GetBolts()[0].Position;
+ Rig.Step();
+ ++Ticks;
+ if (Rig.Manager->NumActive() > 0)
+ {
+ const FVerseBolt& B = Rig.Manager->GetBolts()[0];
+ const double Speed = FVector::Dist(Before, B.Position) / VerseWp02Test::Tick;
+ SpeedErr = FMath::Max(SpeedErr, FMath::Abs(Speed - W->ProjectileSpeed * 100.0) / (W->ProjectileSpeed * 100.0));
+ // Drop: distance of the bolt from the firing line.
+ const FVector Rel = B.Position - Origin;
+ MaxDrop = FMath::Max(MaxDrop, (Rel - Dir * FVector::DotProduct(Rel, Dir)).Size());
+ }
+ }
+ const FString Id = W->WeaponId.ToString();
+ TestTrue(FString::Printf(TEXT("%s: speed within 0.5 %% (%.4f %%)"), *Id, SpeedErr * 100.0), SpeedErr <= 0.005);
+ TestTrue(FString::Printf(TEXT("%s: zero drop (%.6f cm)"), *Id, MaxDrop), MaxDrop < 0.01);
+ if (TestEqual(TEXT("resolved once"), Rig.Results.Num(), 1))
+ {
+ const double Range = W->MaxRange * 100.0;
+ TestEqual(TEXT("expired as a miss"), Rig.Results[0].Result, EVerseShotResult::Miss);
+ TestTrue(FString::Printf(TEXT("%s: despawn at MaxRange + at most 5 m (%.1f cm)"), *Id, Rig.Results[0].Travelled),
+ Rig.Results[0].Travelled >= Range - 1.0 && Rig.Results[0].Travelled <= Range + 500.0);
+ const double FlightS = Rig.Now - Start;
+ TestTrue(TEXT("flight time = range / speed (+1 tick)"), FMath::Abs(FlightS - W->MaxRange / W->ProjectileSpeed) <= VerseWp02Test::Tick + 1e-6);
+ }
+ }
+ return true;
+}
+
+IMPLEMENT_SIMPLE_AUTOMATION_TEST(FVerseProjectileLatencyAdvance, "Verse.Combat.Projectile.LatencyAdvance", VERSE_WP02_TEST_FLAGS)
+bool FVerseProjectileLatencyAdvance::RunTest(const FString&)
+{
+ const UVerseWeaponDefinition* G = VerseWp02Test::Weapon(*this, TEXT("graveline"));
+ if (!G)
+ {
+ return false;
+ }
+ for (const float Latency : {0.f, 0.06f, 0.12f, 0.25f, 0.3f, 2.f})
+ {
+ VerseProjectileTest::FRig Rig;
+ Rig.Manager->SpawnBoltFrom(VerseProjectileTest::Fire(FVector(0, 0, 5000), FVector(1, 0, 0)), *G, Latency, nullptr);
+ if (!TestEqual(TEXT("bolt alive"), Rig.Manager->NumActive(), 1))
+ {
+ continue;
+ }
+ const double Want = FMath::Min(Latency, 0.25f) * G->ProjectileSpeed * 100.0;
+ TestEqual(FString::Printf(TEXT("latency %.2f s advances %.0f cm (capped at 250 ms)"), Latency, Want), Rig.Manager->GetBolts()[0].Travelled, Want, 0.5);
+ }
+ return true;
+}
+
+IMPLEMENT_SIMPLE_AUTOMATION_TEST(FVerseProjectileTraceOrder, "Verse.Combat.Projectile.TraceOrder", VERSE_WP02_TEST_FLAGS)
+bool FVerseProjectileTraceOrder::RunTest(const FString&)
+{
+ const UVerseWeaponDefinition* G = VerseWp02Test::Weapon(*this, TEXT("graveline"));
+ const UVerseWeaponDefinition* T = VerseWp02Test::Weapon(*this, TEXT("tallow"));
+ if (!G || !T)
+ {
+ return false;
+ }
+ const FVector Origin(0, 0, 5000);
+ const FVector Dir(1, 0, 0);
+ auto Wall = [](uint16 Index, EVersePenetrationMaterial M, double X, double ThicknessCm)
+ {
+ FFakeVersePiece P;
+ P.PieceIndex = Index;
+ P.Material = M;
+ P.Bounds = FBox(FVector(X, -200, 4800), FVector(X + ThicknessCm, 200, 5200));
+ return P;
+ };
+ const TArray<FVersePenetrationRow> Rows = UVersePenetrationTable::MakeContractRows();
+ const float Container = Rows[int32(EVersePenetrationMaterial::ContainerWall)].RefThicknessCm;
+
+ // A target behind two container walls: the rifle passes both and keeps 0.75 x 0.75.
+ {
+ VerseProjectileTest::FRig Rig;
+ FFakeVersePenetrationQuery QueryStorage;
+ FFakeVersePenetrationQuery* Query = &QueryStorage;
+ FFakeVersePieceDamage PieceDamage;
+ Query->Pieces = {Wall(1, EVersePenetrationMaterial::ContainerWall, 520, Container),
+ Wall(2, EVersePenetrationMaterial::ContainerWall, 910, Container)};
+ Rig.Manager->SetPenetrationQuery(Query);
+ Rig.Manager->SetPieceDamage(&PieceDamage);
+ APawn* Target = VerseWp02Test::SpawnTarget(Rig.World.World, FVector(1500, 0, 5000 - 135), 1000.f);
+ Rig.Lag->RegisterTarget(Target, [Target](FTransform& Root, TArray<FVerseHitCapsule>& Out)
+ {
+ Root = Target->GetActorTransform();
+ VerseWp02Test::HumanCapsules(Target->GetActorLocation(), Out);
+ });
+ TArray<FVersePenetrationEvent> Pens;
+ TArray<FVerseHitEvent> Hits;
+ UVerseEventHub::Get(Rig.World.World)->OnPenetration.AddLambda([&Pens](const FVersePenetrationEvent& E) { Pens.Add(E); });
+ UVerseEventHub::Get(Rig.World.World)->OnHit.AddLambda([&Hits](const FVerseHitEvent& E) { Hits.Add(E); });
+ Rig.Lag->Record(Rig.Now);
+ Rig.Manager->SpawnBoltFrom(VerseProjectileTest::Fire(Origin, Dir), *G, 0.f, nullptr);
+ Rig.Step(10);
+ TestEqual(TEXT("two passes"), Pens.Num(), 2);
+ TestEqual(TEXT("piece damage on each wall"), PieceDamage.Calls.Num(), 2);
+ if (PieceDamage.Calls.Num() == 2)
+ {
+ TestEqual(TEXT("first piece first"), int32(PieceDamage.Calls[0].PieceIndex), 1);
+ TestEqual(TEXT("bolt cause"), PieceDamage.Calls[0].Cause, EVerseFractureCause::Bolt);
+ TestEqual(TEXT("piece hp per hit"), PieceDamage.Calls[0].Amount, G->PieceDamage);
+ }
+ if (TestEqual(TEXT("body hit behind the walls"), Hits.Num(), 1))
+ {
+ TestEqual(TEXT("upper torso"), Hits[0].Zone, EVerseHitZone::UpperTorso);
+ TestEqual(TEXT("damage x 0.5625"), Hits[0].Damage, G->BaseDamage * 0.5625f, 1e-3f);
+ TestEqual(TEXT("two penetrations on the hit"), int32(Hits[0].PenetrationCount), 2);
+ }
+ if (Pens.Num() == 2)
+ {
+ TestEqual(TEXT("power 100 - 25 - 25"), Pens[1].PowerAfter, 50.f, 1e-3f);
+ }
+ TestTrue(TEXT("HitBody result"), Rig.Results.Num() == 1 && Rig.Results[0].Result == EVerseShotResult::HitBody);
+ }
+
+ // The pistol (50, two passes): 50 - 25 - 25 passes two container walls and stops at the third; concrete stops everything.
+ {
+ VerseProjectileTest::FRig Rig;
+ FFakeVersePenetrationQuery QueryStorage;
+ FFakeVersePenetrationQuery* Query = &QueryStorage;
+ FFakeVersePieceDamage PieceDamage;
+ // Slightly under the reference thickness, so 25 + 25 fits the 50 exactly without float edge.
+ const double Thin = Container * 0.95;
+ Query->Pieces = {Wall(1, EVersePenetrationMaterial::ContainerWall, 310, Thin), Wall(2, EVersePenetrationMaterial::ContainerWall, 410, Thin),
+ Wall(3, EVersePenetrationMaterial::ContainerWall, 460, Thin)};
+ Rig.Manager->SetPenetrationQuery(Query);
+ Rig.Manager->SetPieceDamage(&PieceDamage);
+ Rig.Manager->SpawnBoltFrom(VerseProjectileTest::Fire(Origin, Dir), *T, 0.f, nullptr);
+ Rig.Step(5);
+ TestTrue(TEXT("pistol stops at a piece"), Rig.Results.Num() == 1 && Rig.Results[0].Result == EVerseShotResult::HitPiece);
+ TestEqual(TEXT("pistol: piece damage on all three walls"), PieceDamage.Calls.Num(), 3);
+ }
+ {
+ VerseProjectileTest::FRig Rig;
+ FFakeVersePenetrationQuery QueryStorage;
+ FFakeVersePenetrationQuery* Query = &QueryStorage;
+ FFakeVersePieceDamage PieceDamage;
+ Query->Pieces = {Wall(7, EVersePenetrationMaterial::Concrete, 300, 30.0)};
+ Rig.Manager->SetPenetrationQuery(Query);
+ Rig.Manager->SetPieceDamage(&PieceDamage);
+ Rig.Manager->SpawnBoltFrom(VerseProjectileTest::Fire(Origin, Dir), *G, 0.f, nullptr);
+ Rig.Step(5);
+ TestTrue(TEXT("concrete stops the rifle"), Rig.Results.Num() == 1 && Rig.Results[0].Result == EVerseShotResult::HitPiece);
+ }
+
+ // MaxPenetrations cap: four thin sheets, the rifle (3 passes) stops at the 4th.
+ {
+ VerseProjectileTest::FRig Rig;
+ FFakeVersePenetrationQuery QueryStorage;
+ FFakeVersePenetrationQuery* Query = &QueryStorage;
+ FFakeVersePieceDamage PieceDamage;
+ for (uint16 I = 0; I < 4; ++I)
+ {
+ Query->Pieces.Add(Wall(10 + I, EVersePenetrationMaterial::Glass, 300 + 50 * I, 2.4));
+ }
+ Rig.Manager->SetPenetrationQuery(Query);
+ Rig.Manager->SetPieceDamage(&PieceDamage);
+ TArray<FVersePenetrationEvent> Pens;
+ UVerseEventHub::Get(Rig.World.World)->OnPenetration.AddLambda([&Pens](const FVersePenetrationEvent& E) { Pens.Add(E); });
+ Rig.Manager->SpawnBoltFrom(VerseProjectileTest::Fire(Origin, Dir), *G, 0.f, nullptr);
+ Rig.Step(5);
+ TestEqual(TEXT("three passes, the fourth stops"), Pens.Num(), 3);
+ TestTrue(TEXT("stopped on the 4th"), Rig.Results.Num() == 1 && Rig.Results[0].Result == EVerseShotResult::HitPiece);
+ }
+
+ // A body in front of a wall is hit first; a body behind concrete is never hit.
+ {
+ VerseProjectileTest::FRig Rig;
+ FFakeVersePenetrationQuery QueryStorage;
+ FFakeVersePenetrationQuery* Query = &QueryStorage;
+ Query->Pieces = {Wall(1, EVersePenetrationMaterial::Concrete, 800, 30.0)};
+ FFakeVersePieceDamage PieceDamage;
+ Rig.Manager->SetPenetrationQuery(Query);
+ Rig.Manager->SetPieceDamage(&PieceDamage);
+ APawn* Front = VerseWp02Test::SpawnTarget(Rig.World.World, FVector(400, 0, 5000 - 135), 1000.f);
+ APawn* Behind = VerseWp02Test::SpawnTarget(Rig.World.World, FVector(1200, 0, 5000 - 135), 1000.f);
+ for (APawn* P : {Front, Behind})
+ {
+ Rig.Lag->RegisterTarget(P, [P](FTransform& Root, TArray<FVerseHitCapsule>& Out)
+ {
+ Root = P->GetActorTransform();
+ VerseWp02Test::HumanCapsules(P->GetActorLocation(), Out);
+ });
+ }
+ Rig.Lag->Record(Rig.Now);
+ Rig.Manager->SpawnBoltFrom(VerseProjectileTest::Fire(Origin, Dir, 1), *G, 0.f, nullptr);
+ Rig.Step(3);
+ TestTrue(TEXT("front body hit first"), Rig.Results.Num() == 1 && Rig.Results[0].HitActor.Get() == Front);
+ TestEqual(TEXT("the wall behind is untouched"), PieceDamage.Calls.Num(), 0);
+
+ Rig.Lag->UnregisterTarget(Front);
+ Rig.Results.Reset();
+ Rig.Manager->SpawnBoltFrom(VerseProjectileTest::Fire(Origin, Dir, 2), *G, 0.f, nullptr);
+ Rig.Step(5);
+ TestTrue(TEXT("concrete hides the body behind"), Rig.Results.Num() == 1 && Rig.Results[0].Result == EVerseShotResult::HitPiece);
+ TestEqual(TEXT("behind untouched"), VerseWp02Test::HealthOf(Behind), 1000.f);
+ }
+ return true;
+}
+
+IMPLEMENT_SIMPLE_AUTOMATION_TEST(FVerseProjectileCost, "Verse.Combat.Projectile.Cost", VERSE_WP02_TEST_FLAGS)
+bool FVerseProjectileCost::RunTest(const FString&)
+{
+ const UVerseWeaponDefinition* G = VerseWp02Test::Weapon(*this, TEXT("graveline"));
+ if (!G)
+ {
+ return false;
+ }
+ VerseProjectileTest::FRig Rig;
+ for (int32 I = 0; I < 2; ++I)
+ {
+ APawn* P = VerseWp02Test::SpawnTarget(Rig.World.World, FVector(2000, 3000 * (I ? 1 : -1), 0), 1000.f);
+ Rig.Lag->RegisterTarget(P, [P](FTransform& Root, TArray<FVerseHitCapsule>& Out)
+ {
+ Root = P->GetActorTransform();
+ VerseWp02Test::HumanCapsules(P->GetActorLocation(), Out);
+ });
+ }
+ // Real work for the traces: two container walls across the whole fan (every bolt passes both),
+ // 30 pieces beside it, and 24 bolt-blocking pillars in the world off the fan.
+ FFakeVersePenetrationQuery Query;
+ FFakeVersePieceDamage PieceDamage;
+ const double WallCm = UVersePenetrationTable::MakeContractRows()[int32(EVersePenetrationMaterial::ContainerWall)].RefThicknessCm;
+ for (int32 I = 0; I < 2; ++I)
+ {
+ FFakeVersePiece Wall;
+ Wall.PieceIndex = uint16(I + 1);
+ Wall.Material = EVersePenetrationMaterial::ContainerWall;
+ Wall.Bounds = FBox(FVector(1500 + 400 * I, -2000, 0), FVector(1500 + 400 * I + WallCm, 2000, 400));
+ Query.Pieces.Add(Wall);
+ }
+ for (int32 I = 0; I < 30; ++I)
+ {
+ FFakeVersePiece Side;
+ Side.PieceIndex = uint16(100 + I);
+ Side.Material = EVersePenetrationMaterial::Concrete;
+ const double X = 500.0 * I;
+ Side.Bounds = FBox(FVector(X, -9000, 0), FVector(X + 30, -8800, 400));
+ Query.Pieces.Add(Side);
+ }
+ Rig.Manager->SetPenetrationQuery(&Query);
+ Rig.Manager->SetPieceDamage(&PieceDamage);
+ for (int32 I = 0; I < 24; ++I)
+ {
+ FActorSpawnParameters Params;
+ Params.SpawnCollisionHandlingOverride = ESpawnActorCollisionHandlingMethod::AlwaysSpawn;
+ AActor* Pillar = Rig.World.World->SpawnActor<AActor>(AActor::StaticClass(), FTransform::Identity, Params);
+ UBoxComponent* Box = NewObject<UBoxComponent>(Pillar, TEXT("Box"));
+ Box->SetBoxExtent(FVector(50, 50, 300));
+ Box->SetCollisionEnabled(ECollisionEnabled::QueryOnly);
+ Box->SetCollisionResponseToAllChannels(ECR_Block);
+ Pillar->SetRootComponent(Box);
+ Box->RegisterComponent();
+ Pillar->SetActorLocation(FVector(1000.0 + 500.0 * I, (I % 2) ? 9500.0 : -9500.0, 300.0));
+ }
+ Rig.World.TickFrames(2);
+ Rig.Lag->Record(Rig.Now);
+
+ // Five waves of 64 bolts, 20 measured ticks each (150 m range = 30 ticks), after two warm-up ticks.
+ TArray<double> Ms;
+ int32 MinAlive = 64;
+ for (int32 Wave = 0; Wave < 5; ++Wave)
+ {
+ Rig.Manager->Clear();
+ for (int32 I = 0; I < 64; ++I)
+ {
+ const FVector Dir = FRotator(0.0, -30.0 + I * 0.95, 0.0).Vector();
+ Rig.Manager->SpawnBoltFrom(VerseProjectileTest::Fire(FVector(0, 0, 150), Dir, uint16(Wave * 64 + I + 1)), *G, 0.f, nullptr);
+ }
+ Rig.Step(2);
+ for (int32 I = 0; I < 20; ++I)
+ {
+ Rig.Step();
+ Ms.Add(Rig.Manager->GetLastStepSeconds() * 1000.0);
+ MinAlive = FMath::Min(MinAlive, Rig.Manager->NumActive());
+ }
+ }
+ TestEqual(TEXT("64 in flight through every measured tick"), MinAlive, 64);
+ TestTrue(TEXT("bolts passed the walls"), PieceDamage.Calls.Num() >= 64 * 5);
+ Ms.Sort();
+ const double Median = Ms[Ms.Num() / 2];
+ const double P99 = Ms[FMath::Min(Ms.Num() - 1, int32(FMath::CeilToInt(Ms.Num() * 0.99)) - 1)];
+ const double Max = Ms.Last();
+ AddInfo(FString::Printf(TEXT("projectile manager, 64 bolts, %d ticks: median %.4f ms, p99 %.4f ms, max %.4f ms per tick"), Ms.Num(), Median, P99, Max));
+ TestTrue(FString::Printf(TEXT("A2.8: p99 %.4f ms <= 0.2 ms"), P99), P99 <= 0.2);
+
+ TSharedRef<FJsonObject> Proof = MakeShared<FJsonObject>();
+ Proof->SetNumberField(TEXT("bolts"), 64);
+ Proof->SetNumberField(TEXT("median_ms"), Median);
+ Proof->SetNumberField(TEXT("p99_ms"), P99);
+ Proof->SetNumberField(TEXT("max_ms"), Max);
+ Proof->SetNumberField(TEXT("ticks"), Ms.Num());
+ VerseWp02Test::WriteProof(TEXT("2.7"), TEXT("projectile_cost.json"), Proof);
+ return true;
+}
+
+#endif // WITH_DEV_AUTOMATION_TESTS
diff --git a/unreal/Verse/Source/VerseCombat/Private/Tests/Weapons/VerseDefinitionsTest.cpp b/unreal/Verse/Source/VerseCombat/Private/Tests/Weapons/VerseDefinitionsTest.cpp
new file mode 100644
index 0000000000..9089ba98e5
--- /dev/null
+++ b/unreal/Verse/Source/VerseCombat/Private/Tests/Weapons/VerseDefinitionsTest.cpp
@@ -0,0 +1,164 @@
+#include "Dom/JsonValue.h"
+#include "Misc/AutomationTest.h"
+#include "Serialization/JsonReader.h"
+#include "Tests/Weapons/VerseWp02TestUtils.h"
+
+#if WITH_DEV_AUTOMATION_TESTS
+
+// Verse.Combat.Definitions.*: the JSON text surface and the DA_Weapon_* / DA_Gadget_* assets are
+// field-for-field equal, every field is required, unknown fields and bad names are refused (WP02.1,
+// WP02.14), and the gadget start values are those of combat-state.md 2.3.
+
+namespace VerseDefinitionsTest
+{
+ TSharedPtr<FJsonValue> ReadFile(FAutomationTestBase& Test, const FString& Path)
+ {
+ FString Text;
+ if (!Test.TestTrue(FString::Printf(TEXT("read %s"), *Path), FFileHelper::LoadFileToString(Text, *Path)))
+ {
+ return nullptr;
+ }
+ TSharedPtr<FJsonObject> Obj;
+ const TSharedRef<TJsonReader<TCHAR>> Reader = TJsonReaderFactory<TCHAR>::Create(Text);
+ FJsonSerializer::Deserialize(Reader, Obj);
+ return Obj.IsValid() ? TSharedPtr<FJsonValue>(MakeShared<FJsonValueObject>(Obj)) : TSharedPtr<FJsonValue>();
+ }
+}
+
+IMPLEMENT_SIMPLE_AUTOMATION_TEST(FVerseDefinitionsImportDiff, "Verse.Combat.Definitions.ImportDiff", VERSE_WP02_TEST_FLAGS)
+bool FVerseDefinitionsImportDiff::RunTest(const FString&)
+{
+ const TArray<const UVerseWeaponDefinition*> Weapons = VerseWp02Test::AllWeapons(*this);
+ TSet<FName> Ids;
+ for (const UVerseWeaponDefinition* W : Weapons)
+ {
+ Ids.Add(W->WeaponId);
+ const FString File = FPaths::Combine(FVerseDefinitionJson::DataDir(), W->WeaponId.ToString() + TEXT(".json"));
+ const TSharedPtr<FJsonValue> OnDisk = VerseDefinitionsTest::ReadFile(*this, File);
+ TArray<FString> Diffs;
+ FVerseDefinitionJson::JsonEqual(OnDisk, MakeShared<FJsonValueObject>(FVerseDefinitionJson::ExportWeapon(*W)), W->WeaponId.ToString(), Diffs);
+ for (const FString& D : Diffs)
+ {
+ AddError(TEXT("json round trip: ") + D);
+ }
+ }
+ for (const TCHAR* Id : {TEXT("graveline"), TEXT("tallow"), TEXT("skitter"), TEXT("longsight")})
+ {
+ TestTrue(FString::Printf(TEXT("%s.json present"), Id), Ids.Contains(FName(Id)));
+ }
+
+ // The two start assets exist and match their JSON field for field.
+ for (const TCHAR* Id : {TEXT("graveline"), TEXT("tallow"), TEXT("skitter"), TEXT("longsight")})
+ {
+ const UVerseWeaponDefinition* Asset = FVerseWeaponRegistry::LoadWeaponAsset(FName(Id));
+ if (!TestNotNull(FString::Printf(TEXT("%s asset exists"), *FVerseDefinitionJson::WeaponAssetName(FName(Id))), Asset))
+ {
+ continue;
+ }
+ const TSharedPtr<FJsonValue> OnDisk = VerseDefinitionsTest::ReadFile(*this, FPaths::Combine(FVerseDefinitionJson::DataDir(), FString(Id) + TEXT(".json")));
+ TArray<FString> Diffs;
+ FVerseDefinitionJson::JsonEqual(OnDisk, MakeShared<FJsonValueObject>(FVerseDefinitionJson::ExportWeapon(*Asset)), Id, Diffs);
+ for (const FString& D : Diffs)
+ {
+ AddError(TEXT("asset drift: ") + D);
+ }
+ }
+ for (const TCHAR* Id : {TEXT("bulwark"), TEXT("breach_charge")})
+ {
+ TestNotNull(FString::Printf(TEXT("%s asset exists"), *FVerseDefinitionJson::GadgetAssetName(FName(Id))),
+ FVerseWeaponRegistry::LoadGadgetAsset(FName(Id)));
+ }
+ return true;
+}
+
+IMPLEMENT_SIMPLE_AUTOMATION_TEST(FVerseDefinitionsStrict, "Verse.Combat.Definitions.Strict", VERSE_WP02_TEST_FLAGS)
+bool FVerseDefinitionsStrict::RunTest(const FString&)
+{
+ const UVerseWeaponDefinition* Graveline = VerseWp02Test::Weapon(*this, TEXT("graveline"));
+ if (!Graveline)
+ {
+ return false;
+ }
+ const TSharedRef<FJsonObject> Good = FVerseDefinitionJson::ExportWeapon(*Graveline);
+ {
+ UVerseWeaponDefinition* W = NewObject<UVerseWeaponDefinition>();
+ TArray<FString> Errors;
+ TestTrue(TEXT("canonical export imports"), FVerseDefinitionJson::ApplyWeapon(*Good, *W, Errors));
+ }
+ {
+ TSharedRef<FJsonObject> Missing = MakeShared<FJsonObject>(*Good);
+ Missing->RemoveField(TEXT("RPM"));
+ UVerseWeaponDefinition* W = NewObject<UVerseWeaponDefinition>();
+ TArray<FString> Errors;
+ TestFalse(TEXT("a missing field is refused"), FVerseDefinitionJson::ApplyWeapon(*Missing, *W, Errors));
+ }
+ {
+ TSharedRef<FJsonObject> Extra = MakeShared<FJsonObject>(*Good);
+ Extra->SetNumberField(TEXT("Velocity"), 1.0);
+ UVerseWeaponDefinition* W = NewObject<UVerseWeaponDefinition>();
+ TArray<FString> Errors;
+ TestFalse(TEXT("an unknown field is refused"), FVerseDefinitionJson::ApplyWeapon(*Extra, *W, Errors));
+ }
+ {
+ TSharedRef<FJsonObject> BadEnum = MakeShared<FJsonObject>(*Good);
+ BadEnum->SetStringField(TEXT("FireMode"), TEXT("Rapid"));
+ UVerseWeaponDefinition* W = NewObject<UVerseWeaponDefinition>();
+ TArray<FString> Errors;
+ TestFalse(TEXT("an unknown enum entry is refused"), FVerseDefinitionJson::ApplyWeapon(*BadEnum, *W, Errors));
+ }
+ {
+ TSharedRef<FJsonObject> Cap = MakeShared<FJsonObject>(*Good);
+ Cap->SetNumberField(TEXT("MaxPenetrations"), 4);
+ UVerseWeaponDefinition* W = NewObject<UVerseWeaponDefinition>();
+ TArray<FString> Errors;
+ TestFalse(TEXT("MaxPenetrations above 3 is refused"), FVerseDefinitionJson::ApplyWeapon(*Cap, *W, Errors));
+ }
+ TArray<FString> NameErrors;
+ TestTrue(TEXT("fictional names pass the format"), FVerseDefinitionJson::CheckNames(TEXT("graveline"), FText::FromString(TEXT("Graveline")), NameErrors));
+ TestFalse(TEXT("upper-case ids are refused"), FVerseDefinitionJson::CheckNames(TEXT("Grave"), FText::FromString(TEXT("Grave")), NameErrors));
+ TestFalse(TEXT("model-number punctuation is refused"), FVerseDefinitionJson::CheckNames(TEXT("x"), FText::FromString(TEXT("X/9")), NameErrors));
+ TestEqual(TEXT("asset name"), FVerseDefinitionJson::GadgetAssetName(TEXT("breach_charge")), FString(TEXT("DA_Gadget_BreachCharge")));
+ return true;
+}
+
+IMPLEMENT_SIMPLE_AUTOMATION_TEST(FVerseDefinitionsStartValues, "Verse.Combat.Definitions.StartValues", VERSE_WP02_TEST_FLAGS)
+bool FVerseDefinitionsStartValues::RunTest(const FString&)
+{
+ const UVerseWeaponDefinition* G = VerseWp02Test::Weapon(*this, TEXT("graveline"));
+ const UVerseWeaponDefinition* T = VerseWp02Test::Weapon(*this, TEXT("tallow"));
+ const UVerseGadgetDefinition* B = VerseWp02Test::Gadget(*this, TEXT("bulwark"));
+ const UVerseGadgetDefinition* C = VerseWp02Test::Gadget(*this, TEXT("breach_charge"));
+ if (!G || !T || !B || !C)
+ {
+ return false;
+ }
+ // combat-state.md 3.1 (the fields the acceptance rows depend on).
+ TestEqual(TEXT("Graveline RPM"), G->RPM, 690.f);
+ TestEqual(TEXT("Graveline magazine"), G->MagazineSize, 30);
+ TestEqual(TEXT("Graveline base damage"), G->BaseDamage, 28.f);
+ TestEqual(TEXT("Graveline speed"), G->ProjectileSpeed, 300.f);
+ TestEqual(TEXT("Graveline power"), G->PenetrationPower, 100.f);
+ TestEqual(TEXT("Tallow RPM"), T->RPM, 380.f);
+ TestEqual(TEXT("Tallow fire mode"), T->FireMode, EVerseFireMode::Semi);
+ TestEqual(TEXT("Tallow power"), T->PenetrationPower, 50.f);
+ TestEqual(TEXT("Tallow passes"), T->MaxPenetrations, 2);
+ TestEqual(TEXT("Graveline slot"), G->Slot, EVerseLoadoutSlot::Primary);
+ TestEqual(TEXT("Tallow slot"), T->Slot, EVerseLoadoutSlot::Secondary);
+
+ // combat-state.md 2.3.
+ TestEqual(TEXT("Bulwark charges"), B->Charges, 1);
+ TestEqual(TEXT("Bulwark cooldown"), B->Cooldown, 20.f);
+ TestEqual(TEXT("Bulwark use time"), B->UseTime, 0.6f);
+ TestEqual(TEXT("Bulwark lifetime"), B->Lifetime, 25.f);
+ TestEqual(TEXT("Bulwark health"), B->MaxHealth, 400.f);
+ TestTrue(TEXT("Bulwark size"), B->Size.Equals(FVector3f(1.8f, 1.4f, 0.1f), 1e-6f));
+ TestEqual(TEXT("Breach charges"), C->Charges, 2);
+ TestEqual(TEXT("Breach fuse"), C->Lifetime, 2.5f);
+ TestEqual(TEXT("Breach pawn damage"), C->PawnDamage, 120.f);
+ TestEqual(TEXT("Breach pawn radius"), C->PawnRadius, 3.f);
+ TestEqual(TEXT("Breach piece radius"), C->PieceBreachRadius, 150.f);
+ TestTrue(TEXT("Breach self damage"), C->bSelfDamage);
+ return true;
+}
+
+#endif // WITH_DEV_AUTOMATION_TESTS
diff --git a/unreal/Verse/Source/VerseCombat/Private/Tests/Weapons/VerseEventsTest.cpp b/unreal/Verse/Source/VerseCombat/Private/Tests/Weapons/VerseEventsTest.cpp
new file mode 100644
index 0000000000..3b46a61e71
--- /dev/null
+++ b/unreal/Verse/Source/VerseCombat/Private/Tests/Weapons/VerseEventsTest.cpp
@@ -0,0 +1,229 @@
+#include "Damage/VerseCombatStateComponent.h"
+#include "Events/VerseEventHub.h"
+#include "Gadgets/VerseBreachCharge.h"
+#include "Gadgets/VerseBulwark.h"
+#include "Inventory/VerseInventoryComponent.h"
+#include "Misc/AutomationTest.h"
+#include "Projectiles/VerseBoltPresentation.h"
+#include "Projectiles/VerseProjectileManager.h"
+#include "Tests/Weapons/VerseWp02TestUtils.h"
+#include "VerseGameplayTags.h"
+#include "Weapons/VerseCombatTags.h"
+#include "Weapons/VerseWeaponComponent.h"
+
+#if WITH_DEV_AUTOMATION_TESTS
+
+// Verse.Combat.Events.*: the hub events Fire, Hit, Penetration, Death, Reload and Gadget with the
+// transports of combat-state.md 5.1 (WP02.10), and the authority fire path end to end.
+// Verse.Combat.Presentation.*: own bolts amber, the opponent's red, removal rules (WP02.11).
+
+namespace VerseEventsTest
+{
+ void CheckRpc(FAutomationTestBase& Test, UClass* Class, const TCHAR* Name, EFunctionFlags Kind, bool bReliable)
+ {
+ const UFunction* F = Class->FindFunctionByName(Name);
+ if (!Test.TestNotNull(FString::Printf(TEXT("%s::%s exists"), *Class->GetName(), Name), F))
+ {
+ return;
+ }
+ Test.TestTrue(FString::Printf(TEXT("%s is a net function of the right kind"), Name), F->HasAllFunctionFlags(FUNC_Net | Kind));
+ Test.TestEqual(FString::Printf(TEXT("%s reliability"), Name), F->HasAnyFunctionFlags(FUNC_NetReliable), bReliable);
+ }
+
+ /** A shooter pawn with inventory, weapon and combat state, Graveline and Tallow drawn. */
+ APawn* SpawnShooter(UWorld* World, const UVerseWeaponDefinition* Primary, const UVerseWeaponDefinition* Secondary)
+ {
+ APawn* Pawn = VerseWp02Test::SpawnTarget(World, FVector::ZeroVector);
+ UVerseInventoryComponent* Inv = NewObject<UVerseInventoryComponent>(Pawn, TEXT("Inventory"));
+ Inv->RegisterComponent();
+ TMap<EVerseLoadoutSlot, const UVerseWeaponDefinition*> Loadout;
+ Loadout.Add(EVerseLoadoutSlot::Primary, Primary);
+ Loadout.Add(EVerseLoadoutSlot::Secondary, Secondary);
+ Inv->GiveLoadout(Loadout, World->GetTimeSeconds());
+ UVerseWeaponComponent* Weapon = NewObject<UVerseWeaponComponent>(Pawn, TEXT("Weapon"));
+ Weapon->RegisterComponent();
+ Weapon->MatchSeed = 99;
+ return Pawn;
+ }
+}
+
+IMPLEMENT_SIMPLE_AUTOMATION_TEST(FVerseEventsTransports, "Verse.Combat.Events.Transports", VERSE_WP02_TEST_FLAGS)
+bool FVerseEventsTransports::RunTest(const FString&)
+{
+ using namespace VerseEventsTest;
+ CheckRpc(*this, UVerseWeaponComponent::StaticClass(), TEXT("ServerFire"), FUNC_NetServer, false);
+ CheckRpc(*this, UVerseWeaponComponent::StaticClass(), TEXT("ClientConfirmShot"), FUNC_NetClient, true);
+ CheckRpc(*this, UVerseWeaponComponent::StaticClass(), TEXT("MulticastFire"), FUNC_NetMulticast, false);
+ CheckRpc(*this, UVerseWeaponComponent::StaticClass(), TEXT("MulticastHitCosmetic"), FUNC_NetMulticast, false);
+ CheckRpc(*this, UVerseWeaponComponent::StaticClass(), TEXT("MulticastPenetration"), FUNC_NetMulticast, false);
+ CheckRpc(*this, UVerseCombatStateComponent::StaticClass(), TEXT("ClientReceiveHit"), FUNC_NetClient, true);
+ CheckRpc(*this, UVerseCombatStateComponent::StaticClass(), TEXT("MulticastDeath"), FUNC_NetMulticast, true);
+ CheckRpc(*this, UVerseInventoryComponent::StaticClass(), TEXT("ClientReloadEvent"), FUNC_NetClient, true);
+ CheckRpc(*this, UVerseInventoryComponent::StaticClass(), TEXT("ServerReload"), FUNC_NetServer, true);
+ CheckRpc(*this, UVerseInventoryComponent::StaticClass(), TEXT("ServerSwitchSlot"), FUNC_NetServer, true);
+ CheckRpc(*this, AVerseBulwark::StaticClass(), TEXT("MulticastGadgetEvent"), FUNC_NetMulticast, false);
+ CheckRpc(*this, AVerseBreachCharge::StaticClass(), TEXT("MulticastGadgetEvent"), FUNC_NetMulticast, false);
+ return true;
+}
+
+IMPLEMENT_SIMPLE_AUTOMATION_TEST(FVerseEventsFirePath, "Verse.Combat.Events.FirePath", VERSE_WP02_TEST_FLAGS)
+bool FVerseEventsFirePath::RunTest(const FString&)
+{
+ const UVerseWeaponDefinition* G = VerseWp02Test::Weapon(*this, TEXT("graveline"));
+ const UVerseWeaponDefinition* T = VerseWp02Test::Weapon(*this, TEXT("tallow"));
+ if (!G || !T)
+ {
+ return false;
+ }
+ VerseWp02Test::FTestWorld World;
+ UVerseEventHub* Hub = UVerseEventHub::Get(World.World);
+ UVerseProjectileManager* Manager = UVerseProjectileManager::Get(World.World);
+ UVerseLagCompSubsystem* Lag = UVerseLagCompSubsystem::Get(World.World);
+ Manager->SetManualStepping(true);
+
+ TArray<FVerseFireEvent> Fires;
+ TArray<FVerseHitEvent> Hits;
+ TArray<FVerseDeathEvent> Deaths;
+ TArray<FVerseNoiseEvent> Noises;
+ TArray<FVerseReloadEvent> Reloads;
+ Hub->OnFire.AddLambda([&Fires](const FVerseFireEvent& E) { Fires.Add(E); });
+ Hub->OnHit.AddLambda([&Hits](const FVerseHitEvent& E) { Hits.Add(E); });
+ Hub->OnDeath.AddLambda([&Deaths](const FVerseDeathEvent& E) { Deaths.Add(E); });
+ Hub->OnNoise.AddLambda([&Noises](const FVerseNoiseEvent& E) { Noises.Add(E); });
+ Hub->OnReload.AddLambda([&Reloads](const FVerseReloadEvent& E) { Reloads.Add(E); });
+
+ APawn* Shooter = VerseEventsTest::SpawnShooter(World.World, G, T);
+ APawn* Target = VerseWp02Test::SpawnTarget(World.World, FVector(500, 0, 64 - 135));
+ Lag->RegisterTarget(Target, [Target](FTransform& Root, TArray<FVerseHitCapsule>& Out)
+ {
+ Root = Target->GetActorTransform();
+ VerseWp02Test::HumanCapsules(Target->GetActorLocation(), Out);
+ });
+ UVerseWeaponComponent* Weapon = UVerseWeaponComponent::FindOn(Shooter);
+ UVerseInventoryComponent* Inv = UVerseInventoryComponent::FindOn(Shooter);
+ UVerseCombatStateComponent* State = UVerseCombatStateComponent::FindOn(Shooter);
+ State->BeginSpawnProtection(World.World->GetTimeSeconds(), 2.f);
+
+ Weapon->StepAds(true, 1.f); // full ADS: the spread stays inside the torso at 5 m
+
+ TArray<EVerseShotResult> Answers;
+ Weapon->OnShotAnswered.AddLambda([&Answers](uint16, EVerseShotResult R) { Answers.Add(R); });
+
+ // Hold the trigger with the aim on the target's chest until it dies.
+ int32 ShotsFired = 0;
+ for (int32 I = 0; I < 120 && Deaths.Num() == 0; ++I)
+ {
+ World.TickFrames(1);
+ const float Now = World.World->GetTimeSeconds();
+ Lag->Record(Now);
+ FVerseFireContext Ctx;
+ Ctx.Now = Now;
+ Ctx.Dt = VerseWp02Test::Tick;
+ Ctx.bTriggerDown = true;
+ Ctx.Eye = Shooter->GetPawnViewLocation();
+ Ctx.Control = FRotator::ZeroRotator;
+ TArray<FVerseShotOut> Shots;
+ Weapon->StepFire(Ctx, &Shots);
+ ShotsFired += Shots.Num();
+ Manager->StepAll(VerseWp02Test::Tick, Now);
+ }
+ TestFalse(TEXT("the first shot ended spawn protection"), State->bSpawnProtected);
+ TestTrue(TEXT("shots were fired"), ShotsFired >= 4);
+ TestEqual(TEXT("one fire event per shot"), Fires.Num(), ShotsFired);
+ const int32 ShotNoises = Noises.FilterByPredicate([](const FVerseNoiseEvent& N) { return N.Noise == VerseTags::Noise_Shot; }).Num();
+ TestEqual(TEXT("one shot noise per shot"), ShotNoises, ShotsFired);
+ TestEqual(TEXT("target died once"), Deaths.Num(), 1);
+ TestTrue(TEXT("hits raised"), Hits.Num() >= 4);
+ TestTrue(TEXT("every shot answered"), Answers.Num() >= Hits.Num());
+ TestTrue(TEXT("answers include body hits"), Answers.Contains(EVerseShotResult::HitBody));
+ if (Fires.Num() > 0)
+ {
+ TestEqual(TEXT("fire event carries the weapon"), Fires[0].WeaponId, G->WeaponId);
+ TestEqual(TEXT("fire event carries the shooter"), Fires[0].ShooterId, VerseCombatIds::IdOf(Shooter));
+ }
+ TestEqual(TEXT("rounds spent on the server"), FVerseMagazine::RoundsReady(*Inv->GetActiveState(), *G), G->MagazineSize - ShotsFired);
+
+ // A tampered request is rejected and spends nothing.
+ const int32 Before = FVerseMagazine::RoundsReady(*Inv->GetActiveState(), *G);
+ const EVerseShotResult Bad = Weapon->HandleServerFire(60000, 1, Shooter->GetPawnViewLocation() + FVector(0, 0, 100), FVector(1, 0, 0),
+ World.World->GetTimeSeconds() + 10.f);
+ TestEqual(TEXT("bad seed / origin rejected"), Bad, EVerseShotResult::Rejected);
+ TestEqual(TEXT("rejected shot spends nothing"), FVerseMagazine::RoundsReady(*Inv->GetActiveState(), *G), Before);
+
+ // Reload: event plus noise.
+ const int32 NoisesBefore = Noises.Num();
+ TestTrue(TEXT("reload"), Inv->ServerStartReload(World.World->GetTimeSeconds()));
+ TestEqual(TEXT("reload event"), Reloads.Num(), 1);
+ TestTrue(TEXT("reload noise"), Noises.Num() == NoisesBefore + 1 && Noises.Last().Noise == VerseTags::Noise_Reload);
+ return true;
+}
+
+IMPLEMENT_SIMPLE_AUTOMATION_TEST(FVersePresentationBolts, "Verse.Combat.Presentation.BoltColors", VERSE_WP02_TEST_FLAGS)
+bool FVersePresentationBolts::RunTest(const FString&)
+{
+ VerseWp02Test::FTestWorld World;
+ UVerseBoltPresentation* P = UVerseBoltPresentation::Get(World.World);
+ if (!TestNotNull(TEXT("presentation exists on a viewer world"), P))
+ {
+ return false;
+ }
+ double Clock = 10.0;
+ P->ClockOverride = [&Clock]() { return Clock; };
+ P->LocalPlayerIdOverride = 1;
+ UVerseEventHub* Hub = UVerseEventHub::Get(World.World);
+
+ FVerseFireEvent Own;
+ Own.ShooterId = 1;
+ Own.WeaponId = TEXT("graveline");
+ Own.ShotCounter = 5;
+ Own.Origin = FVector::ZeroVector;
+ Own.Direction = FVector(1, 0, 0);
+ FVerseFireEvent Foe = Own;
+ Foe.ShooterId = 2;
+ Foe.ShotCounter = 9;
+ Hub->OnFire.Broadcast(Own);
+ Hub->OnFire.Broadcast(Foe);
+ TestEqual(TEXT("one own bolt"), P->NumOwn(), 1);
+ TestEqual(TEXT("one foe bolt"), P->NumFoe(), 1);
+ const FLinearColor Amber = VerseCombatTags::BoltColor(VerseCombatTags::Presentation_Bolt_Amber, true);
+ const FLinearColor Red = VerseCombatTags::BoltColor(VerseCombatTags::Presentation_Bolt_Red, false);
+ for (const FVerseVisualBolt& B : P->GetBolts())
+ {
+ TestTrue(TEXT("own amber, foe red"), B.Color.Equals(B.bOwn ? Amber : Red));
+ }
+ TestTrue(TEXT("amber is amber"), Amber.R > 0.9f && Amber.G > 0.4f && Amber.G < 0.7f && Amber.B < 0.15f);
+ TestTrue(TEXT("red is red"), Red.R > 0.8f && Red.G < 0.15f && Red.B < 0.15f);
+
+ // Echo of the own shot is not drawn twice.
+ Hub->OnFire.Broadcast(Own);
+ TestEqual(TEXT("no duplicate"), P->NumOwn(), 1);
+
+ // Flight: 300 m/s, drawn ahead of the muzzle.
+ Clock += 0.1;
+ P->Advance(Clock);
+ TestEqual(TEXT("head at 30 m after 0.1 s"), UVerseBoltPresentation::HeadAt(P->GetBolts()[0], Clock).X, 3000.0, 1.0);
+
+ // Rejected removes the own bolt; the cosmetic hit ends the foe bolt with an impact.
+ UVerseWeaponComponent::OnAnyShotRejected.Broadcast(1, 5);
+ TestEqual(TEXT("rejected own bolt removed"), P->NumOwn(), 0);
+ TestEqual(TEXT("no impact from a rejection"), P->GetImpacts().Num(), 0);
+ FVerseHitEvent Hit;
+ Hit.InstigatorId = 2;
+ Hit.ShotCounter = 9;
+ Hit.ImpactWorld = FVector(500, 0, 0);
+ Hub->OnHit.Broadcast(Hit);
+ TestEqual(TEXT("foe bolt ended at the hit"), P->NumFoe(), 0);
+ TestEqual(TEXT("impact flash from the hit event"), P->GetImpacts().Num(), 1);
+ Clock += 1.0;
+ P->Advance(Clock);
+ TestEqual(TEXT("impact flash is short"), P->GetImpacts().Num(), 0);
+
+ // A bolt that never hits leaves at its range.
+ Hub->OnFire.Broadcast(Foe);
+ Clock += 1.0;
+ P->Advance(Clock);
+ TestEqual(TEXT("bolt gone after MaxRange"), P->GetBolts().Num(), 0);
+ return true;
+}
+
+#endif // WITH_DEV_AUTOMATION_TESTS
diff --git a/unreal/Verse/Source/VerseCombat/Private/Tests/Weapons/VersePredictionTest.cpp b/unreal/Verse/Source/VerseCombat/Private/Tests/Weapons/VersePredictionTest.cpp
new file mode 100644
index 0000000000..4fb1601398
--- /dev/null
+++ b/unreal/Verse/Source/VerseCombat/Private/Tests/Weapons/VersePredictionTest.cpp
@@ -0,0 +1,234 @@
+#include "Misc/AutomationTest.h"
+#include "Tests/Weapons/VerseWp02TestUtils.h"
+#include "VerseRng.h"
+#include "Weapons/VerseFirePrediction.h"
+#include "Weapons/VerseRecoil.h"
+#include "Weapons/VerseSpread.h"
+
+#if WITH_DEV_AUTOMATION_TESTS
+
+// Verse.Combat.Prediction.FireReconcile (A2.6), in-process: the owner predicts with the same
+// cadence, recoil, spread, magazine and predictor code the weapon component runs, talks to a server
+// through a 60 ms one-way delay line, and the server validates with FVerseSpread::ValidateFire. The
+// two-process replication run with PktLag belongs to the WP10 netcode runner (open in the PR).
+
+namespace VersePredictionTest
+{
+ struct FFireMsg
+ {
+ double Arrive = 0.0;
+ uint16 Counter = 0;
+ uint32 Seed = 0;
+ FVector Origin;
+ FVector Dir;
+ float ClientTime = 0.f;
+ };
+
+ struct FConfirmMsg
+ {
+ double Arrive = 0.0;
+ uint16 Counter = 0;
+ EVerseShotResult Result = EVerseShotResult::Miss;
+ };
+
+ FVector Quantize10(const FVector& V)
+ {
+ return FVector(FMath::RoundToDouble(V.X * 10.0) / 10.0, FMath::RoundToDouble(V.Y * 10.0) / 10.0, FMath::RoundToDouble(V.Z * 10.0) / 10.0);
+ }
+}
+
+IMPLEMENT_SIMPLE_AUTOMATION_TEST(FVersePredictionFireReconcile, "Verse.Combat.Prediction.FireReconcile", VERSE_WP02_TEST_FLAGS)
+bool FVersePredictionFireReconcile::RunTest(const FString&)
+{
+ using namespace VersePredictionTest;
+ const UVerseWeaponDefinition* W = VerseWp02Test::Weapon(*this, TEXT("graveline"));
+ if (!W)
+ {
+ return false;
+ }
+ const double OneWay = 0.06;
+ const double Rtt = 2.0 * OneWay;
+ const uint32 ShooterId = 7;
+ const uint32 MatchSeed = 4242;
+
+ // Client side.
+ FVerseFireCadence Cadence;
+ FVerseRecoilState Recoil;
+ FVerseSpread Spread;
+ FVerseFirePredictor Predictor;
+ FVerseWeaponSlotState ClientSlot;
+ FVerseMagazine::InitFull(ClientSlot, *W);
+ // Server side.
+ FVerseWeaponSlotState ServerSlot = ClientSlot;
+ float ServerLastClientTime = -1000.f;
+
+ TArray<FFireMsg> ToServer;
+ TArray<FConfirmMsg> ToClient;
+ TMap<uint16, double> SentAt;
+ TMap<uint16, FVector> ClientOrigin;
+ double MaxOriginErr = 0.0;
+ double MaxRejectLatency = 0.0;
+ int32 Rejected = 0;
+ int32 Accepted = 0;
+ uint16 Counter = 0;
+ FVerseRng Jitter(5);
+
+ double Now = 50.0;
+ const FVector Eye(0, 0, 160);
+ // Replication of the owner-only slot state: snapshots taken after the server's tick, one way late.
+ TArray<TPair<double, FVerseWeaponSlotState>> Snapshots;
+ bool bReloadRequested = false;
+ const int32 FiringTicks = 60 * 12;
+ for (int32 Tick = 0; Tick < FiringTicks + 60 * 4; ++Tick)
+ {
+ const double Start = Now;
+ Now += VerseWp02Test::Tick;
+
+ // Client: replicated state lands; with nothing in flight the prediction takes it (the
+ // weapon component's ResyncPredictedSlot).
+ while (Snapshots.Num() > 0 && Snapshots[0].Key <= Now + 1e-9)
+ {
+ if (Predictor.NumPending() == 0)
+ {
+ ClientSlot = Snapshots[0].Value;
+ bReloadRequested &= !FVerseMagazine::IsReloading(ClientSlot) && FVerseMagazine::RoundsReady(ClientSlot, *W) == 0;
+ }
+ Snapshots.RemoveAt(0);
+ }
+
+ // Client: fire while the trigger is held (1 s on, 0.5 s off); ask for a reload when dry.
+ const bool bTrigger = Tick < FiringTicks && FMath::Fmod(Now, 1.5) < 1.0;
+ if (Tick < FiringTicks && FVerseMagazine::RoundsReady(ClientSlot, *W) == 0 && !bReloadRequested)
+ {
+ bReloadRequested = true;
+ FFireMsg Reload;
+ Reload.Arrive = Now + OneWay;
+ Reload.Counter = 0; // 0 = ServerReload
+ ToServer.Add(Reload);
+ }
+
+ TArray<float> Times;
+ const int32 Rounds = FVerseMagazine::IsReloading(ClientSlot) ? 0 : FVerseMagazine::RoundsReady(ClientSlot, *W);
+ Cadence.Collect(*W, bTrigger, float(Start), float(Now), Rounds, Times);
+ for (const float T : Times)
+ {
+ Recoil.BeginShot(*W, T);
+ uint16 C = ++Counter;
+ if (C == 0)
+ {
+ C = ++Counter; // 0 is the reload message here
+ }
+ const uint32 Seed = FVerseSpread::ShotSeed(ShooterId, C, MatchSeed);
+ FVerseSpreadInput In;
+ const float Sigma = Spread.SigmaFor(*W, In, T);
+ const FVector Dir = FVerseSpread::ShotDirection(FVector(1, 0, 0), Sigma, Seed, Recoil.ShotIndex);
+ const FVector Origin = Eye + FVector(0, float(Jitter.Range(-5.0, 5.0)), 0);
+ // Every 7th shot is tampered with (origin 45 cm off): the server must reject it.
+ const bool bTamper = (C % 7) == 0;
+ const FVector Sent = bTamper ? Origin + FVector(45, 0, 0) : Origin;
+ Recoil.OnShot(Recoil.KickFor(*W, 1.f, Seed), T);
+ Spread.OnShot(*W, T);
+ FVerseMagazine::ConsumeRound(ClientSlot, *W);
+ FVersePredictedShot P;
+ P.Counter = C;
+ P.Time = T;
+ P.Origin = Sent;
+ P.Dir = Dir;
+ Predictor.Add(P);
+ ClientOrigin.Add(C, Sent);
+ SentAt.Add(C, Now);
+ FFireMsg M;
+ M.Arrive = Now + OneWay;
+ M.Counter = C;
+ M.Seed = Seed;
+ M.Origin = Quantize10(Sent);
+ M.Dir = Dir;
+ M.ClientTime = T;
+ ToServer.Add(M);
+ }
+
+ // Server: arrivals in order, then its tick, then the replication snapshot.
+ for (int32 I = 0; I < ToServer.Num();)
+ {
+ if (ToServer[I].Arrive > Now + 1e-9)
+ {
+ ++I;
+ continue;
+ }
+ const FFireMsg M = ToServer[I];
+ ToServer.RemoveAt(I);
+ if (M.Counter == 0)
+ {
+ FVerseMagazine::StartReload(ServerSlot, *W, float(Now));
+ continue;
+ }
+ EVerseShotResult R = EVerseShotResult::Miss;
+ const bool bCadence = M.ClientTime + 0.001f >= ServerLastClientTime + W->FireInterval();
+ const bool bSeed = M.Seed == FVerseSpread::ShotSeed(ShooterId, M.Counter, MatchSeed);
+ FVerseSpreadInput In;
+ const float Sigma = FMath::Max(FVerseSpread::RestingSigma(*W, In, W->BloomMax), W->FirstShotSpread.X);
+ const bool bValid = FVerseSpread::ValidateFire(M.Origin, M.Dir, Eye, FVector(1, 0, 0), Sigma);
+ if (!bCadence || !bSeed || !bValid || !FVerseMagazine::ConsumeRound(ServerSlot, *W))
+ {
+ R = EVerseShotResult::Rejected;
+ ++Rejected;
+ }
+ else
+ {
+ ServerLastClientTime = M.ClientTime;
+ ++Accepted;
+ MaxOriginErr = FMath::Max(MaxOriginErr, FVector::Dist(M.Origin, ClientOrigin[M.Counter]));
+ }
+ FConfirmMsg Back;
+ Back.Arrive = Now + OneWay;
+ Back.Counter = M.Counter;
+ Back.Result = R;
+ ToClient.Add(Back);
+ }
+ FVerseMagazine::Tick(ServerSlot, *W, float(Now));
+ Snapshots.Add({Now + OneWay, ServerSlot});
+
+ // Client: confirmations.
+ for (int32 I = 0; I < ToClient.Num();)
+ {
+ if (ToClient[I].Arrive > Now + 1e-9)
+ {
+ ++I;
+ continue;
+ }
+ const FConfirmMsg M = ToClient[I];
+ ToClient.RemoveAt(I);
+ const FVerseShotReconcile Rec = Predictor.Confirm(M.Counter, M.Result);
+ TestTrue(TEXT("confirmation matches a pending shot"), Rec.bKnown);
+ if (Rec.bRemoveBolt)
+ {
+ MaxRejectLatency = FMath::Max(MaxRejectLatency, Now - SentAt[M.Counter]);
+ }
+ for (int32 R = 0; R < Rec.RefundRounds; ++R)
+ {
+ FVerseMagazine::RefundRound(ClientSlot, *W);
+ }
+ }
+
+ }
+
+ TestTrue(FString::Printf(TEXT("shots accepted (%d)"), Accepted), Accepted > 30);
+ TestTrue(FString::Printf(TEXT("tampered shots rejected (%d)"), Rejected), Rejected >= 4);
+ TestTrue(FString::Printf(TEXT("predicted origin within 1 cm of the server's (%.3f cm)"), MaxOriginErr), MaxOriginErr <= 1.0);
+ TestTrue(FString::Printf(TEXT("rejected bolt gone within one round trip + 1 tick (%.4f s)"), MaxRejectLatency),
+ MaxRejectLatency <= Rtt + VerseWp02Test::Tick + 1e-6);
+ TestEqual(TEXT("everything answered"), Predictor.NumPending(), 0);
+ TestEqual(TEXT("ammo never diverges after reconcile (end)"), FVerseMagazine::RoundsReady(ClientSlot, *W), FVerseMagazine::RoundsReady(ServerSlot, *W));
+
+ TSharedRef<FJsonObject> Proof = MakeShared<FJsonObject>();
+ Proof->SetNumberField(TEXT("one_way_ms"), OneWay * 1000.0);
+ Proof->SetNumberField(TEXT("accepted"), Accepted);
+ Proof->SetNumberField(TEXT("rejected"), Rejected);
+ Proof->SetNumberField(TEXT("max_origin_error_cm"), MaxOriginErr);
+ Proof->SetNumberField(TEXT("max_reject_removal_s"), MaxRejectLatency);
+ Proof->SetNumberField(TEXT("rtt_plus_tick_s"), Rtt + VerseWp02Test::Tick);
+ VerseWp02Test::WriteProof(TEXT("2.6"), TEXT("netcode_report.json"), Proof);
+ return true;
+}
+
+#endif // WITH_DEV_AUTOMATION_TESTS
diff --git a/unreal/Verse/Source/VerseCombat/Private/Tests/Weapons/VerseRecoilTest.cpp b/unreal/Verse/Source/VerseCombat/Private/Tests/Weapons/VerseRecoilTest.cpp
new file mode 100644
index 0000000000..18189a98fd
--- /dev/null
+++ b/unreal/Verse/Source/VerseCombat/Private/Tests/Weapons/VerseRecoilTest.cpp
@@ -0,0 +1,308 @@
+#include "Misc/AutomationTest.h"
+#include "Tests/Weapons/VerseWp02TestUtils.h"
+#include "VerseRng.h"
+#include "Weapons/VerseRecoil.h"
+#include "Weapons/VerseSpread.h"
+
+#if WITH_DEV_AUTOMATION_TESTS
+
+// Verse.Combat.Recoil.*: the recoil invariants R1-R6 of combat-state.md 4.3 for every weapon asset
+// (A2.1), plus the compensation and recovery rules of 4.2. R5 here is the in-process half; the
+// lagged two-process run belongs to the WP10 netcode runner.
+
+namespace VerseRecoilTest
+{
+ const EVerseStance Stances[] = {EVerseStance::Stand, EVerseStance::Crouch, EVerseStance::Prone, EVerseStance::Slide};
+
+ /** Rounds a full magazine holds when fired from spawn (magazine plus the chambered round). */
+ int32 SprayLength(const UVerseWeaponDefinition& W)
+ {
+ return FMath::Max(1, W.MagazineSize);
+ }
+
+ struct FSpray
+ {
+ TArray<FVector2f> Kicks;
+ TArray<float> AccPitch;
+ TArray<float> AccYaw;
+ float SumKickPitch = 0.f;
+ };
+
+ /** Full-magazine spray at max RPM, 60 Hz ticks, no look input; the same path the weapon component runs. */
+ FSpray Spray(const UVerseWeaponDefinition& W, uint32 BaseSeed, EVerseStance Stance, float Ads)
+ {
+ FSpray Out;
+ FVerseRecoilState R;
+ FVerseFireCadence Cadence;
+ const float Mul = FVerseRecoilState::Multiplier(W, Stance, Ads);
+ const int32 Shots = SprayLength(W);
+ float Now = 10.f;
+ int32 Fired = 0;
+ for (int32 Tick = 0; Fired < Shots && Tick < 100000; ++Tick)
+ {
+ const float Start = Now;
+ Now += VerseWp02Test::Tick;
+ TArray<float> Times;
+ // Max RPM: semi weapons get a fresh press on every tick, so each shot goes the moment
+ // the cadence allows it.
+ Cadence.bTriggerWasDown = false;
+ Cadence.Collect(W, true, Start, Now, Shots - Fired, Times);
+ for (const float T : Times)
+ {
+ R.TickKick(W, T);
+ R.BeginShot(W, T);
+ const uint32 Seed = FVerseSpread::ShotSeed(BaseSeed, uint16(Fired + 1), 7u);
+ const FVector2f K = R.KickFor(W, Mul, Seed);
+ R.OnShot(K, T);
+ Out.Kicks.Add(K);
+ Out.SumKickPitch += K.X;
+ Out.AccPitch.Add(R.Accumulated.X);
+ Out.AccYaw.Add(R.Accumulated.Y);
+ ++Fired;
+ }
+ R.TickKick(W, Now);
+ R.TickRecovery(W, Now, VerseWp02Test::Tick);
+ if (Out.AccPitch.Num() > 0)
+ {
+ Out.AccPitch.Last() = R.Accumulated.X; // A after this tick's recovery
+ Out.AccYaw.Last() = R.Accumulated.Y;
+ }
+ }
+ return Out;
+ }
+
+ float MinKickBound(const UVerseWeaponDefinition& W)
+ {
+ const float MMin = FVerseRecoilState::MinMultiplier(W);
+ float Min = TNumericLimits<float>::Max();
+ for (int32 N = 0; N <= SprayLength(W); ++N)
+ {
+ Min = FMath::Min(Min, MMin * W.PatternAt(N).Size() * (1.f - W.RecoilRandomFraction));
+ }
+ return Min;
+ }
+}
+
+IMPLEMENT_SIMPLE_AUTOMATION_TEST(FVerseRecoilRecoveryBelowKick, "Verse.Combat.Recoil.RecoveryBelowKick", VERSE_WP02_TEST_FLAGS)
+bool FVerseRecoilRecoveryBelowKick::RunTest(const FString&)
+{
+ const TArray<const UVerseWeaponDefinition*> Weapons = VerseWp02Test::AllWeapons(*this);
+ TestTrue(TEXT("at least the four weapons load"), Weapons.Num() >= 4);
+
+ TSharedRef<FJsonObject> Proof = MakeShared<FJsonObject>();
+ for (const UVerseWeaponDefinition* W : Weapons)
+ {
+ const FString Id = W->WeaponId.ToString();
+ TestTrue(FString::Printf(TEXT("%s: R1 inequality"), *Id),
+ W->SatisfiesRecoveryBelowKick(FVerseRecoilState::MinMultiplier(*W), VerseRecoilTest::SprayLength(*W)));
+
+ for (const EVerseStance Stance : VerseRecoilTest::Stances)
+ {
+ for (const float Ads : {0.f, 1.f})
+ {
+ const VerseRecoilTest::FSpray S = VerseRecoilTest::Spray(*W, 1234u, Stance, Ads);
+ TestEqual(FString::Printf(TEXT("%s: full magazine fired"), *Id), S.Kicks.Num(), VerseRecoilTest::SprayLength(*W));
+ for (int32 I = 1; I < S.AccPitch.Num(); ++I)
+ {
+ if (S.AccPitch[I] <= S.AccPitch[I - 1])
+ {
+ AddError(FString::Printf(TEXT("%s stance %d ads %.0f: A_p did not rise at shot %d (%.4f -> %.4f)"), *Id, int32(Stance),
+ Ads, I, S.AccPitch[I - 1], S.AccPitch[I]));
+ break;
+ }
+ }
+ if (S.AccPitch.Num() > 0 && S.AccPitch.Last() < 0.5f * S.SumKickPitch)
+ {
+ AddError(FString::Printf(TEXT("%s: A_p %.3f below half the summed kick %.3f"), *Id, S.AccPitch.Last(), S.SumKickPitch));
+ }
+ }
+ }
+
+ // Evidence: pitch and yaw per shot, ten seeds, standing hip fire (section 0.4).
+ TArray<TSharedPtr<FJsonValue>> Seeds;
+ for (uint32 Seed = 1; Seed <= 10; ++Seed)
+ {
+ const VerseRecoilTest::FSpray S = VerseRecoilTest::Spray(*W, Seed, EVerseStance::Stand, 0.f);
+ TArray<TSharedPtr<FJsonValue>> Pitch, Yaw, KickPitch, KickYaw;
+ for (int32 I = 0; I < S.Kicks.Num(); ++I)
+ {
+ Pitch.Add(MakeShared<FJsonValueNumber>(S.AccPitch[I]));
+ Yaw.Add(MakeShared<FJsonValueNumber>(S.AccYaw[I]));
+ KickPitch.Add(MakeShared<FJsonValueNumber>(S.Kicks[I].X));
+ KickYaw.Add(MakeShared<FJsonValueNumber>(S.Kicks[I].Y));
+ }
+ TSharedRef<FJsonObject> One = MakeShared<FJsonObject>();
+ One->SetNumberField(TEXT("seed"), Seed);
+ One->SetArrayField(TEXT("acc_pitch_deg"), Pitch);
+ One->SetArrayField(TEXT("acc_yaw_deg"), Yaw);
+ One->SetArrayField(TEXT("kick_pitch_deg"), KickPitch);
+ One->SetArrayField(TEXT("kick_yaw_deg"), KickYaw);
+ Seeds.Add(MakeShared<FJsonValueObject>(One));
+ }
+ Proof->SetArrayField(Id, Seeds);
+ }
+ VerseWp02Test::WriteProof(TEXT("2.4"), TEXT("recoil_spray.json"), Proof);
+ return true;
+}
+
+IMPLEMENT_SIMPLE_AUTOMATION_TEST(FVerseRecoilKickRate, "Verse.Combat.Recoil.KickRate", VERSE_WP02_TEST_FLAGS)
+bool FVerseRecoilKickRate::RunTest(const FString&)
+{
+ for (const UVerseWeaponDefinition* W : VerseWp02Test::AllWeapons(*this))
+ {
+ const float Rate = VerseRecoilTest::MinKickBound(*W) / FMath::Max(W->RecoilKickTime, UE_SMALL_NUMBER);
+ TestTrue(FString::Printf(TEXT("%s: R2 min|k|/t_k %.2f >= 10 rho %.2f"), *W->WeaponId.ToString(), Rate, 10.f * W->RecoilRecoveryRate),
+ Rate >= 10.f * W->RecoilRecoveryRate);
+
+ // The eased kick is fully applied after t_k and never overshoots.
+ FVerseRecoilState R;
+ R.OnShot(FVector2f(1.f, 0.5f), 0.f);
+ FVector2f Applied = FVector2f::ZeroVector;
+ for (float T = 0.f; T <= W->RecoilKickTime + 0.05f; T += 0.002f)
+ {
+ Applied += R.TickKick(*W, T);
+ }
+ TestTrue(TEXT("kick applied in full"), Applied.Equals(FVector2f(1.f, 0.5f), 1e-4f));
+ }
+ return true;
+}
+
+IMPLEMENT_SIMPLE_AUTOMATION_TEST(FVerseRecoilRandomBound, "Verse.Combat.Recoil.RandomBound", VERSE_WP02_TEST_FLAGS)
+bool FVerseRecoilRandomBound::RunTest(const FString&)
+{
+ for (const UVerseWeaponDefinition* W : VerseWp02Test::AllWeapons(*this))
+ {
+ int32 Violations = 0;
+ for (uint32 Spray = 0; Spray < 10000; ++Spray)
+ {
+ for (int32 N = 0; N < VerseRecoilTest::SprayLength(*W); ++N)
+ {
+ const EVerseStance Stance = VerseRecoilTest::Stances[(Spray + N) % 4];
+ const float Ads = float((Spray >> 2) & 1);
+ const float M = FVerseRecoilState::Multiplier(*W, Stance, Ads);
+ const uint32 Seed = FVerseSpread::ShotSeed(Spray, uint16(N + 1), 99u);
+ const FVector2f K = FVerseRecoilState::KickAt(*W, N, M, Seed);
+ const FVector2f P = W->PatternAt(N);
+ if ((K - M * P).Size() > W->RecoilRandomFraction * M * P.Size() + 1e-4f)
+ {
+ ++Violations;
+ }
+ }
+ }
+ TestEqual(FString::Printf(TEXT("%s: R3 violations over 10,000 sprays"), *W->WeaponId.ToString()), Violations, 0);
+ }
+ return true;
+}
+
+IMPLEMENT_SIMPLE_AUTOMATION_TEST(FVerseRecoilPatternMean, "Verse.Combat.Recoil.PatternMean", VERSE_WP02_TEST_FLAGS)
+bool FVerseRecoilPatternMean::RunTest(const FString&)
+{
+ for (const UVerseWeaponDefinition* W : VerseWp02Test::AllWeapons(*this))
+ {
+ const float M = FVerseRecoilState::Multiplier(*W, EVerseStance::Stand, 0.f);
+ for (int32 N = 0; N < VerseRecoilTest::SprayLength(*W); ++N)
+ {
+ FVector2D Sum = FVector2D::ZeroVector;
+ for (uint32 S = 0; S < 10000; ++S)
+ {
+ const FVector2f K = FVerseRecoilState::KickAt(*W, N, M, FVerseSpread::ShotSeed(S, uint16(N + 1), 3u));
+ Sum += FVector2D(K.X, K.Y);
+ }
+ const FVector2D Mean = Sum / 10000.0;
+ const FVector2f Want = M * W->PatternAt(N);
+ const double Err = (Mean - FVector2D(Want.X, Want.Y)).Size();
+ if (Err > 0.01 * Want.Size())
+ {
+ AddError(FString::Printf(TEXT("%s shot %d: mean off by %.5f deg (%.2f %%)"), *W->WeaponId.ToString(), N, Err, 100.0 * Err / Want.Size()));
+ }
+ }
+ }
+ return true;
+}
+
+IMPLEMENT_SIMPLE_AUTOMATION_TEST(FVerseRecoilDeterminism, "Verse.Combat.Recoil.Determinism", VERSE_WP02_TEST_FLAGS)
+bool FVerseRecoilDeterminism::RunTest(const FString&)
+{
+ // Two independent states fed the same seed, stance, ADS and look input end identical (the
+ // server path itself is R5, Verse.Combat.Recoil.ClientServerMatch in VerseServerFireTest.cpp).
+ for (const UVerseWeaponDefinition* W : VerseWp02Test::AllWeapons(*this))
+ {
+ FVerseRecoilState Server, Client;
+ FVerseRng Look(77);
+ float Now = 5.f;
+ for (int32 Shot = 0; Shot < 200; ++Shot)
+ {
+ Now += W->FireInterval() * (1.f + float(Look.Range(0.0, 3.0)));
+ const EVerseStance Stance = VerseRecoilTest::Stances[Shot % 4];
+ const float Ads = float(Look.Range(0.0, 1.0));
+ const float M = FVerseRecoilState::Multiplier(*W, Stance, Ads);
+ const uint32 Seed = FVerseSpread::ShotSeed(42u, uint16(Shot), 11u);
+ Server.BeginShot(*W, Now);
+ Client.BeginShot(*W, Now);
+ const FVector2f Ks = Server.KickFor(*W, M, Seed);
+ const FVector2f Kc = Client.KickFor(*W, M, Seed);
+ if (!Ks.Equals(Kc, 1e-4f))
+ {
+ AddError(FString::Printf(TEXT("%s shot %d: k differs"), *W->WeaponId.ToString(), Shot));
+ break;
+ }
+ Server.OnShot(Ks, Now);
+ Client.OnShot(Kc, Now);
+ FVector2f In(float(Look.Range(-0.3, 0.1)), float(Look.Range(-0.1, 0.1)));
+ FVector2f In2 = In;
+ Server.OnLookInput(In);
+ Client.OnLookInput(In2);
+ Server.TickRecovery(*W, Now + 0.2f, 0.016f);
+ Client.TickRecovery(*W, Now + 0.2f, 0.016f);
+ }
+ TestTrue(TEXT("accumulators match"), Server.Accumulated.Equals(Client.Accumulated, 1e-4f));
+ TestEqual(TEXT("shot index matches"), Server.ShotIndex, Client.ShotIndex);
+ }
+ return true;
+}
+
+IMPLEMENT_SIMPLE_AUTOMATION_TEST(FVerseRecoilCompensation, "Verse.Combat.Recoil.Compensation", VERSE_WP02_TEST_FLAGS)
+bool FVerseRecoilCompensation::RunTest(const FString&)
+{
+ const UVerseWeaponDefinition* W = VerseWp02Test::Weapon(*this, TEXT("graveline"));
+ if (!W)
+ {
+ return false;
+ }
+ FVerseRecoilState R;
+ R.OnShot(FVector2f(2.f, 0.5f), 0.f);
+ FVector2f Down(-0.5f, 0.f);
+ R.OnLookInput(Down);
+ TestEqual(TEXT("pull-down compensates pitch"), R.Accumulated.X, 1.5f, 1e-5f);
+ TestEqual(TEXT("look input passes through"), Down.X, -0.5f);
+ FVector2f Big(-10.f, -2.f);
+ R.OnLookInput(Big);
+ TestEqual(TEXT("never below zero"), R.Accumulated.X, 0.f);
+ TestEqual(TEXT("yaw against its sign compensates to zero"), R.Accumulated.Y, 0.f);
+ FVector2f Up(1.f, 1.f);
+ R.OnLookInput(Up);
+ TestEqual(TEXT("upward input adds nothing"), R.Accumulated.X, 0.f);
+
+ // Recovery waits d_r, runs at rho and only returns what the weapon added.
+ FVerseRecoilState Q;
+ Q.OnShot(FVector2f(1.f, 0.f), 0.f);
+ TestTrue(TEXT("no recovery before d_r"), Q.TickRecovery(*W, W->RecoilRecoveryDelay * 0.5f, 0.1f).IsNearlyZero());
+ const FVector2f Step = Q.TickRecovery(*W, W->RecoilRecoveryDelay + 0.01f, 0.1f);
+ TestEqual(TEXT("recovery step = rho dt"), Step.X, FMath::Min(1.f, W->RecoilRecoveryRate * 0.1f), 1e-5f);
+ float Total = Step.X;
+ for (int32 I = 0; I < 10000 && !Q.Accumulated.IsNearlyZero(); ++I)
+ {
+ Total += Q.TickRecovery(*W, 10.f, 0.1f).X;
+ }
+ TestEqual(TEXT("recovery returns exactly the kick"), Total, 1.f, 1e-4f);
+
+ // Pattern resets after PatternResetTime.
+ FVerseRecoilState P;
+ P.OnShot(FVector2f(1.f, 0.f), 0.f);
+ P.OnShot(FVector2f(1.f, 0.f), 0.05f);
+ TestEqual(TEXT("index climbs inside a spray"), P.ShotIndexAt(*W, 0.06f), 2);
+ TestEqual(TEXT("index resets after the pause"), P.ShotIndexAt(*W, 0.05f + W->PatternResetTime), 0);
+ return true;
+}
+
+#endif // WITH_DEV_AUTOMATION_TESTS
diff --git a/unreal/Verse/Source/VerseCombat/Private/Tests/Weapons/VerseServerFireTest.cpp b/unreal/Verse/Source/VerseCombat/Private/Tests/Weapons/VerseServerFireTest.cpp
new file mode 100644
index 0000000000..cc71224156
--- /dev/null
+++ b/unreal/Verse/Source/VerseCombat/Private/Tests/Weapons/VerseServerFireTest.cpp
@@ -0,0 +1,361 @@
+#include "Components/BoxComponent.h"
+#include "Events/VerseEventHub.h"
+#include "Gadgets/VerseBulwark.h"
+#include "Inventory/VerseInventoryComponent.h"
+#include "Misc/AutomationTest.h"
+#include "Projectiles/VerseBoltPresentation.h"
+#include "Projectiles/VerseProjectileManager.h"
+#include "Tests/Projectiles/Fakes/VerseFakeDestruction.h"
+#include "Tests/Weapons/VerseWp02TestUtils.h"
+#include "Weapons/VerseRecoil.h"
+#include "Weapons/VerseSpread.h"
+#include "Weapons/VerseWeaponComponent.h"
+
+#if WITH_DEV_AUTOMATION_TESTS
+
+// The server half of the fire path against a client that lies (combat-state.md 4.4, 11.2):
+// Verse.Combat.FireRate.ServerClock (forged timestamps), Verse.Combat.Spread.ServerDirection
+// (no spread, steered shots), Verse.Combat.Recoil.ClientServerMatch (R5: the server's own recoil
+// and spread for the owner's requests), and Verse.Combat.Presentation.ServerStops (bolts end at
+// pieces and Bulwarks on the server's own viewer).
+
+namespace VerseServerFireTest
+{
+ struct FShooterRig
+ {
+ VerseWp02Test::FTestWorld World;
+ UVerseProjectileManager* Manager = nullptr;
+ APawn* Pawn = nullptr;
+ UVerseWeaponComponent* Weapon = nullptr;
+ UVerseInventoryComponent* Inv = nullptr;
+ uint16 Counter = 0;
+
+ explicit FShooterRig(const UVerseWeaponDefinition* Primary)
+ {
+ Manager = UVerseProjectileManager::Get(World.World);
+ Manager->SetManualStepping(true);
+ Pawn = VerseWp02Test::SpawnTarget(World.World, FVector::ZeroVector);
+ Inv = NewObject<UVerseInventoryComponent>(Pawn, TEXT("Inventory"));
+ Inv->RegisterComponent();
+ TMap<EVerseLoadoutSlot, const UVerseWeaponDefinition*> Loadout;
+ Loadout.Add(EVerseLoadoutSlot::Primary, Primary);
+ Inv->GiveLoadout(Loadout, World.World->GetTimeSeconds());
+ Weapon = NewObject<UVerseWeaponComponent>(Pawn, TEXT("Weapon"));
+ Weapon->RegisterComponent();
+ Weapon->SetMatchSeed(1234);
+ World.TickFrames(60); // past the equip time
+ }
+
+ float Now() const
+ {
+ return World.World->GetTimeSeconds();
+ }
+
+ uint32 SeedOf(uint16 C) const
+ {
+ return FVerseSpread::ShotSeed(uint32(Weapon->GetShooterId()), C, Weapon->MatchSeed);
+ }
+
+ /** A request with a correct seed for the next counter. */
+ EVerseShotResult Send(float ClientTime, const FVector& Dir)
+ {
+ const uint16 C = ++Counter;
+ return Weapon->HandleServerFire(C, SeedOf(C), Pawn->GetPawnViewLocation(), Dir, ClientTime);
+ }
+ };
+
+ double AngleDeg(const FVector& A, const FVector& B)
+ {
+ return FMath::RadiansToDegrees(FMath::Acos(FMath::Clamp(FVector::DotProduct(A.GetSafeNormal(), B.GetSafeNormal()), -1.0, 1.0)));
+ }
+}
+
+IMPLEMENT_SIMPLE_AUTOMATION_TEST(FVerseFireRateServerClock, "Verse.Combat.FireRate.ServerClock", VERSE_WP02_TEST_FLAGS)
+bool FVerseFireRateServerClock::RunTest(const FString&)
+{
+ using namespace VerseServerFireTest;
+ const UVerseWeaponDefinition* G = VerseWp02Test::Weapon(*this, TEXT("graveline"));
+ if (!G)
+ {
+ return false;
+ }
+ const float Interval = G->FireInterval();
+
+ // A backlog of correctly spaced past timestamps, all sent in one server frame: the server clock
+ // lets the burst allowance through and no more.
+ {
+ FShooterRig Rig(G);
+ Rig.Weapon->bServerValidates = false; // cadence only
+ const float Now = Rig.Now();
+ int32 Accepted = 0;
+ for (int32 K = 0; K < 5; ++K)
+ {
+ Accepted += Rig.Send(Now - 0.45f + K * Interval, FVector(1, 0, 0)) != EVerseShotResult::Rejected ? 1 : 0;
+ }
+ TestEqual(TEXT("bunched past timestamps: only the burst allowance"), float(Accepted), UVerseWeaponComponent::ServerBurstShots);
+ }
+
+ // Timestamps outside the window around the server clock are rejected.
+ {
+ FShooterRig Rig(G);
+ Rig.Weapon->bServerValidates = false;
+ TestEqual(TEXT("1 s in the future rejected"), Rig.Send(Rig.Now() + 1.f, FVector(1, 0, 0)), EVerseShotResult::Rejected);
+ TestEqual(TEXT("2 s in the past rejected"), Rig.Send(Rig.Now() - 2.f, FVector(1, 0, 0)), EVerseShotResult::Rejected);
+ TestTrue(TEXT("now accepted"), Rig.Send(Rig.Now(), FVector(1, 0, 0)) != EVerseShotResult::Rejected);
+ }
+
+ // A client whose timestamps run four times faster than real time: over two seconds of server
+ // time the accepted rate stays at the weapon's RPM.
+ {
+ FShooterRig Rig(G);
+ Rig.Weapon->bServerValidates = false;
+ float Forged = Rig.Now();
+ int32 Accepted = 0;
+ const int32 Ticks = 120;
+ const float Start = Rig.Now();
+ for (int32 T = 0; T < Ticks; ++T)
+ {
+ Rig.World.TickFrames(1);
+ for (int32 K = 0; K < 3; ++K)
+ {
+ Forged += Interval;
+ const uint16 C = ++Rig.Counter;
+ // Refill the magazine so ammo never limits the count.
+ if (const FVerseWeaponSlotState* S = Rig.Inv->GetActiveState())
+ {
+ FVerseMagazine::InitFull(*const_cast<FVerseWeaponSlotState*>(S), *G);
+ }
+ Accepted += Rig.Weapon->HandleServerFire(C, Rig.SeedOf(C), Rig.Pawn->GetPawnViewLocation(), FVector(1, 0, 0), Forged) !=
+ EVerseShotResult::Rejected ? 1 : 0;
+ }
+ }
+ const float Elapsed = Rig.Now() - Start;
+ const int32 Allowed = FMath::CeilToInt(Elapsed / Interval + UVerseWeaponComponent::ServerBurstShots) + 1;
+ AddInfo(FString::Printf(TEXT("forged 4x clock: %d accepted in %.2f s (RPM %.0f, allowed %d)"), Accepted, Elapsed, 60.f * Accepted / Elapsed, Allowed));
+ TestTrue(FString::Printf(TEXT("accepted %d <= %d"), Accepted, Allowed), Accepted <= Allowed);
+ }
+ return true;
+}
+
+IMPLEMENT_SIMPLE_AUTOMATION_TEST(FVerseSpreadServerDirection, "Verse.Combat.Spread.ServerDirection", VERSE_WP02_TEST_FLAGS)
+bool FVerseSpreadServerDirection::RunTest(const FString&)
+{
+ using namespace VerseServerFireTest;
+ const UVerseWeaponDefinition* G = VerseWp02Test::Weapon(*this, TEXT("graveline"));
+ if (!G)
+ {
+ return false;
+ }
+ FShooterRig Rig(G);
+ const FVector Forward(1, 0, 0);
+ FVerseSpreadInput Hip; // standing, hip fire, still
+
+ // What the server derives for the next request at time T.
+ auto Derived = [&](float T, uint16 C, float& OutSigma, int32& OutIndex)
+ {
+ FVerseSpread Spread = Rig.Weapon->GetServerSpread();
+ FVerseRecoilState Recoil = Rig.Weapon->GetServerRecoil();
+ Spread.DecayUntilShot(*G, T);
+ Recoil.BeginShot(*G, T);
+ OutSigma = Spread.SigmaFor(*G, Hip, T);
+ OutIndex = Recoil.ShotIndex;
+ return FVerseSpread::ShotDirection(Forward, OutSigma, Rig.SeedOf(C), OutIndex);
+ };
+
+ int32 ExactAccepted = 0;
+ int32 SteeredRejected = 0;
+ int32 TightRejected = 0;
+ bool bSteerChecked = false;
+ for (int32 Shot = 0; Shot < 28 && (TightRejected == 0 || !bSteerChecked); ++Shot)
+ {
+ Rig.World.TickFrames(FMath::CeilToInt(G->FireInterval() / VerseWp02Test::Tick));
+ const float T = Rig.Now();
+ const uint16 C = Rig.Counter + 1;
+ float Sigma = 0.f;
+ int32 Index = 0;
+ const FVector Exact = Derived(T, C, Sigma, Index);
+ const double Offset = AngleDeg(Exact, Forward);
+ if (Shot >= 3 && !bSteerChecked)
+ {
+ // Steered 2.5 deg off the derived direction, still inside the old sigma + 1.5 cone.
+ const FVector Steered = FRotator(0.0, 2.5, 0.0).RotateVector(Exact);
+ const bool bInsideOldCone = AngleDeg(Steered, Forward) <= FVerseSpread::RestingSigma(*G, Hip, G->BloomMax) + 1.5;
+ const EVerseShotResult R = Rig.Send(T, Steered);
+ SteeredRejected += R == EVerseShotResult::Rejected ? 1 : 0;
+ bSteerChecked = bInsideOldCone;
+ continue;
+ }
+ if (Offset > 2.0 && Sigma > 2.0)
+ {
+ // No spread at all: a direction no honest client can produce for this seed.
+ TightRejected += Rig.Send(T, Forward) == EVerseShotResult::Rejected ? 1 : 0;
+ continue;
+ }
+ ExactAccepted += Rig.Send(T, Exact) != EVerseShotResult::Rejected ? 1 : 0;
+ }
+ TestTrue(TEXT("derived directions are accepted"), ExactAccepted >= 3);
+ TestTrue(TEXT("a steered shot inside the old cone was tried"), bSteerChecked);
+ TestTrue(TEXT("steered shots are rejected"), SteeredRejected >= 1);
+ TestEqual(TEXT("a zero-spread shot under bloom is rejected"), TightRejected, 1);
+ return true;
+}
+
+IMPLEMENT_SIMPLE_AUTOMATION_TEST(FVerseRecoilClientServerMatch, "Verse.Combat.Recoil.ClientServerMatch", VERSE_WP02_TEST_FLAGS)
+bool FVerseRecoilClientServerMatch::RunTest(const FString&)
+{
+ using namespace VerseServerFireTest;
+ // R5: the owner's StepFire computes its kicks; the server path the request goes through computes
+ // its own from the request alone (time, counter, seed) and the server's stance and ADS.
+ for (const TCHAR* Id : {TEXT("graveline"), TEXT("tallow")})
+ {
+ const UVerseWeaponDefinition* W = VerseWp02Test::Weapon(*this, Id);
+ if (!W)
+ {
+ return false;
+ }
+ FShooterRig Rig(W);
+ int32 Compared = 0;
+ double MaxKickErr = 0.0;
+ double MaxSigmaErr = 0.0;
+ int32 IndexMismatch = 0;
+ for (int32 Tick = 0; Tick < 60 * 6; ++Tick)
+ {
+ Rig.World.TickFrames(1);
+ const float Now = Rig.Now();
+ Rig.Weapon->StepAds(FMath::Fmod(Now, 1.3f) < 0.6f, VerseWp02Test::Tick);
+ if (const FVerseWeaponSlotState* S = Rig.Inv->GetActiveState())
+ {
+ if (FVerseMagazine::RoundsReady(*S, *W) == 0)
+ {
+ FVerseMagazine::InitFull(*const_cast<FVerseWeaponSlotState*>(S), *W);
+ }
+ }
+ FVerseFireContext Ctx;
+ Ctx.Now = Now;
+ Ctx.Dt = VerseWp02Test::Tick;
+ // Semi needs fresh presses; sprays with pauses for the auto rifle.
+ Ctx.bTriggerDown = W->FireMode == EVerseFireMode::Semi ? (Tick % 8) < 4 : FMath::Fmod(Now, 1.0f) < 0.7f;
+ Ctx.Eye = Rig.Pawn->GetPawnViewLocation();
+ TArray<FVerseShotOut> Shots;
+ Rig.Weapon->StepFire(Ctx, &Shots);
+ if (Shots.Num() > 0)
+ {
+ const FVerseShotOut& Last = Shots.Last();
+ MaxKickErr = FMath::Max(MaxKickErr, double((Last.Kick - Rig.Weapon->GetLastServerKick()).Size()));
+ MaxSigmaErr = FMath::Max(MaxSigmaErr, double(FMath::Abs(Last.Sigma - Rig.Weapon->GetLastServerSigma())));
+ IndexMismatch += Last.ShotIndex != Rig.Weapon->GetLastServerShotIndex() ? 1 : 0;
+ ++Compared;
+ }
+ }
+ AddInfo(FString::Printf(TEXT("%s: %d shots, max kick diff %.6f deg, max sigma diff %.4f deg"), Id, Compared, MaxKickErr, MaxSigmaErr));
+ TestTrue(FString::Printf(TEXT("%s: shots compared"), Id), Compared >= 20);
+ TestTrue(FString::Printf(TEXT("%s: server kicks equal the client's"), Id), MaxKickErr < 1e-4);
+ TestEqual(FString::Printf(TEXT("%s: shot index matches"), Id), IndexMismatch, 0);
+ // Both sides decay bloom up to the shot's own time: the same sigma.
+ TestTrue(FString::Printf(TEXT("%s: sigma equals the client's"), Id), MaxSigmaErr <= 1e-4);
+ TestTrue(FString::Printf(TEXT("%s: server spray index equals the client's"), Id),
+ Rig.Weapon->GetServerRecoil().ShotIndex == Rig.Weapon->GetRecoil().ShotIndex);
+ }
+ return true;
+}
+
+IMPLEMENT_SIMPLE_AUTOMATION_TEST(FVersePresentationServerStops, "Verse.Combat.Presentation.ServerStops", VERSE_WP02_TEST_FLAGS)
+bool FVersePresentationServerStops::RunTest(const FString&)
+{
+ using namespace VerseServerFireTest;
+ const UVerseWeaponDefinition* G = VerseWp02Test::Weapon(*this, TEXT("graveline"));
+ const UVerseGadgetDefinition* Def = VerseWp02Test::Gadget(*this, TEXT("bulwark"));
+ if (!G || !Def)
+ {
+ return false;
+ }
+ // The host of a match against bots is the server and a viewer: its own bolts must end where the
+ // server resolves them, at a world hit, a piece or a Bulwark (standalone takes the same authority
+ // path as a listen server: not a dedicated server, authority, a local viewer).
+ enum class EStop : uint8 { World, Piece, Bulwark };
+ for (const EStop Stop : {EStop::World, EStop::Piece, EStop::Bulwark})
+ {
+ FShooterRig Rig(G);
+ UVerseBoltPresentation* P = UVerseBoltPresentation::Get(Rig.World.World);
+ if (!TestNotNull(TEXT("presentation on the host"), P))
+ {
+ return false;
+ }
+ P->LocalPlayerIdOverride = Rig.Weapon->GetShooterId();
+ TArray<FVerseHitEvent> Impacts;
+ UVerseEventHub::Get(Rig.World.World)->OnHit.AddLambda([&Impacts](const FVerseHitEvent& E)
+ {
+ if (E.VictimId == -1)
+ {
+ Impacts.Add(E);
+ }
+ });
+
+ FFakeVersePenetrationQuery Query;
+ FFakeVersePieceDamage PieceDamage;
+ AActor* Blocker = nullptr;
+ const double StopX = 900.0; // beyond the latency advance of the first tick (at most 5 m)
+ const FVector Eye = Rig.Pawn->GetPawnViewLocation();
+ if (Stop == EStop::Piece)
+ {
+ FFakeVersePiece Wall;
+ Wall.PieceIndex = 3;
+ Wall.Material = EVersePenetrationMaterial::Concrete;
+ Wall.Bounds = FBox(FVector(StopX, -400, Eye.Z - 400), FVector(StopX + 30, 400, Eye.Z + 400));
+ Query.Pieces.Add(Wall);
+ Rig.Manager->SetPenetrationQuery(&Query);
+ Rig.Manager->SetPieceDamage(&PieceDamage);
+ }
+ else if (Stop == EStop::Bulwark)
+ {
+ FActorSpawnParameters Params;
+ Params.SpawnCollisionHandlingOverride = ESpawnActorCollisionHandlingMethod::AlwaysSpawn;
+ AVerseBulwark* B = Rig.World.World->SpawnActor<AVerseBulwark>(AVerseBulwark::StaticClass(), FVector(StopX, 0, Eye.Z - 100),
+ FRotator(0, 180, 0), Params);
+ B->InitBulwark(*Def, nullptr, Rig.Now());
+ Blocker = B;
+ }
+ else
+ {
+ FActorSpawnParameters Params;
+ Params.SpawnCollisionHandlingOverride = ESpawnActorCollisionHandlingMethod::AlwaysSpawn;
+ Blocker = Rig.World.World->SpawnActor<AActor>(AActor::StaticClass(), FTransform::Identity, Params);
+ UBoxComponent* Box = NewObject<UBoxComponent>(Blocker, TEXT("Box"));
+ Box->SetBoxExtent(FVector(10, 400, 400));
+ Box->SetCollisionEnabled(ECollisionEnabled::QueryOnly);
+ Box->SetCollisionResponseToAllChannels(ECR_Block);
+ Blocker->SetRootComponent(Box);
+ Box->RegisterComponent();
+ Blocker->SetActorLocation(FVector(StopX + 10, 0, Eye.Z));
+ }
+ Rig.World.TickFrames(2);
+
+ FVerseFireContext Ctx;
+ Ctx.Now = Rig.Now();
+ Ctx.Dt = VerseWp02Test::Tick;
+ Ctx.bTriggerDown = true;
+ Ctx.Eye = Eye;
+ TArray<FVerseShotOut> Shots;
+ Rig.Weapon->StepFire(Ctx, &Shots);
+ const TCHAR* Name = Stop == EStop::World ? TEXT("world") : (Stop == EStop::Piece ? TEXT("piece") : TEXT("Bulwark"));
+ if (!TestEqual(FString::Printf(TEXT("%s: one shot"), Name), Shots.Num(), 1))
+ {
+ continue;
+ }
+ TestEqual(FString::Printf(TEXT("%s: own bolt drawn on the host"), Name), P->NumOwn(), 1);
+ Rig.Manager->StepAll(VerseWp02Test::Tick, Rig.Now() + VerseWp02Test::Tick);
+ TestEqual(FString::Printf(TEXT("%s: bolt resolved on the server"), Name), Rig.Manager->NumActive(), 0);
+ TestEqual(FString::Printf(TEXT("%s: one cosmetic impact on the host's hub"), Name), Impacts.Num(), 1);
+ TestEqual(FString::Printf(TEXT("%s: the drawn bolt ends there"), Name), P->NumOwn(), 0);
+ TestEqual(FString::Printf(TEXT("%s: impact placed"), Name), P->GetImpacts().Num(), 1);
+ if (Impacts.Num() == 1)
+ {
+ TestTrue(FString::Printf(TEXT("%s: impact at the stop (x %.1f)"), Name, Impacts[0].ImpactWorld.X),
+ FMath::Abs(Impacts[0].ImpactWorld.X - StopX) < 40.0);
+ TestEqual(FString::Printf(TEXT("%s: impact carries the shot"), Name), int32(Impacts[0].ShotCounter), int32(Shots[0].Counter));
+ }
+ }
+ return true;
+}
+
+#endif // WITH_DEV_AUTOMATION_TESTS
diff --git a/unreal/Verse/Source/VerseCombat/Private/Tests/Weapons/VerseSpreadTest.cpp b/unreal/Verse/Source/VerseCombat/Private/Tests/Weapons/VerseSpreadTest.cpp
new file mode 100644
index 0000000000..d677d6baef
--- /dev/null
+++ b/unreal/Verse/Source/VerseCombat/Private/Tests/Weapons/VerseSpreadTest.cpp
@@ -0,0 +1,185 @@
+#include "Misc/AutomationTest.h"
+#include "Tests/Weapons/VerseWp02TestUtils.h"
+#include "Weapons/VerseRecoil.h"
+#include "Weapons/VerseSpread.h"
+
+#if WITH_DEV_AUTOMATION_TESTS
+
+// Verse.Combat.Spread.*: first-shot accuracy (R6), bloom, seeded directions and the server's fire
+// validation (combat-state.md 4.4). Verse.Combat.FireRate: the cadence (A2.3).
+
+IMPLEMENT_SIMPLE_AUTOMATION_TEST(FVerseSpreadFirstShot, "Verse.Combat.Spread.FirstShot", VERSE_WP02_TEST_FLAGS)
+bool FVerseSpreadFirstShot::RunTest(const FString&)
+{
+ for (const UVerseWeaponDefinition* W : VerseWp02Test::AllWeapons(*this))
+ {
+ const FString Id = W->WeaponId.ToString();
+ TestTrue(FString::Printf(TEXT("%s: pattern resets no later than first-shot rest"), *Id), W->PatternResetTime <= W->FirstShotRestTime);
+ for (const float Ads : {0.f, 1.f})
+ {
+ FVerseSpread S;
+ FVerseRecoilState R;
+ FVerseSpreadInput In;
+ In.AdsBlend = Ads;
+ // A spray, then a rest of exactly FirstShotRestTime.
+ float Now = 1.f;
+ for (int32 I = 0; I < 6; ++I)
+ {
+ R.BeginShot(*W, Now);
+ R.OnShot(FVector2f(0.5f, 0.f), Now);
+ S.OnShot(*W, Now);
+ Now += W->FireInterval();
+ }
+ Now = S.LastShotTime + W->FirstShotRestTime + 1e-4f; // just past the rest (float-safe)
+ S.DecayTo(*W, Now, W->FirstShotRestTime);
+ R.BeginShot(*W, Now);
+ TestEqual(FString::Printf(TEXT("%s ads %.0f: first shot n = 0"), *Id, Ads), R.ShotIndex, 0);
+ const float Want = FMath::Lerp(W->FirstShotSpread.X, W->FirstShotSpread.Y, Ads);
+ TestEqual(FString::Printf(TEXT("%s ads %.0f: first shot sigma"), *Id, Ads), S.SigmaFor(*W, In, Now), Want, 1e-6f);
+ S.OnShot(*W, Now);
+ TestEqual(TEXT("first shot resets bloom, then one bloom step"), S.Bloom, FMath::Min(W->BloomMax, W->BloomPerShot), 1e-6f);
+
+ // The next shot inside the spray uses base spread plus bloom.
+ const float Next = Now + W->FireInterval();
+ const FVector2f* Base = W->SpreadBase.Find(EVerseStance::Stand);
+ const float WantNext = (Base ? FMath::Lerp(Base->X, Base->Y, Ads) : 0.f) + S.Bloom;
+ TestEqual(TEXT("follow-up sigma = base + bloom"), S.SigmaFor(*W, In, Next), WantNext, 1e-5f);
+ }
+ }
+ return true;
+}
+
+IMPLEMENT_SIMPLE_AUTOMATION_TEST(FVerseSpreadBloomAndInputs, "Verse.Combat.Spread.BloomAndInputs", VERSE_WP02_TEST_FLAGS)
+bool FVerseSpreadBloomAndInputs::RunTest(const FString&)
+{
+ const UVerseWeaponDefinition* W = VerseWp02Test::Weapon(*this, TEXT("graveline"));
+ if (!W)
+ {
+ return false;
+ }
+ FVerseSpread S;
+ for (int32 I = 0; I < 100; ++I)
+ {
+ S.OnShot(*W, 1.f + I * W->FireInterval());
+ }
+ TestEqual(TEXT("bloom capped at BloomMax"), S.Bloom, W->BloomMax, 1e-6f);
+ const float Last = S.LastShotTime;
+ S.DecayTo(*W, Last + W->BloomRecoveryDelay * 0.5f, 0.1f);
+ TestEqual(TEXT("no decay before the delay"), S.Bloom, W->BloomMax, 1e-6f);
+ S.DecayTo(*W, Last + W->BloomRecoveryDelay, 0.1f);
+ TestEqual(TEXT("decay at the rate"), S.Bloom, FMath::Max(0.f, W->BloomMax - W->BloomRecoveryRate * 0.1f), 1e-5f);
+
+ FVerseSpreadInput In;
+ In.HorizontalSpeedMps = 4.f;
+ In.bAirborne = true;
+ const FVector2f* Base = W->SpreadBase.Find(EVerseStance::Stand);
+ TestEqual(TEXT("movement and airborne add"), FVerseSpread::RestingSigma(*W, In, 0.f),
+ Base->X + 4.f * W->SpreadMovePerMps + W->SpreadAirborne, 1e-5f);
+ return true;
+}
+
+IMPLEMENT_SIMPLE_AUTOMATION_TEST(FVerseSpreadSeedAndValidation, "Verse.Combat.Spread.SeedAndValidation", VERSE_WP02_TEST_FLAGS)
+bool FVerseSpreadSeedAndValidation::RunTest(const FString&)
+{
+ // Same inputs, same direction (client and server derive it independently).
+ const uint32 Seed = FVerseSpread::ShotSeed(17u, 300u, 9001u);
+ TestEqual(TEXT("seed is a pure function"), Seed, FVerseSpread::ShotSeed(17u, 300u, 9001u));
+ TestNotEqual(TEXT("seed depends on the counter"), Seed, FVerseSpread::ShotSeed(17u, 301u, 9001u));
+ const FVector Fwd(1, 0, 0);
+ TestTrue(TEXT("direction is a pure function"),
+ FVerseSpread::ShotDirection(Fwd, 2.f, Seed, 3).Equals(FVerseSpread::ShotDirection(Fwd, 2.f, Seed, 3), 1e-12));
+
+ int32 Outside = 0;
+ for (uint32 I = 0; I < 10000; ++I)
+ {
+ const FVector D = FVerseSpread::ShotDirection(Fwd, 1.5f, FVerseSpread::ShotSeed(I, 1, 2), int32(I % 30));
+ const double Angle = FMath::RadiansToDegrees(FMath::Acos(FMath::Clamp(FVector::DotProduct(D, Fwd), -1.0, 1.0)));
+ Outside += Angle > 1.5 + 1e-6 ? 1 : 0;
+ }
+ TestEqual(TEXT("every direction inside the cone"), Outside, 0);
+ TestTrue(TEXT("sigma 0 shoots straight"), FVerseSpread::ShotDirection(Fwd, 0.f, Seed, 0).Equals(Fwd, 1e-9));
+
+ const FVector Eye(0, 0, 160);
+ TestTrue(TEXT("origin 29 cm off passes"), FVerseSpread::ValidateFire(Eye + FVector(29, 0, 0), Fwd, Eye, Fwd, 1.f));
+ TestFalse(TEXT("origin 31 cm off is rejected"), FVerseSpread::ValidateFire(Eye + FVector(31, 0, 0), Fwd, Eye, Fwd, 1.f));
+ const FVector Off2 = FRotator(0, 2.4, 0).Vector();
+ const FVector Off3 = FRotator(0, 2.6, 0).Vector();
+ TestTrue(TEXT("sigma + 1.5 - 0.1 deg passes"), FVerseSpread::ValidateFire(Eye, Off2, Eye, Fwd, 1.f));
+ TestFalse(TEXT("sigma + 1.5 + 0.1 deg is rejected"), FVerseSpread::ValidateFire(Eye, Off3, Eye, Fwd, 1.f));
+ TestFalse(TEXT("zero direction is rejected"), FVerseSpread::ValidateFire(Eye, FVector::ZeroVector, Eye, Fwd, 1.f));
+ return true;
+}
+
+namespace VerseFireRateTest
+{
+ /** Shot times of a full magazine at 60 Hz with the trigger pattern of the fire mode. */
+ TArray<float> FireMagazine(const UVerseWeaponDefinition& W, bool bTapEveryTick)
+ {
+ FVerseFireCadence Cadence;
+ TArray<float> Times;
+ float Now = 3.f;
+ bool bDown = true;
+ for (int32 Tick = 0; Times.Num() < W.MagazineSize && Tick < 100000; ++Tick)
+ {
+ const float Start = Now;
+ Now += VerseWp02Test::Tick;
+ const bool bTrigger = bTapEveryTick ? bDown : true;
+ bDown = !bDown;
+ Cadence.Collect(W, bTrigger, Start, Now, W.MagazineSize - Times.Num(), Times);
+ }
+ return Times;
+ }
+
+ double MeasuredRpm(const TArray<float>& Times)
+ {
+ return Times.Num() > 1 ? 60.0 * double(Times.Num() - 1) / double(Times.Last() - Times[0]) : 0.0;
+ }
+}
+
+IMPLEMENT_SIMPLE_AUTOMATION_TEST(FVerseFireRate, "Verse.Combat.FireRate", VERSE_WP02_TEST_FLAGS)
+bool FVerseFireRate::RunTest(const FString&)
+{
+ const UVerseWeaponDefinition* Graveline = VerseWp02Test::Weapon(*this, TEXT("graveline"));
+ const UVerseWeaponDefinition* Tallow = VerseWp02Test::Weapon(*this, TEXT("tallow"));
+ if (!Graveline || !Tallow)
+ {
+ return false;
+ }
+ const TArray<float> G = VerseFireRateTest::FireMagazine(*Graveline, false);
+ TestEqual(TEXT("Graveline fires the full magazine"), G.Num(), Graveline->MagazineSize);
+ const double GRpm = VerseFireRateTest::MeasuredRpm(G);
+ TestTrue(FString::Printf(TEXT("Graveline %.2f RPM within 1 %% of 690"), GRpm), FMath::Abs(GRpm - 690.0) <= 6.9);
+
+ // Spam the pistol trigger as fast as ticks allow: never above its cap.
+ const TArray<float> T = VerseFireRateTest::FireMagazine(*Tallow, true);
+ const double TRpm = VerseFireRateTest::MeasuredRpm(T);
+ TestTrue(FString::Printf(TEXT("Tallow %.2f RPM never above 380"), TRpm), TRpm <= 380.0 + 1e-3);
+ for (int32 I = 1; I < T.Num(); ++I)
+ {
+ if (T[I] - T[I - 1] < Tallow->FireInterval() - 1e-5f)
+ {
+ AddError(FString::Printf(TEXT("Tallow shots %d and %d closer than the interval"), I - 1, I));
+ }
+ }
+
+ // Semi needs a fresh press; holding fires once.
+ FVerseFireCadence Hold;
+ TArray<float> Held;
+ float Now = 0.f;
+ for (int32 I = 0; I < 120; ++I)
+ {
+ Hold.Collect(*Tallow, true, Now, Now + VerseWp02Test::Tick, 15, Held);
+ Now += VerseWp02Test::Tick;
+ }
+ TestEqual(TEXT("held semi trigger fires once"), Held.Num(), 1);
+
+ // Every weapon: auto and semi never beat their RPM.
+ for (const UVerseWeaponDefinition* W : VerseWp02Test::AllWeapons(*this))
+ {
+ const TArray<float> S = VerseFireRateTest::FireMagazine(*W, W->FireMode != EVerseFireMode::Auto);
+ TestTrue(FString::Printf(TEXT("%s at or under its RPM"), *W->WeaponId.ToString()), VerseFireRateTest::MeasuredRpm(S) <= W->RPM * 1.0001);
+ }
+ return true;
+}
+
+#endif // WITH_DEV_AUTOMATION_TESTS
diff --git a/unreal/Verse/Source/VerseCombat/Private/Tests/Weapons/VerseWp02TestUtils.h b/unreal/Verse/Source/VerseCombat/Private/Tests/Weapons/VerseWp02TestUtils.h
new file mode 100644
index 0000000000..302a32b06f
--- /dev/null
+++ b/unreal/Verse/Source/VerseCombat/Private/Tests/Weapons/VerseWp02TestUtils.h
@@ -0,0 +1,172 @@
+#pragma once
+
+#include "AbilitySystemComponent.h"
+#include "Combat/VerseGadgetDefinition.h"
+#include "Combat/VerseWeaponDefinition.h"
+#include "Components/SceneComponent.h"
+#include "CoreMinimal.h"
+#include "Damage/VerseCombatStateComponent.h"
+#include "Damage/VerseDamageService.h"
+#include "Inventory/VerseWeaponSlot.h"
+#include "Damage/VerseHealthSet.h"
+#include "Dom/JsonObject.h"
+#include "Engine/Engine.h"
+#include "Engine/World.h"
+#include "GameFramework/Pawn.h"
+#include "HAL/FileManager.h"
+#include "LagComp/VerseLagCompensation.h"
+#include "Misc/FileHelper.h"
+#include "Misc/Paths.h"
+#include "Policies/PrettyJsonPrintPolicy.h"
+#include "Serialization/JsonSerializer.h"
+#include "Weapons/VerseDefinitionJson.h"
+#include "Weapons/VerseWeaponRegistry.h"
+
+#if WITH_DEV_AUTOMATION_TESTS
+
+#define VERSE_WP02_TEST_FLAGS (EAutomationTestFlags_ApplicationContextMask | EAutomationTestFlags::EngineFilter)
+
+namespace VerseWp02Test
+{
+ inline constexpr float Tick = 1.f / 60.f;
+
+ /** Every weapon definition from Data/weapons, imported fresh (rooted for the test's life by the caller's world or registry). */
+ inline TArray<const UVerseWeaponDefinition*> AllWeapons(FAutomationTestBase& Test)
+ {
+ TArray<FString> Errors;
+ TArray<UVerseWeaponDefinition*> Loaded = FVerseDefinitionJson::LoadAllWeapons(GetTransientPackage(), Errors);
+ for (const FString& E : Errors)
+ {
+ Test.AddError(E);
+ }
+ TArray<const UVerseWeaponDefinition*> Out;
+ for (UVerseWeaponDefinition* W : Loaded)
+ {
+ W->AddToRoot(); // survive a GC during the test; tests are short-lived processes
+ Out.Add(W);
+ }
+ return Out;
+ }
+
+ inline const UVerseWeaponDefinition* Weapon(FAutomationTestBase& Test, const TCHAR* Id)
+ {
+ const UVerseWeaponDefinition* W = FVerseWeaponRegistry::FindWeapon(FName(Id));
+ Test.TestNotNull(FString::Printf(TEXT("weapon %s loads"), Id), W);
+ return W;
+ }
+
+ inline const UVerseGadgetDefinition* Gadget(FAutomationTestBase& Test, const TCHAR* Id)
+ {
+ const UVerseGadgetDefinition* G = FVerseWeaponRegistry::FindGadget(FName(Id));
+ Test.TestNotNull(FString::Printf(TEXT("gadget %s loads"), Id), G);
+ return G;
+ }
+
+ /** A standalone game world for one test (authority, physics scene, subsystems), destroyed with the scope. */
+ struct FTestWorld
+ {
+ UWorld* World = nullptr;
+
+ FTestWorld()
+ {
+ World = UWorld::CreateWorld(EWorldType::Game, false, MakeUniqueObjectName(GetTransientPackage(), UWorld::StaticClass(), TEXT("VerseWp02Test")));
+ FWorldContext& Context = GEngine->CreateNewWorldContext(EWorldType::Game);
+ Context.SetCurrentWorld(World);
+ const FURL Url;
+ World->InitializeActorsForPlay(Url);
+ World->BeginPlay();
+ }
+
+ ~FTestWorld()
+ {
+ if (World)
+ {
+ World->BeginTearingDown();
+ GEngine->DestroyWorldContext(World);
+ World->DestroyWorld(false);
+ World = nullptr;
+ }
+ }
+
+ void TickFrames(int32 N, float Dt = Tick)
+ {
+ for (int32 I = 0; I < N; ++I)
+ {
+ World->Tick(LEVELTICK_All, Dt);
+ }
+ }
+ };
+
+ /** A pawn with a root, an ability system with UVerseHealthSet, and a combat state component. */
+ inline APawn* SpawnTarget(UWorld* World, const FVector& Location, float MaxHealth = 100.f, const FRotator& Rotation = FRotator::ZeroRotator)
+ {
+ FActorSpawnParameters Params;
+ Params.SpawnCollisionHandlingOverride = ESpawnActorCollisionHandlingMethod::AlwaysSpawn;
+ APawn* Pawn = World->SpawnActor<APawn>(APawn::StaticClass(), FTransform::Identity, Params);
+ USceneComponent* Root = NewObject<USceneComponent>(Pawn, TEXT("Root"));
+ Pawn->SetRootComponent(Root);
+ Root->RegisterComponent();
+ Pawn->SetActorLocationAndRotation(Location, Rotation);
+
+ UAbilitySystemComponent* Asc = NewObject<UAbilitySystemComponent>(Pawn, TEXT("Abilities"));
+ Asc->RegisterComponent();
+ UVerseHealthSet* Set = NewObject<UVerseHealthSet>(Pawn, TEXT("Health"));
+ Asc->AddAttributeSetSubobject(Set);
+ Asc->InitAbilityActorInfo(Pawn, Pawn);
+ Asc->SetNumericAttributeBase(UVerseHealthSet::GetMaxHealthAttribute(), MaxHealth);
+ Asc->SetNumericAttributeBase(UVerseHealthSet::GetHealthAttribute(), MaxHealth);
+
+ UVerseCombatStateComponent* State = NewObject<UVerseCombatStateComponent>(Pawn, TEXT("CombatState"));
+ State->RegisterComponent();
+ return Pawn;
+ }
+
+ inline float HealthOf(const AActor* Actor)
+ {
+ const UAbilitySystemComponent* Asc = Actor ? Actor->FindComponentByClass<UAbilitySystemComponent>() : nullptr;
+ const UVerseHealthSet* Set = Asc ? Asc->GetSet<UVerseHealthSet>() : nullptr;
+ return Set ? Set->GetHealth() : -1.f;
+ }
+
+ /** Hit bodies of a standing human, relative to its root on the floor: legs, torso, neck, head. */
+ inline void HumanCapsules(const FVector& Root, TArray<FVerseHitCapsule>& Out)
+ {
+ auto Add = [&Out, &Root](const TCHAR* Bone, const FVector& A, const FVector& B, float R)
+ {
+ FVerseHitCapsule& C = Out.AddDefaulted_GetRef();
+ C.Bone = FName(Bone);
+ C.Zone = UVerseLagCompSubsystem::ZoneForBone(C.Bone);
+ C.A = Root + A;
+ C.B = Root + B;
+ C.Radius = R;
+ C.BoneTransform = FTransform(Root + 0.5 * (A + B));
+ };
+ Add(TEXT("Calf_L"), FVector(0, -12, 10), FVector(0, -12, 50), 8.f);
+ Add(TEXT("Calf_R"), FVector(0, 12, 10), FVector(0, 12, 50), 8.f);
+ Add(TEXT("Thigh_L"), FVector(0, -12, 55), FVector(0, -12, 90), 10.f);
+ Add(TEXT("Thigh_R"), FVector(0, 12, 55), FVector(0, 12, 90), 10.f);
+ Add(TEXT("Hips"), FVector(0, -8, 98), FVector(0, 8, 98), 14.f);
+ Add(TEXT("Spine_01"), FVector(0, 0, 108), FVector(0, 0, 118), 15.f);
+ Add(TEXT("Spine_03"), FVector(0, 0, 125), FVector(0, 0, 145), 18.f);
+ Add(TEXT("Neck"), FVector(0, 0, 152), FVector(0, 0, 158), 6.f);
+ Add(TEXT("Head"), FVector(0, 0, 168), FVector(0, 0, 172), 11.f);
+ }
+
+ /** Proof files of section 0.4: Saved/Harness/proof/WP02/<sub-task>/<name>. */
+ inline FString ProofPath(const TCHAR* SubTask, const TCHAR* Name)
+ {
+ return FPaths::Combine(FPaths::ProjectSavedDir(), TEXT("Harness"), TEXT("proof"), TEXT("WP02"), SubTask, Name);
+ }
+
+ inline void WriteProof(const TCHAR* SubTask, const TCHAR* Name, const TSharedRef<FJsonObject>& Json)
+ {
+ FString Text;
+ const TSharedRef<TJsonWriter<TCHAR, TPrettyJsonPrintPolicy<TCHAR>>> Writer = TJsonWriterFactory<TCHAR, TPrettyJsonPrintPolicy<TCHAR>>::Create(&Text);
+ FJsonSerializer::Serialize(Json, Writer);
+ const FString Path = ProofPath(SubTask, Name);
+ IFileManager::Get().MakeDirectory(*FPaths::GetPath(Path), true);
+ FFileHelper::SaveStringToFile(Text, *Path);
+ }
+}
+
+#endif // WITH_DEV_AUTOMATION_TESTS
diff --git a/unreal/Verse/Source/VerseCombat/Private/Weapons/VerseCombatEvents.cpp b/unreal/Verse/Source/VerseCombat/Private/Weapons/VerseCombatEvents.cpp
new file mode 100644
index 0000000000..779c2fc12a
--- /dev/null
+++ b/unreal/Verse/Source/VerseCombat/Private/Weapons/VerseCombatEvents.cpp
@@ -0,0 +1,73 @@
+#include "Weapons/VerseCombatEvents.h"
+
+#include "Engine/World.h"
+#include "Events/VerseEventHub.h"
+#include "GameFramework/GameStateBase.h"
+
+namespace VerseCombatEvents
+{
+ float ServerTime(const UObject* WorldContext)
+ {
+ const UWorld* World = WorldContext ? WorldContext->GetWorld() : nullptr;
+ if (!World)
+ {
+ return 0.f;
+ }
+ if (const AGameStateBase* Gs = World->GetGameState())
+ {
+ return float(Gs->GetServerWorldTimeSeconds());
+ }
+ return World->GetTimeSeconds();
+ }
+
+ void RaiseNoise(const UObject* WorldContext, const FGameplayTag& Noise, int32 SourceId, const FVector& Location, float Loudness)
+ {
+ const UWorld* World = WorldContext ? WorldContext->GetWorld() : nullptr;
+ if (!World || World->GetNetMode() == NM_Client)
+ {
+ return;
+ }
+ if (UVerseEventHub* Hub = UVerseEventHub::Get(WorldContext))
+ {
+ FVerseNoiseEvent E;
+ E.Noise = Noise;
+ E.SourceId = SourceId;
+ E.Location = Location;
+ E.Loudness = Loudness;
+ E.ServerTime = ServerTime(WorldContext);
+ Hub->OnNoise.Broadcast(E);
+ }
+ }
+
+ void RaiseFire(const UObject* WorldContext, const FVerseFireEvent& Event)
+ {
+ if (UVerseEventHub* Hub = UVerseEventHub::Get(WorldContext))
+ {
+ Hub->OnFire.Broadcast(Event);
+ }
+ }
+
+ void RaisePenetration(const UObject* WorldContext, const FVersePenetrationEvent& Event)
+ {
+ if (UVerseEventHub* Hub = UVerseEventHub::Get(WorldContext))
+ {
+ Hub->OnPenetration.Broadcast(Event);
+ }
+ }
+
+ void RaiseReload(const UObject* WorldContext, const FVerseReloadEvent& Event)
+ {
+ if (UVerseEventHub* Hub = UVerseEventHub::Get(WorldContext))
+ {
+ Hub->OnReload.Broadcast(Event);
+ }
+ }
+
+ void RaiseGadget(const UObject* WorldContext, const FVerseGadgetEvent& Event)
+ {
+ if (UVerseEventHub* Hub = UVerseEventHub::Get(WorldContext))
+ {
+ Hub->OnGadget.Broadcast(Event);
+ }
+ }
+}
diff --git a/unreal/Verse/Source/VerseCombat/Private/Weapons/VerseCombatTags.cpp b/unreal/Verse/Source/VerseCombat/Private/Weapons/VerseCombatTags.cpp
new file mode 100644
index 0000000000..325f1d2a1f
--- /dev/null
+++ b/unreal/Verse/Source/VerseCombat/Private/Weapons/VerseCombatTags.cpp
@@ -0,0 +1,22 @@
+#include "Weapons/VerseCombatTags.h"
+
+namespace VerseCombatTags
+{
+ UE_DEFINE_GAMEPLAY_TAG_COMMENT(Presentation_Bolt_Amber, "Verse.Presentation.Bolt.Amber", "Own bolt colour");
+ UE_DEFINE_GAMEPLAY_TAG_COMMENT(Presentation_Bolt_Red, "Verse.Presentation.Bolt.Red", "Opponent bolt colour");
+
+ FLinearColor BoltColor(const FGameplayTag& Tag, bool bOwn)
+ {
+ static const FLinearColor Amber(1.0f, 0.55f, 0.05f, 1.f);
+ static const FLinearColor Red(0.95f, 0.06f, 0.04f, 1.f);
+ if (Tag == Presentation_Bolt_Amber)
+ {
+ return Amber;
+ }
+ if (Tag == Presentation_Bolt_Red)
+ {
+ return Red;
+ }
+ return bOwn ? Amber : Red;
+ }
+}
diff --git a/unreal/Verse/Source/VerseCombat/Private/Weapons/VerseDefinitionJson.cpp b/unreal/Verse/Source/VerseCombat/Private/Weapons/VerseDefinitionJson.cpp
new file mode 100644
index 0000000000..55568b7731
--- /dev/null
+++ b/unreal/Verse/Source/VerseCombat/Private/Weapons/VerseDefinitionJson.cpp
@@ -0,0 +1,677 @@
+#include "Weapons/VerseDefinitionJson.h"
+
+#include "Combat/VerseGadgetDefinition.h"
+#include "Combat/VerseWeaponDefinition.h"
+#include "Curves/CurveFloat.h"
+#include "Dom/JsonObject.h"
+#include "Dom/JsonValue.h"
+#include "GameplayTagContainer.h"
+#include "HAL/FileManager.h"
+#include "Misc/FileHelper.h"
+#include "Misc/Paths.h"
+#include "Policies/PrettyJsonPrintPolicy.h"
+#include "Serialization/JsonReader.h"
+#include "Serialization/JsonSerializer.h"
+#include "Serialization/JsonWriter.h"
+#include "UObject/EnumProperty.h"
+#include "UObject/TextProperty.h"
+#include "UObject/UnrealType.h"
+
+const TCHAR* FVerseDefinitionJson::WeaponSchema = TEXT("verse.weapon/1");
+const TCHAR* FVerseDefinitionJson::GadgetsSchema = TEXT("verse.gadgets/1");
+const TCHAR* FVerseDefinitionJson::AssetFolder = TEXT("/Game/Verse/Combat/Abilities/Data");
+
+namespace
+{
+ const FName NameVector2f(TEXT("Vector2f"));
+ const FName NameVector3f(TEXT("Vector3f"));
+ const FName NameCurve(TEXT("RuntimeFloatCurve"));
+ const FName NameTag(TEXT("GameplayTag"));
+ const FString SchemaKey(TEXT("$schema"));
+
+ /** The definition fields a JSON file carries: every edit property declared on the class itself. */
+ TArray<FProperty*> FieldsOf(const UClass* Class)
+ {
+ TArray<FProperty*> Out;
+ for (TFieldIterator<FProperty> It(Class, EFieldIteratorFlags::ExcludeSuper); It; ++It)
+ {
+ if (It->HasAnyPropertyFlags(CPF_Edit))
+ {
+ Out.Add(*It);
+ }
+ }
+ return Out;
+ }
+
+ UEnum* EnumOf(const FProperty* P)
+ {
+ if (const FEnumProperty* E = CastField<FEnumProperty>(P))
+ {
+ return E->GetEnum();
+ }
+ if (const FByteProperty* B = CastField<FByteProperty>(P))
+ {
+ return B->Enum;
+ }
+ return nullptr;
+ }
+
+ int64 GetEnumValue(const FProperty* P, const void* Ptr)
+ {
+ if (const FEnumProperty* E = CastField<FEnumProperty>(P))
+ {
+ return E->GetUnderlyingProperty()->GetSignedIntPropertyValue(Ptr);
+ }
+ return int64(*static_cast<const uint8*>(Ptr));
+ }
+
+ void SetEnumValue(const FProperty* P, void* Ptr, int64 Value)
+ {
+ if (const FEnumProperty* E = CastField<FEnumProperty>(P))
+ {
+ E->GetUnderlyingProperty()->SetIntPropertyValue(Ptr, Value);
+ return;
+ }
+ *static_cast<uint8*>(Ptr) = uint8(Value);
+ }
+
+ TSharedPtr<FJsonValue> ExportValue(const FProperty* P, const void* Ptr);
+
+ TSharedPtr<FJsonValue> Number(double V)
+ {
+ return MakeShared<FJsonValueNumber>(V);
+ }
+
+ TSharedPtr<FJsonValue> ExportValue(const FProperty* P, const void* Ptr)
+ {
+ if (const UEnum* Enum = EnumOf(P))
+ {
+ return MakeShared<FJsonValueString>(Enum->GetNameStringByValue(GetEnumValue(P, Ptr)));
+ }
+ if (const FBoolProperty* B = CastField<FBoolProperty>(P))
+ {
+ return MakeShared<FJsonValueBoolean>(B->GetPropertyValue(Ptr));
+ }
+ if (const FNumericProperty* N = CastField<FNumericProperty>(P))
+ {
+ return Number(N->IsFloatingPoint() ? N->GetFloatingPointPropertyValue(Ptr) : double(N->GetSignedIntPropertyValue(Ptr)));
+ }
+ if (CastField<FNameProperty>(P))
+ {
+ return MakeShared<FJsonValueString>(static_cast<const FName*>(Ptr)->ToString());
+ }
+ if (CastField<FTextProperty>(P))
+ {
+ return MakeShared<FJsonValueString>(static_cast<const FText*>(Ptr)->ToString());
+ }
+ if (const FStructProperty* S = CastField<FStructProperty>(P))
+ {
+ const FName Name = S->Struct->GetFName();
+ if (Name == NameVector2f)
+ {
+ const FVector2f& V = *static_cast<const FVector2f*>(Ptr);
+ return MakeShared<FJsonValueArray>(TArray<TSharedPtr<FJsonValue>>{Number(V.X), Number(V.Y)});
+ }
+ if (Name == NameVector3f)
+ {
+ const FVector3f& V = *static_cast<const FVector3f*>(Ptr);
+ return MakeShared<FJsonValueArray>(TArray<TSharedPtr<FJsonValue>>{Number(V.X), Number(V.Y), Number(V.Z)});
+ }
+ if (Name == NameCurve)
+ {
+ const FRuntimeFloatCurve& C = *static_cast<const FRuntimeFloatCurve*>(Ptr);
+ TArray<TSharedPtr<FJsonValue>> Keys;
+ if (const FRichCurve* Rich = C.GetRichCurveConst())
+ {
+ for (const FRichCurveKey& K : Rich->GetConstRefOfKeys())
+ {
+ Keys.Add(MakeShared<FJsonValueArray>(TArray<TSharedPtr<FJsonValue>>{Number(K.Time), Number(K.Value)}));
+ }
+ }
+ return MakeShared<FJsonValueArray>(Keys);
+ }
+ if (Name == NameTag)
+ {
+ const FGameplayTag& T = *static_cast<const FGameplayTag*>(Ptr);
+ return MakeShared<FJsonValueString>(T.IsValid() ? T.ToString() : FString());
+ }
+ }
+ if (const FMapProperty* M = CastField<FMapProperty>(P))
+ {
+ const UEnum* KeyEnum = EnumOf(M->KeyProp);
+ FScriptMapHelper Helper(M, Ptr);
+ // Deterministic order: by enum value.
+ TArray<TPair<int64, int32>> Order;
+ for (int32 I = 0; I < Helper.GetMaxIndex(); ++I)
+ {
+ if (Helper.IsValidIndex(I))
+ {
+ Order.Add({KeyEnum ? GetEnumValue(M->KeyProp, Helper.GetKeyPtr(I)) : int64(I), I});
+ }
+ }
+ Order.Sort([](const TPair<int64, int32>& A, const TPair<int64, int32>& B) { return A.Key < B.Key; });
+ TSharedRef<FJsonObject> Obj = MakeShared<FJsonObject>();
+ for (const TPair<int64, int32>& O : Order)
+ {
+ const FString Key = KeyEnum ? KeyEnum->GetNameStringByValue(O.Key) : FString::FromInt(O.Value);
+ Obj->SetField(Key, ExportValue(M->ValueProp, Helper.GetValuePtr(O.Value)));
+ }
+ return MakeShared<FJsonValueObject>(Obj);
+ }
+ return MakeShared<FJsonValueNull>();
+ }
+
+ bool ReadNumbers(const TSharedPtr<FJsonValue>& J, int32 Count, double* Out)
+ {
+ const TArray<TSharedPtr<FJsonValue>>* Arr = nullptr;
+ if (!J.IsValid() || !J->TryGetArray(Arr) || Arr->Num() != Count)
+ {
+ return false;
+ }
+ for (int32 I = 0; I < Count; ++I)
+ {
+ if (!(*Arr)[I].IsValid() || !(*Arr)[I]->TryGetNumber(Out[I]))
+ {
+ return false;
+ }
+ }
+ return true;
+ }
+
+ bool ImportValue(const FProperty* P, void* Ptr, const TSharedPtr<FJsonValue>& J, const FString& Path, TArray<FString>& Errors)
+ {
+ auto Fail = [&Errors, &Path](const TCHAR* Why)
+ {
+ Errors.Add(FString::Printf(TEXT("%s: %s"), *Path, Why));
+ return false;
+ };
+ if (!J.IsValid())
+ {
+ return Fail(TEXT("missing"));
+ }
+ if (const UEnum* Enum = EnumOf(P))
+ {
+ FString S;
+ if (!J->TryGetString(S))
+ {
+ return Fail(TEXT("expected an enum name"));
+ }
+ const int64 V = Enum->GetValueByNameString(S);
+ if (V == INDEX_NONE)
+ {
+ return Fail(TEXT("unknown enum entry"));
+ }
+ SetEnumValue(P, Ptr, V);
+ return true;
+ }
+ if (const FBoolProperty* B = CastField<FBoolProperty>(P))
+ {
+ bool V = false;
+ if (!J->TryGetBool(V))
+ {
+ return Fail(TEXT("expected a boolean"));
+ }
+ B->SetPropertyValue(Ptr, V);
+ return true;
+ }
+ if (const FNumericProperty* N = CastField<FNumericProperty>(P))
+ {
+ double V = 0.0;
+ if (!J->TryGetNumber(V))
+ {
+ return Fail(TEXT("expected a number"));
+ }
+ if (N->IsFloatingPoint())
+ {
+ N->SetFloatingPointPropertyValue(Ptr, V);
+ }
+ else
+ {
+ if (V != FMath::RoundToDouble(V))
+ {
+ return Fail(TEXT("expected an integer"));
+ }
+ if (CastField<FByteProperty>(N) && (V < 0.0 || V > 255.0))
+ {
+ return Fail(TEXT("out of range for uint8"));
+ }
+ N->SetIntPropertyValue(Ptr, int64(V));
+ }
+ return true;
+ }
+ if (CastField<FNameProperty>(P))
+ {
+ FString S;
+ if (!J->TryGetString(S))
+ {
+ return Fail(TEXT("expected a string"));
+ }
+ *static_cast<FName*>(Ptr) = FName(*S);
+ return true;
+ }
+ if (CastField<FTextProperty>(P))
+ {
+ FString S;
+ if (!J->TryGetString(S))
+ {
+ return Fail(TEXT("expected a string"));
+ }
+ *static_cast<FText*>(Ptr) = FText::FromString(S);
+ return true;
+ }
+ if (const FStructProperty* S = CastField<FStructProperty>(P))
+ {
+ const FName Name = S->Struct->GetFName();
+ if (Name == NameVector2f)
+ {
+ double V[2];
+ if (!ReadNumbers(J, 2, V))
+ {
+ return Fail(TEXT("expected [x, y]"));
+ }
+ *static_cast<FVector2f*>(Ptr) = FVector2f(float(V[0]), float(V[1]));
+ return true;
+ }
+ if (Name == NameVector3f)
+ {
+ double V[3];
+ if (!ReadNumbers(J, 3, V))
+ {
+ return Fail(TEXT("expected [x, y, z]"));
+ }
+ *static_cast<FVector3f*>(Ptr) = FVector3f(float(V[0]), float(V[1]), float(V[2]));
+ return true;
+ }
+ if (Name == NameCurve)
+ {
+ const TArray<TSharedPtr<FJsonValue>>* Keys = nullptr;
+ if (!J->TryGetArray(Keys) || Keys->Num() == 0)
+ {
+ return Fail(TEXT("expected [[x, y], ...] with at least one key"));
+ }
+ FRuntimeFloatCurve& C = *static_cast<FRuntimeFloatCurve*>(Ptr);
+ FRichCurve* Rich = C.GetRichCurve();
+ Rich->Reset();
+ for (const TSharedPtr<FJsonValue>& K : *Keys)
+ {
+ double V[2];
+ if (!ReadNumbers(K, 2, V))
+ {
+ return Fail(TEXT("a curve key must be [x, y]"));
+ }
+ const FKeyHandle H = Rich->AddKey(float(V[0]), float(V[1]));
+ Rich->SetKeyInterpMode(H, RCIM_Linear);
+ }
+ return true;
+ }
+ if (Name == NameTag)
+ {
+ FString Str;
+ if (!J->TryGetString(Str))
+ {
+ return Fail(TEXT("expected a tag name"));
+ }
+ FGameplayTag& T = *static_cast<FGameplayTag*>(Ptr);
+ T = Str.IsEmpty() ? FGameplayTag() : FGameplayTag::RequestGameplayTag(FName(*Str), false);
+ if (!Str.IsEmpty() && !T.IsValid())
+ {
+ return Fail(TEXT("unknown gameplay tag"));
+ }
+ return true;
+ }
+ return Fail(TEXT("unsupported struct"));
+ }
+ if (const FMapProperty* M = CastField<FMapProperty>(P))
+ {
+ const TSharedPtr<FJsonObject>* Obj = nullptr;
+ if (!J->TryGetObject(Obj))
+ {
+ return Fail(TEXT("expected an object"));
+ }
+ const UEnum* KeyEnum = EnumOf(M->KeyProp);
+ if (!KeyEnum)
+ {
+ return Fail(TEXT("unsupported map key"));
+ }
+ FScriptMapHelper Helper(M, Ptr);
+ Helper.EmptyValues();
+ bool bOk = true;
+ for (const TPair<FString, TSharedPtr<FJsonValue>>& Pair : (*Obj)->Values)
+ {
+ const int64 KeyValue = KeyEnum->GetValueByNameString(Pair.Key);
+ if (KeyValue == INDEX_NONE)
+ {
+ Errors.Add(FString::Printf(TEXT("%s.%s: unknown key"), *Path, *Pair.Key));
+ bOk = false;
+ continue;
+ }
+ const int32 Index = Helper.AddDefaultValue_Invalid_NeedsRehash();
+ SetEnumValue(M->KeyProp, Helper.GetKeyPtr(Index), KeyValue);
+ bOk &= ImportValue(M->ValueProp, Helper.GetValuePtr(Index), Pair.Value, Path + TEXT(".") + Pair.Key, Errors);
+ }
+ Helper.Rehash();
+ return bOk;
+ }
+ return Fail(TEXT("unsupported property type"));
+ }
+
+ bool ApplyObject(const FJsonObject& Json, UObject& Out, const TCHAR* Schema, TArray<FString>& Errors)
+ {
+ const int32 ErrorsBefore = Errors.Num();
+ FString SchemaValue;
+ if (Schema && (!Json.TryGetStringField(SchemaKey, SchemaValue) || SchemaValue != Schema))
+ {
+ Errors.Add(FString::Printf(TEXT("$schema must be \"%s\""), Schema));
+ }
+ const TArray<FProperty*> Fields = FieldsOf(Out.GetClass());
+ TSet<FString> Known;
+ Known.Add(SchemaKey);
+ for (const FProperty* P : Fields)
+ {
+ const FString Key = P->GetName();
+ Known.Add(Key);
+ ImportValue(P, P->ContainerPtrToValuePtr<void>(&Out), Json.TryGetField(Key), Key, Errors);
+ }
+ for (const TPair<FString, TSharedPtr<FJsonValue>>& Pair : Json.Values)
+ {
+ if (!Known.Contains(Pair.Key))
+ {
+ Errors.Add(FString::Printf(TEXT("%s: unknown field"), *Pair.Key));
+ }
+ }
+ return Errors.Num() == ErrorsBefore;
+ }
+
+ TSharedRef<FJsonObject> ExportObject(const UObject& Obj, const TCHAR* Schema)
+ {
+ TSharedRef<FJsonObject> Json = MakeShared<FJsonObject>();
+ if (Schema)
+ {
+ Json->SetStringField(SchemaKey, Schema);
+ }
+ for (const FProperty* P : FieldsOf(Obj.GetClass()))
+ {
+ Json->SetField(P->GetName(), ExportValue(P, P->ContainerPtrToValuePtr<void>(&Obj)));
+ }
+ return Json;
+ }
+
+ FString ToText(const TSharedRef<FJsonObject>& Obj)
+ {
+ FString Out;
+ const TSharedRef<TJsonWriter<TCHAR, TPrettyJsonPrintPolicy<TCHAR>>> Writer = TJsonWriterFactory<TCHAR, TPrettyJsonPrintPolicy<TCHAR>>::Create(&Out);
+ FJsonSerializer::Serialize(Obj, Writer);
+ return Out;
+ }
+
+ TSharedPtr<FJsonObject> Parse(const FString& Text, TArray<FString>& Errors)
+ {
+ TSharedPtr<FJsonObject> Obj;
+ const TSharedRef<TJsonReader<TCHAR>> Reader = TJsonReaderFactory<TCHAR>::Create(Text);
+ if (!FJsonSerializer::Deserialize(Reader, Obj) || !Obj.IsValid())
+ {
+ Errors.Add(TEXT("not a JSON object"));
+ return nullptr;
+ }
+ return Obj;
+ }
+
+ FString Pascal(const FName& Id)
+ {
+ TArray<FString> Parts;
+ Id.ToString().ParseIntoArray(Parts, TEXT("_"));
+ FString Out;
+ for (FString& P : Parts)
+ {
+ if (!P.IsEmpty())
+ {
+ Out += P.Left(1).ToUpper() + P.Mid(1);
+ }
+ }
+ return Out;
+ }
+}
+
+FString FVerseDefinitionJson::DataDir()
+{
+ return FPaths::Combine(FPaths::ProjectDir(), TEXT("Data"), TEXT("weapons"));
+}
+
+bool FVerseDefinitionJson::ApplyWeapon(const FJsonObject& Json, UVerseWeaponDefinition& Out, TArray<FString>& Errors)
+{
+ const int32 Before = Errors.Num();
+ ApplyObject(Json, Out, WeaponSchema, Errors);
+ CheckNames(Out.WeaponId, Out.DisplayName, Errors);
+ if (Out.MaxPenetrations > UVerseWeaponDefinition::MaxPenetrationsCap)
+ {
+ Errors.Add(TEXT("MaxPenetrations: above the contract cap of 3"));
+ }
+ if (Out.RPM <= 0.f)
+ {
+ Errors.Add(TEXT("RPM: must be positive"));
+ }
+ return Errors.Num() == Before;
+}
+
+bool FVerseDefinitionJson::ApplyWeaponText(const FString& Text, UVerseWeaponDefinition& Out, TArray<FString>& Errors)
+{
+ const TSharedPtr<FJsonObject> Obj = Parse(Text, Errors);
+ return Obj.IsValid() && ApplyWeapon(*Obj, Out, Errors);
+}
+
+TSharedRef<FJsonObject> FVerseDefinitionJson::ExportWeapon(const UVerseWeaponDefinition& W)
+{
+ return ExportObject(W, WeaponSchema);
+}
+
+FString FVerseDefinitionJson::ExportWeaponText(const UVerseWeaponDefinition& W)
+{
+ return ToText(ExportWeapon(W));
+}
+
+bool FVerseDefinitionJson::ApplyGadget(const FJsonObject& Json, UVerseGadgetDefinition& Out, TArray<FString>& Errors)
+{
+ const int32 Before = Errors.Num();
+ ApplyObject(Json, Out, nullptr, Errors);
+ CheckNames(Out.GadgetId, Out.DisplayName, Errors);
+ return Errors.Num() == Before;
+}
+
+TSharedRef<FJsonObject> FVerseDefinitionJson::ExportGadget(const UVerseGadgetDefinition& G)
+{
+ return ExportObject(G, nullptr);
+}
+
+bool FVerseDefinitionJson::LoadGadgetsText(const FString& Text, UObject* Outer, TArray<UVerseGadgetDefinition*>& Out, TArray<FString>& Errors)
+{
+ const int32 Before = Errors.Num();
+ const TSharedPtr<FJsonObject> Obj = Parse(Text, Errors);
+ if (!Obj.IsValid())
+ {
+ return false;
+ }
+ FString SchemaValue;
+ if (!Obj->TryGetStringField(SchemaKey, SchemaValue) || SchemaValue != GadgetsSchema)
+ {
+ Errors.Add(FString::Printf(TEXT("$schema must be \"%s\""), GadgetsSchema));
+ }
+ const TArray<TSharedPtr<FJsonValue>>* List = nullptr;
+ if (!Obj->TryGetArrayField(TEXT("gadgets"), List))
+ {
+ Errors.Add(TEXT("gadgets: expected an array"));
+ return false;
+ }
+ for (const TSharedPtr<FJsonValue>& V : *List)
+ {
+ const TSharedPtr<FJsonObject>* G = nullptr;
+ if (!V.IsValid() || !V->TryGetObject(G))
+ {
+ Errors.Add(TEXT("gadgets[]: expected an object"));
+ continue;
+ }
+ UVerseGadgetDefinition* Def = NewObject<UVerseGadgetDefinition>(Outer ? Outer : GetTransientPackage());
+ if (ApplyGadget(**G, *Def, Errors))
+ {
+ Out.Add(Def);
+ }
+ }
+ return Errors.Num() == Before;
+}
+
+bool FVerseDefinitionJson::CheckNames(const FName& Id, const FText& DisplayName, TArray<FString>& Errors)
+{
+ bool bOk = true;
+ const FString IdStr = Id.ToString();
+ if (Id.IsNone() || IdStr.IsEmpty())
+ {
+ Errors.Add(TEXT("id: empty"));
+ bOk = false;
+ }
+ for (const TCHAR C : IdStr)
+ {
+ if (!((C >= 'a' && C <= 'z') || (C >= '0' && C <= '9') || C == '_'))
+ {
+ Errors.Add(FString::Printf(TEXT("id \"%s\": only lower_snake_case ASCII"), *IdStr));
+ bOk = false;
+ break;
+ }
+ }
+ const FString Display = DisplayName.ToString();
+ if (Display.IsEmpty())
+ {
+ Errors.Add(TEXT("DisplayName: empty"));
+ bOk = false;
+ }
+ for (const TCHAR C : Display)
+ {
+ if (!(FChar::IsAlpha(C) || FChar::IsDigit(C) || C == ' ' || C == '-'))
+ {
+ Errors.Add(FString::Printf(TEXT("DisplayName \"%s\": letters, digits, spaces and hyphens only"), *Display));
+ bOk = false;
+ break;
+ }
+ }
+ return bOk;
+}
+
+TArray<UVerseWeaponDefinition*> FVerseDefinitionJson::LoadAllWeapons(UObject* Outer, TArray<FString>& Errors)
+{
+ TArray<UVerseWeaponDefinition*> Out;
+ TArray<FString> Files;
+ IFileManager::Get().FindFiles(Files, *FPaths::Combine(DataDir(), TEXT("*.json")), true, false);
+ Files.Sort();
+ for (const FString& File : Files)
+ {
+ if (File.Equals(TEXT("gadgets.json"), ESearchCase::IgnoreCase))
+ {
+ continue;
+ }
+ FString Text;
+ if (!FFileHelper::LoadFileToString(Text, *FPaths::Combine(DataDir(), File)))
+ {
+ Errors.Add(FString::Printf(TEXT("%s: cannot read"), *File));
+ continue;
+ }
+ UVerseWeaponDefinition* Def = NewObject<UVerseWeaponDefinition>(Outer ? Outer : GetTransientPackage());
+ TArray<FString> FileErrors;
+ if (ApplyWeaponText(Text, *Def, FileErrors))
+ {
+ Out.Add(Def);
+ }
+ for (const FString& E : FileErrors)
+ {
+ Errors.Add(FString::Printf(TEXT("%s: %s"), *File, *E));
+ }
+ }
+ return Out;
+}
+
+bool FVerseDefinitionJson::JsonEqual(const TSharedPtr<FJsonValue>& A, const TSharedPtr<FJsonValue>& B, const FString& Path,
+ TArray<FString>& Diffs, double Tolerance)
+{
+ if (!A.IsValid() || !B.IsValid())
+ {
+ if (A.IsValid() != B.IsValid())
+ {
+ Diffs.Add(Path + TEXT(": missing on one side"));
+ return false;
+ }
+ return true;
+ }
+ if (A->Type != B->Type)
+ {
+ Diffs.Add(Path + TEXT(": type differs"));
+ return false;
+ }
+ switch (A->Type)
+ {
+ case EJson::Number:
+ if (FMath::Abs(A->AsNumber() - B->AsNumber()) > Tolerance)
+ {
+ Diffs.Add(FString::Printf(TEXT("%s: %g != %g"), *Path, A->AsNumber(), B->AsNumber()));
+ return false;
+ }
+ return true;
+ case EJson::String:
+ if (A->AsString() != B->AsString())
+ {
+ Diffs.Add(FString::Printf(TEXT("%s: \"%s\" != \"%s\""), *Path, *A->AsString(), *B->AsString()));
+ return false;
+ }
+ return true;
+ case EJson::Boolean:
+ if (A->AsBool() != B->AsBool())
+ {
+ Diffs.Add(Path + TEXT(": boolean differs"));
+ return false;
+ }
+ return true;
+ case EJson::Array:
+ {
+ const TArray<TSharedPtr<FJsonValue>>& X = A->AsArray();
+ const TArray<TSharedPtr<FJsonValue>>& Y = B->AsArray();
+ if (X.Num() != Y.Num())
+ {
+ Diffs.Add(FString::Printf(TEXT("%s: %d != %d entries"), *Path, X.Num(), Y.Num()));
+ return false;
+ }
+ bool bOk = true;
+ for (int32 I = 0; I < X.Num(); ++I)
+ {
+ bOk &= JsonEqual(X[I], Y[I], FString::Printf(TEXT("%s[%d]"), *Path, I), Diffs, Tolerance);
+ }
+ return bOk;
+ }
+ case EJson::Object:
+ {
+ const TSharedPtr<FJsonObject> X = A->AsObject();
+ const TSharedPtr<FJsonObject> Y = B->AsObject();
+ bool bOk = true;
+ for (const TPair<FString, TSharedPtr<FJsonValue>>& P : X->Values)
+ {
+ bOk &= JsonEqual(P.Value, Y->TryGetField(P.Key), Path + TEXT(".") + P.Key, Diffs, Tolerance);
+ }
+ for (const TPair<FString, TSharedPtr<FJsonValue>>& P : Y->Values)
+ {
+ if (!X->HasField(P.Key))
+ {
+ Diffs.Add(Path + TEXT(".") + P.Key + TEXT(": missing on one side"));
+ bOk = false;
+ }
+ }
+ return bOk;
+ }
+ default:
+ return true;
+ }
+}
+
+FString FVerseDefinitionJson::WeaponAssetName(const FName& WeaponId)
+{
+ return TEXT("DA_Weapon_") + Pascal(WeaponId);
+}
+
+FString FVerseDefinitionJson::GadgetAssetName(const FName& GadgetId)
+{
+ return TEXT("DA_Gadget_") + Pascal(GadgetId);
+}
diff --git a/unreal/Verse/Source/VerseCombat/Private/Weapons/VerseFirePrediction.cpp b/unreal/Verse/Source/VerseCombat/Private/Weapons/VerseFirePrediction.cpp
new file mode 100644
index 0000000000..cdb80074f4
--- /dev/null
+++ b/unreal/Verse/Source/VerseCombat/Private/Weapons/VerseFirePrediction.cpp
@@ -0,0 +1,39 @@
+#include "Weapons/VerseFirePrediction.h"
+
+FVerseShotReconcile FVerseFirePredictor::Confirm(uint16 Counter, EVerseShotResult Result)
+{
+ FVerseShotReconcile Out;
+ const int32 Index = Pending.IndexOfByPredicate([Counter](const FVersePredictedShot& S) { return S.Counter == Counter; });
+ if (Index == INDEX_NONE)
+ {
+ return Out;
+ }
+ Out.bKnown = true;
+ if (Result == EVerseShotResult::Rejected)
+ {
+ Out.bRemoveBolt = true;
+ Out.RefundRounds = 1;
+ }
+ Pending.RemoveAt(Index);
+ return Out;
+}
+
+TArray<uint16> FVerseFirePredictor::Expire(float Now)
+{
+ TArray<uint16> Expired;
+ Pending.RemoveAll([Now, &Expired](const FVersePredictedShot& S)
+ {
+ if (Now - S.Time > TimeoutS)
+ {
+ Expired.Add(S.Counter);
+ return true;
+ }
+ return false;
+ });
+ return Expired;
+}
+
+const FVersePredictedShot* FVerseFirePredictor::Find(uint16 Counter) const
+{
+ return Pending.FindByPredicate([Counter](const FVersePredictedShot& S) { return S.Counter == Counter; });
+}
diff --git a/unreal/Verse/Source/VerseCombat/Private/Weapons/VerseImportDefinitionsCommandlet.cpp b/unreal/Verse/Source/VerseCombat/Private/Weapons/VerseImportDefinitionsCommandlet.cpp
new file mode 100644
index 0000000000..7d486da2bb
--- /dev/null
+++ b/unreal/Verse/Source/VerseCombat/Private/Weapons/VerseImportDefinitionsCommandlet.cpp
@@ -0,0 +1,133 @@
+#include "Weapons/VerseImportDefinitionsCommandlet.h"
+
+#include "Combat/VerseGadgetDefinition.h"
+#include "Combat/VerseWeaponDefinition.h"
+#include "Dom/JsonObject.h"
+#include "Dom/JsonValue.h"
+#include "Misc/FileHelper.h"
+#include "Misc/PackageName.h"
+#include "Misc/Paths.h"
+#include "UObject/Package.h"
+#include "UObject/SavePackage.h"
+#include "VerseLog.h"
+#include "Weapons/VerseDefinitionJson.h"
+#include "Weapons/VerseWeaponRegistry.h"
+
+UVerseImportDefinitionsCommandlet::UVerseImportDefinitionsCommandlet()
+{
+ IsClient = false;
+ IsEditor = true;
+ IsServer = false;
+ LogToConsole = true;
+}
+
+namespace
+{
+ template <typename T>
+ bool SaveDefinition(const FString& AssetName, TFunctionRef<bool(T&, TArray<FString>&)> Fill, TArray<FString>& Errors)
+ {
+#if WITH_EDITOR
+ const FString PackageName = FString::Printf(TEXT("%s/%s"), FVerseDefinitionJson::AssetFolder, *AssetName);
+ UPackage* Package = CreatePackage(*PackageName);
+ Package->FullyLoad();
+ T* Asset = FindObject<T>(Package, *AssetName);
+ if (!Asset)
+ {
+ Asset = NewObject<T>(Package, *AssetName, RF_Public | RF_Standalone | RF_Transactional);
+ }
+ if (!Fill(*Asset, Errors))
+ {
+ return false;
+ }
+ Package->MarkPackageDirty();
+ const FString File = FPackageName::LongPackageNameToFilename(PackageName, FPackageName::GetAssetPackageExtension());
+ FSavePackageArgs Args;
+ Args.TopLevelFlags = RF_Public | RF_Standalone;
+ Args.SaveFlags = SAVE_NoError;
+ if (!UPackage::SavePackage(Package, Asset, *File, Args))
+ {
+ Errors.Add(FString::Printf(TEXT("%s: save failed"), *File));
+ return false;
+ }
+ UE_LOG(LogVerseCombat, Display, TEXT("saved %s"), *File);
+ return true;
+#else
+ Errors.Add(TEXT("the importer needs an editor build"));
+ return false;
+#endif
+ }
+}
+
+int32 UVerseImportDefinitionsCommandlet::Main(const FString& Params)
+{
+ const bool bCheckOnly = Params.Contains(TEXT("-check"));
+ TArray<FString> Errors;
+ TArray<FString> Diffs;
+
+ const TArray<UVerseWeaponDefinition*> Weapons = FVerseDefinitionJson::LoadAllWeapons(GetTransientPackage(), Errors);
+ for (const UVerseWeaponDefinition* W : Weapons)
+ {
+ const TSharedRef<FJsonObject> Want = FVerseDefinitionJson::ExportWeapon(*W);
+ const FString AssetName = FVerseDefinitionJson::WeaponAssetName(W->WeaponId);
+ if (bCheckOnly)
+ {
+ const UVerseWeaponDefinition* Asset = FVerseWeaponRegistry::LoadWeaponAsset(W->WeaponId);
+ if (!Asset)
+ {
+ Diffs.Add(AssetName + TEXT(": missing"));
+ continue;
+ }
+ FVerseDefinitionJson::JsonEqual(MakeShared<FJsonValueObject>(Want),
+ MakeShared<FJsonValueObject>(FVerseDefinitionJson::ExportWeapon(*Asset)), AssetName, Diffs);
+ continue;
+ }
+ SaveDefinition<UVerseWeaponDefinition>(AssetName, [&Want](UVerseWeaponDefinition& Asset, TArray<FString>& E)
+ {
+ return FVerseDefinitionJson::ApplyWeapon(*Want, Asset, E);
+ }, Errors);
+ }
+
+ FString GadgetText;
+ TArray<UVerseGadgetDefinition*> Gadgets;
+ if (!FFileHelper::LoadFileToString(GadgetText, *FPaths::Combine(FVerseDefinitionJson::DataDir(), TEXT("gadgets.json"))))
+ {
+ Errors.Add(TEXT("gadgets.json: cannot read"));
+ }
+ else
+ {
+ FVerseDefinitionJson::LoadGadgetsText(GadgetText, GetTransientPackage(), Gadgets, Errors);
+ }
+ for (const UVerseGadgetDefinition* G : Gadgets)
+ {
+ const TSharedRef<FJsonObject> Want = FVerseDefinitionJson::ExportGadget(*G);
+ const FString AssetName = FVerseDefinitionJson::GadgetAssetName(G->GadgetId);
+ if (bCheckOnly)
+ {
+ const UVerseGadgetDefinition* Asset = FVerseWeaponRegistry::LoadGadgetAsset(G->GadgetId);
+ if (!Asset)
+ {
+ Diffs.Add(AssetName + TEXT(": missing"));
+ continue;
+ }
+ FVerseDefinitionJson::JsonEqual(MakeShared<FJsonValueObject>(Want),
+ MakeShared<FJsonValueObject>(FVerseDefinitionJson::ExportGadget(*Asset)), AssetName, Diffs);
+ continue;
+ }
+ SaveDefinition<UVerseGadgetDefinition>(AssetName, [&Want](UVerseGadgetDefinition& Asset, TArray<FString>& E)
+ {
+ return FVerseDefinitionJson::ApplyGadget(*Want, Asset, E);
+ }, Errors);
+ }
+
+ for (const FString& E : Errors)
+ {
+ UE_LOG(LogVerseCombat, Error, TEXT("import: %s"), *E);
+ }
+ for (const FString& D : Diffs)
+ {
+ UE_LOG(LogVerseCombat, Error, TEXT("drift: %s"), *D);
+ }
+ UE_LOG(LogVerseCombat, Display, TEXT("VerseImportDefinitions: %d weapons, %d gadgets, %d errors, %d diffs"), Weapons.Num(),
+ Gadgets.Num(), Errors.Num(), Diffs.Num());
+ return (Errors.Num() == 0 && Diffs.Num() == 0) ? 0 : 1;
+}
diff --git a/unreal/Verse/Source/VerseCombat/Private/Weapons/VerseRecoil.cpp b/unreal/Verse/Source/VerseCombat/Private/Weapons/VerseRecoil.cpp
new file mode 100644
index 0000000000..d2eb8ed574
--- /dev/null
+++ b/unreal/Verse/Source/VerseCombat/Private/Weapons/VerseRecoil.cpp
@@ -0,0 +1,122 @@
+#include "Weapons/VerseRecoil.h"
+
+#include "Combat/VerseWeaponDefinition.h"
+#include "VerseRng.h"
+
+float FVerseRecoilState::Multiplier(const UVerseWeaponDefinition& W, EVerseStance Stance, float AdsBlend)
+{
+ const float* StanceMul = W.RecoilStanceMultiplier.Find(Stance);
+ const float S = StanceMul ? *StanceMul : 1.f;
+ return S * FMath::Lerp(1.f, W.RecoilAdsMultiplier, FMath::Clamp(AdsBlend, 0.f, 1.f));
+}
+
+float FVerseRecoilState::MinMultiplier(const UVerseWeaponDefinition& W)
+{
+ float Min = TNumericLimits<float>::Max();
+ for (const EVerseStance Stance : {EVerseStance::Stand, EVerseStance::Crouch, EVerseStance::Prone, EVerseStance::Slide})
+ {
+ Min = FMath::Min(Min, Multiplier(W, Stance, 0.f));
+ Min = FMath::Min(Min, Multiplier(W, Stance, 1.f));
+ }
+ return Min;
+}
+
+int32 FVerseRecoilState::ShotIndexAt(const UVerseWeaponDefinition& W, float Now) const
+{
+ return (Now - LastShotTime >= W.PatternResetTime) ? 0 : ShotIndex;
+}
+
+void FVerseRecoilState::BeginShot(const UVerseWeaponDefinition& W, float Now)
+{
+ ShotIndex = ShotIndexAt(W, Now);
+}
+
+FVector2f FVerseRecoilState::KickAt(const UVerseWeaponDefinition& W, int32 N, float Mul, uint32 Seed)
+{
+ const FVector2f P = W.PatternAt(N);
+ FVerseRng Rng(Seed, uint64(FMath::Max(0, N)), EVerseRngSalt::Recoil);
+ const FVector2D U = Rng.UnitDisk();
+ const float Random = W.RecoilRandomFraction * P.Size();
+ return Mul * (P + Random * FVector2f(float(U.X), float(U.Y)));
+}
+
+FVector2f FVerseRecoilState::KickFor(const UVerseWeaponDefinition& W, float Mul, uint32 Seed) const
+{
+ return KickAt(W, ShotIndex, Mul, Seed);
+}
+
+void FVerseRecoilState::OnShot(const FVector2f& Kick, float Now)
+{
+ // Whatever of the previous kick is still pending is applied with the new one.
+ const FVector2f Remainder = KickTotal - KickApplied;
+ KickTotal = Kick + Remainder;
+ KickApplied = FVector2f::ZeroVector;
+ KickStartTime = Now;
+
+ Accumulated += Kick;
+ ++ShotIndex;
+ LastShotTime = Now;
+}
+
+void FVerseRecoilState::OnLookInput(FVector2f& InOutDelta)
+{
+ // Pitch: a downward input (negative) pulls the climb back, never below zero.
+ if (InOutDelta.X < 0.f && Accumulated.X > 0.f)
+ {
+ Accumulated.X = FMath::Max(0.f, Accumulated.X - FMath::Abs(InOutDelta.X));
+ }
+ else if (InOutDelta.X > 0.f && Accumulated.X < 0.f)
+ {
+ Accumulated.X = FMath::Min(0.f, Accumulated.X + FMath::Abs(InOutDelta.X));
+ }
+ // Yaw: input against the sign of A_y compensates.
+ if (InOutDelta.Y < 0.f && Accumulated.Y > 0.f)
+ {
+ Accumulated.Y = FMath::Max(0.f, Accumulated.Y - FMath::Abs(InOutDelta.Y));
+ }
+ else if (InOutDelta.Y > 0.f && Accumulated.Y < 0.f)
+ {
+ Accumulated.Y = FMath::Min(0.f, Accumulated.Y + FMath::Abs(InOutDelta.Y));
+ }
+}
+
+FVector2f FVerseRecoilState::TickKick(const UVerseWeaponDefinition& W, float Now)
+{
+ if (KickTotal.IsNearlyZero(1e-8f))
+ {
+ return FVector2f::ZeroVector;
+ }
+ const float Tk = FMath::Max(W.RecoilKickTime, UE_SMALL_NUMBER);
+ const float T = FMath::Clamp((Now - KickStartTime) / Tk, 0.f, 1.f);
+ const float Eased = 1.f - FMath::Square(1.f - T); // ease-out
+ const FVector2f Target = KickTotal * Eased;
+ const FVector2f Delta = Target - KickApplied;
+ KickApplied = Target;
+ if (T >= 1.f)
+ {
+ KickTotal = FVector2f::ZeroVector;
+ KickApplied = FVector2f::ZeroVector;
+ }
+ return Delta;
+}
+
+FVector2f FVerseRecoilState::TickRecovery(const UVerseWeaponDefinition& W, float Now, float Dt)
+{
+ if (Now - LastShotTime < W.RecoilRecoveryDelay)
+ {
+ return FVector2f::ZeroVector;
+ }
+ const float Len = Accumulated.Size();
+ if (Len <= 0.f)
+ {
+ return FVector2f::ZeroVector;
+ }
+ const float Step = FMath::Min(Len, W.RecoilRecoveryRate * FMath::Max(0.f, Dt));
+ const FVector2f Removed = Accumulated * (Step / Len);
+ Accumulated -= Removed;
+ if (Step >= Len)
+ {
+ Accumulated = FVector2f::ZeroVector;
+ }
+ return Removed;
+}
diff --git a/unreal/Verse/Source/VerseCombat/Private/Weapons/VerseSpread.cpp b/unreal/Verse/Source/VerseCombat/Private/Weapons/VerseSpread.cpp
new file mode 100644
index 0000000000..a4d9429eb6
--- /dev/null
+++ b/unreal/Verse/Source/VerseCombat/Private/Weapons/VerseSpread.cpp
@@ -0,0 +1,190 @@
+#include "Weapons/VerseSpread.h"
+
+#include "Combat/VerseWeaponDefinition.h"
+#include "VerseRng.h"
+
+namespace
+{
+ FVector2f SpreadBaseFor(const UVerseWeaponDefinition& W, EVerseStance Stance)
+ {
+ if (const FVector2f* Found = W.SpreadBase.Find(Stance))
+ {
+ return *Found;
+ }
+ if (const FVector2f* Stand = W.SpreadBase.Find(EVerseStance::Stand))
+ {
+ return *Stand;
+ }
+ return FVector2f::ZeroVector;
+ }
+}
+
+bool FVerseSpread::IsFirstShot(const UVerseWeaponDefinition& W, float Now) const
+{
+ return Now - LastShotTime >= W.FirstShotRestTime;
+}
+
+float FVerseSpread::RestingSigma(const UVerseWeaponDefinition& W, const FVerseSpreadInput& In, float BloomDeg)
+{
+ const float Ads = FMath::Clamp(In.AdsBlend, 0.f, 1.f);
+ const FVector2f Base = SpreadBaseFor(W, In.Stance);
+ float Sigma = FMath::Lerp(Base.X, Base.Y, Ads);
+ Sigma += W.SpreadMovePerMps * FMath::Max(0.f, In.HorizontalSpeedMps);
+ Sigma += In.bAirborne ? W.SpreadAirborne : 0.f;
+ Sigma += FMath::Max(0.f, BloomDeg);
+ return FMath::Max(0.f, Sigma);
+}
+
+float FVerseSpread::SigmaFor(const UVerseWeaponDefinition& W, const FVerseSpreadInput& In, float Now) const
+{
+ if (IsFirstShot(W, Now))
+ {
+ const float Ads = FMath::Clamp(In.AdsBlend, 0.f, 1.f);
+ return FMath::Max(0.f, FMath::Lerp(W.FirstShotSpread.X, W.FirstShotSpread.Y, Ads));
+ }
+ return RestingSigma(W, In, Bloom);
+}
+
+void FVerseSpread::DecayTo(const UVerseWeaponDefinition& W, float Now, float Dt)
+{
+ if (Now - LastShotTime >= W.BloomRecoveryDelay)
+ {
+ Bloom = FMath::Max(0.f, Bloom - W.BloomRecoveryRate * FMath::Max(0.f, Dt));
+ }
+}
+
+void FVerseSpread::DecayUntilShot(const UVerseWeaponDefinition& W, float Now)
+{
+ const float Elapsed = Now - (LastShotTime + W.BloomRecoveryDelay);
+ if (Elapsed > 0.f)
+ {
+ Bloom = FMath::Max(0.f, Bloom - W.BloomRecoveryRate * Elapsed);
+ }
+}
+
+void FVerseSpread::OnShot(const UVerseWeaponDefinition& W, float Now)
+{
+ if (IsFirstShot(W, Now))
+ {
+ Bloom = 0.f;
+ }
+ Bloom = FMath::Min(W.BloomMax, Bloom + W.BloomPerShot);
+ LastShotTime = Now;
+}
+
+uint32 FVerseSpread::ShotSeed(uint32 ShooterNetId, uint16 ShotCounter, uint32 MatchSeed)
+{
+ return FVerseRng::Hash(ShooterNetId, uint32(ShotCounter), MatchSeed);
+}
+
+FVector FVerseSpread::ShotDirection(const FVector& Forward, float SigmaDeg, uint32 Seed, int32 ShotIndex)
+{
+ FVerseRng Rng(Seed, uint64(FMath::Max(0, ShotIndex)), EVerseRngSalt::Spread);
+ return Rng.ConeDirection(Forward, FMath::Max(0.f, SigmaDeg));
+}
+
+bool FVerseSpread::ValidateDirection(const FVector& Dir, const FVector& ServerForward, float SigmaDeg, uint32 Seed, int32 ShotIndex)
+{
+ const FVector A = Dir.GetSafeNormal();
+ const FVector F = ServerForward.GetSafeNormal(UE_SMALL_NUMBER, FVector::ForwardVector);
+ if (A.IsNearlyZero())
+ {
+ return false;
+ }
+ auto AngleDeg = [](const FVector& X, const FVector& Y)
+ {
+ return FMath::RadiansToDegrees(FMath::Acos(FMath::Clamp(FVector::DotProduct(X, Y), -1.0, 1.0)));
+ };
+ // FindBestAxisVectors switches its reference axis where |Z| meets max(|X|, |Y|); close to that,
+ // a forward a little off the client's may draw from another basis.
+ const double Horizontal = FMath::Max(FMath::Abs(F.X), FMath::Abs(F.Y));
+ if (FMath::Abs(FMath::Abs(F.Z) - Horizontal) < 0.1)
+ {
+ return AngleDeg(A, F) <= double(SigmaDeg) + DirectionToleranceDeg;
+ }
+ const FVector Expected = ShotDirection(F, SigmaDeg, Seed, ShotIndex);
+ return AngleDeg(A, Expected) <= DirectionToleranceDeg;
+}
+
+bool FVerseSpread::ValidateFire(const FVector& Origin, const FVector& Dir, const FVector& RewoundEye,
+ const FVector& ServerForward, float SigmaDeg)
+{
+ if (Dir.SizeSquared() < UE_KINDA_SMALL_NUMBER)
+ {
+ return false;
+ }
+ if (FVector::Dist(Origin, RewoundEye) > OriginToleranceCm)
+ {
+ return false;
+ }
+ const FVector A = Dir.GetSafeNormal();
+ const FVector B = ServerForward.GetSafeNormal();
+ const double CosAngle = FMath::Clamp(FVector::DotProduct(A, B), -1.0, 1.0);
+ const double AngleDeg = FMath::RadiansToDegrees(FMath::Acos(CosAngle));
+ return AngleDeg <= double(SigmaDeg) + DirectionToleranceDeg;
+}
+
+void FVerseFireCadence::Collect(const UVerseWeaponDefinition& W, bool bTriggerDown, float TickStart, float Now,
+ int32 RoundsAvailable, TArray<float>& OutShotTimes)
+{
+ const float Interval = W.FireInterval();
+ const bool bPressed = bTriggerDown && !bTriggerWasDown;
+ bTriggerWasDown = bTriggerDown;
+ if (Interval <= 0.f)
+ {
+ return;
+ }
+
+ auto TryShot = [&](float At) -> bool
+ {
+ if (RoundsAvailable <= 0 || At > Now)
+ {
+ return false;
+ }
+ OutShotTimes.Add(At);
+ --RoundsAvailable;
+ NextShotTime = At + Interval;
+ return true;
+ };
+
+ switch (W.FireMode)
+ {
+ case EVerseFireMode::Semi:
+ if (bPressed)
+ {
+ TryShot(FMath::Max(NextShotTime, TickStart));
+ }
+ break;
+ case EVerseFireMode::Burst:
+ if (bPressed && BurstLeft <= 0 && NextShotTime <= Now)
+ {
+ BurstLeft = FMath::Max(1, W.BurstCount);
+ NextShotTime = FMath::Max(NextShotTime, TickStart);
+ }
+ while (BurstLeft > 0 && TryShot(NextShotTime))
+ {
+ --BurstLeft;
+ }
+ if (RoundsAvailable <= 0)
+ {
+ BurstLeft = 0;
+ }
+ break;
+ case EVerseFireMode::Auto:
+ default:
+ if (bTriggerDown)
+ {
+ float At = FMath::Max(NextShotTime, TickStart);
+ while (TryShot(At))
+ {
+ At = NextShotTime;
+ }
+ }
+ break;
+ }
+}
+
+bool FVerseFireCadence::AllowsShotAt(const UVerseWeaponDefinition& W, float Time) const
+{
+ return Time + 0.001f >= NextShotTime;
+}
diff --git a/unreal/Verse/Source/VerseCombat/Private/Weapons/VerseWeaponComponent.cpp b/unreal/Verse/Source/VerseCombat/Private/Weapons/VerseWeaponComponent.cpp
new file mode 100644
index 0000000000..a6f0d4567b
--- /dev/null
+++ b/unreal/Verse/Source/VerseCombat/Private/Weapons/VerseWeaponComponent.cpp
@@ -0,0 +1,504 @@
+#include "Weapons/VerseWeaponComponent.h"
+
+#include "Combat/VerseWeaponDefinition.h"
+#include "Damage/VerseCombatStateComponent.h"
+#include "Damage/VerseDamageService.h"
+#include "Engine/World.h"
+#include "Events/VerseEventHub.h"
+#include "GameFramework/PlayerController.h"
+#include "GameFramework/Pawn.h"
+#include "Inventory/VerseInventoryComponent.h"
+#include "LagComp/VerseLagCompensation.h"
+#include "Movement/VerseMovementQuery.h"
+#include "Net/Core/PushModel/PushModel.h"
+#include "Net/UnrealNetwork.h"
+#include "Projectiles/VerseProjectileManager.h"
+#include "Stubs/VerseNullStubs.h"
+#include "VerseGameplayTags.h"
+#include "Weapons/VerseCombatEvents.h"
+#include "HAL/PlatformTime.h"
+#include "VerseRng.h"
+
+namespace
+{
+ const IVerseMovementQuery& MovementOf(const AActor* Actor)
+ {
+ if (Actor)
+ {
+ for (UActorComponent* C : Actor->GetComponents())
+ {
+ if (const IVerseMovementQuery* Q = Cast<IVerseMovementQuery>(C))
+ {
+ return *Q;
+ }
+ }
+ }
+ return *GetDefault<UVerseNullMovementQuery>();
+ }
+
+ bool IsLocalOwner(const AActor* Owner)
+ {
+ const APawn* Pawn = Cast<APawn>(Owner);
+ return Pawn && Pawn->IsLocallyControlled();
+ }
+}
+
+FOnVerseAnyShotRejected UVerseWeaponComponent::OnAnyShotRejected;
+
+UVerseWeaponComponent::UVerseWeaponComponent()
+{
+ PrimaryComponentTick.bCanEverTick = false;
+ SetIsReplicatedByDefault(true);
+}
+
+void UVerseWeaponComponent::GetLifetimeReplicatedProps(TArray<FLifetimeProperty>& OutLifetimeProps) const
+{
+ Super::GetLifetimeReplicatedProps(OutLifetimeProps);
+ FDoRepLifetimeParams Params;
+ Params.bIsPushBased = true;
+ DOREPLIFETIME_WITH_PARAMS_FAST(UVerseWeaponComponent, AdsBlend, Params);
+ DOREPLIFETIME_WITH_PARAMS_FAST(UVerseWeaponComponent, MatchSeed, Params);
+}
+
+void UVerseWeaponComponent::BeginPlay()
+{
+ Super::BeginPlay();
+ const AActor* Owner = GetOwner();
+ if (Owner && Owner->HasAuthority() && MatchSeed == 0)
+ {
+ // One seed per spawn unless the game mode sets a match seed; clients get it with the actor.
+ SetMatchSeed(FVerseRng::Hash(uint32(FPlatformTime::Cycles()), uint32(GetUniqueID()), uint32(FMath::Rand())));
+ }
+}
+
+void UVerseWeaponComponent::SetMatchSeed(uint32 Seed)
+{
+ MatchSeed = Seed;
+ MARK_PROPERTY_DIRTY_FROM_NAME(UVerseWeaponComponent, MatchSeed, this);
+}
+
+UVerseWeaponComponent* UVerseWeaponComponent::FindOn(const AActor* Actor)
+{
+ return Actor ? Actor->FindComponentByClass<UVerseWeaponComponent>() : nullptr;
+}
+
+UVerseInventoryComponent* UVerseWeaponComponent::GetInventory() const
+{
+ return UVerseInventoryComponent::FindOn(GetOwner());
+}
+
+const UVerseWeaponDefinition* UVerseWeaponComponent::GetActiveDefinition() const
+{
+ const UVerseInventoryComponent* Inv = GetInventory();
+ return Inv ? Inv->GetActiveWeapon() : nullptr;
+}
+
+int32 UVerseWeaponComponent::GetShooterId() const
+{
+ return VerseCombatIds::IdOf(GetOwner());
+}
+
+void UVerseWeaponComponent::ResyncPredictedSlot()
+{
+ const UVerseInventoryComponent* Inv = GetInventory();
+ const FVerseWeaponSlotState* S = Inv ? Inv->GetActiveState() : nullptr;
+ if (S)
+ {
+ PredictedSlot = *S;
+ PredictedWeaponId = S->Definition ? S->Definition->WeaponId : NAME_None;
+ }
+}
+
+void UVerseWeaponComponent::StepAds(bool bAdsHeld, float Dt)
+{
+ const UVerseWeaponDefinition* W = GetActiveDefinition();
+ const float Rate = (W && W->AdsTime > 0.f) ? 1.f / W->AdsTime : 1000.f;
+ const float Current = GetAdsBlend01();
+ const float Next = FMath::Clamp(Current + (bAdsHeld ? 1.f : -1.f) * Rate * Dt, 0.f, 1.f);
+ const uint8 Q = uint8(FMath::RoundToInt(Next * 255.f));
+ if (Q != AdsBlend)
+ {
+ AdsBlend = Q;
+ MARK_PROPERTY_DIRTY_FROM_NAME(UVerseWeaponComponent, AdsBlend, this);
+ }
+}
+
+FRotator UVerseWeaponComponent::StepFire(const FVerseFireContext& Ctx, TArray<FVerseShotOut>* OutShots)
+{
+ const UVerseWeaponDefinition* W = GetActiveDefinition();
+ if (!W)
+ {
+ return FRotator::ZeroRotator;
+ }
+ AActor* Owner = GetOwner();
+ const bool bAuthority = Owner && Owner->HasAuthority();
+ const UVerseInventoryComponent* Inv = GetInventory();
+
+ // The predicted magazine follows the replicated one whenever nothing is in flight.
+ if (bAuthority || Predictor.NumPending() == 0 || PredictedWeaponId != W->WeaponId)
+ {
+ ResyncPredictedSlot();
+ }
+ for (const uint16 Counter : Predictor.Expire(Ctx.Now))
+ {
+ FVerseMagazine::RefundRound(PredictedSlot, *W);
+ OnShotAnswered.Broadcast(Counter, EVerseShotResult::Rejected);
+ OnAnyShotRejected.Broadcast(GetShooterId(), Counter);
+ }
+
+
+ const bool bReady = (!Inv || Inv->IsReady(Ctx.Now)) && !FVerseMagazine::IsReloading(PredictedSlot) && !Ctx.bFiringBlocked;
+ const int32 Rounds = bReady ? FVerseMagazine::RoundsReady(PredictedSlot, *W) : 0;
+ TArray<float> Times;
+ Cadence.Collect(*W, Ctx.bTriggerDown && bReady, Ctx.Now - Ctx.Dt, Ctx.Now, Rounds, Times);
+
+ const float Ads = GetAdsBlend01();
+ const float Mul = FVerseRecoilState::Multiplier(*W, Ctx.Stance, Ads);
+ FRotator Control = Ctx.Control;
+ FRotator Out = FRotator::ZeroRotator;
+ auto AddRot = [&Control, &Out](const FVector2f& PitchYaw, float Sign)
+ {
+ Control.Pitch += Sign * PitchYaw.X;
+ Control.Yaw += Sign * PitchYaw.Y;
+ Out.Pitch += Sign * PitchYaw.X;
+ Out.Yaw += Sign * PitchYaw.Y;
+ };
+
+ const int32 ShooterId = GetShooterId();
+ for (const float T : Times)
+ {
+ AddRot(Recoil.TickKick(*W, T), 1.f);
+ Recoil.BeginShot(*W, T);
+
+ FVerseShotOut Shot;
+ Shot.Counter = ++NextShotCounter;
+ Shot.Seed = FVerseSpread::ShotSeed(uint32(ShooterId), Shot.Counter, MatchSeed);
+ Shot.ShotIndex = Recoil.ShotIndex;
+ Shot.Time = T;
+
+ FVerseSpreadInput In;
+ In.Stance = Ctx.Stance;
+ In.AdsBlend = Ads;
+ In.HorizontalSpeedMps = Ctx.HorizontalSpeedMps;
+ In.bAirborne = Ctx.bAirborne;
+ // Bloom decays up to this shot's own time (not the tick's end), exactly as the server derives it.
+ Spread.DecayUntilShot(*W, T);
+ Shot.Sigma = Spread.SigmaFor(*W, In, T);
+ Shot.Origin = Ctx.Eye;
+ Shot.Dir = FVerseSpread::ShotDirection(Control.Vector(), Shot.Sigma, Shot.Seed, Shot.ShotIndex);
+ Shot.Kick = Recoil.KickFor(*W, Mul, Shot.Seed);
+
+ Recoil.OnShot(Shot.Kick, T);
+ Spread.OnShot(*W, T);
+ FVerseMagazine::ConsumeRound(PredictedSlot, *W);
+
+ FVerseFireEvent E;
+ E.ShooterId = ShooterId;
+ E.WeaponId = W->WeaponId;
+ E.ShotCounter = Shot.Counter;
+ E.Seed = Shot.Seed;
+ E.Origin = Shot.Origin;
+ E.Direction = Shot.Dir;
+ E.ServerTime = T;
+
+ if (bAuthority)
+ {
+ OnPredictedFire.Broadcast(E);
+ HandleServerFire(Shot.Counter, Shot.Seed, Shot.Origin, Shot.Dir, T);
+ }
+ else
+ {
+ FVersePredictedShot P;
+ P.Counter = Shot.Counter;
+ P.Time = T;
+ // What the server will receive: the origin quantised to 0.1 cm.
+ P.Origin = FVector_NetQuantize10(Shot.Origin);
+ P.Dir = Shot.Dir;
+ P.WeaponId = W->WeaponId;
+ Predictor.Add(P);
+ OnPredictedFire.Broadcast(E);
+ VerseCombatEvents::RaiseFire(this, E); // the owner predicts its own fire event
+ ServerFire(Shot.Counter, Shot.Seed, FVector_NetQuantize10(Shot.Origin), FVector_NetQuantizeNormal(Shot.Dir), T);
+ }
+ if (OutShots)
+ {
+ OutShots->Add(Shot);
+ }
+ }
+
+ AddRot(Recoil.TickKick(*W, Ctx.Now), 1.f);
+ AddRot(Recoil.TickRecovery(*W, Ctx.Now, Ctx.Dt), -1.f);
+ LastStepTime = Ctx.Now;
+ if (bAuthority)
+ {
+ ResyncPredictedSlot();
+ }
+ return Out;
+}
+
+FVector UVerseWeaponComponent::ServerEye(double ViewTime) const
+{
+ if (RewoundEyeOverride)
+ {
+ return RewoundEyeOverride(ViewTime);
+ }
+ const AActor* Owner = GetOwner();
+ if (!Owner)
+ {
+ return FVector::ZeroVector;
+ }
+ const APawn* Pawn = Cast<APawn>(Owner);
+ const FVector CurrentEye = Pawn ? Pawn->GetPawnViewLocation() : Owner->GetActorLocation();
+ const UVerseLagCompSubsystem* Lag = UVerseLagCompSubsystem::Get(this);
+ FVerseHitBodyPose Pose;
+ const double Now = VerseCombatEvents::ServerTime(this);
+ if (Lag && Lag->GetPoseAt(Owner, UVerseLagCompSubsystem::ClampRewindTime(Now, ViewTime), Pose))
+ {
+ return Pose.Root.GetLocation() + (CurrentEye - Owner->GetActorLocation());
+ }
+ return CurrentEye;
+}
+
+FVector UVerseWeaponComponent::ServerForward() const
+{
+ if (ServerForwardOverride)
+ {
+ return ServerForwardOverride();
+ }
+ const APawn* Pawn = Cast<APawn>(GetOwner());
+ return Pawn ? Pawn->GetBaseAimRotation().Vector() : (GetOwner() ? GetOwner()->GetActorForwardVector() : FVector::ForwardVector);
+}
+
+EVerseShotResult UVerseWeaponComponent::HandleServerFire(uint16 ShotCounter, uint32 Seed, const FVector& Origin, const FVector& Dir,
+ float ClientServerTime)
+{
+ AActor* Owner = GetOwner();
+ if (!Owner || !Owner->HasAuthority())
+ {
+ return EVerseShotResult::Rejected;
+ }
+ auto Reject = [this, ShotCounter]()
+ {
+ ClientConfirmShot(ShotCounter, EVerseShotResult::Rejected, EVerseHitZone::None, false);
+ return EVerseShotResult::Rejected;
+ };
+
+ const float Now = VerseCombatEvents::ServerTime(this);
+ UVerseInventoryComponent* Inv = GetInventory();
+ const UVerseWeaponDefinition* W = GetActiveDefinition();
+ if (!Inv || !W)
+ {
+ return Reject();
+ }
+ UVerseCombatStateComponent* State = UVerseCombatStateComponent::FindOn(Owner);
+ if (State && State->Phase != EVerseCombatPhase::Alive)
+ {
+ return Reject(); // dead, or locked in a finisher
+ }
+ const IVerseMovementQuery& Move = MovementOf(Owner);
+ if (Move.BlocksFiring())
+ {
+ return Reject();
+ }
+ // The client's predicted server time: never ahead of the server clock, never far behind it.
+ if (!FMath::IsFinite(ClientServerTime) || ClientServerTime > Now + MaxClientLeadS || ClientServerTime < Now - MaxClientLagS)
+ {
+ return Reject();
+ }
+ // Cadence on the client's clock (the owner's shots arrive in order); 1 ms grace.
+ if (ClientServerTime + 0.001f < ServerLastShotClientTime + W->FireInterval())
+ {
+ return Reject();
+ }
+ // Cadence on the server's clock: no more shots than elapsed server time allows, plus a small burst
+ // for requests that arrive bunched. Forged client times cannot raise the rate.
+ const float Interval = FMath::Max(W->FireInterval(), 1e-3f);
+ if (ServerBudgetTime >= 0.f)
+ {
+ ServerShotBudget = FMath::Min(ServerBurstShots, ServerShotBudget + FMath::Max(0.f, Now - ServerBudgetTime) / Interval);
+ }
+ ServerBudgetTime = Now;
+ if (ServerShotBudget < 1.f - 1e-3f)
+ {
+ return Reject();
+ }
+ if (Seed != FVerseSpread::ShotSeed(uint32(GetShooterId()), ShotCounter, MatchSeed))
+ {
+ return Reject();
+ }
+
+ // The server's own recoil and spread for this shot (R5, 4.4), on the client's shot time. Every
+ // request that passed the clock checks was really fired by the owner, so the simulation advances
+ // even when the shot is rejected below; counter gaps (lost requests) advance it too.
+ FVerseSpreadInput In;
+ In.Stance = Move.GetStance();
+ In.AdsBlend = GetAdsBlend01();
+ In.bAirborne = Move.IsAirborne();
+ In.HorizontalSpeedMps = float(Owner->GetVelocity().Size2D() / 100.0);
+ const uint16 Gap = uint16(ShotCounter - ServerLastCounter - 1);
+ ServerRecoil.BeginShot(*W, ClientServerTime);
+ if (Gap > 0 && Gap < 16 && ServerRecoil.ShotIndex > 0)
+ {
+ ServerRecoil.ShotIndex += Gap;
+ ServerSpread.Bloom = FMath::Min(W->BloomMax, ServerSpread.Bloom + Gap * W->BloomPerShot);
+ }
+ ServerSpread.DecayUntilShot(*W, ClientServerTime);
+ const float Sigma = ServerSpread.SigmaFor(*W, In, ClientServerTime);
+ const int32 ShotIndex = ServerRecoil.ShotIndex;
+ const FVector2f Kick = ServerRecoil.KickFor(*W, FVerseRecoilState::Multiplier(*W, In.Stance, In.AdsBlend), Seed);
+ ServerRecoil.OnShot(Kick, ClientServerTime);
+ ServerSpread.OnShot(*W, ClientServerTime);
+ ServerLastCounter = ShotCounter;
+ ServerLastShotClientTime = ClientServerTime;
+ ServerShotBudget -= 1.f;
+ LastServerKick = Kick;
+ LastServerSigma = Sigma;
+ LastServerShotIndex = ShotIndex;
+
+ if (bServerValidates)
+ {
+ const FVector Forward = ServerForward();
+ if (!FVerseSpread::ValidateFire(Origin, Dir, ServerEye(ClientServerTime), Forward, Sigma) ||
+ !FVerseSpread::ValidateDirection(Dir, Forward, Sigma, Seed, ShotIndex))
+ {
+ return Reject();
+ }
+ }
+ if (!Inv->ServerConsumeRound(Now))
+ {
+ return Reject();
+ }
+
+ if (State)
+ {
+ State->NotifyOffensiveAction(Now);
+ }
+ if (UVerseDamageService* Damage = UVerseDamageService::Get(this))
+ {
+ if (Damage->Rules.OnOffensiveAction)
+ {
+ Damage->Rules.OnOffensiveAction(Owner, EVerseDamageSource::Bolt);
+ }
+ }
+
+ FVerseFireEvent E;
+ E.ShooterId = GetShooterId();
+ E.WeaponId = W->WeaponId;
+ E.ShotCounter = ShotCounter;
+ E.Seed = Seed;
+ E.Origin = Origin;
+ E.Direction = Dir.GetSafeNormal();
+ E.ServerTime = Now;
+
+ VerseCombatEvents::RaiseFire(this, E);
+ VerseCombatEvents::RaiseNoise(this, VerseTags::Noise_Shot, E.ShooterId, Origin, 1.f);
+ MulticastFire(E);
+
+ if (UVerseProjectileManager* Manager = UVerseProjectileManager::Get(this))
+ {
+ // The latency advance comes from the validated client time and is capped at 250 ms by the manager.
+ Manager->SpawnBoltFrom(E, *W, FMath::Clamp(Now - ClientServerTime, 0.f, UVerseProjectileManager::MaxLatencyS), Owner);
+ }
+ return EVerseShotResult::Miss;
+}
+
+void UVerseWeaponComponent::HandleBoltResolved(const FVerseBoltResult& Result)
+{
+ ClientConfirmShot(Result.ShotCounter, Result.Result, Result.Zone, Result.bKillingBlow);
+}
+
+void UVerseWeaponComponent::HandleConfirm(uint16 ShotCounter, EVerseShotResult Result)
+{
+ const FVerseShotReconcile R = Predictor.Confirm(ShotCounter, Result);
+ const UVerseWeaponDefinition* W = GetActiveDefinition();
+ const AActor* Owner = GetOwner();
+ if (R.RefundRounds > 0 && W && Owner && !Owner->HasAuthority())
+ {
+ FVerseMagazine::RefundRound(PredictedSlot, *W);
+ }
+ OnShotAnswered.Broadcast(ShotCounter, Result);
+ if (Result == EVerseShotResult::Rejected)
+ {
+ OnAnyShotRejected.Broadcast(GetShooterId(), ShotCounter);
+ }
+}
+
+void UVerseWeaponComponent::ServerFire_Implementation(uint16 ShotCounter, uint32 Seed, FVector_NetQuantize10 Origin,
+ FVector_NetQuantizeNormal Dir, float ClientServerTime)
+{
+ HandleServerFire(ShotCounter, Seed, Origin, Dir, ClientServerTime);
+}
+
+void UVerseWeaponComponent::ClientConfirmShot_Implementation(uint16 ShotCounter, EVerseShotResult Result, EVerseHitZone,
+ bool)
+{
+ HandleConfirm(ShotCounter, Result);
+}
+
+void UVerseWeaponComponent::MulticastFire_Implementation(const FVerseFireEvent& E)
+{
+ const AActor* Owner = GetOwner();
+ if (!Owner || Owner->HasAuthority() || IsLocalOwner(Owner))
+ {
+ return; // the server raised it; the owner predicted it
+ }
+ VerseCombatEvents::RaiseFire(this, E);
+}
+
+void UVerseWeaponComponent::RaiseLocalImpact(const UObject* WorldContext, const FVerseHitEvent& Impact)
+{
+ const UWorld* World = WorldContext ? WorldContext->GetWorld() : nullptr;
+ if (!World || World->GetNetMode() == NM_DedicatedServer)
+ {
+ return;
+ }
+ if (UVerseEventHub* Hub = UVerseEventHub::Get(WorldContext))
+ {
+ Hub->OnHit.Broadcast(Impact);
+ }
+}
+
+void UVerseWeaponComponent::MulticastHitCosmetic_Implementation(const FVerseHitEvent& E)
+{
+ const AActor* Owner = GetOwner();
+ if (!Owner)
+ {
+ return;
+ }
+ if (Owner->HasAuthority())
+ {
+ // Body hits reached the server's hub through the damage service; world, piece and Bulwark
+ // impacts reach a listen-server or standalone viewer here.
+ if (E.VictimId == -1)
+ {
+ RaiseLocalImpact(this, E);
+ }
+ return;
+ }
+ // The victim's owner gets the reliable copy instead.
+ if (const UWorld* World = GetWorld())
+ {
+ for (FConstPlayerControllerIterator It = World->GetPlayerControllerIterator(); It; ++It)
+ {
+ const APlayerController* Pc = It->Get();
+ if (Pc && Pc->IsLocalController() && VerseCombatIds::IdOf(Pc->GetPawn()) == E.VictimId && E.VictimId != -1)
+ {
+ return;
+ }
+ }
+ }
+ if (UVerseEventHub* Hub = UVerseEventHub::Get(this))
+ {
+ Hub->OnHit.Broadcast(E);
+ }
+}
+
+void UVerseWeaponComponent::MulticastPenetration_Implementation(const FVersePenetrationEvent& E)
+{
+ const AActor* Owner = GetOwner();
+ if (!Owner || Owner->HasAuthority())
+ {
+ return;
+ }
+ VerseCombatEvents::RaisePenetration(this, E);
+}
diff --git a/unreal/Verse/Source/VerseCombat/Private/Weapons/VerseWeaponRegistry.cpp b/unreal/Verse/Source/VerseCombat/Private/Weapons/VerseWeaponRegistry.cpp
new file mode 100644
index 0000000000..7a79de0b28
--- /dev/null
+++ b/unreal/Verse/Source/VerseCombat/Private/Weapons/VerseWeaponRegistry.cpp
@@ -0,0 +1,105 @@
+#include "Weapons/VerseWeaponRegistry.h"
+
+#include "Combat/VerseGadgetDefinition.h"
+#include "Combat/VerseWeaponDefinition.h"
+#include "Misc/FileHelper.h"
+#include "Misc/Paths.h"
+#include "Weapons/VerseDefinitionJson.h"
+
+namespace
+{
+ TMap<FName, UVerseWeaponDefinition*>& WeaponCache()
+ {
+ static TMap<FName, UVerseWeaponDefinition*> Cache;
+ return Cache;
+ }
+
+ TMap<FName, UVerseGadgetDefinition*>& GadgetCache()
+ {
+ static TMap<FName, UVerseGadgetDefinition*> Cache;
+ return Cache;
+ }
+
+ FString ObjectPath(const FString& AssetName)
+ {
+ return FString::Printf(TEXT("%s/%s.%s"), FVerseDefinitionJson::AssetFolder, *AssetName, *AssetName);
+ }
+}
+
+const UVerseWeaponDefinition* FVerseWeaponRegistry::LoadWeaponAsset(FName WeaponId)
+{
+ const FString Name = FVerseDefinitionJson::WeaponAssetName(WeaponId);
+ return LoadObject<UVerseWeaponDefinition>(nullptr, *ObjectPath(Name), nullptr, LOAD_NoWarn | LOAD_Quiet);
+}
+
+const UVerseGadgetDefinition* FVerseWeaponRegistry::LoadGadgetAsset(FName GadgetId)
+{
+ const FString Name = FVerseDefinitionJson::GadgetAssetName(GadgetId);
+ return LoadObject<UVerseGadgetDefinition>(nullptr, *ObjectPath(Name), nullptr, LOAD_NoWarn | LOAD_Quiet);
+}
+
+const UVerseWeaponDefinition* FVerseWeaponRegistry::FindWeapon(FName WeaponId)
+{
+ if (const UVerseWeaponDefinition* Asset = LoadWeaponAsset(WeaponId))
+ {
+ return Asset;
+ }
+ if (UVerseWeaponDefinition* const* Cached = WeaponCache().Find(WeaponId))
+ {
+ return *Cached;
+ }
+ FString Text;
+ const FString File = FPaths::Combine(FVerseDefinitionJson::DataDir(), WeaponId.ToString() + TEXT(".json"));
+ if (!FFileHelper::LoadFileToString(Text, *File))
+ {
+ return nullptr;
+ }
+ UVerseWeaponDefinition* Def = NewObject<UVerseWeaponDefinition>(GetTransientPackage());
+ TArray<FString> Errors;
+ if (!FVerseDefinitionJson::ApplyWeaponText(Text, *Def, Errors))
+ {
+ return nullptr;
+ }
+ Def->AddToRoot(); // process lifetime; never released
+ WeaponCache().Add(WeaponId, Def);
+ return Def;
+}
+
+const UVerseGadgetDefinition* FVerseWeaponRegistry::FindGadget(FName GadgetId)
+{
+ if (const UVerseGadgetDefinition* Asset = LoadGadgetAsset(GadgetId))
+ {
+ return Asset;
+ }
+ if (GadgetCache().Num() == 0)
+ {
+ FString Text;
+ if (FFileHelper::LoadFileToString(Text, *FPaths::Combine(FVerseDefinitionJson::DataDir(), TEXT("gadgets.json"))))
+ {
+ TArray<UVerseGadgetDefinition*> Defs;
+ TArray<FString> Errors;
+ FVerseDefinitionJson::LoadGadgetsText(Text, GetTransientPackage(), Defs, Errors);
+ for (UVerseGadgetDefinition* D : Defs)
+ {
+ D->AddToRoot();
+ GadgetCache().Add(D->GadgetId, D);
+ }
+ }
+ }
+ UVerseGadgetDefinition* const* Found = GadgetCache().Find(GadgetId);
+ return Found ? *Found : nullptr;
+}
+
+void FVerseWeaponRegistry::ResetCache()
+{
+ for (TPair<FName, UVerseWeaponDefinition*>& P : WeaponCache())
+ {
+ P.Value->RemoveFromRoot();
+ }
+ for (TPair<FName, UVerseGadgetDefinition*>& P : GadgetCache())
+ {
+ P.Value->RemoveFromRoot();
+ }
+ WeaponCache().Reset();
+ GadgetCache().Reset();
+}
diff --git a/unreal/Verse/Source/VerseCombat/Public/Damage/VerseCombatStateComponent.h b/unreal/Verse/Source/VerseCombat/Public/Damage/VerseCombatStateComponent.h
index ee0ab3c3db..fdada08e1a 100644
--- a/unreal/Verse/Source/VerseCombat/Public/Damage/VerseCombatStateComponent.h
+++ b/unreal/Verse/Source/VerseCombat/Public/Damage/VerseCombatStateComponent.h
@@ -9,8 +9,9 @@
/**
* Combat state on the pawn (contracts/combat-state.md 2.1, 11.2). AVerseCharacter is a
* VerseMovement class, so the combat phase and spawn protection live here; the primary
- * module's default pawn adds this component. Fields only: WP02 adds the behaviour.
- * Replicated to all with the push model.
+ * module's default pawn adds this component. Replicated to all with the push model.
+ * It also carries the two per-victim transports of 5.1: the reliable hit copy to the victim
+ * and the reliable death multicast.
*/
UCLASS(ClassGroup = (Verse), meta = (BlueprintSpawnableComponent))
class VERSECOMBAT_API UVerseCombatStateComponent : public UActorComponent
@@ -22,6 +23,8 @@ public:
virtual void GetLifetimeReplicatedProps(TArray<FLifetimeProperty>& OutLifetimeProps) const override;
+ static UVerseCombatStateComponent* FindOn(const AActor* Actor);
+
UPROPERTY(Replicated, VisibleInstanceOnly, BlueprintReadOnly, Category = "Verse|Combat")
EVerseCombatPhase Phase = EVerseCombatPhase::Alive;
@@ -31,4 +34,26 @@ public:
/** Server time at which spawn protection ends (combat-state.md 9.3). */
UPROPERTY(Replicated, VisibleInstanceOnly, BlueprintReadOnly, Category = "Verse|Combat")
float SpawnProtectedUntil = 0.f;
+
+ /** Server: sets the phase (push model). */
+ void SetPhase(EVerseCombatPhase NewPhase);
+
+ /** Server: protection from Now for Duration seconds (the ruleset decides the duration). */
+ void BeginSpawnProtection(float Now, float Duration);
+
+ /** Server: ends protection on the first own offensive action (fire, melee, gadget). */
+ void NotifyOffensiveAction(float Now);
+
+ /** Protection holds at Now (flag set and the end time not reached). */
+ bool IsSpawnProtected(float Now) const;
+
+ bool IsAlive() const { return Phase == EVerseCombatPhase::Alive || Phase == EVerseCombatPhase::FinisherAttacker; }
+
+ /** Reliable copy of a hit to the victim's owner (damage direction indicator). */
+ UFUNCTION(Client, Reliable)
+ void ClientReceiveHit(const FVerseHitEvent& Hit);
+
+ /** Reliable death to everyone (score, kill cam, gore, respawn timer). */
+ UFUNCTION(NetMulticast, Reliable)
+ void MulticastDeath(const FVerseDeathEvent& Death);
};
diff --git a/unreal/Verse/Source/VerseCombat/Public/Damage/VerseDamageMath.h b/unreal/Verse/Source/VerseCombat/Public/Damage/VerseDamageMath.h
new file mode 100644
index 0000000000..f44bcdcf78
--- /dev/null
+++ b/unreal/Verse/Source/VerseCombat/Public/Damage/VerseDamageMath.h
@@ -0,0 +1,35 @@
+#pragma once
+
+#include "Combat/VerseCombatTypes.h"
+#include "CoreMinimal.h"
+
+class UVerseWeaponDefinition;
+
+/** Result of applying damage to health and armor (armor absorbs first, combat-state.md 5). */
+struct FVerseDamageSplit
+{
+ float ToArmor = 0.f;
+ float ToHealth = 0.f;
+ float HealthAfter = 0.f;
+ float ArmorAfter = 0.f;
+ bool bKilled = false;
+};
+
+/** The damage formula of combat-state.md 5. Pure; the damage service and the tests share it. */
+struct VERSECOMBAT_API FVerseDamageMath
+{
+ /** 1 up to FalloffStart, linear to FalloffMinFraction at FalloffEnd, FalloffMinFraction beyond. */
+ static float Falloff(const UVerseWeaponDefinition& W, float DistanceM);
+
+ /** ZoneMultipliers[zone]; 1.0 when the zone has no entry, 0 for None. */
+ static float ZoneMultiplier(const UVerseWeaponDefinition& W, EVerseHitZone Zone);
+
+ /** D = BaseDamage * ZoneMultipliers[zone] * falloff(distance) * penetration_factor */
+ static float BoltDamage(const UVerseWeaponDefinition& W, EVerseHitZone Zone, float DistanceM, float PenetrationFactor);
+
+ /** Armor first (when MaxArmor > 0), the rest to health. */
+ static FVerseDamageSplit Split(float Damage, float Health, float Armor, float MaxArmor);
+
+ /** Hits of BoltDamage(zone, distance) needed to take MaxHealth to 0. */
+ static int32 HitsToKill(const UVerseWeaponDefinition& W, EVerseHitZone Zone, float DistanceM, float MaxHealth);
+};
diff --git a/unreal/Verse/Source/VerseCombat/Public/Damage/VerseDamageService.h b/unreal/Verse/Source/VerseCombat/Public/Damage/VerseDamageService.h
new file mode 100644
index 0000000000..aa1866137c
--- /dev/null
+++ b/unreal/Verse/Source/VerseCombat/Public/Damage/VerseDamageService.h
@@ -0,0 +1,72 @@
+#pragma once
+
+#include "Combat/VerseCombatTypes.h"
+#include "CoreMinimal.h"
+#include "Subsystems/WorldSubsystem.h"
+
+#include "VerseDamageService.generated.h"
+
+class UAbilitySystemComponent;
+class UVerseHealthSet;
+
+/** What a rule hook is asked about (the shape of FVerseDamageContext in combat-state.md 11.2). */
+struct FVerseDamageQuery
+{
+ AActor* Instigator = nullptr;
+ AActor* Victim = nullptr;
+ EVerseDamageSource Source = EVerseDamageSource::Bolt;
+ EVerseHitZone Zone = EVerseHitZone::None;
+};
+
+/**
+ * The ruleset hooks damage asks (combat-state.md 10: CanDamage, ModifyDamage, OnPlayerAction).
+ * AVerseGameMode (WP11) binds its ruleset here; unbound hooks allow all and change nothing, which
+ * is the WP11 fake WP02 tests against.
+ */
+struct FVerseDamageRules
+{
+ TFunction<bool(const FVerseDamageQuery&)> CanDamage;
+ TFunction<float(const FVerseDamageQuery&, float)> ModifyDamage;
+ TFunction<void(AActor* /*Player*/, EVerseDamageSource /*Offensive action*/)> OnOffensiveAction;
+};
+
+/** Ids of combat participants as events carry them. */
+namespace VerseCombatIds
+{
+ /** Player state id for a pawn with one; a stable negative id below -1 for other actors; -1 for none (world). */
+ VERSECOMBAT_API int32 IdOf(const AActor* Actor);
+}
+
+/**
+ * Server damage (WP02.9): spawn protection and finisher rules, the ruleset hooks, the GAS damage
+ * effect (armor first), the killing blow, FVerseDeathEvent and the hub and per-victim transports
+ * of combat-state.md 5.1.
+ */
+UCLASS()
+class VERSECOMBAT_API UVerseDamageService : public UWorldSubsystem
+{
+ GENERATED_BODY()
+
+public:
+ static UVerseDamageService* Get(const UObject* WorldContextObject);
+
+ FVerseDamageRules Rules;
+
+ /** Default respawn delay put into FVerseDeathEvent::RespawnAt until a ruleset answers (start 3.0 s). */
+ float DefaultRespawnDelay = 3.f;
+
+ /**
+ * Applies Hit.Damage from Instigator to Victim on the server and completes the hit event
+ * (killing blow, spawn-protection marker, server time). Raises OnHit on the hub, the reliable copy
+ * to the victim and, on a kill, the death event. Returns the damage that reached health and armor.
+ * Server only; a call without authority does nothing.
+ */
+ float ApplyHit(AActor* Instigator, AActor* Victim, FVerseHitEvent& Hit);
+
+ /** Health and armor of a victim; nullptr when it has none. */
+ static const UVerseHealthSet* FindHealth(const AActor* Actor);
+ static UAbilitySystemComponent* FindAsc(const AActor* Actor);
+
+ /** Server time used by combat on this world. */
+ float Now() const;
+};
diff --git a/unreal/Verse/Source/VerseCombat/Public/Damage/VerseHealthSet.h b/unreal/Verse/Source/VerseCombat/Public/Damage/VerseHealthSet.h
new file mode 100644
index 0000000000..782c3cb4c4
--- /dev/null
+++ b/unreal/Verse/Source/VerseCombat/Public/Damage/VerseHealthSet.h
@@ -0,0 +1,83 @@
+#pragma once
+
+#include "AbilitySystemComponent.h"
+#include "AttributeSet.h"
+#include "CoreMinimal.h"
+#include "GameplayEffect.h"
+
+#include "VerseHealthSet.generated.h"
+
+/**
+ * Health and armor (combat-state.md 2.1, 11.2). Health and armor replicate to the owner only:
+ * the opponent's health is never shown. IncomingDamage is a server-only meta attribute that the
+ * damage effect writes; PostGameplayEffectExecute spends it on armor first, then health.
+ */
+UCLASS()
+class VERSECOMBAT_API UVerseHealthSet : public UAttributeSet
+{
+ GENERATED_BODY()
+
+public:
+ UVerseHealthSet();
+
+ ATTRIBUTE_ACCESSORS_BASIC(UVerseHealthSet, Health)
+ ATTRIBUTE_ACCESSORS_BASIC(UVerseHealthSet, MaxHealth)
+ ATTRIBUTE_ACCESSORS_BASIC(UVerseHealthSet, Armor)
+ ATTRIBUTE_ACCESSORS_BASIC(UVerseHealthSet, MaxArmor)
+ ATTRIBUTE_ACCESSORS_BASIC(UVerseHealthSet, IncomingDamage)
+
+ virtual void GetLifetimeReplicatedProps(TArray<FLifetimeProperty>& OutLifetimeProps) const override;
+ virtual void PreAttributeChange(const FGameplayAttribute& Attribute, float& NewValue) override;
+ virtual void PostGameplayEffectExecute(const FGameplayEffectModCallbackData& Data) override;
+
+ /** Start: 100 (combat-state.md 2.1). */
+ static constexpr float StartHealth = 100.f;
+
+ /** Owner only. */
+ UPROPERTY(ReplicatedUsing = OnRep_Health, BlueprintReadOnly, Category = "Verse|Health")
+ FGameplayAttributeData Health;
+
+ UPROPERTY(ReplicatedUsing = OnRep_MaxHealth, BlueprintReadOnly, Category = "Verse|Health")
+ FGameplayAttributeData MaxHealth;
+
+ /** 0 in deathmatch (MaxArmor 0 makes it inert). */
+ UPROPERTY(ReplicatedUsing = OnRep_Armor, BlueprintReadOnly, Category = "Verse|Health")
+ FGameplayAttributeData Armor;
+
+ UPROPERTY(ReplicatedUsing = OnRep_MaxArmor, BlueprintReadOnly, Category = "Verse|Health")
+ FGameplayAttributeData MaxArmor;
+
+ /** Meta, server only. */
+ UPROPERTY(BlueprintReadOnly, Category = "Verse|Health")
+ FGameplayAttributeData IncomingDamage;
+
+ /** Damage spent on armor and health by the last executed damage effect (server). */
+ float LastToArmor = 0.f;
+ float LastToHealth = 0.f;
+
+protected:
+ UFUNCTION()
+ void OnRep_Health(const FGameplayAttributeData& Old);
+ UFUNCTION()
+ void OnRep_MaxHealth(const FGameplayAttributeData& Old);
+ UFUNCTION()
+ void OnRep_Armor(const FGameplayAttributeData& Old);
+ UFUNCTION()
+ void OnRep_MaxArmor(const FGameplayAttributeData& Old);
+};
+
+/**
+ * The damage effect (combat-state.md 5): instant, adds the set-by-caller magnitude
+ * `Verse.Damage` to IncomingDamage. The damage service builds one spec per hit.
+ */
+UCLASS()
+class VERSECOMBAT_API UVerseDamageEffect : public UGameplayEffect
+{
+ GENERATED_BODY()
+
+public:
+ UVerseDamageEffect();
+
+ /** Set-by-caller name of the damage magnitude. */
+ static const FName DamageName;
+};
diff --git a/unreal/Verse/Source/VerseCombat/Public/Gadgets/VerseBreachCharge.h b/unreal/Verse/Source/VerseCombat/Public/Gadgets/VerseBreachCharge.h
new file mode 100644
index 0000000000..c422d6a08e
--- /dev/null
+++ b/unreal/Verse/Source/VerseCombat/Public/Gadgets/VerseBreachCharge.h
@@ -0,0 +1,99 @@
+#pragma once
+
+#include "Combat/VerseCombatTypes.h"
+#include "CoreMinimal.h"
+#include "GameFramework/Actor.h"
+
+#include "VerseBreachCharge.generated.h"
+
+class IVersePieceDamage;
+class UStaticMeshComponent;
+class UVerseGadgetDefinition;
+
+/** One pawn the detonation reached. */
+struct FVerseBreachVictim
+{
+ TWeakObjectPtr<AActor> Pawn;
+ float DistanceM = 0.f;
+ float Damage = 0.f;
+};
+
+/**
+ * The breach charge (combat-state.md 2.3): planted on a piece breakable by breach, detonates
+ * FuseTime after the plant completes, damages every pawn whose pelvis is within PawnRadius and in
+ * line of sight on VerseBolt (linear falloff, owner included), drives the target piece to its breach
+ * result through IVersePieceDamage and removes Bulwarks within 3 m. No pawn collision; cannot be
+ * shot or defused. Server spawns it; it replicates to all.
+ */
+UCLASS()
+class VERSECOMBAT_API AVerseBreachCharge : public AActor
+{
+ GENERATED_BODY()
+
+public:
+ AVerseBreachCharge();
+
+ virtual void GetLifetimeReplicatedProps(TArray<FLifetimeProperty>& OutLifetimeProps) const override;
+
+ virtual void BeginPlay() override;
+ virtual void Tick(float DeltaSeconds) override;
+
+ /** Bulwarks within this distance of a detonation are removed, cm. */
+ static constexpr double BulwarkClearRadiusCm = 300.0;
+
+ /** Server: arms the charge. PlantCompleteTime is when the plant (UseTime) finished. */
+ void InitCharge(const UVerseGadgetDefinition& Def, AActor* InOwnerPawn, uint16 InPieceIndex, const FVector& SurfaceNormal,
+ double PlantCompleteTime);
+
+ /** Server: detonates once the fuse is over. Tick calls it with the server time; tests call it directly. */
+ void ServerAdvance(double Now);
+
+ /** Server: the detonation itself (normally from ServerAdvance). */
+ void Detonate(double Now);
+
+ /** Piece damage target; unset uses the null stub. Destruction (WP06) or tests set it. */
+ void SetPieceDamage(IVersePieceDamage* InPieceDamage) { PieceDamage = InPieceDamage; }
+
+ double GetDetonateAt() const { return DetonateAt; }
+ bool IsArmed() const { return bArmed; }
+ bool HasDetonated() const { return bDetonated; }
+ double GetDetonatedTime() const { return DetonatedTime; }
+ uint16 GetPieceIndex() const { return PieceIndex; }
+ const TArray<FVerseBreachVictim>& GetLastVictims() const { return LastVictims; }
+
+ /** Pelvis point of a pawn: the Hips bone when it has a skeletal mesh, else the actor location. */
+ static FVector PelvisOf(const AActor* Pawn);
+
+ UFUNCTION(NetMulticast, Unreliable)
+ void MulticastGadgetEvent(const FVerseGadgetEvent& Event);
+
+ UPROPERTY(VisibleAnywhere, Category = "Verse|Gadget")
+ TObjectPtr<UStaticMeshComponent> Look;
+
+ /** Called on the server after the detonation (charge bookkeeping in the gadget component). */
+ TFunction<void(AVerseBreachCharge*)> OnDetonated;
+
+private:
+ void Raise(EVerseGadgetEventKind Kind);
+
+ /** Clients raise the spawn event (Plant) from replication: a multicast in the spawn frame has no open channel yet. */
+ UFUNCTION()
+ void OnRep_SpawnEvent();
+
+ UPROPERTY(ReplicatedUsing = OnRep_SpawnEvent)
+ FVerseGadgetEvent SpawnEvent;
+
+ UPROPERTY()
+ TObjectPtr<const UVerseGadgetDefinition> Definition;
+
+ TWeakObjectPtr<AActor> OwnerPawn;
+ IVersePieceDamage* PieceDamage = nullptr;
+ FVector Normal = FVector::UpVector;
+ int32 OwnerId = -1;
+ uint16 PieceIndex = 0;
+ double DetonateAt = 0.0;
+ double DetonatedTime = -1.0;
+ bool bArmed = false;
+ bool bDetonated = false;
+ TArray<FVerseBreachVictim> LastVictims;
+};
diff --git a/unreal/Verse/Source/VerseCombat/Public/Gadgets/VerseBulwark.h b/unreal/Verse/Source/VerseCombat/Public/Gadgets/VerseBulwark.h
new file mode 100644
index 0000000000..96f3cae4d3
--- /dev/null
+++ b/unreal/Verse/Source/VerseCombat/Public/Gadgets/VerseBulwark.h
@@ -0,0 +1,96 @@
+#pragma once
+
+#include "Combat/VerseCombatTypes.h"
+#include "CoreMinimal.h"
+#include "GameFramework/Actor.h"
+
+#include "VerseBulwark.generated.h"
+
+class UBoxComponent;
+class UStaticMeshComponent;
+class UVerseGadgetDefinition;
+
+/**
+ * The Bulwark (combat-state.md 2.3): a deployable energy barricade. Blocks pawns and the VerseBolt
+ * channel and ignores VerseSight, so both sides see through it and nobody shoots through it. Bolts
+ * stop at the field and their damage after all factors goes to its health. It ends at health 0, at
+ * the end of its lifetime, on its owner's death or a breach detonation within 3 m. Server spawns it;
+ * it replicates to all.
+ */
+UCLASS()
+class VERSECOMBAT_API AVerseBulwark : public AActor
+{
+ GENERATED_BODY()
+
+public:
+ AVerseBulwark();
+
+ virtual void GetLifetimeReplicatedProps(TArray<FLifetimeProperty>& OutLifetimeProps) const override;
+ virtual void BeginPlay() override;
+ virtual void Tick(float DeltaSeconds) override;
+ virtual void EndPlay(const EEndPlayReason::Type Reason) override;
+
+ /** Server: sets size, health, lifetime and owner; raises Deploy. Call right after spawning. */
+ void InitBulwark(const UVerseGadgetDefinition& Def, AActor* InOwnerPawn, double Now);
+
+ /** Server: a bolt's damage after all factors. Removes the field on the tick its health reaches 0. */
+ void ApplyBoltDamage(float Damage, AActor* Instigator);
+
+ /** Server: lifetime and hum. Tick calls it with the server time; tests call it directly. */
+ void ServerAdvance(double Now);
+
+ /** Server: removes the field with Destroyed or Expired. */
+ void RemoveBulwark(EVerseGadgetEventKind Kind);
+
+ bool IsActive() const { return bActive; }
+ float GetHealth() const { return Health; }
+ double GetExpireAt() const { return ExpireAt; }
+ int32 GetOwnerId() const { return OwnerId; }
+ AActor* GetOwnerPawn() const { return OwnerPawn.Get(); }
+
+ /** Every active Bulwark whose centre is within RadiusCm of Location. */
+ static TArray<AVerseBulwark*> FindWithin(const UWorld* World, const FVector& Location, double RadiusCm);
+
+ UFUNCTION(NetMulticast, Unreliable)
+ void MulticastGadgetEvent(const FVerseGadgetEvent& Event);
+
+ UPROPERTY(VisibleAnywhere, Category = "Verse|Gadget")
+ TObjectPtr<UBoxComponent> Field;
+
+ /** Placeholder look: a thin amber slab (WP14 replaces it). */
+ UPROPERTY(VisibleAnywhere, Category = "Verse|Gadget")
+ TObjectPtr<UStaticMeshComponent> Look;
+
+ /** Hum noise interval, s. */
+ static constexpr double HumIntervalS = 1.0;
+
+ /** Called on the server when the field goes (cooldown start in the gadget component). */
+ TFunction<void(AVerseBulwark*)> OnRemoved;
+
+private:
+ void Raise(EVerseGadgetEventKind Kind);
+
+ /** Clients raise the spawn event (Deploy) from replication: a multicast in the spawn frame has no open channel yet. */
+ UFUNCTION()
+ void OnRep_SpawnEvent();
+
+ UPROPERTY(ReplicatedUsing = OnRep_SpawnEvent)
+ FVerseGadgetEvent SpawnEvent;
+ void OnOwnerDeath(const FVerseDeathEvent& Death);
+
+ UPROPERTY(Replicated)
+ float Health = 0.f;
+
+ UPROPERTY(Replicated)
+ float MaxHealth = 0.f;
+
+ UPROPERTY()
+ TObjectPtr<const UVerseGadgetDefinition> Definition;
+
+ TWeakObjectPtr<AActor> OwnerPawn;
+ int32 OwnerId = -1;
+ double ExpireAt = 0.0;
+ double NextHumAt = 0.0;
+ bool bActive = false;
+ FDelegateHandle DeathHandle;
+};
diff --git a/unreal/Verse/Source/VerseCombat/Public/Gadgets/VerseGadgetAbilities.h b/unreal/Verse/Source/VerseCombat/Public/Gadgets/VerseGadgetAbilities.h
new file mode 100644
index 0000000000..1cf591e602
--- /dev/null
+++ b/unreal/Verse/Source/VerseCombat/Public/Gadgets/VerseGadgetAbilities.h
@@ -0,0 +1,50 @@
+#pragma once
+
+#include "Abilities/GameplayAbility.h"
+#include "Combat/VerseCombatTypes.h"
+#include "CoreMinimal.h"
+
+#include "VerseGadgetAbilities.generated.h"
+
+/**
+ * Base of the gadget abilities (combat-state.md 2.3): local-predicted, so the owning client plays
+ * only the deploy or plant animation with a prediction key; the server asks the pawn's
+ * UVerseGadgetComponent to start the use, which owns charges, cooldown, use time and spawning.
+ */
+UCLASS(Abstract)
+class VERSECOMBAT_API UVerseGA_Gadget : public UGameplayAbility
+{
+ GENERATED_BODY()
+
+public:
+ UVerseGA_Gadget();
+
+ virtual void ActivateAbility(const FGameplayAbilitySpecHandle Handle, const FGameplayAbilityActorInfo* ActorInfo,
+ const FGameplayAbilityActivationInfo ActivationInfo, const FGameplayEventData* TriggerEventData) override;
+
+ /** The loadout slot this ability uses. */
+ EVerseLoadoutSlot GadgetSlot = EVerseLoadoutSlot::GadgetA;
+
+ /** Server answer of the last activation (tests). */
+ bool bLastServerUseStarted = false;
+};
+
+/** Deploys the Bulwark (GadgetA). */
+UCLASS()
+class VERSECOMBAT_API UVerseGA_Bulwark : public UVerseGA_Gadget
+{
+ GENERATED_BODY()
+
+public:
+ UVerseGA_Bulwark();
+};
+
+/** Plants a breach charge (GadgetB). */
+UCLASS()
+class VERSECOMBAT_API UVerseGA_BreachCharge : public UVerseGA_Gadget
+{
+ GENERATED_BODY()
+
+public:
+ UVerseGA_BreachCharge();
+};
diff --git a/unreal/Verse/Source/VerseCombat/Public/Gadgets/VerseGadgetComponent.h b/unreal/Verse/Source/VerseCombat/Public/Gadgets/VerseGadgetComponent.h
new file mode 100644
index 0000000000..72b58f8593
--- /dev/null
+++ b/unreal/Verse/Source/VerseCombat/Public/Gadgets/VerseGadgetComponent.h
@@ -0,0 +1,97 @@
+#pragma once
+
+#include "Combat/VerseCombatTypes.h"
+#include "Components/ActorComponent.h"
+#include "CoreMinimal.h"
+
+#include "VerseGadgetComponent.generated.h"
+
+class AVerseBreachCharge;
+class AVerseBulwark;
+class IVersePenetrationQuery;
+class IVersePieceDamage;
+class UVerseGadgetDefinition;
+
+/** Where a gadget goes, as placement found it. */
+struct FVerseGadgetPlacement
+{
+ bool bValid = false;
+ FVector Location = FVector::ZeroVector;
+ FRotator Rotation = FRotator::ZeroRotator;
+ /** Breach charge: the piece it sticks to and the surface normal. */
+ uint16 PieceIndex = 0;
+ FVector Normal = FVector::UpVector;
+};
+
+/**
+ * The two start gadgets of a pawn (WP02.12, 2.13, combat-state.md 2.3): charges per life, cooldown
+ * after the Bulwark is gone, the interruptible use time, placement and spawning. Server only; the
+ * GAS abilities UVerseGA_Bulwark and UVerseGA_BreachCharge call into it, and the owning client
+ * predicts only the deploy or plant animation.
+ */
+UCLASS(ClassGroup = (Verse), meta = (BlueprintSpawnableComponent))
+class VERSECOMBAT_API UVerseGadgetComponent : public UActorComponent
+{
+ GENERATED_BODY()
+
+public:
+ UVerseGadgetComponent();
+
+ virtual void BeginPlay() override;
+ virtual void EndPlay(const EEndPlayReason::Type Reason) override;
+ virtual void TickComponent(float DeltaTime, ELevelTick TickType, FActorComponentTickFunction* ThisTickFunction) override;
+
+ static UVerseGadgetComponent* FindOn(const AActor* Actor);
+
+ /** GadgetA. */
+ UPROPERTY(EditAnywhere, Category = "Verse|Gadget")
+ TObjectPtr<const UVerseGadgetDefinition> Bulwark;
+
+ /** GadgetB. */
+ UPROPERTY(EditAnywhere, Category = "Verse|Gadget")
+ TObjectPtr<const UVerseGadgetDefinition> BreachCharge;
+
+ /** Server: charges back to full (respawn). */
+ void ResetForLife();
+
+ /** Server: starts deploying (GadgetA) or planting (GadgetB). False when out of charges, cooling down or busy. */
+ bool ServerBeginUse(EVerseLoadoutSlot Slot, float Now);
+
+ /** Server: completes a use whose time is over. TickComponent calls it; tests call it directly. */
+ void ServerAdvance(float Now);
+
+ /** Server: taking damage interrupts a deploy or plant (the charge is kept). */
+ void Interrupt();
+
+ bool IsUsing() const { return bUsing; }
+ int32 GetChargesLeft(EVerseLoadoutSlot Slot) const;
+ float GetCooldownEndsAt() const { return BulwarkCooldownEndsAt; }
+ AVerseBulwark* GetActiveBulwark() const { return ActiveBulwark.Get(); }
+ int32 NumPlantedCharges() const;
+
+ /** Placement overrides (tests); unset uses the eye-based placement of 2.3. */
+ TFunction<FVerseGadgetPlacement(EVerseLoadoutSlot)> PlacementOverride;
+
+ void SetPenetrationQuery(const IVersePenetrationQuery* Query) { PenetrationQuery = Query; }
+ void SetPieceDamage(IVersePieceDamage* Damage) { PieceDamage = Damage; }
+
+ /** Eye-based placement (2.3): Bulwark on the floor in front, breach charge on a breachable piece. */
+ FVerseGadgetPlacement FindPlacement(EVerseLoadoutSlot Slot) const;
+
+private:
+ const UVerseGadgetDefinition* DefinitionFor(EVerseLoadoutSlot Slot) const;
+ void Complete(float Now);
+ void OnHubHit(const FVerseHitEvent& Hit);
+
+ int32 BulwarkCharges = 0;
+ int32 BreachCharges = 0;
+ float BulwarkCooldownEndsAt = 0.f;
+ bool bUsing = false;
+ EVerseLoadoutSlot UsingSlot = EVerseLoadoutSlot::GadgetA;
+ float UseEndsAt = 0.f;
+ TWeakObjectPtr<AVerseBulwark> ActiveBulwark;
+ TArray<TWeakObjectPtr<AVerseBreachCharge>> Planted;
+ const IVersePenetrationQuery* PenetrationQuery = nullptr;
+ IVersePieceDamage* PieceDamage = nullptr;
+ FDelegateHandle HitHandle;
+};
diff --git a/unreal/Verse/Source/VerseCombat/Public/Inventory/VerseInventoryComponent.h b/unreal/Verse/Source/VerseCombat/Public/Inventory/VerseInventoryComponent.h
new file mode 100644
index 0000000000..612915ebcd
--- /dev/null
+++ b/unreal/Verse/Source/VerseCombat/Public/Inventory/VerseInventoryComponent.h
@@ -0,0 +1,96 @@
+#pragma once
+
+#include "Combat/VerseCombatTypes.h"
+#include "Components/ActorComponent.h"
+#include "CoreMinimal.h"
+#include "Inventory/VerseWeaponSlot.h"
+
+#include "VerseInventoryComponent.generated.h"
+
+class UVerseWeaponDefinition;
+
+DECLARE_MULTICAST_DELEGATE_OneParam(FOnVerseInventoryReload, const FVerseReloadEvent&);
+
+/**
+ * Loadout slots (WP02.2, combat-state.md 2.1, 11.2): the per-slot weapon state as a fast array
+ * replicated to the owner only, the active slot and the reloading flag replicated to all, equip and
+ * holster timing, and the reload state machine (WP02.3) driven on the server. The opponent learns
+ * of a reload only through the reload noise event.
+ */
+UCLASS(ClassGroup = (Verse), meta = (BlueprintSpawnableComponent))
+class VERSECOMBAT_API UVerseInventoryComponent : public UActorComponent
+{
+ GENERATED_BODY()
+
+public:
+ UVerseInventoryComponent();
+
+ virtual void GetLifetimeReplicatedProps(TArray<FLifetimeProperty>& OutLifetimeProps) const override;
+ virtual void TickComponent(float DeltaTime, ELevelTick TickType, FActorComponentTickFunction* ThisTickFunction) override;
+
+ static UVerseInventoryComponent* FindOn(const AActor* Actor);
+
+ /** Owner only. */
+ UPROPERTY(Replicated)
+ FVerseWeaponSlotArray Slots;
+
+ /** All. */
+ UPROPERTY(Replicated)
+ EVerseLoadoutSlot ActiveSlot = EVerseLoadoutSlot::Primary;
+
+ /** All; animation only, carries no round count. */
+ UPROPERTY(Replicated)
+ bool bReloading = false;
+
+ UFUNCTION(Server, Reliable)
+ void ServerReload(uint16 ClientCounter);
+
+ UFUNCTION(Server, Reliable)
+ void ServerSwitchSlot(EVerseLoadoutSlot NewSlot);
+
+ /** The owner-only transport of FVerseReloadEvent (combat-state.md 5.1). */
+ UFUNCTION(Client, Reliable)
+ void ClientReloadEvent(const FVerseReloadEvent& Event);
+
+ /** Server: full magazines and reserve for every firearm slot, the primary drawn (respawn loadout). */
+ void GiveLoadout(const TMap<EVerseLoadoutSlot, const UVerseWeaponDefinition*>& Weapons, float Now);
+
+ /** Server: refills every slot (respawn). */
+ void RefillAll();
+
+ const FVerseWeaponSlotState* GetSlotState(EVerseLoadoutSlot Slot) const { return Slots.Find(Slot); }
+ const FVerseWeaponSlotState* GetActiveState() const { return Slots.Find(ActiveSlot); }
+ const UVerseWeaponDefinition* GetActiveWeapon() const;
+
+ /** The active weapon finished equipping at Now. */
+ bool IsReady(float Now) const { return Now >= ReadyAt; }
+ float GetReadyAt() const { return ReadyAt; }
+
+ /** Server: spends one round of the active weapon; false when it cannot fire. */
+ bool ServerConsumeRound(float Now);
+
+ /** Server: starts a reload of the active weapon; raises the event and the noise. */
+ bool ServerStartReload(float Now);
+
+ /** Server: cancels a running reload (before the commit the old magazine stays). */
+ void ServerCancelReload(float Now);
+
+ /** Server: switches slot, cancelling a reload; the new weapon is ready after holster + equip. */
+ void ServerSwitch(EVerseLoadoutSlot NewSlot, float Now);
+
+ /** Server: advances the reload of every slot to Now. TickComponent calls it; tests call it directly. */
+ void ServerAdvance(float Now);
+
+ /** Local reload events (server and owner), for UI and tests. */
+ FOnVerseInventoryReload OnReloadEvent;
+
+ float Now() const;
+
+private:
+ void MarkSlotDirty(FVerseWeaponSlotState& S);
+ void SetReloading(bool bNew);
+ void RaiseReload(const FVerseWeaponSlotState& S, bool bCancelled);
+
+ /** Server time the active weapon is ready (equip done). */
+ float ReadyAt = 0.f;
+};
diff --git a/unreal/Verse/Source/VerseCombat/Public/Inventory/VerseWeaponSlot.h b/unreal/Verse/Source/VerseCombat/Public/Inventory/VerseWeaponSlot.h
new file mode 100644
index 0000000000..bb347b3cd2
--- /dev/null
+++ b/unreal/Verse/Source/VerseCombat/Public/Inventory/VerseWeaponSlot.h
@@ -0,0 +1,139 @@
+#pragma once
+
+#include "Combat/VerseCombatTypes.h"
+#include "CoreMinimal.h"
+#include "Net/Serialization/FastArraySerializer.h"
+
+#include "VerseWeaponSlot.generated.h"
+
+class UVerseWeaponDefinition;
+
+/** combat-state.md 11.2 */
+UENUM()
+enum class EVerseReloadPhase : uint8
+{
+ None,
+ Tactical,
+ Empty
+};
+
+/**
+ * Per-slot weapon state (combat-state.md 2.1, 11.2): definition, magazine, chambered round,
+ * reserve, reload phase. Replicated to the owner only, inside UVerseInventoryComponent::Slots.
+ * Magazine never counts the chambered round.
+ */
+USTRUCT()
+struct VERSECOMBAT_API FVerseWeaponSlotState : public FFastArraySerializerItem
+{
+ GENERATED_BODY()
+
+ UPROPERTY()
+ EVerseLoadoutSlot Slot = EVerseLoadoutSlot::Primary;
+
+ UPROPERTY()
+ TObjectPtr<const UVerseWeaponDefinition> Definition;
+
+ UPROPERTY()
+ uint8 Magazine = 0;
+
+ UPROPERTY()
+ bool bChambered = false;
+
+ UPROPERTY()
+ uint16 Reserve = 0;
+
+ UPROPERTY()
+ EVerseReloadPhase Reload = EVerseReloadPhase::None;
+
+ /** Server time. */
+ UPROPERTY()
+ float ReloadEndsAt = 0.f;
+
+ /** Server time the reload started; local bookkeeping, not replicated. */
+ UPROPERTY(NotReplicated)
+ float ReloadStartedAt = 0.f;
+
+ /** The rounds of the running reload have moved (ReloadCommitFraction passed). Not replicated. */
+ UPROPERTY(NotReplicated)
+ bool bReloadCommitted = false;
+};
+
+USTRUCT()
+struct VERSECOMBAT_API FVerseWeaponSlotArray : public FFastArraySerializer
+{
+ GENERATED_BODY()
+
+ UPROPERTY()
+ TArray<FVerseWeaponSlotState> Items;
+
+ bool NetDeltaSerialize(FNetDeltaSerializeInfo& DeltaParms)
+ {
+ return FFastArraySerializer::FastArrayDeltaSerialize<FVerseWeaponSlotState, FVerseWeaponSlotArray>(Items, DeltaParms, *this);
+ }
+
+ FVerseWeaponSlotState* Find(EVerseLoadoutSlot Slot);
+ const FVerseWeaponSlotState* Find(EVerseLoadoutSlot Slot) const;
+};
+
+template <>
+struct TStructOpsTypeTraits<FVerseWeaponSlotArray> : public TStructOpsTypeTraitsBase2<FVerseWeaponSlotArray>
+{
+ enum
+ {
+ WithNetDeltaSerializer = true,
+ };
+};
+
+/** What a magazine tick or call did, for events and noise. */
+enum class EVerseMagazineChange : uint8
+{
+ None,
+ ReloadStarted,
+ ReloadCommitted,
+ ReloadFinished,
+ ReloadCancelled
+};
+
+/**
+ * The magazine and reload state machine (WP02.3): tactical vs empty, commit fraction, cancel,
+ * chambered round. Pure functions on a slot state; the inventory component calls them on the
+ * server and the owning client predicts with the same calls.
+ */
+struct VERSECOMBAT_API FVerseMagazine
+{
+ /** Full magazine and chamber, full reserve (spawn and respawn loadout). */
+ static void InitFull(FVerseWeaponSlotState& S, const UVerseWeaponDefinition& W);
+
+ /** Rounds that can be fired without a reload (magazine plus a chambered round). */
+ static int32 RoundsReady(const FVerseWeaponSlotState& S, const UVerseWeaponDefinition& W);
+
+ static bool IsReloading(const FVerseWeaponSlotState& S) { return S.Reload != EVerseReloadPhase::None; }
+
+ /** A reload now would be tactical (a round is chambered, or an open-bolt magazine is not empty). */
+ static bool WouldBeTactical(const FVerseWeaponSlotState& S, const UVerseWeaponDefinition& W);
+
+ static bool CanFire(const FVerseWeaponSlotState& S, const UVerseWeaponDefinition& W);
+
+ /** Spends one round; false when nothing could be fired. */
+ static bool ConsumeRound(FVerseWeaponSlotState& S, const UVerseWeaponDefinition& W);
+
+ /** Undoes one ConsumeRound (a predicted shot the server rejected). */
+ static void RefundRound(FVerseWeaponSlotState& S, const UVerseWeaponDefinition& W);
+
+ static bool CanReload(const FVerseWeaponSlotState& S, const UVerseWeaponDefinition& W);
+
+ /** Starts a tactical or empty reload at Now. */
+ static bool StartReload(FVerseWeaponSlotState& S, const UVerseWeaponDefinition& W, float Now);
+
+ /** Time at which the rounds move. */
+ static float CommitTime(const FVerseWeaponSlotState& S, const UVerseWeaponDefinition& W);
+
+ /** Advances a running reload to Now; returns the last change that happened. */
+ static EVerseMagazineChange Tick(FVerseWeaponSlotState& S, const UVerseWeaponDefinition& W, float Now);
+
+ /** Cancels a running reload: before the commit the old magazine stays, after it the new one. */
+ static EVerseMagazineChange Cancel(FVerseWeaponSlotState& S);
+
+private:
+ static void Commit(FVerseWeaponSlotState& S, const UVerseWeaponDefinition& W);
+};
diff --git a/unreal/Verse/Source/VerseCombat/Public/LagComp/VerseLagCompensation.h b/unreal/Verse/Source/VerseCombat/Public/LagComp/VerseLagCompensation.h
new file mode 100644
index 0000000000..a7fef84a9a
--- /dev/null
+++ b/unreal/Verse/Source/VerseCombat/Public/LagComp/VerseLagCompensation.h
@@ -0,0 +1,142 @@
+#pragma once
+
+#include "Combat/VerseCombatTypes.h"
+#include "CoreMinimal.h"
+#include "Subsystems/WorldSubsystem.h"
+
+#include "VerseLagCompensation.generated.h"
+
+class USkeletalMeshComponent;
+
+/** One per-bone hit body as a capsule in world space (cm). */
+struct FVerseHitCapsule
+{
+ FName Bone;
+ EVerseHitZone Zone = EVerseHitZone::None;
+ /** Axis end points. */
+ FVector A = FVector::ZeroVector;
+ FVector B = FVector::ZeroVector;
+ float Radius = 0.f;
+ /** World transform of the bone, for the bone-local impact point (gore). */
+ FTransform BoneTransform = FTransform::Identity;
+};
+
+/** The hit bodies and root transform of one target at one server time. */
+struct FVerseHitBodyPose
+{
+ double Time = 0.0;
+ FTransform Root = FTransform::Identity;
+ TArray<FVerseHitCapsule> Capsules;
+};
+
+/** A hit body a rewound trace entered. */
+struct FVerseRewindHit
+{
+ TWeakObjectPtr<AActor> Actor;
+ FName Bone;
+ EVerseHitZone Zone = EVerseHitZone::None;
+ FVector ImpactWorld = FVector::ZeroVector;
+ FVector ImpactBoneLocal = FVector::ZeroVector;
+ /** Distance from the segment start, cm. */
+ double Distance = 0.0;
+ /** Server time the bodies were rewound to (after the clamp). */
+ double PoseTime = 0.0;
+};
+
+/** Ring buffer of poses of one target, one per server tick, 1 s deep (architecture.md 3.2). */
+class VERSECOMBAT_API FVerseHitBodyHistory
+{
+public:
+ explicit FVerseHitBodyHistory(int32 InCapacity = 72);
+
+ void Push(FVerseHitBodyPose&& Pose);
+ void Reset() { Count = 0; Head = 0; }
+ int32 Num() const { return Count; }
+ double OldestTime() const;
+ double NewestTime() const;
+
+ /** The pose at Time, interpolated between the two snapshots around it; clamped to the buffer's span. */
+ bool Sample(double Time, FVerseHitBodyPose& Out) const;
+
+private:
+ const FVerseHitBodyPose& At(int32 IndexFromOldest) const;
+
+ TArray<FVerseHitBodyPose> Ring;
+ int32 Capacity = 72;
+ int32 Head = 0;
+ int32 Count = 0;
+};
+
+/** Produces the current hit bodies of a target (world space). */
+using FVerseHitBodyProvider = TFunction<void(FTransform& OutRoot, TArray<FVerseHitCapsule>& OutCapsules)>;
+
+/**
+ * Lag compensation (WP02.8, combat-state.md 1, 5): a 1 s ring buffer of per-bone hit bodies per
+ * target, recorded every server tick, and rewound queries capped at 250 ms. Bolts (the projectile
+ * manager) and melee and finisher checks (WP04) use the same query API. Traces are analytic
+ * capsule tests on the recorded poses, so a rewound query never moves physics bodies.
+ */
+UCLASS()
+class VERSECOMBAT_API UVerseLagCompSubsystem : public UWorldSubsystem
+{
+ GENERATED_BODY()
+
+public:
+ /** Rewind cap, s (architecture.md 3.2). */
+ static constexpr double MaxRewindS = 0.25;
+ /** History depth, s. */
+ static constexpr double HistoryS = 1.0;
+
+ static UVerseLagCompSubsystem* Get(const UObject* WorldContextObject);
+
+ virtual void Initialize(FSubsystemCollectionBase& Collection) override;
+ virtual void Deinitialize() override;
+
+ /** Registers a target with its own hit body provider (tests, future non-skeletal targets). */
+ void RegisterTarget(AActor* Target, FVerseHitBodyProvider Provider);
+
+ /** Registers a pawn whose hit bodies are the capsules of its mesh's physics asset (SK_Test_Human, PHYS_Verse_Human). */
+ void RegisterSkeletalTarget(AActor* Target, USkeletalMeshComponent* Mesh);
+
+ void UnregisterTarget(AActor* Target);
+
+ /** Records every registered target's pose at server time Now. Runs after actor tick on the server. */
+ void Record(double Now);
+
+ /** The rewind target time: ViewTime clamped to [Now - 250 ms, Now]. */
+ static double ClampRewindTime(double Now, double ViewTime);
+
+ /** The pose of a target at Time (interpolated). WP04 uses it for rewound transforms. */
+ bool GetPoseAt(const AActor* Target, double Time, FVerseHitBodyPose& Out) const;
+
+ /** Nearest hit body a segment enters, with bodies at ClampRewindTime(Now, ViewTime). */
+ bool TraceRewound(const FVector& Start, const FVector& End, double Now, double ViewTime, const AActor* Ignore,
+ FVerseRewindHit& Out) const;
+
+ /** Same against the poses at exactly Time (no clamp; Time inside the buffer). */
+ bool TraceAt(const FVector& Start, const FVector& End, double Time, const AActor* Ignore, FVerseRewindHit& Out) const;
+
+ /** Nearest hit body of one pose a segment enters. */
+ static bool TracePose(const FVerseHitBodyPose& Pose, const FVector& Start, const FVector& End, FVerseRewindHit& Out);
+
+ /** Distance along the ray (unit Dir) to the capsule's surface; < 0 when missed. Start inside = 0. */
+ static double RayCapsule(const FVector& Origin, const FVector& Dir, const FVector& A, const FVector& B, double Radius);
+
+ /** The bone table of the frozen rig (art-pipeline.md 12.1) to hit zones. */
+ static EVerseHitZone ZoneForBone(FName Bone);
+
+ int32 NumTargets() const { return Targets.Num(); }
+
+private:
+ struct FTarget
+ {
+ TWeakObjectPtr<AActor> Actor;
+ FVerseHitBodyProvider Provider;
+ FVerseHitBodyHistory History;
+ };
+
+ void OnPostActorTick(UWorld* World, ELevelTick TickType, float DeltaSeconds);
+
+ TArray<FTarget> Targets;
+ FDelegateHandle PostTickHandle;
+};
diff --git a/unreal/Verse/Source/VerseCombat/Public/Projectiles/VerseBoltPresentation.h b/unreal/Verse/Source/VerseCombat/Public/Projectiles/VerseBoltPresentation.h
new file mode 100644
index 0000000000..5ddd9377e4
--- /dev/null
+++ b/unreal/Verse/Source/VerseCombat/Public/Projectiles/VerseBoltPresentation.h
@@ -0,0 +1,105 @@
+#pragma once
+
+#include "Combat/VerseCombatTypes.h"
+#include "CoreMinimal.h"
+#include "Subsystems/WorldSubsystem.h"
+
+#include "VerseBoltPresentation.generated.h"
+
+class AActor;
+class UInstancedStaticMeshComponent;
+
+/** One bolt as the viewer sees it. */
+struct FVerseVisualBolt
+{
+ int32 ShooterId = 0;
+ uint16 ShotCounter = 0;
+ FName WeaponId;
+ FVector Origin = FVector::ZeroVector;
+ FVector Dir = FVector::ForwardVector;
+ double SpawnTime = 0.0;
+ double SpeedCmS = 30000.0;
+ double MaxRangeCm = 15000.0;
+ /** Own predicted bolt (amber) or the opponent's (red). */
+ bool bOwn = false;
+ FLinearColor Color = FLinearColor::White;
+};
+
+/** A short impact flash from the cosmetic hit event. */
+struct FVerseVisualImpact
+{
+ FVector Location = FVector::ZeroVector;
+ double SpawnTime = 0.0;
+};
+
+/**
+ * Bolt presentation (WP02.11): the owner's predicted bolt drawn amber at fire time, every other
+ * shooter's bolt drawn red from FVerseFireEvent, removal on Rejected and on the bolt's cosmetic hit,
+ * impact flashes only from the cosmetic hit event (never from the client's own trace). Placeholder
+ * look (engine basic shapes) until WP14.9. Not created on a dedicated server; without a renderer
+ * (-nullrhi) it draws nothing but keeps the same bookkeeping, which the tests read.
+ */
+UCLASS()
+class VERSECOMBAT_API UVerseBoltPresentation : public UTickableWorldSubsystem
+{
+ GENERATED_BODY()
+
+public:
+ static constexpr double StreakLengthCm = 150.0;
+ static constexpr double StreakRadiusCm = 3.0;
+ static constexpr double ImpactLifeS = 0.08;
+
+ static UVerseBoltPresentation* Get(const UObject* WorldContextObject);
+
+ virtual bool ShouldCreateSubsystem(UObject* Outer) const override;
+ virtual void Initialize(FSubsystemCollectionBase& Collection) override;
+ virtual void Deinitialize() override;
+ virtual void Tick(float DeltaTime) override;
+ virtual TStatId GetStatId() const override;
+
+ /** The local viewer's player id; bolts with this shooter id are own (amber). Tests may set it. */
+ TOptional<int32> LocalPlayerIdOverride;
+ int32 GetLocalPlayerId() const;
+
+ /** A fire event reached this viewer (hub OnFire: own prediction or the server's multicast). */
+ void HandleFire(const FVerseFireEvent& E);
+ /** The cosmetic hit: the bolt ends there with an impact flash. */
+ void HandleHit(const FVerseHitEvent& E);
+ /** A predicted shot the server rejected. */
+ void HandleRejected(int32 ShooterId, uint16 ShotCounter);
+
+ /** Advances the visuals to Now (Tick uses world time). */
+ void Advance(double Now);
+
+ const TArray<FVerseVisualBolt>& GetBolts() const { return Bolts; }
+ const TArray<FVerseVisualImpact>& GetImpacts() const { return Impacts; }
+ int32 NumOwn() const;
+ int32 NumFoe() const;
+ /** Where a bolt's streak head is at Now. */
+ static FVector HeadAt(const FVerseVisualBolt& B, double Now);
+
+ /** Time source override (tests). */
+ TFunction<double()> ClockOverride;
+
+private:
+ void Subscribe();
+ void EnsureRender();
+ void UpdateRender(double Now);
+ double WorldNow() const;
+
+ TArray<FVerseVisualBolt> Bolts;
+ TArray<FVerseVisualImpact> Impacts;
+ FDelegateHandle FireHandle;
+ FDelegateHandle HitHandle;
+ FDelegateHandle RejectHandle;
+ bool bSubscribed = false;
+
+ UPROPERTY(Transient)
+ TObjectPtr<AActor> RenderActor;
+ UPROPERTY(Transient)
+ TObjectPtr<UInstancedStaticMeshComponent> OwnMeshes;
+ UPROPERTY(Transient)
+ TObjectPtr<UInstancedStaticMeshComponent> FoeMeshes;
+ UPROPERTY(Transient)
+ TObjectPtr<UInstancedStaticMeshComponent> ImpactMeshes;
+};
diff --git a/unreal/Verse/Source/VerseCombat/Public/Projectiles/VerseProjectileManager.h b/unreal/Verse/Source/VerseCombat/Public/Projectiles/VerseProjectileManager.h
new file mode 100644
index 0000000000..a55c908f29
--- /dev/null
+++ b/unreal/Verse/Source/VerseCombat/Public/Projectiles/VerseProjectileManager.h
@@ -0,0 +1,132 @@
+#pragma once
+
+#include "Combat/VerseCombatTypes.h"
+#include "CoreMinimal.h"
+#include "Engine/HitResult.h"
+#include "Subsystems/WorldSubsystem.h"
+
+#include "VerseProjectileManager.generated.h"
+
+class IVersePenetrationQuery;
+class IVersePieceDamage;
+class UVersePenetrationTable;
+class UVerseWeaponDefinition;
+
+/** One bolt in flight (server). Not an actor (combat-state.md 5). */
+struct FVerseBolt
+{
+ FVerseFireEvent Fire;
+ TWeakObjectPtr<const UVerseWeaponDefinition> Weapon;
+ TWeakObjectPtr<AActor> Shooter;
+ FVector Position = FVector::ZeroVector;
+ FVector Dir = FVector::ForwardVector;
+ /** Distance flown, cm. */
+ double Travelled = 0.0;
+ /** Server time at which the bolt is at Position. */
+ double Time = 0.0;
+ /** Remaining penetration power, and the damage factor after the pieces passed. */
+ float Power = 0.f;
+ float Factor = 1.f;
+ int32 Passes = 0;
+ /** Pieces already passed; a straight bolt never enters one twice (segment starts on an exit face). */
+ TArray<uint16, TInlineAllocator<4>> PassedPieces;
+ bool bAlive = true;
+};
+
+/** How a bolt ended; the shooter's weapon component turns it into ClientConfirmShot. */
+struct FVerseBoltResult
+{
+ TWeakObjectPtr<AActor> Shooter;
+ FName WeaponId;
+ uint16 ShotCounter = 0;
+ EVerseShotResult Result = EVerseShotResult::Miss;
+ EVerseHitZone Zone = EVerseHitZone::None;
+ bool bKillingBlow = false;
+ TWeakObjectPtr<AActor> HitActor;
+ FVector Location = FVector::ZeroVector;
+ /** Distance flown when it ended, cm. */
+ double Travelled = 0.0;
+ /** Server time when it ended. */
+ double Time = 0.0;
+};
+
+DECLARE_MULTICAST_DELEGATE_OneParam(FOnVerseBoltResolved, const FVerseBoltResult&);
+
+/** Something in the world (not a piece, not a hit body) that a bolt segment struck. */
+using FVerseBoltWorldTrace = TFunction<bool(const FVector& Start, const FVector& End, const AActor* Ignore, FHitResult& OutHit)>;
+
+/**
+ * Server bolts (WP02.7, combat-state.md 5, 6). Each tick every bolt moves ProjectileSpeed x dt
+ * (300 m/s = 5 m per 60 Hz tick), straight, no drop, and despawns at MaxRange. A new bolt first
+ * covers the shooter's latency (capped 250 ms) in tick-sized segments traced against hit bodies
+ * rewound to the time the bolt was at that point; later segments trace current bodies. Per
+ * segment: pieces (IVersePenetrationQuery), the world on VerseBolt (Bulwarks included), then
+ * per-bone hit bodies; the nearest event wins, pieces run the penetration loop of section 6.
+ */
+UCLASS()
+class VERSECOMBAT_API UVerseProjectileManager : public UTickableWorldSubsystem
+{
+ GENERATED_BODY()
+
+public:
+ /** Latency advance cap, s (architecture.md 3.2). */
+ static constexpr float MaxLatencyS = 0.25f;
+ /** Fixed server step, s (architecture.md 3.2: 60 Hz). */
+ static constexpr float ServerStepS = 1.f / 60.f;
+
+ static UVerseProjectileManager* Get(const UObject* WorldContextObject);
+
+ virtual void Initialize(FSubsystemCollectionBase& Collection) override;
+ virtual void Deinitialize() override;
+ virtual void Tick(float DeltaTime) override;
+ virtual TStatId GetStatId() const override;
+
+ /** Contract entry (combat-state.md 11.2): a bolt without a known shooter actor. */
+ void SpawnBolt(const FVerseFireEvent& Fire, const UVerseWeaponDefinition& Weapon, float LatencyS);
+
+ /** Spawns a bolt and advances it by the latency (capped). Server only. */
+ void SpawnBoltFrom(const FVerseFireEvent& Fire, const UVerseWeaponDefinition& Weapon, float LatencyS, AActor* Shooter);
+
+ /** Moves every bolt by Dt to server time Now. Tick calls it; tests call it directly. */
+ void StepAll(float Dt, double Now);
+
+ void SetPenetrationQuery(const IVersePenetrationQuery* Query) { PenetrationQuery = Query; }
+ void SetPieceDamage(IVersePieceDamage* Damage) { PieceDamage = Damage; }
+ void SetPenetrationTable(const UVersePenetrationTable* Table) { PenetrationTable = Table; }
+ /** Replaces the world trace (tests). Unset: a line trace on VerseBolt. */
+ void SetWorldTrace(FVerseBoltWorldTrace Trace) { WorldTrace = MoveTemp(Trace); }
+ /** Server time source (tests). Unset: the world's time. */
+ void SetClock(TFunction<double()> Clock) { ClockOverride = MoveTemp(Clock); }
+
+ double Now() const;
+
+ int32 NumActive() const { return Bolts.Num(); }
+ const TArray<FVerseBolt>& GetBolts() const { return Bolts; }
+ /** Wall time of the last StepAll, seconds (A2.8 cost gate). */
+ double GetLastStepSeconds() const { return LastStepSeconds; }
+
+ /** Drops every bolt without resolving it. */
+ void Clear() { Bolts.Reset(); }
+
+ FOnVerseBoltResolved OnBoltResolved;
+
+private:
+ /** Moves one bolt over [From, To] by Len cm, resolving what it meets; PoseTime < 0 = current bodies. */
+ void StepBolt(FVerseBolt& Bolt, double Len, double PoseTime, double EndTime);
+ void Resolve(FVerseBolt& Bolt, EVerseShotResult Result, EVerseHitZone Zone, bool bKillingBlow, AActor* HitActor,
+ const FVector& Where);
+ bool TraceWorld(const FVector& Start, const FVector& End, const AActor* Ignore, FHitResult& Out) const;
+
+ TArray<FVerseBolt> Bolts;
+ const IVersePenetrationQuery* PenetrationQuery = nullptr;
+ IVersePieceDamage* PieceDamage = nullptr;
+ const UVersePenetrationTable* PenetrationTable = nullptr;
+ FVerseBoltWorldTrace WorldTrace;
+ TFunction<double()> ClockOverride;
+ double LastStepSeconds = 0.0;
+ bool bManualStepping = false;
+
+public:
+ /** Tests step by hand: the world tick then leaves the bolts alone. */
+ void SetManualStepping(bool bManual) { bManualStepping = bManual; }
+};
diff --git a/unreal/Verse/Source/VerseCombat/Public/Weapons/VerseCombatEvents.h b/unreal/Verse/Source/VerseCombat/Public/Weapons/VerseCombatEvents.h
new file mode 100644
index 0000000000..8bb0ca65b6
--- /dev/null
+++ b/unreal/Verse/Source/VerseCombat/Public/Weapons/VerseCombatEvents.h
@@ -0,0 +1,26 @@
+#pragma once
+
+#include "Combat/VerseCombatTypes.h"
+#include "CoreMinimal.h"
+#include "GameplayTagContainer.h"
+
+/**
+ * Hub helpers of WP02.10 (combat-state.md 5.1). Every combat event is raised on the server's
+ * UVerseEventHub; the per-event network transport lives on the component that owns the event
+ * (weapon component: fire, cosmetic hit, penetration; combat state: victim hit copy, death;
+ * inventory: reload; gadget actors: gadget events).
+ */
+namespace VerseCombatEvents
+{
+ /** Server time of the world: the game state's server clock when there is one, else world time. */
+ VERSECOMBAT_API float ServerTime(const UObject* WorldContext);
+
+ /** Raises a FVerseNoiseEvent on the server hub (bot hearing). No-op on clients. */
+ VERSECOMBAT_API void RaiseNoise(const UObject* WorldContext, const FGameplayTag& Noise, int32 SourceId, const FVector& Location,
+ float Loudness = 1.f);
+
+ VERSECOMBAT_API void RaiseFire(const UObject* WorldContext, const FVerseFireEvent& Event);
+ VERSECOMBAT_API void RaisePenetration(const UObject* WorldContext, const FVersePenetrationEvent& Event);
+ VERSECOMBAT_API void RaiseReload(const UObject* WorldContext, const FVerseReloadEvent& Event);
+ VERSECOMBAT_API void RaiseGadget(const UObject* WorldContext, const FVerseGadgetEvent& Event);
+}
diff --git a/unreal/Verse/Source/VerseCombat/Public/Weapons/VerseCombatTags.h b/unreal/Verse/Source/VerseCombat/Public/Weapons/VerseCombatTags.h
new file mode 100644
index 0000000000..48728dc899
--- /dev/null
+++ b/unreal/Verse/Source/VerseCombat/Public/Weapons/VerseCombatTags.h
@@ -0,0 +1,15 @@
+#pragma once
+
+#include "CoreMinimal.h"
+#include "NativeGameplayTags.h"
+
+// Presentation tags of the weapon definition (combat-state.md 3: BoltColorOwn, BoltColorFoe).
+// Own bolts amber, the opponent's red (README Projectiles).
+namespace VerseCombatTags
+{
+ VERSECOMBAT_API UE_DECLARE_GAMEPLAY_TAG_EXTERN(Presentation_Bolt_Amber);
+ VERSECOMBAT_API UE_DECLARE_GAMEPLAY_TAG_EXTERN(Presentation_Bolt_Red);
+
+ /** Linear colour of a bolt presentation tag; amber for an unknown tag on the own side. */
+ VERSECOMBAT_API FLinearColor BoltColor(const struct FGameplayTag& Tag, bool bOwn);
+}
diff --git a/unreal/Verse/Source/VerseCombat/Public/Weapons/VerseDefinitionJson.h b/unreal/Verse/Source/VerseCombat/Public/Weapons/VerseDefinitionJson.h
new file mode 100644
index 0000000000..850c5ed2ed
--- /dev/null
+++ b/unreal/Verse/Source/VerseCombat/Public/Weapons/VerseDefinitionJson.h
@@ -0,0 +1,59 @@
+#pragma once
+
+#include "CoreMinimal.h"
+
+class FJsonObject;
+class UVerseGadgetDefinition;
+class UVerseWeaponDefinition;
+
+/**
+ * The text surface of the weapon and gadget definitions (WP02.1, combat-state.md 2.3, 3):
+ * unreal/Verse/Data/weapons/<weapon_id>.json (one weapon) and gadgets.json (every gadget). Keys
+ * are the UPROPERTY names of the definition classes, every field is required and unknown keys are
+ * errors, so a JSON file and its DA_Weapon_* / DA_Gadget_* asset are always field-for-field equal.
+ *
+ * Value forms: numbers, booleans and names as JSON scalars; FText and FGameplayTag as strings; enums
+ * by entry name ("Primary", "Auto"); FVector2f as [x, y]; FVector3f as [x, y, z]; FRuntimeFloatCurve
+ * as [[x, y], ...] with linear keys; maps keyed by enum entry name.
+ */
+struct VERSECOMBAT_API FVerseDefinitionJson
+{
+ /** Schema tag every weapon file carries in "$schema". */
+ static const TCHAR* WeaponSchema;
+ /** Schema tag of gadgets.json. */
+ static const TCHAR* GadgetsSchema;
+
+ /** unreal/Verse/Data/weapons/ */
+ static FString DataDir();
+
+ /** Fills Out from a weapon object; false with Errors on any missing, unknown or malformed field. */
+ static bool ApplyWeapon(const FJsonObject& Json, UVerseWeaponDefinition& Out, TArray<FString>& Errors);
+ static bool ApplyWeaponText(const FString& Text, UVerseWeaponDefinition& Out, TArray<FString>& Errors);
+
+ /** The canonical JSON object of a weapon (what the file holds). */
+ static TSharedRef<FJsonObject> ExportWeapon(const UVerseWeaponDefinition& W);
+ static FString ExportWeaponText(const UVerseWeaponDefinition& W);
+
+ static bool ApplyGadget(const FJsonObject& Json, UVerseGadgetDefinition& Out, TArray<FString>& Errors);
+ static TSharedRef<FJsonObject> ExportGadget(const UVerseGadgetDefinition& G);
+
+ /** gadgets.json: { "$schema": ..., "gadgets": [ {...}, ... ] } */
+ static bool LoadGadgetsText(const FString& Text, UObject* Outer, TArray<UVerseGadgetDefinition*>& Out, TArray<FString>& Errors);
+
+ /** Names: ids lower_snake_case ASCII, display names letters, digits, spaces and hyphens only. */
+ static bool CheckNames(const FName& Id, const FText& DisplayName, TArray<FString>& Errors);
+
+ /** Every weapon file of DataDir() (all *.json except gadgets.json), each into a new transient definition. */
+ static TArray<UVerseWeaponDefinition*> LoadAllWeapons(UObject* Outer, TArray<FString>& Errors);
+
+ /** Field-for-field comparison of two JSON values (numbers within Tolerance); appends the differing paths. */
+ static bool JsonEqual(const TSharedPtr<class FJsonValue>& A, const TSharedPtr<class FJsonValue>& B, const FString& Path,
+ TArray<FString>& Diffs, double Tolerance = 1e-5);
+
+ /** Asset name of a weapon or gadget id: graveline -> DA_Weapon_Graveline, breach_charge -> DA_Gadget_BreachCharge. */
+ static FString WeaponAssetName(const FName& WeaponId);
+ static FString GadgetAssetName(const FName& GadgetId);
+
+ /** Content folder of the definition assets. */
+ static const TCHAR* AssetFolder;
+};
diff --git a/unreal/Verse/Source/VerseCombat/Public/Weapons/VerseFirePrediction.h b/unreal/Verse/Source/VerseCombat/Public/Weapons/VerseFirePrediction.h
new file mode 100644
index 0000000000..8a9ac437bb
--- /dev/null
+++ b/unreal/Verse/Source/VerseCombat/Public/Weapons/VerseFirePrediction.h
@@ -0,0 +1,49 @@
+#pragma once
+
+#include "Combat/VerseCombatTypes.h"
+#include "CoreMinimal.h"
+
+/** One shot the owning client predicted and has not heard back about. */
+struct FVersePredictedShot
+{
+ uint16 Counter = 0;
+ /** Predicted server time of the shot. */
+ float Time = 0.f;
+ FVector Origin = FVector::ZeroVector;
+ FVector Dir = FVector::ForwardVector;
+ FName WeaponId;
+};
+
+/** Outcome of one confirmation for the owning client. */
+struct FVerseShotReconcile
+{
+ bool bKnown = false;
+ /** The predicted bolt has to go (Rejected or timed out). */
+ bool bRemoveBolt = false;
+ /** Rounds to give back to the predicted magazine (the server never spent them). */
+ int32 RefundRounds = 0;
+};
+
+/**
+ * Owner-side fire prediction bookkeeping (WP02.6, combat-state.md 1, 5): pending shots keyed by the
+ * wrapping uint16 shot counter, answered by ClientConfirmShot. A Rejected answer removes the
+ * predicted bolt and refunds its round; a shot with no answer after TimeoutS (its unreliable
+ * ServerFire was lost) is treated the same way.
+ */
+struct VERSECOMBAT_API FVerseFirePredictor
+{
+ static constexpr float TimeoutS = 1.0f;
+
+ TArray<FVersePredictedShot> Pending;
+
+ void Add(const FVersePredictedShot& Shot) { Pending.Add(Shot); }
+
+ FVerseShotReconcile Confirm(uint16 Counter, EVerseShotResult Result);
+
+ /** Drops shots older than TimeoutS at Now; returns their counters. */
+ TArray<uint16> Expire(float Now);
+
+ int32 NumPending() const { return Pending.Num(); }
+
+ const FVersePredictedShot* Find(uint16 Counter) const;
+};
diff --git a/unreal/Verse/Source/VerseCombat/Public/Weapons/VerseImportDefinitionsCommandlet.h b/unreal/Verse/Source/VerseCombat/Public/Weapons/VerseImportDefinitionsCommandlet.h
new file mode 100644
index 0000000000..834f8afd3c
--- /dev/null
+++ b/unreal/Verse/Source/VerseCombat/Public/Weapons/VerseImportDefinitionsCommandlet.h
@@ -0,0 +1,26 @@
+#pragma once
+
+#include "Commandlets/Commandlet.h"
+#include "CoreMinimal.h"
+
+#include "VerseImportDefinitionsCommandlet.generated.h"
+
+/**
+ * WP02.1 importer: writes every weapon JSON of Data/weapons to its DA_Weapon_* asset and every
+ * entry of gadgets.json to its DA_Gadget_* asset under FVerseDefinitionJson::AssetFolder.
+ *
+ * UnrealEditor-Cmd.exe Verse.uproject -run=VerseImportDefinitions -unattended -nullrhi
+ * UnrealEditor-Cmd.exe Verse.uproject -run=VerseImportDefinitions -check (diff only, exit 1 on drift)
+ *
+ * Agents run it through scripts/unreal/with_lock.py (machine lock).
+ */
+UCLASS()
+class VERSECOMBAT_API UVerseImportDefinitionsCommandlet : public UCommandlet
+{
+ GENERATED_BODY()
+
+public:
+ UVerseImportDefinitionsCommandlet();
+
+ virtual int32 Main(const FString& Params) override;
+};
diff --git a/unreal/Verse/Source/VerseCombat/Public/Weapons/VerseRecoil.h b/unreal/Verse/Source/VerseCombat/Public/Weapons/VerseRecoil.h
new file mode 100644
index 0000000000..3c92378fc1
--- /dev/null
+++ b/unreal/Verse/Source/VerseCombat/Public/Weapons/VerseRecoil.h
@@ -0,0 +1,61 @@
+#pragma once
+
+#include "Combat/VerseCombatTypes.h"
+#include "CoreMinimal.h"
+
+class UVerseWeaponDefinition;
+
+/**
+ * Recoil state of one weapon (combat-state.md 4.1, 4.2, 11.2). Not replicated: the server and the
+ * owning client simulate it identically from the same seed, stance, ADS blend and look input (R5).
+ * Angles are degrees, X = pitch (positive = up), Y = yaw (positive = right).
+ */
+struct VERSECOMBAT_API FVerseRecoilState
+{
+ /** Shot index n within the current spray. */
+ int32 ShotIndex = 0;
+
+ /** Time of the last shot, seconds (server time on the server, predicted server time on the owner). */
+ float LastShotTime = -1000.f;
+
+ /** A: recoil applied and not yet recovered or compensated. */
+ FVector2f Accumulated = FVector2f::ZeroVector;
+
+ /** Spread bloom, degrees (4.4). */
+ float Bloom = 0.f;
+
+ /** Kick still being applied over RecoilKickTime (ease-out). */
+ FVector2f KickTotal = FVector2f::ZeroVector;
+ FVector2f KickApplied = FVector2f::ZeroVector;
+ float KickStartTime = -1000.f;
+
+ /** m = RecoilStanceMultiplier[stance] * lerp(1, RecoilAdsMultiplier, ads). */
+ static float Multiplier(const UVerseWeaponDefinition& W, EVerseStance Stance, float AdsBlend);
+
+ /** The smallest stance x ADS multiplier of the weapon (m_min of R1). */
+ static float MinMultiplier(const UVerseWeaponDefinition& W);
+
+ /** Index n the next shot at `Now` uses: 0 after PatternResetTime without a shot. */
+ int32 ShotIndexAt(const UVerseWeaponDefinition& W, float Now) const;
+
+ /** Resets the shot index when the pattern reset time has passed. Call before KickFor. */
+ void BeginShot(const UVerseWeaponDefinition& W, float Now);
+
+ /** k_n = m * (P(n) + f * |P(n)| * u_n), u_n from VerseRng(seed, n, Recoil). */
+ FVector2f KickFor(const UVerseWeaponDefinition& W, float Multiplier, uint32 Seed) const;
+
+ /** The pure kick formula for an explicit shot index. */
+ static FVector2f KickAt(const UVerseWeaponDefinition& W, int32 N, float Multiplier, uint32 Seed);
+
+ /** A += k_n, n += 1; starts the eased kick on the control rotation. */
+ void OnShot(const FVector2f& Kick, float Now);
+
+ /** Pulling against the recoil compensates it (4.2); the input itself is passed through unchanged. */
+ void OnLookInput(FVector2f& InOutDelta);
+
+ /** Part of the kick to add to the control rotation since the last call (ease-out over t_k). */
+ FVector2f TickKick(const UVerseWeaponDefinition& W, float Now);
+
+ /** Recovery of 4.2: returns the rotation to remove from the control rotation this tick. */
+ FVector2f TickRecovery(const UVerseWeaponDefinition& W, float Now, float Dt);
+};
diff --git a/unreal/Verse/Source/VerseCombat/Public/Weapons/VerseSpread.h b/unreal/Verse/Source/VerseCombat/Public/Weapons/VerseSpread.h
new file mode 100644
index 0000000000..b0d964a453
--- /dev/null
+++ b/unreal/Verse/Source/VerseCombat/Public/Weapons/VerseSpread.h
@@ -0,0 +1,98 @@
+#pragma once
+
+#include "Combat/VerseCombatTypes.h"
+#include "CoreMinimal.h"
+
+class UVerseWeaponDefinition;
+
+/** Everything the spread formula of combat-state.md 4.4 reads at the moment of a shot. */
+struct FVerseSpreadInput
+{
+ EVerseStance Stance = EVerseStance::Stand;
+ float AdsBlend = 0.f;
+ /** Horizontal speed, m/s. */
+ float HorizontalSpeedMps = 0.f;
+ bool bAirborne = false;
+};
+
+/**
+ * Spread, bloom, first-shot accuracy, the per-shot seed and the server's fire validation
+ * (combat-state.md 4.4). Pure functions plus a small bloom state; the server and the owning client
+ * evaluate the same inputs and draw the same direction.
+ */
+struct VERSECOMBAT_API FVerseSpread
+{
+ /** Server-side tolerance on the shot direction beyond sigma, degrees. */
+ static constexpr float DirectionToleranceDeg = 1.5f;
+ /** Largest accepted distance of the fire origin from the rewound eye point, cm. */
+ static constexpr float OriginToleranceCm = 30.f;
+
+ /** Bloom, degrees; grows per shot, decays at BloomRecoveryRate after BloomRecoveryDelay. */
+ float Bloom = 0.f;
+ float LastShotTime = -1000.f;
+
+ /** True when the next shot at `Now` is a first shot (rested at least FirstShotRestTime). */
+ bool IsFirstShot(const UVerseWeaponDefinition& W, float Now) const;
+
+ /** sigma of 4.4 for a shot at `Now` (before this shot's bloom is added). */
+ float SigmaFor(const UVerseWeaponDefinition& W, const FVerseSpreadInput& In, float Now) const;
+
+ /** sigma without the first-shot rule and without bloom decay (the server's validation bound uses this with Bloom = BloomMax). */
+ static float RestingSigma(const UVerseWeaponDefinition& W, const FVerseSpreadInput& In, float BloomDeg);
+
+ /** Decay bloom up to `Now`; call each tick or before a shot. */
+ void DecayTo(const UVerseWeaponDefinition& W, float Now, float Dt);
+
+ /**
+ * Decay between two shots: bloom drops at BloomRecoveryRate from LastShotTime + BloomRecoveryDelay
+ * up to `Now`. Owner and server both call it once per shot, before SigmaFor, so they derive the
+ * same sigma from the same shot times.
+ */
+ void DecayUntilShot(const UVerseWeaponDefinition& W, float Now);
+
+ /** Registers a shot at `Now`: first shot resets bloom to 0, then bloom += BloomPerShot (capped). */
+ void OnShot(const UVerseWeaponDefinition& W, float Now);
+
+ /** seed = Hash(shooter net id, shot counter, match seed). */
+ static uint32 ShotSeed(uint32 ShooterNetId, uint16 ShotCounter, uint32 MatchSeed);
+
+ /** dir = uniform in the cone of half-angle sigma around Forward, from VerseRng(seed, n, Spread). */
+ static FVector ShotDirection(const FVector& Forward, float SigmaDeg, uint32 Seed, int32 ShotIndex);
+
+ /**
+ * Server check of the drawn direction (4.4): the direction the server derives from its forward,
+ * its sigma, the seed and the shot index, against the client's, within DirectionToleranceDeg. A
+ * client that skips spread or steers the shot fails it. Near the aim pitch where the cone basis
+ * of ShotDirection switches axes, the check falls back to the sigma + tolerance cone.
+ */
+ static bool ValidateDirection(const FVector& Dir, const FVector& ServerForward, float SigmaDeg, uint32 Seed, int32 ShotIndex);
+
+ /** Server check of a fire request (4.4). False means the shot is answered with Rejected. */
+ static bool ValidateFire(const FVector& Origin, const FVector& Dir, const FVector& RewoundEye,
+ const FVector& ServerForward, float SigmaDeg);
+};
+
+/**
+ * Cyclic fire cadence with sub-tick timing. Shots are scheduled exactly FireInterval apart; a tick
+ * fires every shot whose scheduled time has passed, so the measured rate equals RPM at any tick
+ * rate and each shot carries its exact time (the projectile manager advances it by the remainder).
+ */
+struct VERSECOMBAT_API FVerseFireCadence
+{
+ /** Earliest time the next shot may go. */
+ float NextShotTime = -1000.f;
+ /** Rounds left in the current burst (Burst mode). */
+ int32 BurstLeft = 0;
+ /** Trigger was held on the previous tick (Semi needs a fresh press). */
+ bool bTriggerWasDown = false;
+
+ /**
+ * Scheduled times of the shots to fire during the tick ending at `Now`, given the trigger and the
+ * rounds available. `TickStart` is the start of the tick.
+ */
+ void Collect(const UVerseWeaponDefinition& W, bool bTriggerDown, float TickStart, float Now, int32 RoundsAvailable,
+ TArray<float>& OutShotTimes);
+
+ /** Server check: a shot at `Time` is not earlier than the cadence allows (1 ms grace). */
+ bool AllowsShotAt(const UVerseWeaponDefinition& W, float Time) const;
+};
diff --git a/unreal/Verse/Source/VerseCombat/Public/Weapons/VerseWeaponComponent.h b/unreal/Verse/Source/VerseCombat/Public/Weapons/VerseWeaponComponent.h
new file mode 100644
index 0000000000..24af280555
--- /dev/null
+++ b/unreal/Verse/Source/VerseCombat/Public/Weapons/VerseWeaponComponent.h
@@ -0,0 +1,196 @@
+#pragma once
+
+#include "Combat/VerseCombatTypes.h"
+#include "Components/ActorComponent.h"
+#include "CoreMinimal.h"
+#include "Inventory/VerseWeaponSlot.h"
+#include "Weapons/VerseFirePrediction.h"
+#include "Weapons/VerseRecoil.h"
+#include "Weapons/VerseSpread.h"
+
+#include "VerseWeaponComponent.generated.h"
+
+class UVerseInventoryComponent;
+class UVerseWeaponDefinition;
+struct FVerseBoltResult;
+
+/** Owner-side: a predicted shot left the muzzle (presentation draws the amber bolt). */
+DECLARE_MULTICAST_DELEGATE_OneParam(FOnVersePredictedFire, const FVerseFireEvent&);
+/** Owner-side: the server answered a shot (Rejected removes the predicted bolt). */
+DECLARE_MULTICAST_DELEGATE_TwoParams(FOnVerseShotAnswered, uint16 /*ShotCounter*/, EVerseShotResult /*Result*/);
+
+/** Any shooter's predicted shot was rejected or timed out (presentation removes the bolt). */
+DECLARE_MULTICAST_DELEGATE_TwoParams(FOnVerseAnyShotRejected, int32 /*ShooterId*/, uint16 /*ShotCounter*/);
+
+/** What the owner's fire step reads besides the definition (movement comes through IVerseMovementQuery). */
+struct FVerseFireContext
+{
+ /** Predicted server time at the end of this tick. */
+ float Now = 0.f;
+ float Dt = 1.f / 60.f;
+ bool bTriggerDown = false;
+ EVerseStance Stance = EVerseStance::Stand;
+ float HorizontalSpeedMps = 0.f;
+ bool bAirborne = false;
+ /** Sprinting or mantling (IVerseMovementQuery::BlocksFiring). */
+ bool bFiringBlocked = false;
+ /** Eye point, cm. */
+ FVector Eye = FVector::ZeroVector;
+ /** Control rotation at the start of the tick (recoil is added on top). */
+ FRotator Control = FRotator::ZeroRotator;
+};
+
+/** One shot the fire step produced. */
+struct FVerseShotOut
+{
+ uint16 Counter = 0;
+ uint32 Seed = 0;
+ int32 ShotIndex = 0;
+ float Time = 0.f;
+ float Sigma = 0.f;
+ FVector Origin = FVector::ZeroVector;
+ FVector Dir = FVector::ForwardVector;
+ FVector2f Kick = FVector2f::ZeroVector;
+};
+
+/**
+ * Firearms on a pawn (WP02.4-2.6, combat-state.md 4, 5, 11.2): ADS blend, recoil, spread, fire
+ * cadence, owner prediction and the server fire path. Recoil and spread are simulated on the owning
+ * client and the server from the same seed. ServerFire validates (30 cm origin, sigma + 1.5 deg),
+ * spends the round, spawns the bolt with the shooter's latency and raises the fire and shot noise
+ * events; the bolt's end comes back as ClientConfirmShot.
+ */
+UCLASS(ClassGroup = (Verse), meta = (BlueprintSpawnableComponent))
+class VERSECOMBAT_API UVerseWeaponComponent : public UActorComponent
+{
+ GENERATED_BODY()
+
+public:
+ UVerseWeaponComponent();
+
+ virtual void GetLifetimeReplicatedProps(TArray<FLifetimeProperty>& OutLifetimeProps) const override;
+ virtual void BeginPlay() override;
+
+ static UVerseWeaponComponent* FindOn(const AActor* Actor);
+
+ /** 0..255 = 0..1, replicated to all; drives spread, recoil multiplier and speed. */
+ UPROPERTY(Replicated)
+ uint8 AdsBlend = 0;
+
+ /** Match seed for the per-shot seed hash. The server draws one per spawn (BeginPlay) unless the game mode set it; it replicates. */
+ UPROPERTY(Replicated)
+ uint32 MatchSeed = 0;
+
+ /** Server: sets the match seed (game mode, per match). */
+ void SetMatchSeed(uint32 Seed);
+
+ /** How far a fire request's client time may lead the server clock, s. */
+ static constexpr float MaxClientLeadS = 0.05f;
+ /** How far it may lag behind; older requests are rejected (the latency advance is capped at 250 ms regardless). */
+ static constexpr float MaxClientLagS = 0.5f;
+ /** Shots the server-clock cadence lets through back to back (unreliable RPCs arrive bunched). */
+ static constexpr float ServerBurstShots = 3.f;
+
+ UFUNCTION(Server, Unreliable)
+ void ServerFire(uint16 ShotCounter, uint32 Seed, FVector_NetQuantize10 Origin, FVector_NetQuantizeNormal Dir, float ClientServerTime);
+
+ UFUNCTION(Client, Reliable)
+ void ClientConfirmShot(uint16 ShotCounter, EVerseShotResult Result, EVerseHitZone Zone, bool bKillingBlow);
+
+ UFUNCTION(NetMulticast, Unreliable)
+ void MulticastFire(const FVerseFireEvent& E);
+
+ UFUNCTION(NetMulticast, Unreliable)
+ void MulticastHitCosmetic(const FVerseHitEvent& E);
+
+ /** Unreliable multicast of FVersePenetrationEvent (combat-state.md 5.1). */
+ UFUNCTION(NetMulticast, Unreliable)
+ void MulticastPenetration(const FVersePenetrationEvent& E);
+
+ /**
+ * One fire step of the owner (person, bot or harness model): cadence, recoil, spread, ammo
+ * prediction. Shots are sent with ServerFire (or handled in place on the server). Returns the
+ * rotation to add to the control rotation this tick (kick minus recovery).
+ */
+ FRotator StepFire(const FVerseFireContext& Ctx, TArray<FVerseShotOut>* OutShots = nullptr);
+
+ /** Look input passes through the recoil compensation rule (4.2). */
+ void ApplyLookInput(FVector2f& InOutLookDeltaDeg) { Recoil.OnLookInput(InOutLookDeltaDeg); }
+
+ /** Sets the ADS blend target (0..1) and moves AdsBlend toward it at 1 / AdsTime. */
+ void StepAds(bool bAdsHeld, float Dt);
+ float GetAdsBlend01() const { return float(AdsBlend) / 255.f; }
+
+ /** Server side of a fire request; ServerFire forwards here, the listen-server owner and bots call it directly. */
+ EVerseShotResult HandleServerFire(uint16 ShotCounter, uint32 Seed, const FVector& Origin, const FVector& Dir, float ClientServerTime);
+
+ /** The projectile manager reports how a bolt of this shooter ended. */
+ void HandleBoltResolved(const FVerseBoltResult& Result);
+
+ /** Owner: the answer for a shot (ClientConfirmShot lands here). */
+ void HandleConfirm(uint16 ShotCounter, EVerseShotResult Result);
+
+ /** Raises a cosmetic impact (victim -1) on the local hub when this world has a viewer (not a dedicated server). */
+ static void RaiseLocalImpact(const UObject* WorldContext, const FVerseHitEvent& Impact);
+
+ /** Player id of the shooter as events carry it. */
+ int32 GetShooterId() const;
+
+ const FVerseRecoilState& GetRecoil() const { return Recoil; }
+ const FVerseSpread& GetSpread() const { return Spread; }
+ const FVerseFirePredictor& GetPredictor() const { return Predictor; }
+
+ /** Server simulation of this shooter's recoil and spread from the requests it accepted (R5, 4.4). */
+ const FVerseRecoilState& GetServerRecoil() const { return ServerRecoil; }
+ const FVerseSpread& GetServerSpread() const { return ServerSpread; }
+ /** Kick, sigma and shot index the server derived for the last request that passed the clock checks. */
+ FVector2f GetLastServerKick() const { return LastServerKick; }
+ float GetLastServerSigma() const { return LastServerSigma; }
+ int32 GetLastServerShotIndex() const { return LastServerShotIndex; }
+
+ /** Owner-side predicted state of the active weapon. */
+ const FVerseWeaponSlotState& GetPredictedSlot() const { return PredictedSlot; }
+
+ /** Re-reads the predicted slot from the replicated state (no shot pending). */
+ void ResyncPredictedSlot();
+
+ FOnVersePredictedFire OnPredictedFire;
+ FOnVerseShotAnswered OnShotAnswered;
+ static FOnVerseAnyShotRejected OnAnyShotRejected;
+
+ /** Server-side validation of the eye point: the rewound eye at the shot's view time. Tests may override. */
+ TFunction<FVector(double ViewTime)> RewoundEyeOverride;
+ /** Server control-rotation forward. Tests may override. */
+ TFunction<FVector()> ServerForwardOverride;
+
+ /** Validation can be turned off for harness bots that fire without a controller (never in a match). */
+ bool bServerValidates = true;
+
+private:
+ UVerseInventoryComponent* GetInventory() const;
+ const UVerseWeaponDefinition* GetActiveDefinition() const;
+ FVector ServerEye(double ViewTime) const;
+ FVector ServerForward() const;
+
+ FVerseRecoilState Recoil;
+ FVerseSpread Spread;
+ FVerseFireCadence Cadence;
+ FVerseFirePredictor Predictor;
+ FVerseWeaponSlotState PredictedSlot;
+ FName PredictedWeaponId;
+ uint16 NextShotCounter = 0;
+ float LastStepTime = -1.f;
+
+ /** Server cadence check on client times. */
+ float ServerLastShotClientTime = -1000.f;
+ /** Server-clock cadence: shots allowed now (refills at 1 / FireInterval per server second). */
+ float ServerShotBudget = ServerBurstShots;
+ float ServerBudgetTime = -1.f;
+ /** Server simulation of the owner's recoil and spread. */
+ FVerseRecoilState ServerRecoil;
+ FVerseSpread ServerSpread;
+ uint16 ServerLastCounter = 0;
+ FVector2f LastServerKick = FVector2f::ZeroVector;
+ float LastServerSigma = 0.f;
+ int32 LastServerShotIndex = 0;
+};
diff --git a/unreal/Verse/Source/VerseCombat/Public/Weapons/VerseWeaponRegistry.h b/unreal/Verse/Source/VerseCombat/Public/Weapons/VerseWeaponRegistry.h
new file mode 100644
index 0000000000..b92d41654b
--- /dev/null
+++ b/unreal/Verse/Source/VerseCombat/Public/Weapons/VerseWeaponRegistry.h
@@ -0,0 +1,24 @@
+#pragma once
+
+#include "CoreMinimal.h"
+
+class UVerseGadgetDefinition;
+class UVerseWeaponDefinition;
+
+/**
+ * Finds weapon and gadget definitions by id: the DA_Weapon_* / DA_Gadget_* asset under
+ * FVerseDefinitionJson::AssetFolder when it exists, else the definition imported from the JSON in
+ * Data/weapons (kept alive for the process). Game thread only.
+ */
+struct VERSECOMBAT_API FVerseWeaponRegistry
+{
+ static const UVerseWeaponDefinition* FindWeapon(FName WeaponId);
+ static const UVerseGadgetDefinition* FindGadget(FName GadgetId);
+
+ /** The definition saved as an asset, or nullptr. */
+ static const UVerseWeaponDefinition* LoadWeaponAsset(FName WeaponId);
+ static const UVerseGadgetDefinition* LoadGadgetAsset(FName GadgetId);
+
+ /** Drops the JSON cache (tests). */
+ static void ResetCache();
+};
diff --git a/unreal/Verse/Source/VerseCombat/VerseCombat.Build.cs b/unreal/Verse/Source/VerseCombat/VerseCombat.Build.cs
index acd5b3448a..7484dc941a 100644
--- a/unreal/Verse/Source/VerseCombat/VerseCombat.Build.cs
+++ b/unreal/Verse/Source/VerseCombat/VerseCombat.Build.cs
@@ -9,5 +9,11 @@ public class VerseCombat : ModuleRules
PCHUsage = PCHUsageMode.UseExplicitOrSharedPCHs;
PublicDependencyModuleNames.AddRange(new string[] { "Core", "CoreUObject", "Engine", "NetCore" });
PublicDependencyModuleNames.AddRange(new string[] { "VerseCore", "VerseMovement", "VerseDestruction" });
+ // GAS for health, damage effects and the gadget abilities (architecture.md 2 rule 4, 3.2 "Abilities").
+ PublicDependencyModuleNames.AddRange(new string[] { "GameplayTags", "GameplayAbilities", "GameplayTasks" });
+ // Json: the weapon and gadget definition importer (WP02.1).
+ PrivateDependencyModuleNames.AddRange(new string[] { "Json" });
+ // MeshDescription: the WP02 placeholder shapes are built in code until WP14 art lands.
+ PrivateDependencyModuleNames.AddRange(new string[] { "MeshDescription", "StaticMeshDescription" });
}
}