diff --git a/Assets/Gothic-Core/Localizations/Gothic-UI Shared Data.asset b/Assets/Gothic-Core/Localizations/Gothic-UI Shared Data.asset index 05deaaae1..c3ddf5408 100644 --- a/Assets/Gothic-Core/Localizations/Gothic-UI Shared Data.asset +++ b/Assets/Gothic-Core/Localizations/Gothic-UI Shared Data.asset @@ -579,6 +579,18 @@ MonoBehaviour: m_Key: menuitem.heroLandingView.description m_Metadata: m_Items: [] + - m_Id: 199086245615902720 + m_Key: menuitem.ledgeGrabFalling.label + m_Metadata: + m_Items: [] + - m_Id: 199086245653651456 + m_Key: menuitem.ledgeGrabFalling.value + m_Metadata: + m_Items: [] + - m_Id: 199086245653651457 + m_Key: menuitem.ledgeGrabFalling.description + m_Metadata: + m_Items: [] m_Metadata: m_Items: [] m_KeyGenerator: diff --git a/Assets/Gothic-Core/Localizations/Gothic-UI_cs.asset b/Assets/Gothic-Core/Localizations/Gothic-UI_cs.asset index 8ca0925b0..a17a49b9b 100644 --- a/Assets/Gothic-Core/Localizations/Gothic-UI_cs.asset +++ b/Assets/Gothic-Core/Localizations/Gothic-UI_cs.asset @@ -482,6 +482,19 @@ MonoBehaviour: z\u016Fstane stranou (nekles\xE1) nebo klesne a vstane s t\u011Blem" m_Metadata: m_Items: [] + - m_Id: 199086245615902720 + m_Localized: "\xDAchop p\u0159i p\xE1du" + m_Metadata: + m_Items: [] + - m_Id: 199086245653651456 + m_Localized: vyp|zap + m_Metadata: + m_Items: [] + - m_Id: 199086245653651457 + m_Localized: "Chyt\xE1n\xED \u0159\xEDmsy p\u0159i p\xE1du. Vyp: jako v Gothicu, + bez \xFAchopu." + m_Metadata: + m_Items: [] references: version: 2 RefIds: [] diff --git a/Assets/Gothic-Core/Localizations/Gothic-UI_de.asset b/Assets/Gothic-Core/Localizations/Gothic-UI_de.asset index 38b6584e1..d22f75ec6 100644 --- a/Assets/Gothic-Core/Localizations/Gothic-UI_de.asset +++ b/Assets/Gothic-Core/Localizations/Gothic-UI_de.asset @@ -608,6 +608,18 @@ MonoBehaviour: bleibt daneben (sie sinkt nicht) oder geht mit dem K\xF6rper runter und hoch" m_Metadata: m_Items: [] + - m_Id: 199086245615902720 + m_Localized: Greifen im Fall + m_Metadata: + m_Items: [] + - m_Id: 199086245653651456 + m_Localized: aus|an + m_Metadata: + m_Items: [] + - m_Id: 199086245653651457 + m_Localized: 'Kanten im Fallen greifen. Aus: wie in Gothic, kein Griff.' + m_Metadata: + m_Items: [] references: version: 2 RefIds: [] diff --git a/Assets/Gothic-Core/Localizations/Gothic-UI_en.asset b/Assets/Gothic-Core/Localizations/Gothic-UI_en.asset index c8728bcaf..68a648463 100644 --- a/Assets/Gothic-Core/Localizations/Gothic-UI_en.asset +++ b/Assets/Gothic-Core/Localizations/Gothic-UI_en.asset @@ -620,6 +620,18 @@ MonoBehaviour: aside (it doesn''t go down) or goes down and up with the body' m_Metadata: m_Items: [] + - m_Id: 199086245615902720 + m_Localized: Grab While Falling + m_Metadata: + m_Items: [] + - m_Id: 199086245653651456 + m_Localized: off|on + m_Metadata: + m_Items: [] + - m_Id: 199086245653651457 + m_Localized: 'Catch ledges while falling. Off: like Gothic, no grab.' + m_Metadata: + m_Items: [] references: version: 2 RefIds: [] diff --git a/Assets/Gothic-Core/Localizations/Gothic-UI_es.asset b/Assets/Gothic-Core/Localizations/Gothic-UI_es.asset index 9194dac85..9ef17b2e2 100644 --- a/Assets/Gothic-Core/Localizations/Gothic-UI_es.asset +++ b/Assets/Gothic-Core/Localizations/Gothic-UI_es.asset @@ -471,6 +471,18 @@ MonoBehaviour: la vista se queda a un lado (no baja) o baja y sube con el cuerpo" m_Metadata: m_Items: [] + - m_Id: 199086245615902720 + m_Localized: Agarrar al caer + m_Metadata: + m_Items: [] + - m_Id: 199086245653651456 + m_Localized: "no|s\xED" + m_Metadata: + m_Items: [] + - m_Id: 199086245653651457 + m_Localized: 'Agarrar bordes al caer. No: como en Gothic, sin agarre.' + m_Metadata: + m_Items: [] references: version: 2 RefIds: [] diff --git a/Assets/Gothic-Core/Localizations/Gothic-UI_fr.asset b/Assets/Gothic-Core/Localizations/Gothic-UI_fr.asset index 141239cfd..c937f11cc 100644 --- a/Assets/Gothic-Core/Localizations/Gothic-UI_fr.asset +++ b/Assets/Gothic-Core/Localizations/Gothic-UI_fr.asset @@ -477,6 +477,18 @@ MonoBehaviour: remonte avec le corps" m_Metadata: m_Items: [] + - m_Id: 199086245615902720 + m_Localized: Saisir en chute + m_Metadata: + m_Items: [] + - m_Id: 199086245653651456 + m_Localized: non|oui + m_Metadata: + m_Items: [] + - m_Id: 199086245653651457 + m_Localized: 'Saisir les rebords en tombant. Non : comme dans Gothic.' + m_Metadata: + m_Items: [] references: version: 2 RefIds: [] diff --git a/Assets/Gothic-Core/Localizations/Gothic-UI_it.asset b/Assets/Gothic-Core/Localizations/Gothic-UI_it.asset index 5456bf584..6739a9e30 100644 --- a/Assets/Gothic-Core/Localizations/Gothic-UI_it.asset +++ b/Assets/Gothic-Core/Localizations/Gothic-UI_it.asset @@ -472,6 +472,18 @@ MonoBehaviour: visuale resta a lato (non scende) o scende e risale col corpo' m_Metadata: m_Items: [] + - m_Id: 199086245615902720 + m_Localized: Presa in caduta + m_Metadata: + m_Items: [] + - m_Id: 199086245653651456 + m_Localized: "no|s\xEC" + m_Metadata: + m_Items: [] + - m_Id: 199086245653651457 + m_Localized: 'Afferrare sporgenze cadendo. No: come in Gothic, nessuna presa.' + m_Metadata: + m_Items: [] references: version: 2 RefIds: [] diff --git a/Assets/Gothic-Core/Localizations/Gothic-UI_pl.asset b/Assets/Gothic-Core/Localizations/Gothic-UI_pl.asset index bf4c32307..c5f92eb1f 100644 --- a/Assets/Gothic-Core/Localizations/Gothic-UI_pl.asset +++ b/Assets/Gothic-Core/Localizations/Gothic-UI_pl.asset @@ -478,6 +478,18 @@ MonoBehaviour: zostaje z boku (nie opada) albo opada i wstaje razem z cia\u0142em" m_Metadata: m_Items: [] + - m_Id: 199086245615902720 + m_Localized: Chwyt przy spadaniu + m_Metadata: + m_Items: [] + - m_Id: 199086245653651456 + m_Localized: nie|tak + m_Metadata: + m_Items: [] + - m_Id: 199086245653651457 + m_Localized: "\u0141apanie kraw\u0119dzi podczas spadania. Nie: jak w Gothicu." + m_Metadata: + m_Items: [] references: version: 2 RefIds: [] diff --git a/Assets/Gothic-Core/Localizations/Gothic-UI_ru.asset b/Assets/Gothic-Core/Localizations/Gothic-UI_ru.asset index 54b13c3a7..804e2710b 100644 --- a/Assets/Gothic-Core/Localizations/Gothic-UI_ru.asset +++ b/Assets/Gothic-Core/Localizations/Gothic-UI_ru.asset @@ -567,6 +567,20 @@ MonoBehaviour: \u0441 \u0442\u0435\u043B\u043E\u043C" m_Metadata: m_Items: [] + - m_Id: 199086245615902720 + m_Localized: "\u0425\u0432\u0430\u0442 \u043F\u0440\u0438 \u043F\u0430\u0434\u0435\u043D\u0438\u0438" + m_Metadata: + m_Items: [] + - m_Id: 199086245653651456 + m_Localized: "\u0432\u044B\u043A\u043B|\u0432\u043A\u043B" + m_Metadata: + m_Items: [] + - m_Id: 199086245653651457 + m_Localized: "\u0425\u0432\u0430\u0442\u0430\u0442\u044C\u0441\u044F \u0437\u0430 + \u0443\u0441\u0442\u0443\u043F\u044B \u043F\u0440\u0438 \u043F\u0430\u0434\u0435\u043D\u0438\u0438. + \u0412\u044B\u043A\u043B: \u043A\u0430\u043A \u0432 Gothic." + m_Metadata: + m_Items: [] references: version: 2 RefIds: [] diff --git a/Assets/Gothic-Core/Scripts/Domain/Movement/LedgeProbeDomain.cs b/Assets/Gothic-Core/Scripts/Domain/Movement/LedgeProbeDomain.cs index ce3fbb65a..135dc6aef 100644 --- a/Assets/Gothic-Core/Scripts/Domain/Movement/LedgeProbeDomain.cs +++ b/Assets/Gothic-Core/Scripts/Domain/Movement/LedgeProbeDomain.cs @@ -37,6 +37,11 @@ public class LedgeProbeDomain /// private const float _wallSearchBack = 0.4f; + /// + /// With a reach (ProbeEdge), the top is searched with one ray down per this many m further along the approach. + /// + private const float _reachStep = 0.15f; + private const float _edgeSearchStep = 0.1f; private const float _edgeSearchMax = 2f; private const float _clearance = 0.05f; @@ -117,25 +122,25 @@ public LedgeInfo ProbeAhead(Vector3 feet, Vector3 forward, LedgeBody body, Ledge /// /// A point near a lip (e.g. a hand), approached along approach. The ledge counts from baseFeetY (the floor /// the climb starts from) or, without one, from the floor at the wall's foot. + /// reach (m, 0 = right at the point): the top is also searched this much higher, lower and further along the + /// approach - a hand jumping below a lip finds it from further away. The other rules stay the same. /// public LedgeInfo ProbeEdge(Vector3 nearPoint, Vector3 approach, float? baseFeetY, LedgeBody body, - LedgeRules rules) + LedgeRules rules, float reach = 0f) { var direction = Flatten(approach); if (direction == Vector3.zero) return LedgeInfo.NoLedge; - // The top right behind the point. - var topStart = nearPoint + direction * _topInward + Vector3.up * _topSearchRange; - if (!Physics.Raycast(topStart, Vector3.down, out var topHit, _topSearchRange * 2f, body.SurfaceLayerMask, - QueryTriggerInteraction.Ignore) || !IsWalkable(topHit.normal, rules)) + // The top right behind the point (with a reach: the walkable top nearest to it). + if (!TryFindTop(nearPoint, direction, Mathf.Max(0f, reach), body, rules, out var topHit, out var inward)) return LedgeInfo.NoLedge; var topY = topHit.point.y; // A wall below the top: without one, the point is above a slope or open floor, not at a lip. var wallStart = new Vector3(nearPoint.x, topY - _lipDepth, nearPoint.z) - direction * _wallSearchBack; - if (!Physics.Raycast(wallStart, direction, out var wallHit, _wallSearchBack + _topInward * 2f, + if (!Physics.Raycast(wallStart, direction, out var wallHit, _wallSearchBack + inward + _topInward, body.SurfaceLayerMask, QueryTriggerInteraction.Ignore) || IsWalkable(wallHit.normal, rules)) return LedgeInfo.NoLedge; @@ -263,6 +268,40 @@ public LedgeInfo ProbeNpcClimb(Vector3 position, float restHeight, Vector3 direc }; } + /// + /// ProbeEdge's top: a ray down _topInward behind the point, from _topSearchRange above it to as far below. + /// With a reach, one more ray every _reachStep up to reach further along direction, each reach higher and + /// lower: the walkable hit nearest to the point wins (a crate below the hand doesn't hide the lip above it). + /// inward: how far along direction the winning ray went down. + /// + private static bool TryFindTop(Vector3 nearPoint, Vector3 direction, float reach, LedgeBody body, + LedgeRules rules, out RaycastHit topHit, out float inward) + { + topHit = default; + inward = _topInward; + var range = _topSearchRange + reach; + var bestDistanceSqr = float.MaxValue; + var steps = Mathf.CeilToInt(reach / _reachStep); + for (var i = 0; i <= steps; i++) + { + var rayInward = _topInward + Mathf.Min(i * _reachStep, reach); + var start = nearPoint + direction * rayInward + Vector3.up * range; + if (!Physics.Raycast(start, Vector3.down, out var hit, range * 2f, body.SurfaceLayerMask, + QueryTriggerInteraction.Ignore) || !IsWalkable(hit.normal, rules)) + continue; + + var distanceSqr = (hit.point - nearPoint).sqrMagnitude; + if (distanceSqr >= bestDistanceSqr) + continue; + + bestDistanceSqr = distanceSqr; + topHit = hit; + inward = rayInward; + } + + return bestDistanceSqr < float.MaxValue; + } + private static LedgeBand Classify(float height, LedgeRules rules) { if (height < rules.JumpLowHeight) diff --git a/Assets/Gothic-Core/Scripts/Services/Movement/LedgeService.cs b/Assets/Gothic-Core/Scripts/Services/Movement/LedgeService.cs index 49c732d5d..c6ff88c7b 100644 --- a/Assets/Gothic-Core/Scripts/Services/Movement/LedgeService.cs +++ b/Assets/Gothic-Core/Scripts/Services/Movement/LedgeService.cs @@ -94,11 +94,13 @@ public LedgeInfo ProbeAhead(Vector3 feet, Vector3 forward, LedgeBody body) } /// - /// A ledge at a point near its lip (a hand), counted from the floor the climb starts from. + /// A ledge at a point near its lip (a hand), counted from the floor the climb starts from. reach (m): the lip + /// may also be this much further away (a hand in a jump, LedgeProbeDomain.ProbeEdge). /// - public LedgeInfo ProbeEdge(Vector3 nearPoint, Vector3 approach, float baseFeetY, LedgeBody body) + public LedgeInfo ProbeEdge(Vector3 nearPoint, Vector3 approach, float baseFeetY, LedgeBody body, + float reach = 0f) { - return _probeDomain.ProbeEdge(nearPoint, approach, baseFeetY, body, HeroRules); + return _probeDomain.ProbeEdge(nearPoint, approach, baseFeetY, body, HeroRules, reach); } /// @@ -110,6 +112,16 @@ public LedgeInfo ProbeTop(Vector3 target, Vector3 from, LedgeBody body) return _probeDomain.ProbeTop(target, from, body, HeroRules); } + /// + /// Whether the hero can catch a ledge in this air phase (HeroFallService.Phase): not while falling, like in + /// Gothic - a falling hero lands. allowWhileFalling: the player's option to catch ledges anyway (VR's + /// ledgeGrabFalling). How far a hand reaches is up to the platform. + /// + public bool CanCatchLedge(HeroAirPhase phase, bool allowWhileFalling) + { + return phase != HeroAirPhase.Falling || allowWhileFalling; + } + private static LedgeRules CreateHeroRules(GuildValuesInstance values) { const int guild = (int)VmGothicEnums.Guild.GIL_HUMAN; diff --git a/Assets/Gothic-Tests/PlayMode/LedgeProbeTest.cs b/Assets/Gothic-Tests/PlayMode/LedgeProbeTest.cs index e1b340fb8..dd7251567 100644 --- a/Assets/Gothic-Tests/PlayMode/LedgeProbeTest.cs +++ b/Assets/Gothic-Tests/PlayMode/LedgeProbeTest.cs @@ -117,6 +117,22 @@ public void ProbeEdgeAtHand(float height, LedgeBand expected) Assert.That(info.StandPoint.z, Is.GreaterThan(WallZ + Body.Radius), "The stand point is on the top."); } + [Test] + public void ProbeEdgeWithReachFindsTheLipAboveAJumpingHand() + { + CreateBlock(2.5f); + var hand = new Vector3(0f, 2f, WallZ - 0.3f); + + Assert.AreEqual(LedgeBand.None, _domain.ProbeEdge(hand, Vector3.forward, 0f, Body, Rules).Band, + "Without a reach the lip is too far from the hand."); + + var info = _domain.ProbeEdge(hand, Vector3.forward, 0f, Body, Rules, 0.6f); + + Assert.AreEqual(LedgeBand.High, info.Band); + Assert.AreEqual(WallZ, info.EdgePoint.z, 0.01f); + Assert.AreEqual(2.5f, info.EdgePoint.y, 0.01f); + } + [Test] public void ProbeEdgeAtOpenFloorIsNoLedge() { diff --git a/Assets/Gothic-VR/Scripts/Domain/Player/VrLedgeClimber.cs b/Assets/Gothic-VR/Scripts/Domain/Player/VrLedgeClimber.cs index 59cdf474c..44c5932b8 100644 --- a/Assets/Gothic-VR/Scripts/Domain/Player/VrLedgeClimber.cs +++ b/Assets/Gothic-VR/Scripts/Domain/Player/VrLedgeClimber.cs @@ -58,16 +58,17 @@ public LedgeInfo ProbeAhead() } /// - /// The lip a hand reaches from the head, counted from the floor at baseFeetY. + /// The lip a hand reaches from the head, counted from the floor at baseFeetY. reach (m): the lip may also be + /// this much further from the hand (VrLedgeReach's jump reach). /// - public LedgeInfo ProbeAtHand(Vector3 hand, float baseFeetY) + public LedgeInfo ProbeAtHand(Vector3 hand, float baseFeetY, float reach = 0f) { var approach = hand - Rig.Head.position; approach.y = 0f; if (approach.sqrMagnitude < 0.01f) approach = Rig.Head.forward; - return _ledgeService.ProbeEdge(hand, approach, baseFeetY, Body); + return _ledgeService.ProbeEdge(hand, approach, baseFeetY, Body, reach); } /// diff --git a/Assets/Gothic-VR/Scripts/Domain/Player/VrLedgeReachMode.cs b/Assets/Gothic-VR/Scripts/Domain/Player/VrLedgeReachMode.cs new file mode 100644 index 000000000..a638c0c23 --- /dev/null +++ b/Assets/Gothic-VR/Scripts/Domain/Player/VrLedgeReachMode.cs @@ -0,0 +1,73 @@ +using Gothic.Core.Logging; +using Gothic.Core.Models.Movement; +using Gothic.Core.Services.Movement; +using Gothic.VR.Interaction.Models; +using Logger = Gothic.Core.Logging.Logger; + +namespace Gothic.VR.Domain.Player +{ + /// + /// Which reach the hands have for ledges (VrLedgeReach), from the hero's air phase (HeroFallService.Phase): + /// Blocked while he can't catch a ledge (LedgeService.CanCatchLedge: falling, unless the player's option allows + /// it), Jump in his jump and for the grace after its landing (not while climbing), else Normal. Logged when it + /// changes. Owned by VrLedgeReach. + /// + public class VrLedgeReachMode + { + private readonly LedgeService _ledgeService; + private readonly float _jumpReach; + private readonly float _jumpGrace; + + // The jump reach holds until this time, set while jumping. + private float _jumpEndTime = float.MinValue; + + /// The hands' reach in a jump (m), for the log. + /// Seconds after a jump's landing in which the jump reach still holds. + public VrLedgeReachMode(LedgeService ledgeService, float jumpReach, float jumpGrace) + { + _ledgeService = ledgeService; + _jumpReach = jumpReach; + _jumpGrace = jumpGrace; + } + + public VrLedgeReachKind Current { get; private set; } = VrLedgeReachKind.Normal; + + /// + /// The Immersion option ledgeGrabFalling: a falling hero catches ledges, with the normal reach. + /// + public bool IsGrabWhileFalling { get; set; } + + /// + /// Once per frame, before the hands look for lips. time: Time.time. true if the mode changed. + /// + public bool Update(HeroAirPhase phase, bool isClimbing, float time) + { + if (phase == HeroAirPhase.Jumping) + _jumpEndTime = time + _jumpGrace; + else if (phase == HeroAirPhase.Falling) + _jumpEndTime = float.MinValue; + + VrLedgeReachKind mode; + if (!_ledgeService.CanCatchLedge(phase, IsGrabWhileFalling)) + mode = VrLedgeReachKind.Blocked; + else if (!isClimbing && time <= _jumpEndTime) + mode = VrLedgeReachKind.Jump; + else + mode = VrLedgeReachKind.Normal; + + if (mode == Current) + return false; + + Current = mode; + Logger.Log(mode switch + { + VrLedgeReachKind.Jump => $"[Ledge] Jump reach on: lips within {_jumpReach:F2} m of a hand can be " + + "gripped.", + VrLedgeReachKind.Blocked => "[Ledge] Falling: no ledge can be grabbed (Immersion option " + + "ledgeGrabFalling is off).", + _ => $"[Ledge] Normal reach ({phase})." + }, LogCat.VR); + return true; + } + } +} diff --git a/Assets/Gothic-VR/Scripts/Domain/Player/VrLedgeReachMode.cs.meta b/Assets/Gothic-VR/Scripts/Domain/Player/VrLedgeReachMode.cs.meta new file mode 100644 index 000000000..bb30f32f1 --- /dev/null +++ b/Assets/Gothic-VR/Scripts/Domain/Player/VrLedgeReachMode.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: cda0ab3731bda27468f3abcf8a4793ec \ No newline at end of file diff --git a/Assets/Gothic-VR/Scripts/Interaction/Backends/Xri/XriGrabberBridge.cs b/Assets/Gothic-VR/Scripts/Interaction/Backends/Xri/XriGrabberBridge.cs index a9b539d44..4feadca56 100644 --- a/Assets/Gothic-VR/Scripts/Interaction/Backends/Xri/XriGrabberBridge.cs +++ b/Assets/Gothic-VR/Scripts/Interaction/Backends/Xri/XriGrabberBridge.cs @@ -1,4 +1,5 @@ using System; +using System.Collections.Generic; using Gothic.Core.Logging; using Gothic.VR.Interaction.Components; using Gothic.VR.Interaction.Models; @@ -34,6 +35,9 @@ public class XriGrabberBridge : MonoBehaviour, IVrGrabber public event Action Grabbed; public event Action Released; + // GetTouched's overlap, shared by both hands (main thread, one call at a time). + private static readonly Collider[] _touchBuffer = new Collider[16]; + private NearFarInteractor _interactor; private VrGrabberKind _heldKind = VrGrabberKind.Hand; private bool _isSubscribed; @@ -213,6 +217,33 @@ public void ForceRelease() Interactor.interactionManager.CancelInteractorSelection((IXRSelectInteractor)Interactor); } + /// + /// One overlap at the near caster, as far as a grab still counts as Hand (ResolveKind), with the caster's + /// layers and triggers. Colliders map to interactables like the caster's do (the interaction manager), so + /// the list is what the hand could take now - not only the closest one, which is all the hover shows. + /// + public void GetTouched(List results) + { + results.Clear(); + var manager = Interactor.interactionManager; + if (manager == null || !Interactor.enableNearCasting || + Interactor.nearInteractionCaster is not SphereInteractionCaster caster) + return; + + var origin = caster.effectiveCastOrigin != null ? caster.effectiveCastOrigin : Interactor.transform; + var count = Physics.OverlapSphereNonAlloc(origin.position, caster.castRadius + _nearGrabMargin, + _touchBuffer, caster.physicsLayerMask, caster.physicsTriggerInteraction); + for (var i = 0; i < count; i++) + { + if (!manager.TryGetInteractableForCollider(_touchBuffer[i], out var xrInteractable)) + continue; + + var interactable = GetInteractable(xrInteractable); + if (interactable != null && !results.Contains(interactable)) + results.Add(interactable); + } + } + /// /// Args of a selection that starts now. Remembers the kind (Hand or Distance) until the release. /// diff --git a/Assets/Gothic-VR/Scripts/Interaction/Backends/Xri/XriInteractableBridge.cs b/Assets/Gothic-VR/Scripts/Interaction/Backends/Xri/XriInteractableBridge.cs index 71de66498..6b0d018a0 100644 --- a/Assets/Gothic-VR/Scripts/Interaction/Backends/Xri/XriInteractableBridge.cs +++ b/Assets/Gothic-VR/Scripts/Interaction/Backends/Xri/XriInteractableBridge.cs @@ -1,3 +1,4 @@ +using System.Collections; using System.Collections.Generic; using System.Linq; using Gothic.Core.Logging; @@ -22,9 +23,21 @@ namespace Gothic.VR.Interaction.Backends.Xri /// Prefabs carry the components of both backends. The XRI interactable is disabled in the prefab and only this /// bridge enables it, if XRI is the active backend. Otherwise, it stays disabled and never looks for (or /// creates) an XRInteractionManager. + /// + /// A climbable with an IVrGripOffset next to it (a ledge anchor in the jump reach) pulls the body when a hand + /// grips it directly, before XRI's ClimbProvider holds the hand (PullToGrip). /// public class XriInteractableBridge : MonoBehaviour, IVrInteractableBackend { + // A grip offset shorter than this (m) grips where the hand is. + private const float GripMinPull = 0.01f; + + // A pulled hand this far (m) from its grip a frame later is off its hold: warned. + private const float GripPullTolerance = 0.05f; + + // Once per session for all bridges: the cause is the same each time. + private static bool _isGripPullWarned; + [Tooltip("Trigger colliders that count for hovering and grabbing by hand anyway (XRI ignores triggers). " + "E.g. the backpack's grab volume, which HVR used, as its hull alone is hard to grab.")] [SerializeField] @@ -41,6 +54,8 @@ public class XriInteractableBridge : MonoBehaviour, IVrInteractableBackend private XRBaseInteractable _xrInteractable; private VrInteractable _interactable; + // Climbables only: asked how far a hand's grip pulls the body, null for most. + private IVrGripOffset _gripOffset; private bool _isSubscribed; private float _lastHandReleaseTime = float.NegativeInfinity; private bool _isGrabEnabled = true; @@ -135,6 +150,9 @@ private void TrySubscribe() return; } + if (_xrInteractable is ClimbInteractable) + _gripOffset = GetComponent(); + _xrInteractable.hoverEntered.AddListener(OnHoverEntered); _xrInteractable.hoverExited.AddListener(OnHoverExited); _xrInteractable.selectEntered.AddListener(OnSelectEntered); @@ -340,9 +358,67 @@ private void OnSelectEntered(SelectEnterEventArgs args) _selectArgs[args.interactorObject] = grabArgs; } + if (_gripOffset != null && grabArgs.Kind == VrGrabberKind.Hand) + PullToGrip(args.interactorObject, grabArgs); + _interactable.RaiseGrabbed(grabArgs); } + /// + /// Moves the body by the climbable's grip offset (IVrGripOffset), so that the climb starts with the hand on + /// its hold. XRI 3.6.1: ClimbInteractable.OnSelectEntered raises selectEntered (this listener) before + /// ClimbProvider.StartClimbGrab, which anchors the hand at its world position then - with all + /// allowFree*Movement on, moving the anchor afterwards changes nothing. So the move happens here, within the + /// select event; CheckPulledGrip warns once if that order ever changes. Not while a hand already climbs: the + /// move would tear that hand off its hold, this one grips where it is. + /// + private void PullToGrip(IXRSelectInteractor interactor, VrGrabArgs grabArgs) + { + var rig = interactor is Component component ? component.GetComponentInParent() : null; + if (rig == null) + return; + + var hand = grabArgs.HandSide == VrHandSide.Left ? rig.LeftHand : rig.RightHand; + var start = hand.position; + var offset = _gripOffset.GetGripOffset(start); + if (offset.sqrMagnitude < GripMinPull * GripMinPull) + return; + + if (rig.IsClimbing) + { + Logger.Log($"[XRI] Grip pull: the {grabArgs.HandSide} hand grips {name} at {transform.position} " + + $"{offset.magnitude:F2} m off, where it is - another hand climbs already.", LogCat.VR); + return; + } + + rig.PullBody(offset); + var pulled = Vector3.Distance(start, hand.position); + Logger.Log($"[XRI] Grip pull: the {grabArgs.HandSide} hand gripped {name} at {transform.position} from " + + $"{offset.magnitude:F2} m, the body was pulled {pulled:F2} m.", LogCat.VR); + + if (!_isGripPullWarned && offset.magnitude > GripPullTolerance) + StartCoroutine(CheckPulledGrip(hand, start + offset)); + } + + /// + /// A frame after a pulled grip, once XRI's climb held the hand: it should be at its grip. If not, a wall + /// stopped the body, or XRI's climb no longer anchors after selectEntered (an XRI upgrade, see + /// Docs/ledge-climbing.md > Pitfalls) - then every pulled grip hangs off its hold. + /// + private IEnumerator CheckPulledGrip(Transform hand, Vector3 grip) + { + yield return null; + + var distance = Vector3.Distance(hand.position, grip); + if (_isGripPullWarned || !IsHeld || distance <= GripPullTolerance) + yield break; + + _isGripPullWarned = true; + Logger.LogWarning($"[XRI] Grip pull: the hand holding {name} is {distance:F2} m off its grip - a wall " + + "stopped the body, or XRI's ClimbProvider anchored the hand before the pull " + + "(Docs/ledge-climbing.md > Pitfalls). Warned once.", LogCat.VR); + } + private void OnSelectExited(SelectExitEventArgs args) { if (!_selectArgs.Remove(args.interactorObject, out var grabArgs)) diff --git a/Assets/Gothic-VR/Scripts/Interaction/Backends/Xri/XriRig.cs b/Assets/Gothic-VR/Scripts/Interaction/Backends/Xri/XriRig.cs index 0f9cec68f..42b9d914b 100644 --- a/Assets/Gothic-VR/Scripts/Interaction/Backends/Xri/XriRig.cs +++ b/Assets/Gothic-VR/Scripts/Interaction/Backends/Xri/XriRig.cs @@ -165,6 +165,7 @@ public class XriRig : MonoBehaviour, IVrRig private IVrLedgeHandler _ledgeHandler; // SetLeapVelocity: a running jump's horizontal velocity, zero = none. private Vector3 _leapVelocity; + private bool _isPullBodyWarned; public event Action Teleported; @@ -798,6 +799,28 @@ public void SetLedgeHandler(IVrLedgeHandler handler) _jumpProvider.SetHandler(handler); } + /// + /// Moves the body by motion (m) at once, stopped by walls - like the leap, the CharacterController moves the + /// XR Origin with the hands. For a grip that pulls the body (XriInteractableBridge, IVrGripOffset). Without an + /// enabled CharacterController nothing moves (moving the origin directly would pass through walls), warned + /// once. + /// + internal void PullBody(Vector3 motion) + { + if (_characterController != null && _characterController.enabled) + { + _characterController.Move(motion); + return; + } + + if (_isPullBodyWarned) + return; + + _isPullBodyWarned = true; + Logger.LogWarning("[XRI] A grip wanted to pull the body, but the CharacterController is off: the body " + + "stays, the hand grips where it is.", LogCat.VR); + } + /// /// Applied by the TeleportationProvider in its next Update(). Teleported is raised once the XRBodyTransformer /// moved the rig (same frame). The camera (not the XR Origin) ends up above the position and looks along the rotation. diff --git a/Assets/Gothic-VR/Scripts/Interaction/Components/VrLedgeAnchor.cs b/Assets/Gothic-VR/Scripts/Interaction/Components/VrLedgeAnchor.cs index 7121fc64b..bf82c816a 100644 --- a/Assets/Gothic-VR/Scripts/Interaction/Components/VrLedgeAnchor.cs +++ b/Assets/Gothic-VR/Scripts/Interaction/Components/VrLedgeAnchor.cs @@ -1,5 +1,7 @@ using Gothic.Core.Logging; using Gothic.Core.Models.Movement; +using Gothic.VR.Interaction.Models; +using Gothic.VR.Interaction.Ports; using UnityEngine; using Logger = Gothic.Core.Logging.Logger; @@ -14,9 +16,12 @@ namespace Gothic.VR.Interaction.Components /// Its Rigidbody (needed by XRI's ClimbInteractable) is kinematic: it doesn't fall, and moving it reaches the /// physics scene at once, without a global Physics.SyncTransforms() (Physics.autoSyncTransforms is off). /// Local axes: x along the lip, y up, z into the wall. + /// In a jump (VrLedgeReach's jump reach) the box stretches from the lip to the hand (ReachTo), so that the hand + /// can grip from further away: GetGripOffset (IVrGripOffset) is then how far the backend pulls the body for the + /// hand to sit on the lip. The box shrinks back by itself once it's placed, hidden, gripped or let go. /// [RequireComponent(typeof(VrInteractable), typeof(Rigidbody))] - public class VrLedgeAnchor : MonoBehaviour + public class VrLedgeAnchor : MonoBehaviour, IVrGripOffset { [Tooltip("Grab box in m along the lip (x), up (y) and into the wall (z), centered on the lip.")] [SerializeField] @@ -35,8 +40,14 @@ public class VrLedgeAnchor : MonoBehaviour [Tooltip("Length in m of the glowing strip along the lip.")] [SerializeField] private float _glowLength = 0.35f; + // A hand moving less than this (m) doesn't resize the stretched box: no broadphase update per frame. + private const float ReachResizeStep = 0.01f; + private Color _glowColor = Color.white; private Rigidbody _body; + private bool _isStretched; + // The point the box was last stretched to, local. + private Vector3 _reachPoint; public VrInteractable Interactable { get; private set; } @@ -51,6 +62,9 @@ public class VrLedgeAnchor : MonoBehaviour private void Awake() { Interactable = GetComponent(); + // Subscribed before VrLedgeReach: the box is back on the lip before a grip reaches VrLedgeClimb. + Interactable.Grabbed += OnGrabbed; + Interactable.Released += OnReleased; _body = GetComponent(); if (!_body.isKinematic) Logger.LogWarning($"[Ledge] {name}: the anchor's Rigidbody isn't kinematic, it falls once placed.", @@ -68,6 +82,15 @@ private void Awake() Hide(); } + private void OnDestroy() + { + if (Interactable == null) + return; + + Interactable.Grabbed -= OnGrabbed; + Interactable.Released -= OnReleased; + } + /// /// Puts the anchor onto the lip at point (on the lip). /// @@ -80,21 +103,43 @@ public void Place(LedgeInfo info, Vector3 point) // The body's pose reaches the physics scene at once: the hands' grab casts see the new place this frame. _body.position = point; _body.rotation = rotation; - _collider.size = _size; - _collider.center = Vector3.zero; + ResetReach(); _collider.enabled = true; } + /// + /// Stretches the grab box from the lip to the point (a hand), padded by half the box's height. The anchor + /// itself stays on the lip, with its glow strip. Until it's placed, hidden, gripped or let go. + /// + public void ReachTo(Vector3 point) + { + var local = transform.InverseTransformPoint(point); + if (_isStretched && (local - _reachPoint).sqrMagnitude < ReachResizeStep * ReachResizeStep) + return; + + _reachPoint = local; + var half = _size / 2f; + var pad = Vector3.one * half.y; + var min = Vector3.Min(-half, local - pad); + var max = Vector3.Max(half, local + pad); + _collider.center = (min + max) / 2f; + _collider.size = max - min; + _isStretched = true; + } + public void Hide() { if (_collider != null) + { + ResetReach(); _collider.enabled = false; + } SetGlow(0f); } /// - /// The point is inside the grab box, grown by margin (m). + /// The point is inside the grab box on the lip (not stretched), grown by margin (m). /// public bool Contains(Vector3 point, float margin) { @@ -102,10 +147,71 @@ public bool Contains(Vector3 point, float margin) return false; var local = transform.InverseTransformPoint(point); - var half = _collider.size / 2f + Vector3.one * margin; + var half = _size / 2f + Vector3.one * margin; return Mathf.Abs(local.x) <= half.x && Mathf.Abs(local.y) <= half.y && Mathf.Abs(local.z) <= half.z; } + /// + /// The point is at most range (m) from the lip and beside the box on the lip, grown by margin (m), along it - + /// on the open side: not behind the wall's face below the lip (in the wall). + /// + public bool IsWithinReach(Vector3 point, float range, float margin) + { + if (!IsPlaced) + return false; + + var local = transform.InverseTransformPoint(point); + var half = _size / 2f; + if (local.z > half.z + margin && local.y < half.y) + return false; + + var crossSqr = local.y * local.y + local.z * local.z; + return Mathf.Abs(local.x) <= half.x + margin && crossSqr <= range * range; + } + + /// + /// While stretched (ReachTo): from the point (a hand) to the nearest point of the grab box on the lip, zero + /// inside it. Not stretched: zero, the hand grips where it is. + /// + public Vector3 GetGripOffset(Vector3 point) + { + if (!_isStretched) + return Vector3.zero; + + var local = transform.InverseTransformPoint(point); + var half = _size / 2f; + var onBox = new Vector3(Mathf.Clamp(local.x, -half.x, half.x), Mathf.Clamp(local.y, -half.y, half.y), + Mathf.Clamp(local.z, -half.z, half.z)); + return transform.TransformPoint(onBox) - point; + } + + /// + /// Within the backend's select event, after the backend pulled the body (IVrGripOffset): the hand holds the + /// lip, the box goes back onto it - the other hand can't grab the stretched box meanwhile. + /// + private void OnGrabbed(VrGrabArgs args) + { + ResetReach(); + } + + private void OnReleased(VrGrabArgs args) + { + ResetReach(); + } + + /// + /// Back to the grab box on the lip. + /// + private void ResetReach() + { + if (!_isStretched) + return; + + _collider.size = _size; + _collider.center = Vector3.zero; + _isStretched = false; + } + /// /// Strength 0 (hidden) to 1 (full alpha). /// diff --git a/Assets/Gothic-VR/Scripts/Interaction/Components/VrLedgeReach.cs b/Assets/Gothic-VR/Scripts/Interaction/Components/VrLedgeReach.cs index 182fa170a..cc0e74485 100644 --- a/Assets/Gothic-VR/Scripts/Interaction/Components/VrLedgeReach.cs +++ b/Assets/Gothic-VR/Scripts/Interaction/Components/VrLedgeReach.cs @@ -1,6 +1,8 @@ using System; +using System.Collections.Generic; using Gothic.Core; using Gothic.Core.Logging; +using Gothic.Core.Models.Movement; using Gothic.Core.Services.Config; using Gothic.Core.Services.Movement; using Gothic.VR.Domain.Player; @@ -18,6 +20,11 @@ namespace Gothic.VR.Interaction.Components /// climbable lip it reaches, so that the hand can grip it. What a grip does is VrLedgeClimb's part. /// Hints (Gothic.ini ledgeHints): a hand near a climbable lip half closes and ticks once, with ledgeHints Glow a /// short strip glows on the lip. Nothing is shown from afar. + /// Reach (VrLedgeReachMode): in the hero's jump (HeroFallService.Phase Jumping) and _jumpReachGrace after its + /// landing, a hand reaches lips _jumpReach away. The anchor's grab box stretches to the hand + /// (VrLedgeAnchor.ReachTo), the hints are on in full, and the backend pulls the body on the grip until the hand + /// sits on the lip (IVrGripOffset) - from there the climb is a normal one. While falling no ledge can be grabbed, + /// like in Gothic (Immersion option ledgeGrabFalling turns it on, with the normal reach). /// Owns whether ledge climbing is on (Climber): VrLedgeClimb and VrLedgeLocomotion work only while the reach does. /// /// Sits on the player rig. Runs before XRI's interaction manager (-105), so that the anchors are in place when the @@ -29,6 +36,7 @@ public class VrLedgeReach : MonoBehaviour { [Inject] private readonly LedgeService _ledgeService; [Inject] private readonly ConfigService _configService; + [Inject] private readonly HeroFallService _heroFallService; [Tooltip("Grab point put on a lip. One is created per hand.")] [SerializeField] private VrLedgeAnchor _anchorPrefab; @@ -44,19 +52,36 @@ public class VrLedgeReach : MonoBehaviour [SerializeField] private float _anchorKeepMargin = 0.05f; + [Tooltip("In a jump: distance in m between hand and lip from which the hand can grip it. The lip's grab box " + + "stretches to the hand, the grip pulls the body until the hand sits on the lip.")] + [SerializeField] + private float _jumpReach = 0.6f; + + [Tooltip("Seconds after a jump's landing in which the jump reach still holds: a grip at the top of a jump " + + "that landed a frame early still works.")] + [SerializeField] + private float _jumpReachGrace = 0.2f; + + // A hand this close (m) to where the jump reach's probe last found nothing isn't probed again. + private const float JumpProbeStep = 0.05f; + private readonly VrLedgeAnchor[] _anchors = new VrLedgeAnchor[2]; private readonly VrBlockHand[] _blockHands = new VrBlockHand[2]; private readonly IVrGrabber[] _grabbers = new IVrGrabber[2]; private readonly bool[] _isInTouchRange = new bool[2]; + // Per hand: where the jump reach's probe last found no lip, null = probe. + private readonly Vector3?[] _jumpProbeMisses = new Vector3?[2]; + private readonly List _touched = new(); private VrLedgeClimber _climber; private bool _isClimberChecked; private GameObject _anchorRoot; private VrLedgeHint _hint = (VrLedgeHint)VRConstants.LedgeHintsDefaultValue; private float _baseFeetY; + private VrLedgeReachMode _reachMode; /// - /// A hand gripped an anchor. Raised within XRI's select event. + /// A hand gripped an anchor. Raised within the backend's select event, after a pull onto the lip. /// public event Action Grabbed; @@ -93,6 +118,10 @@ private void Start() return; } + _reachMode = new VrLedgeReachMode(_ledgeService, _jumpReach, _jumpReachGrace) + { + IsGrabWhileFalling = VRConstants.LedgeGrabFallingDefaultValue == 1 + }; CreateAnchors(); FindHands(); ReadSettings(); @@ -121,6 +150,12 @@ private void OnDestroy() private void Update() { + // Before the guards: the mode follows the hero's jump and fall also while nothing is shown. + var rig = _climber.Rig; + var phase = _heroFallService?.Phase ?? HeroAirPhase.Grounded; + if (_reachMode.Update(phase, rig.IsClimbing, Time.time)) + OnReachModeChanged(); + if (IsSuspended) { HideHand(VrHandSide.Left); @@ -128,7 +163,6 @@ private void Update() return; } - var rig = _climber.Rig; if (rig.IsGrounded && !rig.IsClimbing) _baseFeetY = _climber.Feet.y; @@ -175,13 +209,19 @@ private void UpdateHand(VrHandSide side) return; } - if (!CanReach(side)) + if (_reachMode.Current == VrLedgeReachKind.Blocked || !CanReach(side)) { HideHand(side); return; } var hand = GetHand(side).position; + if (_reachMode.Current == VrLedgeReachKind.Jump) + { + UpdateJumpReach(side, anchor, hand); + return; + } + if (anchor.Contains(hand, _anchorKeepMargin)) { UpdateHints(side, Vector3.Distance(hand, VrLedgeClimber.ClosestOnLip(anchor.Info, hand))); @@ -201,6 +241,76 @@ private void UpdateHand(VrHandSide side) UpdateHints(side, distance); } + /// + /// The hand's anchor in the jump reach: kept while the hand stays within the reach of its lip (and beside it, + /// by the keep margin), else placed on the nearest lip within the reach. Its box stretches to the hand, so the + /// hand grips from there, and the hints are on in full. + /// + private void UpdateJumpReach(VrHandSide side, VrLedgeAnchor anchor, Vector3 hand) + { + // The stretched box would win XRI's pick over a ladder or item at the hand (it's ranked by the lip, not + // by the box): the ledge yields to what the hand touches. + if (IsTouchingOther(side)) + { + HideHand(side); + return; + } + + if (!anchor.IsWithinReach(hand, _jumpReach, _anchorKeepMargin) && !TryPlaceInJumpReach(side, anchor, hand)) + { + HideHand(side); + return; + } + + anchor.ReachTo(hand); + SetTouch(side, true); + anchor.SetGlow(_hint == VrLedgeHint.Glow ? 1f : 0f); + } + + /// + /// The nearest lip within the jump reach. Pre-gate: a hand that stays within JumpProbeStep of where the probe + /// last found nothing isn't probed again (up to 5 rays down plus the wall rays) - the world doesn't change + /// within a jump. + /// + private bool TryPlaceInJumpReach(VrHandSide side, VrLedgeAnchor anchor, Vector3 hand) + { + var index = (int)side; + var miss = _jumpProbeMisses[index]; + if (miss.HasValue && (hand - miss.Value).sqrMagnitude < JumpProbeStep * JumpProbeStep) + return false; + + var info = _climber.ProbeAtHand(hand, _baseFeetY, _jumpReach); + var point = VrLedgeClimber.ClosestOnLip(info, hand); + if (!info.IsClimbable || Vector3.Distance(hand, point) > _jumpReach) + { + _jumpProbeMisses[index] = hand; + return false; + } + + _jumpProbeMisses[index] = null; + anchor.Place(info, point); + return true; + } + + /// + /// The hand's direct grab range holds an interactable other than the ledge anchors. + /// + private bool IsTouchingOther(VrHandSide side) + { + var grabber = _grabbers[(int)side]; + if (grabber == null) + return false; + + grabber.GetTouched(_touched); + foreach (var interactable in _touched) + { + if (interactable != _anchors[0].Interactable && interactable != _anchors[1].Interactable) + return true; + } + + return false; + } + private bool CanReach(VrHandSide side) { var grabber = _grabbers[(int)side]; @@ -231,6 +341,24 @@ private void SetTouch(VrHandSide side, bool isTouching) GlobalEventDispatcher.LedgeTouched.Invoke(index); } + /// + /// A new jump probes afresh. When the jump reach ends, the anchors it stretched go and the hands place them + /// again with the new reach. The hints stay - a hand that still touches its lip doesn't tick again. + /// + private void OnReachModeChanged() + { + _jumpProbeMisses[0] = null; + _jumpProbeMisses[1] = null; + if (_reachMode.Current == VrLedgeReachKind.Jump) + return; + + foreach (var anchor in _anchors) + { + if (!anchor.IsHeld) + anchor.Hide(); + } + } + private void HideHand(VrHandSide side) { var anchor = _anchors[(int)side]; @@ -297,14 +425,18 @@ private void FindHands() private void ReadSettings() { var gothicIni = _configService.Gothic; - if (gothicIni != null) - _hint = (VrLedgeHint)gothicIni.GetInt(VRConstants.IniNames.LedgeHints, - VRConstants.LedgeHintsDefaultValue); + if (gothicIni == null) + return; + + _hint = (VrLedgeHint)gothicIni.GetInt(VRConstants.IniNames.LedgeHints, + VRConstants.LedgeHintsDefaultValue); + _reachMode.IsGrabWhileFalling = gothicIni.GetInt(VRConstants.IniNames.LedgeGrabFalling, + VRConstants.LedgeGrabFallingDefaultValue) == 1; } private void OnPlayerPrefUpdated(string key, object value) { - if (key == VRConstants.IniNames.LedgeHints) + if (key is VRConstants.IniNames.LedgeHints or VRConstants.IniNames.LedgeGrabFalling) ReadSettings(); } } diff --git a/Assets/Gothic-VR/Scripts/Interaction/Models/VrLedgeReachKind.cs b/Assets/Gothic-VR/Scripts/Interaction/Models/VrLedgeReachKind.cs new file mode 100644 index 000000000..33e89ad5b --- /dev/null +++ b/Assets/Gothic-VR/Scripts/Interaction/Models/VrLedgeReachKind.cs @@ -0,0 +1,24 @@ +namespace Gothic.VR.Interaction.Models +{ + /// + /// How far the hands reach ledges right now (VrLedgeReachMode, Docs/ledge-climbing.md). + /// + public enum VrLedgeReachKind + { + /// + /// On the ground, a step down, or falling with the Immersion option ledgeGrabFalling: a hand grips lips it + /// touches. + /// + Normal, + + /// + /// The hero's jump and shortly after its landing: a hand grips lips further away, the grip pulls the body up. + /// + Jump, + + /// + /// Falling: no ledge can be grabbed, like in Gothic. + /// + Blocked + } +} diff --git a/Assets/Gothic-VR/Scripts/Interaction/Models/VrLedgeReachKind.cs.meta b/Assets/Gothic-VR/Scripts/Interaction/Models/VrLedgeReachKind.cs.meta new file mode 100644 index 000000000..061c5467e --- /dev/null +++ b/Assets/Gothic-VR/Scripts/Interaction/Models/VrLedgeReachKind.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: e252ca212957030449cbde2d562e6f9e \ No newline at end of file diff --git a/Assets/Gothic-VR/Scripts/Interaction/Ports/IVrGrabber.cs b/Assets/Gothic-VR/Scripts/Interaction/Ports/IVrGrabber.cs index 895a353e0..dfc72d455 100644 --- a/Assets/Gothic-VR/Scripts/Interaction/Ports/IVrGrabber.cs +++ b/Assets/Gothic-VR/Scripts/Interaction/Ports/IVrGrabber.cs @@ -1,4 +1,5 @@ using System; +using System.Collections.Generic; using Gothic.VR.Interaction.Components; using Gothic.VR.Interaction.Models; @@ -31,5 +32,15 @@ public interface IVrGrabber event Action Released; void ForceRelease(); + + /// + /// The interactables within the hand's direct grab range right now (a grab now would take one of them as + /// Kind Hand), each once. Asked per frame only while needed (VrLedgeReach in a jump). Default: none, for + /// grabbers without a direct range (sockets). + /// + void GetTouched(List results) + { + results.Clear(); + } } } diff --git a/Assets/Gothic-VR/Scripts/Interaction/Ports/IVrGripOffset.cs b/Assets/Gothic-VR/Scripts/Interaction/Ports/IVrGripOffset.cs new file mode 100644 index 000000000..b9df24f72 --- /dev/null +++ b/Assets/Gothic-VR/Scripts/Interaction/Ports/IVrGripOffset.cs @@ -0,0 +1,19 @@ +using UnityEngine; + +namespace Gothic.VR.Interaction.Ports +{ + /// + /// A climbable whose grip from afar pulls the player's body (a ledge anchor in the jump reach, VrLedgeAnchor). + /// Implemented by a component next to the VrInteractable, asked by the backend when a hand grips it directly: + /// the backend moves the body by the offset, stopped by walls, before its climb holds the hand - so the climb + /// starts with the hand where it should grip. Not while another hand already climbs (the move would tear that + /// hand off its hold): that grip holds where it is. + /// + public interface IVrGripOffset + { + /// + /// From the hand (the tracked controller, world space) to where it grips. Vector3.zero: it grips where it is. + /// + Vector3 GetGripOffset(Vector3 hand); + } +} diff --git a/Assets/Gothic-VR/Scripts/Interaction/Ports/IVrGripOffset.cs.meta b/Assets/Gothic-VR/Scripts/Interaction/Ports/IVrGripOffset.cs.meta new file mode 100644 index 000000000..824e1ce50 --- /dev/null +++ b/Assets/Gothic-VR/Scripts/Interaction/Ports/IVrGripOffset.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 3d9ddeb8660d0374d8aad8b0526a0a50 \ No newline at end of file diff --git a/Assets/Gothic-VR/Scripts/Services/Context/VRContextMenuService.cs b/Assets/Gothic-VR/Scripts/Services/Context/VRContextMenuService.cs index 4dfe92f35..98a45d6de 100644 --- a/Assets/Gothic-VR/Scripts/Services/Context/VRContextMenuService.cs +++ b/Assets/Gothic-VR/Scripts/Services/Context/VRContextMenuService.cs @@ -112,6 +112,11 @@ public void UpdateMainMenu(AbstractMenuInstance mainMenu) CreateOptionChoice(gameMenu, "MENUITEM_GOTHIC_OPT_VR_IMMERSION_LEDGE_HINTS", "ledgeHints", VRConstants.IniNames.LedgeHints, VRConstants.IniSectionImmersion, VRConstants.LedgeHintsDefaultValue)), + // Off = like Gothic, no ledge can be grabbed while falling (VrLedgeReach). + (CreateOptionLabel(gameMenu, "MENUITEM_GOTHIC_OPT_VR_IMMERSION_LEDGE_GRAB_FALLING", "ledgeGrabFalling"), + CreateOptionChoice(gameMenu, "MENUITEM_GOTHIC_OPT_VR_IMMERSION_LEDGE_GRAB_FALLING", + "ledgeGrabFalling", VRConstants.IniNames.LedgeGrabFalling, VRConstants.IniSectionImmersion, + VRConstants.LedgeGrabFallingDefaultValue)), (CreateOptionLabel(gameMenu, "MENUITEM_GOTHIC_OPT_VR_IMMERSION_MOVE_VIGNETTE", "moveVignette"), CreateOptionChoice(gameMenu, "MENUITEM_GOTHIC_OPT_VR_IMMERSION_MOVE_VIGNETTE", "moveVignette", VRConstants.IniNames.MoveVignette, VRConstants.IniSectionImmersion, diff --git a/Assets/Gothic-VR/Scripts/VRConstants.cs b/Assets/Gothic-VR/Scripts/VRConstants.cs index bf29692c1..82086521a 100644 --- a/Assets/Gothic-VR/Scripts/VRConstants.cs +++ b/Assets/Gothic-VR/Scripts/VRConstants.cs @@ -56,6 +56,9 @@ public static class IniNames // VrLedgeHint: 0 = off (hand half closes and ticks), 1 = glow (and a strip on the lip glows). public const string LedgeHints = "ledgeHints"; + // 0 = like Gothic, no ledge can be grabbed while falling (default), 1 = it can, with the normal reach. + public const string LedgeGrabFalling = "ledgeGrabFalling"; + // 1 = backpack in one hand + item in the other shows the item's Gothic inventory text (VRItemDetailsPopup). public const string ItemDetailsPopup = "itemDetailsPopup"; // 1 = the held backpack's opening pulls nearby world items and stores them (VRBackpackVacuum). @@ -129,6 +132,7 @@ public static class IniNames public const int HeroFallModeDefaultValue = 0; public const int HeroLandingViewDefaultValue = 0; public const int LedgeHintsDefaultValue = 1; + public const int LedgeGrabFallingDefaultValue = 0; public const int ItemDetailsPopupDefaultValue = 1; public const int BackpackVacuumDefaultValue = 1; diff --git a/Docs/adr/2026-11-30-ledge-air-reach.md b/Docs/adr/2026-11-30-ledge-air-reach.md new file mode 100644 index 000000000..62b3b3a18 --- /dev/null +++ b/Docs/adr/2026-11-30-ledge-air-reach.md @@ -0,0 +1,26 @@ +# ADR: Grabbing a ledge in a jump + +- Date: 2026-11-30 +- Technical details: Docs/ledge-climbing.md + +## Context + +In the play test, grabbing a ledge while jumping straight up below it was very hard: the hand had to touch the edge within a few centimetres during the short moment at the top of the jump. In the original game the hero holds the action key at a wall, the engine picks the ledge he will jump to and he climbs it. The original game also never lets the hero catch a ledge while he falls: walking off an edge or a jump that turned into a fall ends on the ground. + +## Decisions + +1. **In a jump the hands reach a ledge from about 60 cm away instead of about 20 cm.** Hands up while jumping below a ledge is enough: the edge glows (with the glow hint) and the hand half closes and vibrates as soon as it could grip. Not chosen: a key that picks the ledge for you like in Gothic, because in VR the hands already say where you want to go. +2. **Gripping from there pulls you up until the hand is on the edge, then climbing is the same as always.** You pull yourself up or fade onto the top exactly like after a normal grab. Not chosen: hanging where the hand gripped, half a metre below the edge, which would need a much longer pull than an arm can do. +3. **The larger reach lasts only for the hero's own jump and a fifth of a second after its landing.** So a grip at the top of a jump that lands a moment too early still works. On the ground nothing changes. +4. **While falling no ledge can be grabbed, like in Gothic.** A fall is walking off an edge, or a jump that took you clearly below where you jumped off. A new Immersion option ("grab while falling", off by default) allows it again, with the normal short reach - catching a ledge while falling is a VR habit some players like, but not the original game. Not chosen: the larger jump reach while falling as well, which would make every fall past a ledge end on it. +5. **Ladders stay as they are.** + +## Consequences + +- Grabbing in a jump moves you up to 60 cm at once, which feels like a short pull. Players who get motion sick can use the comfort climb, which fades anyway. +- If the second hand grips in the same moment as the first, only the first one is pulled onto its edge; the second holds where it gripped. +- The pull happens in the VR backend, at the moment a hand grips, before the backend's climbing takes over the hand. It depends on the order inside the XR Interaction Toolkit 3.6.1; the game warns once in the log if a pulled hand doesn't end up on the edge (e.g. after an upgrade), see Docs/ledge-climbing.md > Pitfalls. The ledge parts themselves only say how far a grip pulls. +- While a hand touches a ladder or an item in a jump, the ledge next to it can't be gripped from afar, so the ladder or item is taken. +- "A falling hero catches no ledge" is a game rule in Core (LedgeService), the 60 cm reach stays a VR matter. +- Nothing new is saved. +- The new option needs its texts (label, choices, description) in the localization tables. diff --git a/Docs/ledge-climbing.md b/Docs/ledge-climbing.md index 3cd8fe987..a217d57c2 100644 --- a/Docs/ledge-climbing.md +++ b/Docs/ledge-climbing.md @@ -24,7 +24,9 @@ they block room and headroom. - `Models/Movement/*`: `LedgeRules` (values in m), `LedgeBody` (capsule + layers), `LedgeInfo` (result), `LedgeBand`. - `Domain/Movement/LedgeProbeDomain`: the probes - `ProbeAhead` (jump), `ProbeEdge` (a point near a lip, a hand), - `ProbeTop` (a teleport target, walks back to the lip). + `ProbeTop` (a teleport target, walks back to the lip). `ProbeEdge` takes a `reach` (the jump reach): the top is + then also searched that much higher, lower and further along the approach, one ray down per 15 cm, the walkable hit + nearest to the hand wins. The other checks (wall, height band, room on top) are the same; reach 0 is the old probe. - `Services/Movement/LedgeService`: reads the hero's values (Gothic's values if the scripts have none) and runs the probes. Not VR-specific: Flat jumps and NPCs can use it later. @@ -35,7 +37,30 @@ All on the XR Origin of `VR - Player XRI.prefab`: - `VrLedgeReach`: owns whether climbing is on (`Climber`: null if there is no rig or no anchor prefab - then the other two stay off as well). Moves one `VrLedgeAnchor` per empty hand along the climbable lip it reaches, plus the hints (hand half closes, haptic tick, glow strip). Lips count from the floor the player last stood on, so a jump - doesn't lower them. + doesn't lower them. The ranges are `VrLedgeReachMode`'s (plain C#, `Domain/Player/`: Normal / Jump / Blocked from + `HeroFallService.Phase`, Core's hero jump/fall, updated first thing each frame; logged `[Ledge] ...`, LogCat VR, on + every change): + - On the ground (also `Airborne`, a step down): `_touchRange` 0.2 m, with glow the anchor shows from `_glowRange` + 0.45 m; the hand grips the anchor's 0.4 x 0.12 x 0.12 m box on the lip. + - Jump reach (`Jumping`, and `_jumpReachGrace` 0.2 s after its landing so a grip at the top of a jump that landed a + frame early still works; not while climbing): `_jumpReach` 0.6 m. `ProbeAtHand` probes with that reach (not again + while the hand stays within 5 cm of where it last found nothing), the anchor stays on the lip (its glow strip + too) but its box stretches to the hand (`VrLedgeAnchor.ReachTo`, resized only when the hand moved 1 cm), the hand + half closes, ticks and the strip glows in full. A placed anchor is kept while the hand is within the reach of its + lip, beside its box (`_anchorKeepMargin`) and not inside the wall. While the hand's direct grab range touches + another interactable (`IVrGrabber.GetTouched`: a ladder, an item) the hand's anchor hides: XRI ranks near + targets by their attach point, so the stretched box (ranked by its lip) could win over a ladder whose transform is + further away. The grip pulls the body onto the lip: `VrLedgeAnchor` answers `IVrGripOffset.GetGripOffset` (to its + box on the lip, zero unless stretched) and `XriInteractableBridge` moves the rig by it (`XriRig.PullBody`, + `CharacterController.Move`) before XRI's climb holds the hand - from there it's a normal grab (`VrLedgeClimb`). + Not when another hand already climbs (it would be torn off its lip): that grip holds where it is. Logged + `[XRI] Grip pull ...` per pulled grip. The anchor shrinks its box by itself when placed, hidden, gripped or let + go; the anchors hide when the jump reach ends and are placed again with the ground ranges. + - Falling (`Falling`, Blocked): no anchor, no hints - like Gothic, a falling hero catches no ledge + (`LedgeService.CanCatchLedge`). The Immersion option `ledgeGrabFalling` allows it, with the ground ranges (not + the jump reach). + Holding an item, swimming (grabbing off) and the comfort climb's blink (`IsSuspended`) show nothing, as before. + Ladders are separate `ClimbInteractable`s, untouched by the reach. - `VrLedgeClimber` (plain C#, `Domain/Player/`): the player's feet and body (standing height, a crouch doesn't count) and the probes from the player's view. The one place the VR side builds a `LedgeBody`. - `VrLedgeClimb`: what a grip does. Physical: XRI's `ClimbProvider` moves the rig, once pulled up 25 cm and the head @@ -53,8 +78,10 @@ anchor. Queries without a mask do see its box: leave the layer out (`NpcInitiali ## Settings -Gothic.ini, in the VR menus: `ledgeClimbMode` (Accessibility: pull up / fade) and `ledgeHints` (Immersion: off / -glow). The hand always half closes and ticks near a lip; glow adds the strip on the lip. +Gothic.ini, in the VR menus: `ledgeClimbMode` (Accessibility: pull up / fade), `ledgeHints` (Immersion: off / +glow) and `ledgeGrabFalling` (Immersion, `[GOTHIC_VR_IMMERSION]`: off / on, default off = no ledge grab while falling). +The hand always half closes and ticks near a lip; glow adds the strip on the lip. Menu texts: +`menuitem.ledgeGrabFalling.label` / `.value` / `.description` in the Gothic-UI string table. ## Pitfalls @@ -70,9 +97,18 @@ glow). The hand always half closes and ticks near a lip; glow adds the strip on - `Physics.autoSyncTransforms` is off: the anchor's Rigidbody is kinematic, and `VrLedgeAnchor.Place` sets its pose, which the physics scene sees at once. No global `Physics.SyncTransforms()` (its cost grows with every moved collider in the world, e.g. NPCs). A non-kinematic anchor would also fall once placed: `VrLedgeAnchor` warns. +- The jump reach's pull relies on XRI 3.6.1's order: `ClimbInteractable.OnSelectEntered` raises `selectEntered` + before `ClimbProvider.StartClimbGrab`, which anchors the hand at its world position then. With all + `allowFree*Movement` on (our settings) the provider keeps that world position, moving the anchor afterwards does + nothing - so the backend moves the body inside the event: `XriInteractableBridge.PullToGrip`, the only place that + knows the order (components only answer `IVrGripOffset`). Deferring the move by a frame breaks the pull. If the + order changes on an XRI upgrade, the hand hangs where it gripped: a frame after a pull of more than 5 cm the bridge + checks the hand is at its grip and warns once if not (`[XRI] Grip pull: ... off its grip`; a wall that stopped + the body warns the same way). Without an enabled CharacterController the body doesn't move (warned once). - Saving while hanging stores a mid-air position. ## Tests -PlayMode `LedgeProbeTest` (bands, room, headroom, slope, hand and top probes on primitives) and +PlayMode `LedgeProbeTest` (bands, room, headroom, slope, hand probes with and without the jump reach, top probes on +primitives) and `GothicJumpProviderTest` (jump height for a rise).