diff --git a/Assets/Gothic-Core/Scripts/Services/Vobs/MobAnimationService.cs b/Assets/Gothic-Core/Scripts/Services/Vobs/MobAnimationService.cs index 1e16875c3..b816043c8 100644 --- a/Assets/Gothic-Core/Scripts/Services/Vobs/MobAnimationService.cs +++ b/Assets/Gothic-Core/Scripts/Services/Vobs/MobAnimationService.cs @@ -143,7 +143,8 @@ public void Stop([CanBeNull] VobContainer mob, [CanBeNull] NpcContainer user) /// /// The hero uses a mob with a dialog (the anvil's smithing choices, the grindstone, a rune table): it works - /// like for a smith, S0 -> S1 and its loop, until StopHeroUse (the dialog closed). One at a time. + /// like for a smith, S0 -> S1 and its loop, until StopHeroUse (the dialog closed). One at a time. VR: a water + /// pipe's mouthpiece at the mouth too (VRWaterPipe) - it bubbles and smokes, nothing else. /// public void StartHeroUse([CanBeNull] VobContainer mob, [CanBeNull] NpcContainer hero) { @@ -156,6 +157,16 @@ public void StartHeroUse([CanBeNull] VobContainer mob, [CanBeNull] NpcContainer OnStateChanged(mob, hero, 0, 1); } + /// + /// Ends the hero's use only if it is this mob: a water pipe taken from the mouth doesn't stop the anvil whose + /// dialog opened meanwhile. + /// + public void StopHeroUse([CanBeNull] VobContainer mob) + { + if (mob != null && mob == _heroMob) + StopHeroUse(); + } + public void StopHeroUse() { if (_heroMob == null) diff --git a/Assets/Gothic-Core/Scripts/Services/Vobs/VobService.cs b/Assets/Gothic-Core/Scripts/Services/Vobs/VobService.cs index bcff9ee93..89976ec1b 100644 --- a/Assets/Gothic-Core/Scripts/Services/Vobs/VobService.cs +++ b/Assets/Gothic-Core/Scripts/Services/Vobs/VobService.cs @@ -1124,6 +1124,16 @@ public IEnumerable GetOtherMobUsers(VobContainer mob, NpcContainer i.Props.CurrentAction is Gothic.Core.Domain.Npc.Actions.AnimationActions.UseMob)); } + /// + /// A living NPC other than except uses this mob right now or walks to it (GetOtherMobUsers) - "busy" for a + /// mob the hero takes hold of (a VR water pipe). Not MobState: above 0 it also means switched or open (levers, + /// lids), and a state saved while an NPC used the mob comes back with a load without that NPC at it. + /// + public bool IsUsedByOtherNpc(VobContainer mob, NpcContainer except) + { + return mob != null && GetOtherMobUsers(mob, except).Any(i => !i.Props.IsDead); + } + private int GetSlotCount(VobContainer mob) { var slots = GetSlots(mob.Go); diff --git a/Assets/Gothic-VR/Scripts/Adapters/Vob/HoseIk.cs b/Assets/Gothic-VR/Scripts/Adapters/Vob/HoseIk.cs new file mode 100644 index 000000000..b5b469292 --- /dev/null +++ b/Assets/Gothic-VR/Scripts/Adapters/Vob/HoseIk.cs @@ -0,0 +1,41 @@ +using UnityEngine; + +namespace Gothic.VR.Adapters.Vob +{ + /// + /// Bends a chain of a model's nodes (a water pipe's hose) so that its tip reaches a point: CCD (cyclic coordinate + /// descent) - from the last link to the first, each one turns the tip towards the target, a few rounds. Each turn + /// is limited, so the bend spreads over the whole hose instead of kinking at its end. Plain math on the + /// transforms, no allocations. + /// + public static class HoseIk + { + private const float _minDistanceSqr = 0.000001f; + + /// The turning nodes, first = the one fixed to the model (BIP01 FLEX0). + /// The node that should reach target (BIP01 FLEXEND), below the last link. + public static void Solve(Transform[] links, Transform tip, Vector3 target, int iterations, + float maxTurnDegrees, float tolerance) + { + var toleranceSqr = tolerance * tolerance; + for (var iteration = 0; iteration < iterations; iteration++) + { + for (var i = links.Length - 1; i >= 0; i--) + { + var link = links[i]; + var linkPosition = link.position; + var toTip = tip.position - linkPosition; + var toTarget = target - linkPosition; + if (toTip.sqrMagnitude < _minDistanceSqr || toTarget.sqrMagnitude < _minDistanceSqr) + continue; + + var turn = Quaternion.FromToRotation(toTip, toTarget); + link.rotation = Quaternion.RotateTowards(Quaternion.identity, turn, maxTurnDegrees) * link.rotation; + } + + if ((tip.position - target).sqrMagnitude <= toleranceSqr) + return; + } + } + } +} diff --git a/Assets/Gothic-VR/Scripts/Adapters/Vob/HoseIk.cs.meta b/Assets/Gothic-VR/Scripts/Adapters/Vob/HoseIk.cs.meta new file mode 100644 index 000000000..719ac5c14 --- /dev/null +++ b/Assets/Gothic-VR/Scripts/Adapters/Vob/HoseIk.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: c5efb3a6f22c53e47abd28bde5dbfc85 \ No newline at end of file diff --git a/Assets/Gothic-VR/Scripts/Adapters/Vob/VRMobInteraction.cs b/Assets/Gothic-VR/Scripts/Adapters/Vob/VRMobInteraction.cs index 02d9e6afe..f5db9657d 100644 --- a/Assets/Gothic-VR/Scripts/Adapters/Vob/VRMobInteraction.cs +++ b/Assets/Gothic-VR/Scripts/Adapters/Vob/VRMobInteraction.cs @@ -23,9 +23,12 @@ public class VRMobInteraction : MonoBehaviour private bool _mobActivated; private VrInteractable _interactable; + // The mouthpiece of a water pipe (null for other mobs). + private VRWaterPipe _waterPipe; /// - /// Subscribed in Start (not Awake), so that e.g. VRSeat handles a grab first (as before). + /// Subscribed in Start (not Awake), so that e.g. VRSeat handles a grab first (as before). The mob's model is + /// built by then: a water pipe's mouthpiece becomes a handle of its own (VRWaterPipe). /// private void Start() { @@ -34,6 +37,7 @@ private void Start() _interactable.Grabbed += OnGrabbed; _interactable.Released += OnReleased; + _waterPipe = VRWaterPipe.TryAdd(gameObject); } private void OnDestroy() @@ -50,6 +54,10 @@ private void OnGrabbed(VrGrabArgs args) if (_mobActivated) return; + // The hand closed at a water pipe's mouthpiece but caught the pipe: it takes the mouthpiece instead. + if (_waterPipe != null && _waterPipe.TryTakeOverGrab(args)) + return; + var vobLoader = GetComponentInParent(); var vob = vobLoader?.Container?.Vob; // A lidless container (mummy) is a plain mob here too: the grab toggles its loot (VRMobUseService). diff --git a/Assets/Gothic-VR/Scripts/Adapters/Vob/VRWaterPipe.cs b/Assets/Gothic-VR/Scripts/Adapters/Vob/VRWaterPipe.cs new file mode 100644 index 000000000..559e22a1f --- /dev/null +++ b/Assets/Gothic-VR/Scripts/Adapters/Vob/VRWaterPipe.cs @@ -0,0 +1,501 @@ +using System; +using System.Collections; +using Gothic.Core.Adapters.Vob; +using Gothic.Core.Const; +using Gothic.Core.Extensions; +using Gothic.Core.Logging; +using Gothic.Core.Models.Container; +using Gothic.Core.Services.Player; +using Gothic.Core.Services.Vobs; +using Gothic.VR.Adapters.Vob.VobItem; +using Gothic.VR.Interaction.Components; +using Gothic.VR.Interaction.Models; +using Gothic.VR.Interaction.Ports; +using Gothic.VR.Services; +using Reflex.Attributes; +using UnityEngine; +using Logger = Gothic.Core.Logging.Logger; + +namespace Gothic.VR.Adapters.Vob +{ + /// + /// A water pipe's mouthpiece in the hero's hand (Docs/mobs.md, ADR 2026-11-26-vr-water-pipe). Added by + /// VRMobInteraction to a mob whose model ends a hose (BIP01 FLEX0..BIP01 FLEX4) in BIP01 FLEXEND - mods' pipes + /// with these nodes work the same: + /// - A small grab trigger on the mouthpiece is a handle of its own (IVrBackend.AddHandle). The hand holds it, the + /// hose's links bend towards the hand (HoseIk) - the model's own nodes, no physics. + /// - Pulled further than the hose is long (plus a little slack), the mouthpiece slips out of the hand. + /// - Let go, the links swing back to their rest pose (or to the pose the pipe's own animation gives them). + /// - Busy while an NPC smokes it (a living NPC uses it or walks to it): checked when a hand hovers, tries to grab + /// (twice a second) or grabs it. + /// - At the mouth (VRMouthSmoking, IVrMouthSmokable) the pipe works like for an NPC + /// (MobAnimationService.StartHeroUse: PIPE_BUBBLES, FIRE_SMOKE at the bowl) and after a drag the hero blows out + /// LIGHTSMOKE (HUMANS S_SMOKE_S1). + /// Away from the mouth or let go, it rests again (StopHeroUse). Like in the original, nothing else happens: no + /// item is used, no script runs. + /// Nothing is saved: the pipe rests again after a load. + /// + /// LateUpdate runs only while the mouthpiece is held or swings back, else the component is disabled. + /// + public class VRWaterPipe : MonoBehaviour, IVrMouthSmokable + { + private const string _mouthpieceNodeName = "BIP01 FLEXEND"; + private static readonly string[] _hoseNodeNames = + { + "BIP01 FLEX0", "BIP01 FLEX1", "BIP01 FLEX2", "BIP01 FLEX3", "BIP01 FLEX4" + }; + + private const string _handleName = "MouthpieceHandle"; + private const float _handleRadius = 0.15f; + // The hand may be this much further from the hose's start than the hose is long before it slips out. + private const float _slack = 0.15f; + private const float _swingBackSeconds = 0.3f; + // A hand grabbing the pipe this close to the mouthpiece takes the mouthpiece (VRMobInteraction). + private const float _takeOverDistance = 0.15f; + private const int _ikIterations = 10; + private const float _ikMaxTurnDegrees = 25f; + private const float _ikTolerance = 0.005f; + // While a hand tries to grab the mouthpiece, whether an NPC smokes it is asked again this often (not each + // frame: IsBusy walks all NPCs). + private const float _busyRecheckSeconds = 0.5f; + // The hero's smoking animation: its particle effect (LIGHTSMOKE) is the smoke blown out. + private const string _exhaleAnimationName = "S_SMOKE_S1"; + // The joint's smoking sound (SfxInst SMOKE_JOINT, smoke_joint.wav) - the snoring breath-out isn't in every game. + private const string _exhaleSoundName = "SMOKE_JOINT"; + + [Inject] private readonly IVrBackend _vrBackend; + [Inject] private readonly VRPlayerService _vrPlayerService; + [Inject] private readonly VobService _vobService; + [Inject] private readonly PlayerService _playerService; + [Inject] private readonly MobAnimationService _mobAnimationService; + + private VobContainer _mob; + // The mob's VOB name for the logs (this GameObject is its root node, BIP01 PIPE). + private string _logName; + private Transform[] _links; + private Transform _mouthpiece; + private VrInteractable _handle; + private Collider _handleTrigger; + + // Rest pose of the links and the mouthpiece (the model's), baked once. + private Vector3[] _restPositions; + private Quaternion[] _restRotations; + private Vector3 _mouthpieceRestPosition; + private Quaternion _mouthpieceRestRotation; + private float _maxReachSqr; + + // The links' local rotations: solved while held (the next frame starts from them), at the release, and last + // written while swinging back. + private Quaternion[] _solvedRotations; + private Quaternion[] _releasedRotations; + private Quaternion[] _writtenRotations; + + private bool _isHeld; + private bool _isBusy; + private float _busyCheckTime; + private Transform _hand; + private Vector3 _grabOffset; + private float _swingBack; + // The frame a take-over or a refused grab's release was deferred in (-1: none). A frame, not a flag: culling + // stops the coroutine, and OnDisable doesn't come while the component is disabled (idle). + private int _takeOverFrame = -1; + private int _releaseFrame = -1; + private bool _isAtMouth; + + + /// + /// Adds the component if the mob's model has the hose with the mouthpiece at its end (checked once per built + /// mob). The nodes carry their Gothic names (architecture.md rule C exception, like MobAnimator's root node). + /// + public static VRWaterPipe TryAdd(GameObject mobGo) + { + var mouthpiece = mobGo.transform.FindChildRecursively(_mouthpieceNodeName); + if (mouthpiece == null) + return null; + + var links = new Transform[_hoseNodeNames.Length]; + var node = mouthpiece.parent; + for (var i = links.Length - 1; i >= 0; i--) + { + if (node == null || !node.name.Equals(_hoseNodeNames[i], StringComparison.OrdinalIgnoreCase)) + { + Logger.LogWarning($"[VRWaterPipe] {mobGo.name}: {_mouthpieceNodeName} hangs on no hose " + + $"({_hoseNodeNames[i]} missing) - the mouthpiece can't be grabbed.", LogCat.VR); + return null; + } + + links[i] = node; + node = node.parent; + } + + var pipe = mobGo.AddComponent().Inject(); + pipe.Init(links, mouthpiece); + return pipe; + } + + private void Init(Transform[] links, Transform mouthpiece) + { + // Only LateUpdate needs it, and only while held or swinging back. + enabled = false; + + _mob = GetComponentInParent()?.Container; + _logName = _mob?.Vob?.Name ?? name; + _links = links; + _mouthpiece = mouthpiece; + _restPositions = new Vector3[links.Length]; + _restRotations = new Quaternion[links.Length]; + _solvedRotations = new Quaternion[links.Length]; + _releasedRotations = new Quaternion[links.Length]; + _writtenRotations = new Quaternion[links.Length]; + + var hoseLength = 0f; + for (var i = 0; i < links.Length; i++) + { + _restPositions[i] = links[i].localPosition; + _restRotations[i] = links[i].localRotation; + var next = i + 1 < links.Length ? links[i + 1] : mouthpiece; + hoseLength += Vector3.Distance(links[i].position, next.position); + } + + _mouthpieceRestPosition = mouthpiece.localPosition; + _mouthpieceRestRotation = mouthpiece.localRotation; + var maxReach = hoseLength + _slack; + _maxReachSqr = maxReach * maxReach; + + if (CreateHandle()) + Logger.LogEditor($"[VRWaterPipe] {_logName}: the mouthpiece can be grabbed (hose {hoseLength:0.00} m).", + LogCat.VR); + } + + /// + /// A trigger on the mouthpiece the hands grab - not one of the mob's own colliders, so the mob's interactable + /// doesn't take it. Layer VobItemNoWorldCollision: the hands' near grab and VRMouth's trigger see it, the world + /// doesn't. + /// + private bool CreateHandle() + { + var handleGo = new GameObject(_handleName); + handleGo.SetActive(false); + handleGo.layer = Constants.VobItemNoWorldCollision; + handleGo.transform.SetParent(_mouthpiece, false); + + var trigger = handleGo.AddComponent(); + trigger.isTrigger = true; + trigger.radius = _handleRadius / Mathf.Max(0.01f, _mouthpiece.lossyScale.x); + _handleTrigger = trigger; + + _handle = _vrBackend?.AddHandle(handleGo, trigger); + if (_handle == null) + { + Logger.LogWarning($"[VRWaterPipe] {_logName}: the VR backend can't make the mouthpiece a handle - it " + + "can't be grabbed.", LogCat.VR); + Destroy(handleGo); + return false; + } + + _handle.CanGrab = CanGrab; + _handle.HoverEntered += OnHoverEntered; + _handle.Grabbed += OnGrabbed; + _handle.Released += OnReleased; + + handleGo.Inject(); + handleGo.SetActive(true); + return true; + } + + private void OnDestroy() + { + if (_handle == null) + return; + + _handle.CanGrab = null; + _handle.HoverEntered -= OnHoverEntered; + _handle.Grabbed -= OnGrabbed; + _handle.Released -= OnReleased; + } + + /// + /// An NPC smokes it right now (ZS_Smoke_Waterpipe: AI_UseMob "SMOKE") - Core decides (VobService). The hero's + /// own use (MobAnimationService.StartHeroUse) sets no user. + /// + private bool IsBusy() + { + return _vobService.IsUsedByOtherNpc(_mob, _playerService.HeroContainer); + } + + /// + /// VrInteractable.CanGrab: answered from the cached check, the backend asks each frame while a hand tries to + /// grab. An NPC may sit down or get up meanwhile: the check is made again every _busyRecheckSeconds. + /// + private bool CanGrab() + { + if (Time.time >= _busyCheckTime + _busyRecheckSeconds) + RefreshBusy(isLogged: false); + + return !_isBusy; + } + + private void OnHoverEntered(VrGrabArgs args) + { + RefreshBusy(isLogged: true); + } + + private void RefreshBusy(bool isLogged) + { + var wasBusy = _isBusy; + _isBusy = IsBusy(); + _busyCheckTime = Time.time; + if (_isBusy && (isLogged || !wasBusy)) + Logger.LogEditor($"[VRWaterPipe] {_logName}: an NPC smokes it - the mouthpiece can't be taken.", + LogCat.VR); + else if (!_isBusy && wasBusy) + Logger.LogEditor($"[VRWaterPipe] {_logName}: no NPC smokes it any more - the mouthpiece is free.", + LogCat.VR); + } + + private static bool IsPending(int frame) + { + return frame >= 0 && Time.frameCount - frame <= 1; + } + + private void OnGrabbed(VrGrabArgs args) + { + if (!args.IsHandOrDistance) + return; + + // Hovered before the NPC sat down (or put into the hand by VRMobInteraction). + if (IsBusy()) + { + _isBusy = true; + _busyCheckTime = Time.time; + Logger.Log($"[VRWaterPipe] {_logName}: an NPC smokes it - the mouthpiece is let go again.", LogCat.VR); + ReleaseAfterGrab(); + return; + } + + _hand = _vrPlayerService.Rig?.GetHandVisual(args.HandSide); + if (_hand == null) + { + Logger.LogWarning($"[VRWaterPipe] {_logName}: no {args.HandSide} hand - the mouthpiece is let go.", + LogCat.VR); + ReleaseAfterGrab(); + return; + } + + _grabOffset = _hand.InverseTransformPoint(_mouthpiece.position); + for (var i = 0; i < _links.Length; i++) + _solvedRotations[i] = _links[i].localRotation; + + _isHeld = true; + enabled = true; + Logger.Log($"[VRWaterPipe] {_logName}: mouthpiece taken ({args.HandSide} hand).", LogCat.VR); + } + + /// + /// A grab the pipe refuses after all: let go a frame later, not inside the backend's grab event + /// (architecture.md "Inside Gothic-VR" 4), like TakeOverGrab. + /// + private void ReleaseAfterGrab() + { + if (IsPending(_releaseFrame)) + return; + + _releaseFrame = Time.frameCount; + StartCoroutine(ReleaseNextFrame()); + } + + private IEnumerator ReleaseNextFrame() + { + yield return null; + _releaseFrame = -1; + + // Not let go meanwhile, and not taken properly since (_isHeld). + if (!_isHeld && _handle.IsHeld) + _handle.ForceRelease(); + } + + private void OnReleased(VrGrabArgs args) + { + EndHold(); + } + + /// + /// The hand let go (or the mouthpiece slipped out): the links swing back from where they are now. + /// + private void EndHold() + { + if (!_isHeld) + return; + + _isHeld = false; + _hand = null; + StopHeroUse(); + _handleTrigger.transform.localPosition = Vector3.zero; + for (var i = 0; i < _links.Length; i++) + { + _releasedRotations[i] = _links[i].localRotation; + _writtenRotations[i] = _releasedRotations[i]; + } + + _swingBack = 0f; + enabled = true; + Logger.Log($"[VRWaterPipe] {_logName}: mouthpiece let go - the hose swings back.", LogCat.VR); + } + + /// + /// VRMouth isn't the only way to the mouthpiece: a hand closing right at it may hit the pipe's own collider + /// first (the near grab takes whichever it finds). Then the pipe isn't used - the mouthpiece is put into that + /// hand a frame later instead (not inside the backend's grab event, architecture.md "Inside Gothic-VR" 4). + /// true: taken over, the mob's grab does nothing else. + /// + public bool TryTakeOverGrab(VrGrabArgs args) + { + if (args.Kind != VrGrabberKind.Hand || _handle == null || _isHeld || IsPending(_takeOverFrame)) + return false; + + var hand = _vrPlayerService.Rig?.GetHandVisual(args.HandSide); + if (hand == null || + (hand.position - _mouthpiece.position).sqrMagnitude > _takeOverDistance * _takeOverDistance) + return false; + + RefreshBusy(isLogged: true); + if (_isBusy) + return false; + + _takeOverFrame = Time.frameCount; + StartCoroutine(TakeOverGrab(args.HandSide)); + return true; + } + + private IEnumerator TakeOverGrab(VrHandSide side) + { + yield return null; + _takeOverFrame = -1; + + var rig = _vrPlayerService.Rig; + if (rig == null || !rig.TryGrabIntoHand(side, _handle)) + Logger.LogWarning($"[VRWaterPipe] {_logName}: the mouthpiece couldn't be put into the {side} hand.", + LogCat.VR); + } + + private void OnDisable() + { + // Culled at the mouth (held, so enabled): the mouth's trigger may not report it leaving. Also called by + // enabled = false (Init, after the swing-back) - nothing is at the mouth then. + StopHeroUse(); + } + + public string ExhaleAnimation => _exhaleAnimationName; + + public string ExhaleSound => _exhaleSoundName; + + /// + /// The held mouthpiece at the mouth: the pipe works for the hero like for a smoking NPC (S0 -> S1 and its + /// loop: it bubbles, the bowl smokes). + /// + public bool TryStartSmoking(Collider part) + { + if (part != _handleTrigger || !_isHeld) + return false; + + if (_isAtMouth) + return true; + + _isAtMouth = true; + _mobAnimationService.StartHeroUse(_mob, _playerService.HeroContainer); + Logger.Log($"[VRWaterPipe] {_logName}: smoked - it bubbles.", LogCat.VR); + return true; + } + + public void StopSmoking(Collider part) + { + if (part == _handleTrigger) + StopHeroUse(); + } + + /// + /// Away from the mouth, let go or culled: the pipe rests again (T_S1_2_S0). Only this pipe - not another mob + /// the hero uses meanwhile. + /// + private void StopHeroUse() + { + if (!_isAtMouth) + return; + + _isAtMouth = false; + _mobAnimationService.StopHeroUse(_mob); + Logger.Log($"[VRWaterPipe] {_logName}: away from the mouth - it rests.", LogCat.VR); + } + + private void LateUpdate() + { + if (_isHeld) + UpdateHeld(); + else + UpdateSwingBack(); + } + + /// + /// Late: after MobAnimator (Update) - the hand wins over the pipe's own animation. Starts from the last solved + /// pose, so the hose bends smoothly over the frames. + /// + private void UpdateHeld() + { + if (_hand == null) + { + Slip("the hand is gone"); + return; + } + + var target = _hand.TransformPoint(_grabOffset); + if ((target - _links[0].position).sqrMagnitude > _maxReachSqr) + { + Slip("pulled further than the hose is long"); + return; + } + + for (var i = 0; i < _links.Length; i++) + _links[i].SetLocalPositionAndRotation(_restPositions[i], _solvedRotations[i]); + _mouthpiece.SetLocalPositionAndRotation(_mouthpieceRestPosition, _mouthpieceRestRotation); + + HoseIk.Solve(_links, _mouthpiece, target, _ikIterations, _ikMaxTurnDegrees, _ikTolerance); + + for (var i = 0; i < _links.Length; i++) + _solvedRotations[i] = _links[i].localRotation; + + // The mouth meets the mouthpiece where the hand holds it, even when the hose falls a bit short of the hand + // (the trigger stayed at the hose's end and never reached the mouth). + _handleTrigger.transform.position = target; + } + + private void Slip(string reason) + { + Logger.Log($"[VRWaterPipe] {_logName}: the mouthpiece slips out of the hand ({reason}).", LogCat.VR); + _handle.ForceRelease(); + // The backend didn't report a release (not held any more): end it here. + EndHold(); + } + + /// + /// The links turn back within _swingBackSeconds - to their rest pose, or, while the pipe's own animation moves + /// them (MobAnimator wrote another rotation since the last frame), to that pose. + /// + private void UpdateSwingBack() + { + _swingBack = Mathf.Min(1f, _swingBack + Time.deltaTime / _swingBackSeconds); + var blend = Mathf.SmoothStep(0f, 1f, _swingBack); + for (var i = 0; i < _links.Length; i++) + { + var link = _links[i]; + var current = link.localRotation; + var goal = current == _writtenRotations[i] ? _restRotations[i] : current; + var rotation = Quaternion.Slerp(_releasedRotations[i], goal, blend); + link.localRotation = rotation; + _writtenRotations[i] = rotation; + } + + if (_swingBack >= 1f) + enabled = false; + } + } +} diff --git a/Assets/Gothic-VR/Scripts/Adapters/Vob/VRWaterPipe.cs.meta b/Assets/Gothic-VR/Scripts/Adapters/Vob/VRWaterPipe.cs.meta new file mode 100644 index 000000000..176a983e9 --- /dev/null +++ b/Assets/Gothic-VR/Scripts/Adapters/Vob/VRWaterPipe.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 8fd8a5a339ac0064e9b1a15c0a6aa82f \ No newline at end of file diff --git a/Assets/Gothic-VR/Scripts/Adapters/Vob/VobItem/IVrMouthSmokable.cs b/Assets/Gothic-VR/Scripts/Adapters/Vob/VobItem/IVrMouthSmokable.cs new file mode 100644 index 000000000..ac793a364 --- /dev/null +++ b/Assets/Gothic-VR/Scripts/Adapters/Vob/VobItem/IVrMouthSmokable.cs @@ -0,0 +1,34 @@ +using UnityEngine; + +namespace Gothic.VR.Adapters.Vob.VobItem +{ + /// + /// Something smoked at the VR mouth without being used up, e.g. a water pipe's mouthpiece (VRWaterPipe). + /// VRMouthSmoking finds it above the collider that touches the mouth, tells it when that part comes and goes, and + /// after a drag plays ExhaleSound and blows out the smoke of ExhaleAnimation - like a joint, but nothing is eaten + /// and no script runs. + /// + public interface IVrMouthSmokable + { + /// + /// The Humans.mds animation whose first particle effect is the smoke blown out (S_SMOKE_S1: LIGHTSMOKE). + /// + string ExhaleAnimation { get; } + + /// + /// The sound (SfxInst) of breathing out the smoke, e.g. SMOKE_JOINT. + /// + string ExhaleSound { get; } + + /// + /// The part touched the mouth. true: it is smoked now (e.g. the mouthpiece is in a hand), the mouth blows out + /// its smoke. false: not now (lying around, another collider of the same object). + /// + bool TryStartSmoking(Collider part); + + /// + /// The part smoked since TryStartSmoking left the mouth. + /// + void StopSmoking(Collider part); + } +} diff --git a/Assets/Gothic-VR/Scripts/Adapters/Vob/VobItem/IVrMouthSmokable.cs.meta b/Assets/Gothic-VR/Scripts/Adapters/Vob/VobItem/IVrMouthSmokable.cs.meta new file mode 100644 index 000000000..8f730f797 --- /dev/null +++ b/Assets/Gothic-VR/Scripts/Adapters/Vob/VobItem/IVrMouthSmokable.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 791bf415b07fb3946b554b0bdcba917f \ No newline at end of file diff --git a/Assets/Gothic-VR/Scripts/Adapters/Vob/VobItem/VRMouth.cs b/Assets/Gothic-VR/Scripts/Adapters/Vob/VobItem/VRMouth.cs index 8caa17e7b..4c11daf23 100644 --- a/Assets/Gothic-VR/Scripts/Adapters/Vob/VobItem/VRMouth.cs +++ b/Assets/Gothic-VR/Scripts/Adapters/Vob/VobItem/VRMouth.cs @@ -66,9 +66,16 @@ public class VRMouth : MonoBehaviour // Do not eat them twice during destroy time. private List _objectsInDestroyGracePeriod = new(); + // A water pipe's mouthpiece at the mouth (created on first use: the services are injected by then). + private VRMouthSmoking _smoking; + private void OnTriggerEnter(Collider other) { + _smoking ??= new VRMouthSmoking(this, _mouthAudio, _audioService); + if (_smoking.TryStartSmoking(other)) + return; + var go = other.gameObject; if (!TryGetItemToEat(go, out var item)) @@ -101,7 +108,19 @@ private void OnTriggerEnter(Collider other) StartCoroutine(ConsumeObject(rootGo, clip, destroyTime, startDelay)); if (IsSmokable(item)) - StartCoroutine(ExhaleSmoke(item, destroyTime, startDelay)); + TryExhaleSmoke(TryGetUseAnimation(item), string.Format(_animationSchemeWithSfx, item.SchemeName), + destroyTime, startDelay); + } + + private void OnTriggerExit(Collider other) + { + _smoking?.OnLeftMouth(other); + } + + private void OnDisable() + { + // Coroutines end with the component; the smoked thing must still hear that it left the mouth. + _smoking?.StopSmoking(isExhaling: false); } /// @@ -115,21 +134,40 @@ private bool IsSmokable(ItemInstance item) } /// - /// The animation's own particle effect (LIGHTSMOKE) puffed out in front of the VR head. + /// VRMouthSmoking: the smoke of the Humans.mds animation animationName (its first particle effect). /// - private IEnumerator ExhaleSmoke(ItemInstance item, float inhaleSeconds, float startDelay) + internal void TryExhaleHumansSmoke(string animationName, float inhaleSeconds, float startDelay, int puffCount) { - var puffs = Mathf.Max(1, _smokePuffs); - if (startDelay > 0f) - yield return new WaitForSeconds(startDelay); + TryExhaleSmoke(TryGetHumansAnimation(animationName), animationName, inhaleSeconds, startDelay, puffCount); + } - var pfxName = TryGetUseAnimation(item)?.ParticleEffects.FirstOrDefault()?.Name; + /// + /// The smoke of a Humans.mds animation - its first particle effect (LIGHTSMOKE) - puffed out in front of the VR + /// head after startDelay. animationName only names it in the warning when it has none. + /// + [CanBeNull] + private Coroutine TryExhaleSmoke([CanBeNull] IAnimation smokeAnimation, string animationName, + float inhaleSeconds, float startDelay, int puffCount = 0) + { + var pfxName = smokeAnimation?.ParticleEffects.FirstOrDefault()?.Name; if (string.IsNullOrEmpty(pfxName)) { - Logger.LogWarning($"[VRMouth] No smoke PFX in 't_{item.SchemeName}_S0_2_Stand'.", LogCat.VR); - yield break; + Logger.LogWarning($"[VRMouth] No smoke PFX in '{animationName}'.", LogCat.VR); + return null; } + return StartCoroutine(ExhaleSmoke(pfxName, inhaleSeconds, startDelay, puffCount)); + } + + /// + /// The particle effect pfxName puffed out in front of the VR head. + /// + private IEnumerator ExhaleSmoke(string pfxName, float inhaleSeconds, float startDelay, int puffCount = 0) + { + var puffs = Mathf.Max(1, puffCount > 0 ? puffCount : _smokePuffs); + if (startDelay > 0f) + yield return new WaitForSeconds(startDelay); + // Puffs spread over the smoking sound - the first one right with it (it came only after a pause). for (var puff = 0; puff < puffs; puff++) { @@ -235,9 +273,14 @@ private bool TryExtractSfx(ItemInstance item, out AudioClip clip) [CanBeNull] private IAnimation TryGetUseAnimation(ItemInstance item) + { + return TryGetHumansAnimation(string.Format(_animationSchemeWithSfx, item.SchemeName)); + } + + [CanBeNull] + private IAnimation TryGetHumansAnimation(string animationName) { var mds = _resourceCacheService.TryGetModelScript("Humans"); - var animationName = string.Format(_animationSchemeWithSfx, item.SchemeName); return mds?.Animations.FirstOrDefault(i => i.Name.EqualsIgnoreCase(animationName)); } diff --git a/Assets/Gothic-VR/Scripts/Adapters/Vob/VobItem/VRMouthSmoking.cs b/Assets/Gothic-VR/Scripts/Adapters/Vob/VobItem/VRMouthSmoking.cs new file mode 100644 index 000000000..22c114fff --- /dev/null +++ b/Assets/Gothic-VR/Scripts/Adapters/Vob/VobItem/VRMouthSmoking.cs @@ -0,0 +1,135 @@ +using System.Collections; +using Gothic.Core.Logging; +using Gothic.Core.Manager; +using UnityEngine; +using Logger = Gothic.Core.Logging.Logger; + +namespace Gothic.VR.Adapters.Vob.VobItem +{ + /// + /// The part smoked at the VR mouth right now (IVrMouthSmokable: a water pipe's mouthpiece) and its drag. Owned by + /// VRMouth, which keeps the triggers and the eating and lends its coroutines, audio source and smoke puffs. + /// - While at the mouth only the smokable works (the pipe bubbles, its bowl smokes). + /// - Taken away after at least _minDragSeconds: _exhaleDelay later the smokable's ExhaleSound and a cloud of + /// _exhalePuffs puffs of its ExhaleAnimation's smoke in front of the face. Taken away sooner: nothing. + /// - Destroyed or culled at the mouth (its exit never came): forgotten without smoke. + /// + public class VRMouthSmoking + { + private const float _minDragSeconds = 0.8f; + private const float _exhaleSeconds = 0.6f; + private const int _exhalePuffs = 2; + // The smoke is held for a moment before it is blown out. + private const float _exhaleDelay = 1f; + + private readonly VRMouth _mouth; + private readonly AudioSource _mouthAudio; + private readonly AudioService _audioService; + + private IVrMouthSmokable _smokable; + private Collider _smokedPart; + private float _dragStart; + + + public VRMouthSmoking(VRMouth mouth, AudioSource mouthAudio, AudioService audioService) + { + _mouth = mouth; + _mouthAudio = mouthAudio; + _audioService = audioService; + } + + /// + /// A collider touched the mouth. true: it belongs to something smokable - it's no food, whether it is smoked + /// now or not. + /// + public bool TryStartSmoking(Collider other) + { + var smokable = other.GetComponentInParent(); + if (smokable == null) + return false; + + // In again without having left: its exit was missed (culled at the mouth). + if (other == _smokedPart) + StopSmoking(); + + if (!smokable.TryStartSmoking(other)) + return true; + + // Another part was still at the mouth. + StopSmoking(); + _smokable = smokable; + _smokedPart = other; + _dragStart = Time.time; + // While at the mouth only the pipe works (it bubbles, the bowl smokes); the smoke comes out of the mouth + // when the mouthpiece is taken away (StopSmoking). + Logger.Log($"[VRMouth] Smoking {other.name}.", LogCat.VR); + return true; + } + + /// + /// A collider left the mouth: if it is the smoked part, its drag ends. + /// + public void OnLeftMouth(Collider other) + { + if (other == _smokedPart) + StopSmoking(); + } + + /// + /// The smoked part left the mouth. Taken away before the drag ended, no smoke comes; puffs already blown out + /// drift on. Destroyed or culled at the mouth (its exit never came): the mouth is free again, without smoke. + /// isExhaling false: VRMouth is disabled - its coroutines end, the smokable only hears that the part left. + /// + public void StopSmoking(bool isExhaling = true) + { + if (_smokable == null) + return; + + // Cleared first: nothing below may leave the mouth stuck on this part. + var smokable = _smokable; + var part = _smokedPart; + var dragStart = _dragStart; + _smokable = null; + _smokedPart = null; + + if (IsGone(smokable, part)) + { + Logger.Log("[VRMouth] The smoked part is gone - nothing is breathed out.", LogCat.VR); + return; + } + + // Taken from the mouth after a drag: a breath out and a cloud of smoke in front of the face. + if (isExhaling && Time.time >= dragStart + _minDragSeconds) + { + _mouth.TryExhaleHumansSmoke(smokable.ExhaleAnimation, _exhaleSeconds, _exhaleDelay, _exhalePuffs); + _mouth.StartCoroutine(PlayExhaleSound(smokable.ExhaleSound, _exhaleDelay)); + Logger.Log($"[VRMouth] Breathing out the smoke of {part.name} in {_exhaleDelay} s.", LogCat.VR); + } + + smokable.StopSmoking(part); + } + + /// + /// The part or its smokable was destroyed or deactivated (culled, world left). Unity's null check first: `?.` + /// doesn't do it, and .name of a destroyed collider throws. + /// + private static bool IsGone(IVrMouthSmokable smokable, Collider part) + { + if (part == null || !part.enabled || !part.gameObject.activeInHierarchy) + return true; + + return smokable is Behaviour behaviour && (behaviour == null || !behaviour.gameObject.activeInHierarchy); + } + + private IEnumerator PlayExhaleSound(string soundName, float delay) + { + yield return new WaitForSeconds(delay); + + var exhaleClip = _audioService.GetRandomSoundClip(soundName); + if (exhaleClip != null) + _mouthAudio.PlayOneShot(exhaleClip); + else + Logger.LogWarning($"[VRMouth] No sound '{soundName}' for breathing out the smoke.", LogCat.VR); + } + } +} diff --git a/Assets/Gothic-VR/Scripts/Adapters/Vob/VobItem/VRMouthSmoking.cs.meta b/Assets/Gothic-VR/Scripts/Adapters/Vob/VobItem/VRMouthSmoking.cs.meta new file mode 100644 index 000000000..8e0a413ec --- /dev/null +++ b/Assets/Gothic-VR/Scripts/Adapters/Vob/VobItem/VRMouthSmoking.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: eca7f8cc698f1c243b8330381fa2dcd8 \ No newline at end of file diff --git a/Assets/Gothic-VR/Scripts/Interaction/Backends/Xri/GothicGrabInteractable.cs b/Assets/Gothic-VR/Scripts/Interaction/Backends/Xri/GothicGrabInteractable.cs index 13bc10669..193747348 100644 --- a/Assets/Gothic-VR/Scripts/Interaction/Backends/Xri/GothicGrabInteractable.cs +++ b/Assets/Gothic-VR/Scripts/Interaction/Backends/Xri/GothicGrabInteractable.cs @@ -113,12 +113,49 @@ public override bool IsSelectableBy(IXRSelectInteractor interactor) { if (interactor is not XriSocketBridge && (IsLockedInSocket || IsHeldByOtherHand(interactor) || IsTooFarFor(interactor) || - IsDistanceGrabOfHeldItem(interactor) || IsOutOfLineReach(interactor))) + IsDistanceGrabOfHeldItem(interactor) || IsOutOfLineReach(interactor) || IsGrabRefused(interactor))) return false; return base.IsSelectableBy(interactor); } + /// + /// VrInteractable.CanGrab says no (a water pipe an NPC smokes). Only for a new grab: XRI asks again while the + /// hand holds it. + /// + private bool IsGrabRefused(IXRSelectInteractor interactor) + { + if (interactorsSelecting.Contains(interactor)) + return false; + + _vrInteractable ??= GetComponent(); + var canGrab = _vrInteractable != null ? _vrInteractable.CanGrab : null; + return canGrab != null && !canGrab(); + } + + /// + /// Set up as a handle (IVrBackend.AddHandle, a water pipe's mouthpiece) before its GameObject is activated: + /// held without being moved (tracking off, kinematic, like a door leaf), never thrown or unparented, only right + /// at a hand and by one hand at a time. + /// + internal void SetUpAsHandle() + { + movementType = MovementType.Kinematic; + trackPosition = false; + trackRotation = false; + trackScale = false; + throwOnDetach = false; + unparentTransformOnGrab = false; + IsDistanceGrabbable = false; + _isOneHandOnly = true; + + if (TryGetComponent(out var body)) + { + body.isKinematic = true; + body.useGravity = false; + } + } + /// /// The other hand holds it - this hand grabs it only right at /// it, not from afar (the line still hovers it: highlighted, readable). diff --git a/Assets/Gothic-VR/Scripts/Interaction/Backends/Xri/XriBackend.cs b/Assets/Gothic-VR/Scripts/Interaction/Backends/Xri/XriBackend.cs index bd038bce7..1b116b61d 100644 --- a/Assets/Gothic-VR/Scripts/Interaction/Backends/Xri/XriBackend.cs +++ b/Assets/Gothic-VR/Scripts/Interaction/Backends/Xri/XriBackend.cs @@ -1,6 +1,8 @@ using Gothic.Core.Logging; +using Gothic.VR.Interaction.Components; using Gothic.VR.Interaction.Ports; using Reflex.Core; +using UnityEngine; using Logger = Gothic.Core.Logging.Logger; namespace Gothic.VR.Interaction.Backends.Xri @@ -16,8 +18,8 @@ namespace Gothic.VR.Interaction.Backends.Xri /// on the rig, ClimbInteractable + VrLadderExit on oCMobLadder), ledges (VrLedgeReach on the rig moves a /// ClimbInteractable ("VR Ledge Anchor XRI.prefab") under the hands, VrLedgeLocomotion makes GothicJumpProvider /// jump as high as Gothic's ledges need and lets teleports reach climbable tops), block hands (VrBlockHand - /// under each controller) and physical hands (VrPhysicsHand next to VrBlockHand; held items follow it, contact - /// haptics). + /// under each controller), physical hands (VrPhysicsHand next to VrBlockHand; held items follow it, contact + /// haptics) and handles on Gothic models made at runtime (AddHandle: a water pipe's mouthpiece). /// Missing: teleport/ladder/swim handling of physical hands (5d). /// public class XriBackend : IVrBackend @@ -42,5 +44,28 @@ public bool OwnsRig(IVrRig rig) { return rig is XriRig; } + + /// + /// VrInteractable, a GothicGrabInteractable set up as a handle (its Rigidbody comes with it) and the bridge - + /// in this order, as their Awake (on activation) looks for each other. The XR interactable stays disabled until + /// the bridge's Start has collected the grab trigger (like in the prefabs). + /// + public VrInteractable AddHandle(GameObject go, Collider grabTrigger) + { + if (go == null || grabTrigger == null || go.activeSelf) + { + var goName = go != null ? go.name : "none"; + Logger.LogError($"[XRI] AddHandle needs an inactive GameObject and a grab trigger ({goName}).", + LogCat.VR); + return null; + } + + var interactable = go.AddComponent(); + var grab = go.AddComponent(); + grab.enabled = false; + grab.SetUpAsHandle(); + go.AddComponent().SetGrabTriggers(grabTrigger); + return interactable; + } } } diff --git a/Assets/Gothic-VR/Scripts/Interaction/Backends/Xri/XriInteractableBridge.cs b/Assets/Gothic-VR/Scripts/Interaction/Backends/Xri/XriInteractableBridge.cs index 71de66498..0a1b18e3e 100644 --- a/Assets/Gothic-VR/Scripts/Interaction/Backends/Xri/XriInteractableBridge.cs +++ b/Assets/Gothic-VR/Scripts/Interaction/Backends/Xri/XriInteractableBridge.cs @@ -223,6 +223,14 @@ public bool IsJustReleasedByHand(float seconds) return Time.time - _lastHandReleaseTime <= seconds; } + /// + /// The trigger colliders hands grab it by, for a bridge added at runtime (XriBackend.AddHandle) - before Start. + /// + internal void SetGrabTriggers(params Collider[] grabTriggers) + { + _grabTriggers = grabTriggers; + } + /// /// Called by GothicGrabInteractable before XRI moves the interactable (BeforeGrabbed of HVR). /// diff --git a/Assets/Gothic-VR/Scripts/Interaction/Components/VrInteractable.cs b/Assets/Gothic-VR/Scripts/Interaction/Components/VrInteractable.cs index 3319868d4..b7ca07959 100644 --- a/Assets/Gothic-VR/Scripts/Interaction/Components/VrInteractable.cs +++ b/Assets/Gothic-VR/Scripts/Interaction/Components/VrInteractable.cs @@ -53,6 +53,12 @@ public class VrInteractable : MonoBehaviour /// public Func CanSecondHandGrabAt { get; set; } + /// + /// May a hand take it now? null = yes. Asked by the XRI backend while a hand tries to grab it (each frame + /// then): answer from a cached state, without allocations. VRWaterPipe: not while an NPC smokes the pipe. + /// + public Func CanGrab { get; set; } + /// /// See IVrInteractableBackend.IsGrabEnabled. /// diff --git a/Assets/Gothic-VR/Scripts/Interaction/Ports/IVrBackend.cs b/Assets/Gothic-VR/Scripts/Interaction/Ports/IVrBackend.cs index 7cf3501f1..062005265 100644 --- a/Assets/Gothic-VR/Scripts/Interaction/Ports/IVrBackend.cs +++ b/Assets/Gothic-VR/Scripts/Interaction/Ports/IVrBackend.cs @@ -1,4 +1,6 @@ +using Gothic.VR.Interaction.Components; using Reflex.Core; +using UnityEngine; namespace Gothic.VR.Interaction.Ports { @@ -21,5 +23,17 @@ public interface IVrBackend /// Used to pick the backend's player prefab. null (e.g., a rig whose scripts are missing) returns false. /// bool OwnsRig(IVrRig rig); + + /// + /// Makes a part of a Gothic model a handle that a hand grabs at runtime (a water pipe's mouthpiece): adds a + /// VrInteractable and the backend's parts to go. The grab holds it without moving it - the game moves it + /// itself, like VrHinge a door - and only a hand right at it takes it, one hand at a time. The hands grab it + /// by grabTrigger, a trigger collider on go, which a mob's own interactable above doesn't count. + /// go must be inactive: inject and activate it afterwards. null if the backend can't (logged by the caller). + /// + VrInteractable AddHandle(GameObject go, Collider grabTrigger) + { + return null; + } } } diff --git a/Docs/adr/2026-11-26-vr-water-pipe.md b/Docs/adr/2026-11-26-vr-water-pipe.md new file mode 100644 index 000000000..c0b321d1c --- /dev/null +++ b/Docs/adr/2026-11-26-vr-water-pipe.md @@ -0,0 +1,23 @@ +# ADR: Smoking a water pipe with your own hands in VR + +- Date: 2026-11-26 +- Technical details: Docs/mobs.md + +## Context + +The water pipes in Khorinis (and in Gothic 1) are mobs: NPCs sit down at them, pick up the mouthpiece and smoke, the pipe bubbles and smokes. The scripts give the player nothing there, it is a moment of atmosphere. + +In VR you couldn't use them at all: grabbing the pipe did nothing. + +## Decisions + +1. **You grab the mouthpiece and the hose follows your hand.** The pipe's own hose bends towards the hand; pulled further than the hose is long, the mouthpiece slips out and swings back. Not chosen: a physics rope (livelier but costly and jittery on the headset) or a straight stretched line (looks wrong). +2. **At your mouth the pipe bubbles and smokes, and you blow out smoke like with a swampweed joint.** Nothing else happens, like in the original. Not chosen: the joint's effect, which the original doesn't give at a water pipe. +3. **You don't need to sit or crouch.** As long as the mouthpiece reaches your mouth, it works. Not chosen: only while crouched, which would make the hand's reach pointless. +4. **A pipe an NPC is smoking is busy.** Its mouthpiece can't be grabbed, like a mob in use in Gothic. Not chosen: taking it from him. + +## Consequences + +- The water pipes in Khorinis can be smoked in VR; on the flat screen nothing changes. +- Nothing is saved: the pipe is free again after a load. +- Pipes in mods with the same hose parts work the same way. diff --git a/Docs/mobs.md b/Docs/mobs.md index 5437c4088..71f16df0f 100644 --- a/Docs/mobs.md +++ b/Docs/mobs.md @@ -72,6 +72,11 @@ dialog (anvil, grindstone, rune table) works like for a smith while its dialog i the mob dialog anchor - also when `_S1` opened no dialog: the mob works once, there and back). The forge's item swap without a dialog works once too. +VR water pipe (`VRWaterPipe`, ADR 2026-11-26-vr-water-pipe): the hose `BIP01 FLEX0..4` bends towards the hand holding +the mouthpiece `BIP01 FLEXEND` (its own handle); at the mouth (`VRMouth`) `StartHeroUse`, away from it or let go +`StopHeroUse(mob)` - it bubbles and smokes, the hero blows out `LIGHTSMOKE`, nothing else; busy (not grabbable) while an +NPC smokes it. + ### The light player (MobAnimator) `AnimationSystem` is built for skinned NPCs: a PlayableGraph, an Animator and a Burst job per NPC, layers, blending,