diff --git a/.claude/skills/feature-checklist/SKILL.md b/.claude/skills/feature-checklist/SKILL.md
index 61a01b7cc..7fa1d1055 100644
--- a/.claude/skills/feature-checklist/SKILL.md
+++ b/.claude/skills/feature-checklist/SKILL.md
@@ -15,6 +15,10 @@ description: Implementation checklist for new features and fixes in Gothic-Unity
the `daedalus-bridge` skill).
- **Search narrowly.** The repo is huge - never grep the project root or all of `Assets/`. Scope to e.g.
`Assets/Gothic-Core/Scripts/Services/`.
+- **Beyond the original game?** A special case Gothic doesn't have (e.g. Fellan's hammering carrying 24 m) is an
+ *improvement*: put it in the game-version module (`Assets/Gothic2/`, via a Core `Context*Service` proxy), gate it
+ with `DeveloperConfig.EnableImprovements` and no active mod - never a special case in Core
+ (`G2SoundRangeService`).
## DeveloperConfig flags
diff --git a/Assets/Gothic-Core/Resources/DeveloperConfigs/Lab.HVR.Simulator.asset b/Assets/Gothic-Core/Resources/DeveloperConfigs/Lab.HVR.Simulator.asset
index 5b1b69c7a..68d9c9ae3 100644
--- a/Assets/Gothic-Core/Resources/DeveloperConfigs/Lab.HVR.Simulator.asset
+++ b/Assets/Gothic-Core/Resources/DeveloperConfigs/Lab.HVR.Simulator.asset
@@ -14,6 +14,7 @@ MonoBehaviour:
m_EditorClassIdentifier:
PreselectGameVersion: 1
GameVersion: 0
+ EnableImprovements: 1
PreSelectMod: 0
ModIni:
ModPath:
@@ -71,6 +72,7 @@ MonoBehaviour:
SunLightIntensity: 1
SunUpdateInterval: 2
AmbientLightColor: {r: 0.10196079, g: 0.10196079, b: 0.10196079, a: 1}
+ EnableWorldLightmaps: 1
StartTimeHour: 8
StartTimeMinute: 0
TimeSpeedMultiplier: 1
diff --git a/Assets/Gothic-Core/Resources/DeveloperConfigs/Production.asset b/Assets/Gothic-Core/Resources/DeveloperConfigs/Production.asset
index dfc440af2..8abc29b2d 100644
--- a/Assets/Gothic-Core/Resources/DeveloperConfigs/Production.asset
+++ b/Assets/Gothic-Core/Resources/DeveloperConfigs/Production.asset
@@ -14,6 +14,7 @@ MonoBehaviour:
m_EditorClassIdentifier:
PreselectGameVersion: 0
GameVersion: 0
+ EnableImprovements: 1
PreSelectMod: 0
ModIni:
ModPath:
diff --git a/Assets/Gothic-Core/Resources/Prefabs/Vobs/oCNpc.prefab b/Assets/Gothic-Core/Resources/Prefabs/Vobs/oCNpc.prefab
index 54563ec00..99a2bf056 100644
--- a/Assets/Gothic-Core/Resources/Prefabs/Vobs/oCNpc.prefab
+++ b/Assets/Gothic-Core/Resources/Prefabs/Vobs/oCNpc.prefab
@@ -118,7 +118,7 @@ AudioSource:
m_GameObject: {fileID: 2815092147823170342}
m_Enabled: 1
serializedVersion: 4
- OutputAudioMixerGroup: {fileID: 0}
+ OutputAudioMixerGroup: {fileID: 6160132109742411210, guid: 118dcb5485ad4894fb619aab7e1f8708, type: 2}
m_audioClip: {fileID: 0}
m_Resource: {fileID: 0}
m_PlayOnAwake: 0
@@ -247,10 +247,10 @@ Rigidbody:
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 3647559741746323219}
- serializedVersion: 4
+ serializedVersion: 5
m_Mass: 80
- m_Drag: 0
- m_AngularDrag: 0.05
+ m_LinearDamping: 0
+ m_AngularDamping: 0.05
m_CenterOfMass: {x: 0, y: 0, z: 0}
m_InertiaTensor: {x: 1, y: 1, z: 1}
m_InertiaRotation: {x: 0, y: 0, z: 0, w: 1}
@@ -302,4 +302,4 @@ MonoBehaviour:
m_Script: {fileID: 11500000, guid: e31e900fff574068b5e83a20a4f2df42, type: 3}
m_Name:
m_EditorClassIdentifier:
- _capsuleCollider: {fileID: 0}
+ _walkCollider: {fileID: 0}
diff --git a/Assets/Gothic-Core/Scripts/Adapters/Animations/AnimationEffectPlayer.cs b/Assets/Gothic-Core/Scripts/Adapters/Animations/AnimationEffectPlayer.cs
new file mode 100644
index 000000000..eb74d9739
--- /dev/null
+++ b/Assets/Gothic-Core/Scripts/Adapters/Animations/AnimationEffectPlayer.cs
@@ -0,0 +1,304 @@
+using System.Collections.Generic;
+using Gothic.Core.Extensions;
+using Gothic.Core.Logging;
+using Gothic.Core.Manager;
+using Gothic.Core.Models.Animations;
+using Gothic.Core.Services.Meshes;
+using Reflex.Attributes;
+using UnityEngine;
+using ZenKit;
+using Logger = Gothic.Core.Logging.Logger;
+using Object = UnityEngine.Object;
+
+namespace Gothic.Core.Adapters.Animations
+{
+ ///
+ /// Plays the sound (*eventSFX) and particle (*eventPFX, *eventPFXStop) events of an animation track instance
+ /// whose frames were crossed this frame (AnimationTrackInstance.GetPending*). Owned by the object that plays the
+ /// animation: AnimationSystem (NPCs) and MobAnimator (used mobs).
+ ///
+ /// Two ways to handle particles:
+ /// - one-off (NPCs): every event builds its effect, which destroys itself after playing (_pfxMaxSeconds at most).
+ /// - reusing (mobs): an effect is built on its first event and replayed on the next ones - an anvil hit twice per
+ /// loop rebuilt its sparks (meshes, materials) every time otherwise. DestroyAllPfx() removes them.
+ ///
+ public class AnimationEffectPlayer
+ {
+ [Inject] private readonly AudioService _audioService;
+ [Inject] private readonly MeshService _meshService;
+
+ // *eventPFX effects that run until their *eventPFXStop (same index). Safety: gone after this time anyway.
+ private const float _pfxMaxSeconds = 12f;
+ private const float _pfxFadeSeconds = 8f;
+
+ ///
+ /// An effect of the reusing mode, built once: the event it belongs to (name + bone) and its particle systems.
+ ///
+ private struct ReusedPfx
+ {
+ public string Name;
+ public string Bone;
+ public int Index;
+ public GameObject Root;
+ public ParticleSystem[] Systems;
+ }
+
+ private readonly Transform _boneRoot;
+ private readonly Transform _stepOrigin;
+ private readonly AudioSource _stepSound;
+ private readonly AudioSource _clipSound;
+ // The volume the clip source had: Gothic's volume of each sound is applied on top of it.
+ private readonly float _soundBaseVolume;
+ // Daedalus instance index of the NPC, -1 for a mob: a game version module may change its sound ranges.
+ private readonly int _npcInstanceIndex;
+ private readonly bool _isReusingPfx;
+
+ // One-off mode: effects with an index, until their *eventPFXStop.
+ private readonly Dictionary _activePfx = new();
+ private readonly List _activePfxIndices = new();
+
+ // Reusing mode: every effect built so far.
+ private readonly List _reusedPfx = new();
+
+
+ /// The bones of *eventPFX are searched below it; effects without a bone start at it.
+ ///
+ /// Where a step sound (*eventSFXGrnd) asks for the ground below.
+ /// Plays the step sounds as one-shots on top of everything else. An NPC's NpcSound
+ /// (shared with hits, weapon draws, ...).
+ /// Plays the *eventSFX clips, one at a time like the engine's model sound. Needs an own
+ /// source: a clip's volume (Gothic's of each sound) and range would turn down the one-shots of a shared source.
+ /// Mobs pass their single source for both.
+ /// Daedalus instance index of the NPC playing the animations, -1 for a mob.
+ ///
+ /// Build each effect once and replay it (mobs), see class summary.
+ public AnimationEffectPlayer(Transform boneRoot, Transform stepOrigin, AudioSource stepSound,
+ AudioSource clipSound, int npcInstanceIndex, bool isReusingPfx)
+ {
+ _boneRoot = boneRoot;
+ _stepOrigin = stepOrigin;
+ _stepSound = stepSound;
+ _clipSound = clipSound;
+ _soundBaseVolume = clipSound != null ? clipSound.volume : 1f;
+ _npcInstanceIndex = npcInstanceIndex;
+ _isReusingPfx = isReusingPfx;
+ }
+
+ ///
+ /// Plays the sounds whose frame was crossed. Returns true if there were any (also skipped footsteps).
+ ///
+ public bool ApplySfxEvents(AnimationTrackInstance trackInstance)
+ {
+ var sfxEvents = trackInstance.GetPendingSoundEffects();
+ if (sfxEvents == null)
+ return false;
+
+ foreach (var sfx in sfxEvents)
+ {
+ // What to play (footstep by the ground below, Gothic's volume and range) is AudioService's decision.
+ // No clip (footsteps off, missing or nosound): nothing changes, a clip still playing on the source
+ // (a fire loop) keeps playing.
+ var toPlay = _audioService.GetAnimationSfx(_npcInstanceIndex, sfx.Name, sfx.Range.ToMeter(),
+ _stepOrigin.position);
+ if (toPlay.Clip == null)
+ continue;
+
+ // A step plays on top of the other sounds (it mustn't cut a swing or a scream).
+ if (toPlay.IsStep)
+ {
+ _stepSound.PlayOneShot(toPlay.Clip, toPlay.Volume);
+ continue;
+ }
+
+ // Gothic's volume of the sound (Forge_Sharpen 40 of 127). The player's sound effects slider works
+ // through the source's mixer group (AudioService.SoundEffectsGroup). One clip at a time.
+ _clipSound.clip = toPlay.Clip;
+ _clipSound.volume = _soundBaseVolume * toPlay.Volume;
+ _clipSound.maxDistance = toPlay.RangeMeters;
+ _clipSound.Play();
+ }
+
+ return sfxEvents.Count > 0;
+ }
+
+ ///
+ /// *eventPFX (frame, index, name, bone, ATTACH) creates the effect at the
+ /// bone (following it if attached), *eventPFXStop (frame, index) lets it fade out. Joint smoke, bubbles, ...
+ ///
+ public void ApplyPfxEvents(AnimationTrackInstance trackInstance)
+ {
+ var stops = trackInstance.GetPendingParticleEffectStops();
+ if (stops != null)
+ {
+ foreach (var stop in stops)
+ StopPfx(stop.Index);
+ }
+
+ var pfxEvents = trackInstance.GetPendingParticleEffects();
+ if (pfxEvents == null)
+ return;
+
+ foreach (var pfx in pfxEvents)
+ {
+ if (_isReusingPfx && TryReplayPfx(pfx))
+ continue;
+
+ var root = CreatePfx(pfx, trackInstance.AnimationName);
+ if (root == null)
+ continue;
+
+ if (_isReusingPfx)
+ {
+ _reusedPfx.Add(new ReusedPfx
+ {
+ Name = pfx.Name,
+ Bone = pfx.Position,
+ Index = pfx.Index,
+ Root = root,
+ Systems = root.GetComponentsInChildren()
+ });
+ continue;
+ }
+
+ if (pfx.Index != 0)
+ {
+ StopPfx(pfx.Index);
+ _activePfx[pfx.Index] = root;
+ _activePfxIndices.Add(pfx.Index);
+ }
+ Object.Destroy(root, _pfxMaxSeconds);
+ }
+ }
+
+ ///
+ /// Builds the effect of a *eventPFX. Returns its root (the effect and its sub emitters), null if it failed.
+ ///
+ private GameObject CreatePfx(IEventParticleEffect pfx, string animationName)
+ {
+ var bone = FindBone(pfx.Position) ?? _boneRoot;
+ // A reused effect lives as long as the animator: it must not destroy itself after its first play.
+ var isDestroyedAfterPlay = !_isReusingPfx;
+ var pfxGo = pfx.Attached
+ ? _meshService.CreateVobPfx(pfx.Name, parent: bone.gameObject, destroyAfterPlay: isDestroyedAfterPlay)
+ : _meshService.CreateVobPfx(pfx.Name, bone.position, bone.rotation,
+ destroyAfterPlay: isDestroyedAfterPlay);
+ if (pfxGo == null)
+ {
+ Logger.LogWarning($"[AnimationPfx] {pfx.Name} couldn't be created ({animationName}).",
+ LogCat.Animation);
+ return null;
+ }
+
+ var parent = pfxGo.transform.parent;
+ var root = parent != null && parent != bone ? parent.gameObject : pfxGo;
+ foreach (var particleSystem in root.GetComponentsInChildren())
+ {
+ var main = particleSystem.main;
+ main.simulationSpace = ParticleSystemSimulationSpace.World;
+ }
+
+ // A mob's effect stays with the mob (culled with it, destroyed with the world).
+ if (_isReusingPfx && !pfx.Attached)
+ root.transform.SetParent(_boneRoot, true);
+
+ return root;
+ }
+
+ ///
+ /// Reusing mode: the effect of this event was built before - it starts again. Stopping its emission first
+ /// restarts a burst that is still running (the second anvil hit), its particles in the air stay.
+ ///
+ private bool TryReplayPfx(IEventParticleEffect pfx)
+ {
+ for (var i = 0; i < _reusedPfx.Count; i++)
+ {
+ var reused = _reusedPfx[i];
+ if (reused.Root == null || !reused.Name.EqualsIgnoreCase(pfx.Name) ||
+ !reused.Bone.EqualsIgnoreCase(pfx.Position))
+ continue;
+
+ foreach (var particleSystem in reused.Systems)
+ {
+ if (particleSystem == null)
+ continue;
+ particleSystem.Stop(false, ParticleSystemStopBehavior.StopEmitting);
+ particleSystem.Play(false);
+ }
+ return true;
+ }
+
+ return false;
+ }
+
+ private void StopPfx(int index)
+ {
+ if (_isReusingPfx)
+ {
+ // Reusing mode: the effect only stops emitting, the next event of its index starts it again.
+ for (var i = 0; i < _reusedPfx.Count; i++)
+ {
+ if (_reusedPfx[i].Index == index)
+ StopEmitting(_reusedPfx[i].Systems);
+ }
+ return;
+ }
+
+ if (!_activePfx.Remove(index, out var pfxGo))
+ return;
+ _activePfxIndices.Remove(index);
+ if (pfxGo == null)
+ return;
+
+ foreach (var particleSystem in pfxGo.GetComponentsInChildren())
+ particleSystem.Stop(true, ParticleSystemStopBehavior.StopEmitting);
+ Object.Destroy(pfxGo, _pfxFadeSeconds);
+ }
+
+ ///
+ /// Every effect running until its *eventPFXStop fades out now (one-off mode). In reusing mode all effects stop
+ /// emitting and are destroyed once their particles faded.
+ ///
+ public void StopAllPfx()
+ {
+ if (_isReusingPfx)
+ {
+ foreach (var reused in _reusedPfx)
+ {
+ StopEmitting(reused.Systems);
+ if (reused.Root != null)
+ Object.Destroy(reused.Root, _pfxFadeSeconds);
+ }
+ _reusedPfx.Clear();
+ return;
+ }
+
+ // Backwards: StopPfx removes the index from the list.
+ for (var i = _activePfxIndices.Count - 1; i >= 0; i--)
+ StopPfx(_activePfxIndices[i]);
+ }
+
+ private static void StopEmitting(ParticleSystem[] systems)
+ {
+ foreach (var particleSystem in systems)
+ {
+ if (particleSystem != null)
+ particleSystem.Stop(false, ParticleSystemStopBehavior.StopEmitting);
+ }
+ }
+
+ ///
+ /// MDS bone names differ in case from the bone GameObjects ("Bip01 Head" vs "BIP01 HEAD").
+ ///
+ private Transform FindBone(string boneName)
+ {
+ if (string.IsNullOrEmpty(boneName))
+ return null;
+ foreach (var child in _boneRoot.GetComponentsInChildren())
+ {
+ if (child.name.EqualsIgnoreCase(boneName))
+ return child;
+ }
+ return null;
+ }
+ }
+}
diff --git a/Assets/Gothic-Core/Scripts/Adapters/Animations/AnimationEffectPlayer.cs.meta b/Assets/Gothic-Core/Scripts/Adapters/Animations/AnimationEffectPlayer.cs.meta
new file mode 100644
index 000000000..95f0fb738
--- /dev/null
+++ b/Assets/Gothic-Core/Scripts/Adapters/Animations/AnimationEffectPlayer.cs.meta
@@ -0,0 +1,2 @@
+fileFormatVersion: 2
+guid: fdfe762b5b38a304cac7cfc2d5db07c3
\ No newline at end of file
diff --git a/Assets/Gothic-Core/Scripts/Adapters/Animations/AnimationSystem.cs b/Assets/Gothic-Core/Scripts/Adapters/Animations/AnimationSystem.cs
index ad2b69016..1484d897b 100644
--- a/Assets/Gothic-Core/Scripts/Adapters/Animations/AnimationSystem.cs
+++ b/Assets/Gothic-Core/Scripts/Adapters/Animations/AnimationSystem.cs
@@ -47,13 +47,10 @@ public class AnimationSystem : BasePlayerBehaviour
#endif
[Inject] private readonly AnimationService _animationService;
- [Inject] private readonly AudioService _audioService;
[Inject] private readonly VobService _vobService;
[Inject] private readonly NpcService _npcService;
[Inject] private readonly ConfigService _configService;
- [Inject] private readonly Services.Audio.GroundSoundService _groundSoundService;
[Inject] private readonly NpcWaterService _npcWaterService;
- [Inject] private readonly Gothic.Core.Services.Meshes.MeshService _meshService;
[Inject] private readonly Gothic.Core.Services.Caches.VmCacheService _vmCacheService;
// Item states (smoking, drinking): the engine's random item animations every few seconds.
@@ -62,10 +59,8 @@ public class AnimationSystem : BasePlayerBehaviour
private const int _maxItemRandomAnis = 4;
private float _nextItemRandomAniTime;
- // *eventPFX effects that run until their *eventPFXStop (same index). Safety: gone after this time anyway.
- private readonly Dictionary _activePfx = new();
- private const float _pfxMaxSeconds = 12f;
- private const float _pfxFadeSeconds = 8f;
+ // Plays the *eventSFX/*eventPFX of the tracks (created in Start, after the injection).
+ private AnimationEffectPlayer _effectPlayer;
// Initial bone pose is needed to reset culled-out NPCs to an idle starting state.
@@ -144,6 +139,9 @@ private void Start()
_initialMeshBonePos = _bones.Select(i => i.localPosition).ToArray();
_initialMeshBoneRot = _bones.Select(i => i.localRotation).ToArray();
+ _effectPlayer = new AnimationEffectPlayer(Go.transform, transform, PrefabProps.NpcSound,
+ PrefabProps.AnimationSfxSound, NpcData.Instance.Index, isReusingPfx: false).Inject();
+
CreateGraph();
ResizeRootCollider();
@@ -488,7 +486,7 @@ private void OnValidate()
public void DisableObject()
{
_trackInstances.Clear();
- StopAllPfx();
+ _effectPlayer?.StopAllPfx();
// Forget the last animated pose - the NPC restarts from an idle rest state when culled in again.
if (_posePositions.IsCreated)
@@ -861,7 +859,7 @@ private void ApplyEvents()
ApplyEventTags(trackInstance);
ApplySfxEvents(trackInstance);
- ApplyPfxEvents(trackInstance);
+ _effectPlayer.ApplyPfxEvents(trackInstance);
ApplyMorphEvents(trackInstance);
}
}
@@ -924,38 +922,11 @@ private void ApplyEventTags(AnimationTrackInstance trackInstance)
private void ApplySfxEvents(AnimationTrackInstance trackInstance)
{
- var sfxEvents = trackInstance.GetPendingSoundEffects();
- if (sfxEvents == null)
+ if (!_effectPlayer.ApplySfxEvents(trackInstance))
return;
- if (sfxEvents.Count > 0)
- {
- LastSfxEventAnimation = trackInstance.AnimationName;
- LastSfxEventTime = Time.time;
- }
-
- foreach (var sfx in sfxEvents)
- {
- // A step - its sound by the ground below (RUN_EARTH, RUN_STONE), on top of the other sounds (it mustn't
- // cut a swing or a scream). Skipped if the player turned footsteps off (Gothic.ini footstepSounds).
- if (sfx.Name.StartsWith(Domain.Audio.GroundSoundDomain.GroundEventPrefix))
- {
- if (!_groundSoundService.IsEnabled)
- continue;
- var stepName = _groundSoundService.GetSoundName(
- sfx.Name.Substring(Domain.Audio.GroundSoundDomain.GroundEventPrefix.Length),
- transform.position);
- var stepClip = _audioService.GetRandomSoundClip(stepName);
- if (stepClip != null)
- PrefabProps.NpcSound.PlayOneShot(stepClip);
- continue;
- }
-
- var clip = _audioService.GetRandomSoundClip(sfx.Name);
- PrefabProps.NpcSound.clip = clip;
- PrefabProps.NpcSound.maxDistance = sfx.Range.ToMeter();
- PrefabProps.NpcSound.Play();
- }
+ LastSfxEventAnimation = trackInstance.AnimationName;
+ LastSfxEventTime = Time.time;
}
///
@@ -998,83 +969,6 @@ private void UpdateItemRandomAni()
PlayAnimation(candidates[UnityEngine.Random.Range(0, candidates.Count)]);
}
- ///
- /// *eventPFX (frame, index, name, bone, ATTACH) creates the effect at the
- /// bone (following it if attached), *eventPFXStop (frame, index) lets it fade out. Joint smoke, bubbles, ...
- ///
- private void ApplyPfxEvents(AnimationTrackInstance trackInstance)
- {
- var stops = trackInstance.GetPendingParticleEffectStops();
- if (stops != null)
- {
- foreach (var stop in stops)
- StopPfx(stop.Index);
- }
-
- var pfxEvents = trackInstance.GetPendingParticleEffects();
- if (pfxEvents == null)
- return;
-
- foreach (var pfx in pfxEvents)
- {
- var bone = FindBone(pfx.Position) ?? Go.transform;
- var pfxGo = pfx.Attached
- ? _meshService.CreateVobPfx(pfx.Name, parent: bone.gameObject, destroyAfterPlay: true)
- : _meshService.CreateVobPfx(pfx.Name, bone.position, bone.rotation, destroyAfterPlay: true);
- if (pfxGo == null)
- {
- Logger.LogWarning($"[AnimationPfx] {pfx.Name} couldn't be created ({trackInstance.AnimationName}).",
- LogCat.Animation);
- continue;
- }
-
- var parent = pfxGo.transform.parent;
- var root = parent != null && parent != bone ? parent.gameObject : pfxGo;
- foreach (var particleSystem in root.GetComponentsInChildren())
- {
- var main = particleSystem.main;
- main.simulationSpace = ParticleSystemSimulationSpace.World;
- }
- if (pfx.Index != 0)
- {
- StopPfx(pfx.Index);
- _activePfx[pfx.Index] = root;
- }
- Destroy(root, _pfxMaxSeconds);
- }
- }
-
- private void StopPfx(int index)
- {
- if (!_activePfx.Remove(index, out var pfxGo) || pfxGo == null)
- return;
-
- foreach (var particleSystem in pfxGo.GetComponentsInChildren())
- particleSystem.Stop(true, ParticleSystemStopBehavior.StopEmitting);
- Destroy(pfxGo, _pfxFadeSeconds);
- }
-
- private void StopAllPfx()
- {
- foreach (var index in _activePfx.Keys.ToList())
- StopPfx(index);
- }
-
- ///
- /// MDS bone names differ in case from the bone GameObjects ("Bip01 Head" vs "BIP01 HEAD").
- ///
- private Transform FindBone(string boneName)
- {
- if (string.IsNullOrEmpty(boneName))
- return null;
- foreach (var child in Go.GetComponentsInChildren())
- {
- if (child.name.EqualsIgnoreCase(boneName))
- return child;
- }
- return null;
- }
-
private void ApplyMorphEvents(AnimationTrackInstance trackInstance)
{
var morphEvents = trackInstance.GetPendingMorphAnimations();
diff --git a/Assets/Gothic-Core/Scripts/Adapters/Npc/AiHandler.cs b/Assets/Gothic-Core/Scripts/Adapters/Npc/AiHandler.cs
index 3290640ef..483215623 100644
--- a/Assets/Gothic-Core/Scripts/Adapters/Npc/AiHandler.cs
+++ b/Assets/Gothic-Core/Scripts/Adapters/Npc/AiHandler.cs
@@ -790,19 +790,7 @@ public void ReEnableNpc()
Properties.CurrentAction = new None(new AnimationAction(), NpcData);
Properties.StateTime = 0.0f;
- // Mob usage (sitting on a bench, ...) ends with the respawn at the routine waypoint - the routine walks
- // there and sits down again. Before, the NPC kept its sitting state and sat in the air at the respawn
- // point.
- if (Properties.CurrentInteractableStateId >= 0)
- {
- if (PrefabProps.CurrentInteractable != null)
- PrefabProps.CurrentInteractable.MobState = -1;
-
- PrefabProps.CurrentInteractable = null;
- PrefabProps.CurrentInteractableSlot = null;
- Properties.CurrentInteractableStateId = -1;
- Properties.BodyState = VmGothicEnums.BodyState.BsStand;
- }
+ LeaveMobToStartOver();
// WayNet handling
// Nothing to do -> Even a despawned NPC (based on culling) needs to stick with its WPs/FPs.
@@ -885,11 +873,27 @@ public void ResetAfterTimeSkip()
$"{(isWeaponDrawn ? ", weapon away" : "")})", LogCat.Ai);
}
+ ///
+ /// Mob usage (sitting on a bench, ...) ends when the NPC starts over at its routine waypoint (culled out, then
+ /// re-enabled) - the routine walks there and sits down again. Before, the NPC kept its sitting state and sat in
+ /// the air at the respawn point. The mob's own animation (an anvil's sparks) stops with it.
+ ///
+ private void LeaveMobToStartOver()
+ {
+ if (Properties.CurrentInteractableStateId < 0)
+ return;
+
+ _npcService.ReleaseMob(NpcData);
+ }
+
public void DisableNpc()
{
// Stop all animations and reset to T-Pose
PrefabProps.AnimationSystem.DisableObject();
+ // Culled out, it's moved to its routine waypoint (NpcMeshCullingDomain): it doesn't use its mob any more.
+ LeaveMobToStartOver();
+
// We need to free the FP. When the NPC is re-enabled, it can walk to it again.
if (Properties.CurrentFreePoint != null)
{
diff --git a/Assets/Gothic-Core/Scripts/Adapters/Npc/NpcBurnEffect.cs b/Assets/Gothic-Core/Scripts/Adapters/Npc/NpcBurnEffect.cs
index 06a55806b..7046d3c89 100644
--- a/Assets/Gothic-Core/Scripts/Adapters/Npc/NpcBurnEffect.cs
+++ b/Assets/Gothic-Core/Scripts/Adapters/Npc/NpcBurnEffect.cs
@@ -173,7 +173,7 @@ private void AddLightAndSound(string sfxId)
var clip = string.IsNullOrEmpty(sfxId) ? null : _audioService.GetRandomSoundClip(sfxId);
if (clip == null)
return;
- var source = lightGo.AddComponent();
+ var source = _audioService.AddSfxSource(lightGo);
source.clip = clip;
source.loop = true;
source.spatialBlend = 1f;
diff --git a/Assets/Gothic-Core/Scripts/Adapters/Npc/NpcPrefabProperties.cs b/Assets/Gothic-Core/Scripts/Adapters/Npc/NpcPrefabProperties.cs
index d0da15ae6..21818589f 100644
--- a/Assets/Gothic-Core/Scripts/Adapters/Npc/NpcPrefabProperties.cs
+++ b/Assets/Gothic-Core/Scripts/Adapters/Npc/NpcPrefabProperties.cs
@@ -17,6 +17,9 @@ public class NpcPrefabProperties : MonoBehaviour
// Values set via Inspector
public AudioSource NpcSound;
+ [Tooltip("Plays the *eventSFX clips of animations. Own source with the settings of NpcSound: "
+ + "their volume and range mustn't turn down its one-shots.")]
+ public AudioSource AnimationSfxSound;
public Transform Bip01;
public Transform ColliderRootMotion;
public AiHandler AiHandler;
diff --git a/Assets/Gothic-Core/Scripts/Adapters/Scenes/WorldScene.cs b/Assets/Gothic-Core/Scripts/Adapters/Scenes/WorldScene.cs
index 889bf268c..2d87d2e31 100644
--- a/Assets/Gothic-Core/Scripts/Adapters/Scenes/WorldScene.cs
+++ b/Assets/Gothic-Core/Scripts/Adapters/Scenes/WorldScene.cs
@@ -48,6 +48,7 @@ public class WorldScene : MonoBehaviour, IScene
[Inject] private readonly ResourceCacheService _resourceCacheService;
[Inject] private readonly ContextInteractionService _contextInteractionService;
[Inject] private readonly SurroundingsBuildService _surroundingsBuildService;
+ [Inject] private readonly MobAnimationService _mobAnimationService;
[Inject] private readonly AchievementService _achievementService;
private Vector3? _spawnPosition;
@@ -70,6 +71,7 @@ public void Init()
/// 2. World - Mesh of the world
/// 3. WayPoints - Needed for spawning NPCs when world is loaded the first time
/// 4. VOBs - First entry, as we slice world chunks based on light VOBs
+ /// 4.1 Mob animations - baked now, not on the first lever pull
/// 5. NPCs - If we load the world for the first time, we leverage their current routine's values
/// 6. Stationary lights
///
@@ -135,6 +137,12 @@ await _meshService.CreateWorld(
await _vobService.CreateWorldVobsAsync(_configService.Dev, _loadingService, _saveGameService.CurrentWorldData.Vobs, vobRoot)
.AwaitAndLog();
watch.LogAndRestart("VOBs created");
+
+ // 4.1 Mob animations
+ // The mobs are known now (GameStateService.VobsInteractable). Their own state animations are
+ // baked while the loading screen is shown, frame by frame (Docs/mobs.md).
+ await _mobAnimationService.WarmWorldMobsAsync().AwaitAndLog();
+ watch.LogAndRestart("Mob animations baked");
}
// 5. NPCs
diff --git a/Assets/Gothic-Core/Scripts/Adapters/Vob/MobAnimator.cs b/Assets/Gothic-Core/Scripts/Adapters/Vob/MobAnimator.cs
new file mode 100644
index 000000000..586735076
--- /dev/null
+++ b/Assets/Gothic-Core/Scripts/Adapters/Vob/MobAnimator.cs
@@ -0,0 +1,231 @@
+using Gothic.Core.Adapters.Animations;
+using Gothic.Core.Extensions;
+using Gothic.Core.Logging;
+using Gothic.Core.Models.Animations;
+using Gothic.Core.Services.Vobs;
+using UnityEngine;
+using UnityEngine.Audio;
+using AnimationState = Gothic.Core.Models.Animations.AnimationState;
+using Logger = Gothic.Core.Logging.Logger;
+
+namespace Gothic.Core.Adapters.Vob
+{
+ ///
+ /// Plays a mob's own animations while it is used (MobAnimationService decides what): a transition, then the
+ /// state's loop, with the tracks' sounds and particles. Created on first use by MobAnimatorFactory.
+ ///
+ /// A light player instead of AnimationSystem: a mob's nodes are rigid (an anvil's hammer spot, a grindstone's
+ /// wheel), a few per mob, so they're sampled on the CPU (AnimationSampling) and written to the node transforms -
+ /// no PlayableGraph, no blending. Like NPC tracks, the baked root node has X/Z pinned to zero, which matches mobs:
+ /// the mesh builder rests their root node at zero.
+ ///
+ /// Update runs only while a transition or loop plays, else the component is disabled. A mob culled with its VOB
+ /// pauses and goes on when it's visible again. It doesn't know its users: a loop runs until MobAnimationService
+ /// stops it (the last user's NpcService.ReleaseMob, the hero's dialog closed).
+ ///
+ public class MobAnimator : MonoBehaviour, IMobAnimator
+ {
+ // The mob's node transforms, index == mdh node index (AnimationTrack.BoneToNode). Null if not found.
+ private Transform[] _nodes;
+ private AnimationEffectPlayer _effectPlayer;
+ private AudioSource _sound;
+
+ private AnimationTrackInstance _current;
+ private bool _isCurrentLoop;
+ // Played once the current transition ended (null: the mob rests in its last pose).
+ private AnimationTrack _nextLoop;
+ // Stopping: after the current transition (and the transition back, if any) the mob rests.
+ private bool _isStopPending;
+ private AnimationTrack _pendingBack;
+
+ public int State { get; private set; }
+
+
+ ///
+ /// Called once by MobAnimatorFactory: maps the skeleton's nodes to the mob's node GameObjects and creates the
+ /// sound source for its *eventSFX (3D, linear fall-off to the event's range like an NPC's sound), played through
+ /// soundGroup (the sound effects slider).
+ ///
+ public void Init(AnimationSkeleton skeleton, AudioMixerGroup soundGroup)
+ {
+ MapNodes(skeleton);
+
+ _sound = gameObject.AddComponent();
+ _sound.outputAudioMixerGroup = soundGroup;
+ _sound.playOnAwake = false;
+ _sound.spatialBlend = 1f;
+ _sound.rolloffMode = AudioRolloffMode.Linear;
+ _sound.minDistance = 0f;
+ _effectPlayer = new AnimationEffectPlayer(transform, transform, _sound, _sound, npcInstanceIndex: -1,
+ isReusingPfx: true).Inject();
+
+ Rest(isSoundStopped: true);
+ }
+
+ ///
+ /// The node GameObjects carry the names of the model's nodes (Gothic-defined, architecture.md rule C): the root
+ /// node is searched once below the mob, the others by their path below the root's parent.
+ ///
+ private void MapNodes(AnimationSkeleton skeleton)
+ {
+ _nodes = new Transform[skeleton.NodeCount];
+ if (skeleton.RootNodeIndex < 0)
+ {
+ Logger.LogWarning($"[MobAnimation] {name}: its skeleton has no root node - the mob won't move.",
+ LogCat.Vob);
+ return;
+ }
+
+ var rootName = skeleton.Paths[skeleton.RootNodeIndex];
+ var root = transform.FindChildRecursively(rootName);
+ if (root == null)
+ {
+ Logger.LogWarning($"[MobAnimation] {name}: node {rootName} not found - the mob won't move.",
+ LogCat.Vob);
+ return;
+ }
+
+ var missingCount = 0;
+ for (var node = 0; node < skeleton.NodeCount; node++)
+ {
+ _nodes[node] = root.parent.Find(skeleton.Paths[node]);
+ if (_nodes[node] == null)
+ missingCount++;
+ }
+
+ if (missingCount > 0)
+ Logger.LogWarning($"[MobAnimation] {name}: {missingCount} of {skeleton.NodeCount} nodes not found.",
+ LogCat.Vob);
+ }
+
+ public void Play(int state, AnimationTrack transition, AnimationTrack loop)
+ {
+ State = state;
+ _nextLoop = loop;
+ _isStopPending = false;
+ _pendingBack = null;
+
+ if (transition != null)
+ StartTrack(transition, isLoop: false);
+ else if (loop != null)
+ StartTrack(loop, isLoop: true);
+ else
+ Rest(isSoundStopped: true);
+ }
+
+ public void PlayBackAndStop(AnimationTrack backTransition)
+ {
+ State = Mathf.Max(0, State - 1);
+ _nextLoop = null;
+ _isStopPending = true;
+
+ // A transition still runs (T_S0_2_S1 of a user who left at once): the way back starts after it.
+ if (_current != null && !_isCurrentLoop)
+ {
+ _pendingBack = backTransition;
+ return;
+ }
+
+ if (backTransition != null)
+ StartTrack(backTransition, isLoop: false);
+ else
+ Rest(isSoundStopped: true);
+ }
+
+ private void StartTrack(AnimationTrack track, bool isLoop)
+ {
+ _current = new AnimationTrackInstance(track);
+ _isCurrentLoop = isLoop;
+ enabled = true;
+ }
+
+ ///
+ /// Nothing plays any more: the nodes keep their last pose, the particles fade out, Update is off.
+ /// isSoundStopped: the last user left, so a long clip (FORGE_FIRE) ends with the mob. A transition without
+ /// a user (a lever pull) lets its sound play out.
+ ///
+ private void Rest(bool isSoundStopped)
+ {
+ _current = null;
+ _isCurrentLoop = false;
+ _nextLoop = null;
+ _isStopPending = false;
+ _pendingBack = null;
+ _effectPlayer?.StopAllPfx();
+ if (isSoundStopped && _sound != null)
+ _sound.Stop();
+ enabled = false;
+ }
+
+ private void Update()
+ {
+ if (_current == null)
+ {
+ enabled = false;
+ return;
+ }
+
+ var stateChange = _current.Update(Time.deltaTime);
+ ApplyPose(_current);
+
+ if (_current.Track.HasEvents)
+ {
+ _effectPlayer.ApplySfxEvents(_current);
+ _effectPlayer.ApplyPfxEvents(_current);
+ }
+
+ // A track without a loop of its own reached its last frame (it starts blending out).
+ if (stateChange is not (AnimationState.BlendOut or AnimationState.Stop))
+ return;
+
+ if (_isCurrentLoop)
+ StartTrack(_current.Track, isLoop: true);
+ else
+ OnTransitionEnded();
+ }
+
+ private void OnTransitionEnded()
+ {
+ if (_pendingBack != null)
+ {
+ var back = _pendingBack;
+ _pendingBack = null;
+ StartTrack(back, isLoop: false);
+ return;
+ }
+
+ if (_isStopPending || _nextLoop == null)
+ {
+ Rest(isSoundStopped: _isStopPending);
+ return;
+ }
+
+ StartTrack(_nextLoop, isLoop: true);
+ }
+
+ private void ApplyPose(AnimationTrackInstance instance)
+ {
+ var track = instance.Track;
+ if (track.BoneCount == 0 || track.BakedFrameCount == 0)
+ return;
+
+ AnimationSampling.GetFrames(instance.CurrentFrame, track.BakedFrameCount, out var frame0, out var frame1,
+ out var frameBlend);
+
+ for (var bone = 0; bone < track.BoneCount; bone++)
+ {
+ var nodeIndex = track.BoneToNode[bone];
+ if (nodeIndex < 0 || nodeIndex >= _nodes.Length)
+ continue;
+
+ var node = _nodes[nodeIndex];
+ if (node == null)
+ continue;
+
+ AnimationSampling.SampleBone(track.Positions, track.Rotations, track.BoneCount, frame0, frame1,
+ frameBlend, bone, out var position, out var rotation);
+ node.SetLocalPositionAndRotation(position, rotation);
+ }
+ }
+ }
+}
diff --git a/Assets/Gothic-Core/Scripts/Adapters/Vob/MobAnimator.cs.meta b/Assets/Gothic-Core/Scripts/Adapters/Vob/MobAnimator.cs.meta
new file mode 100644
index 000000000..9a5f23946
--- /dev/null
+++ b/Assets/Gothic-Core/Scripts/Adapters/Vob/MobAnimator.cs.meta
@@ -0,0 +1,2 @@
+fileFormatVersion: 2
+guid: fadded1121e646b46ab27410976f0fe6
\ No newline at end of file
diff --git a/Assets/Gothic-Core/Scripts/Adapters/Vob/MobAnimatorFactory.cs b/Assets/Gothic-Core/Scripts/Adapters/Vob/MobAnimatorFactory.cs
new file mode 100644
index 000000000..c8543a005
--- /dev/null
+++ b/Assets/Gothic-Core/Scripts/Adapters/Vob/MobAnimatorFactory.cs
@@ -0,0 +1,44 @@
+using Gothic.Core.Logging;
+using Gothic.Core.Manager;
+using Gothic.Core.Models.Animations;
+using Gothic.Core.Models.Container;
+using Gothic.Core.Services.Vobs;
+using Reflex.Attributes;
+using Logger = Gothic.Core.Logging.Logger;
+
+namespace Gothic.Core.Adapters.Vob
+{
+ public class MobAnimatorFactory : IMobAnimatorFactory
+ {
+ [Inject] private readonly AudioService _audioService;
+
+ public IMobAnimator GetOrCreate(VobContainer mob, AnimationSkeleton skeleton)
+ {
+ if (mob?.Go == null || skeleton == null)
+ return null;
+
+ if (mob.Go.TryGetComponent(out var animator))
+ return animator;
+
+ // The nodes are mapped once: a lazily loaded mob without its mesh yet gets its animator later.
+ if (mob.Go.TryGetComponent(out var loader) && !loader.IsLoaded)
+ {
+ Logger.LogEditor($"[MobAnimation] {mob.Vob?.Name} isn't loaded yet - its animation is skipped.",
+ LogCat.Vob);
+ return null;
+ }
+
+ animator = mob.Go.AddComponent();
+ animator.Init(skeleton, _audioService.SoundEffectsGroup);
+ return animator;
+ }
+
+ public IMobAnimator TryGet(VobContainer mob)
+ {
+ if (mob?.Go == null)
+ return null;
+
+ return mob.Go.TryGetComponent(out var animator) ? animator : null;
+ }
+ }
+}
diff --git a/Assets/Gothic-Core/Scripts/Adapters/Vob/MobAnimatorFactory.cs.meta b/Assets/Gothic-Core/Scripts/Adapters/Vob/MobAnimatorFactory.cs.meta
new file mode 100644
index 000000000..5f6ad2bde
--- /dev/null
+++ b/Assets/Gothic-Core/Scripts/Adapters/Vob/MobAnimatorFactory.cs.meta
@@ -0,0 +1,2 @@
+fileFormatVersion: 2
+guid: a2487edb4ee930d419f988527d3d0b95
\ No newline at end of file
diff --git a/Assets/Gothic-Core/Scripts/Adapters/Vob/MoverAdapter.cs b/Assets/Gothic-Core/Scripts/Adapters/Vob/MoverAdapter.cs
index 983c4fb82..efe05a06c 100644
--- a/Assets/Gothic-Core/Scripts/Adapters/Vob/MoverAdapter.cs
+++ b/Assets/Gothic-Core/Scripts/Adapters/Vob/MoverAdapter.cs
@@ -556,7 +556,7 @@ private void PlaySfx(string sfxName)
var clip = _audioService.GetRandomSoundClip(sfxName);
if (clip != null)
- AudioSource.PlayClipAtPoint(clip, transform.position);
+ _audioService.PlaySfxAtPoint(clip, transform.position);
}
}
}
diff --git a/Assets/Gothic-Core/Scripts/Const/Constants.cs b/Assets/Gothic-Core/Scripts/Const/Constants.cs
index 61ed0b6d5..632d46f49 100644
--- a/Assets/Gothic-Core/Scripts/Const/Constants.cs
+++ b/Assets/Gothic-Core/Scripts/Const/Constants.cs
@@ -31,6 +31,11 @@ public static class IniNames
public const string IniSectionSound = "SOUND";
public const int FootstepSoundsDefaultValue = 1;
+ // Gothic's own [SOUND] 0..1, the options' sound effects slider: the SoundEffects mixer group's volume
+ // (AudioService). 1 = Gothic's own volume of each sound, the engine's default.
+ public const string SoundVolume = "soundVolume";
+ public const float SoundVolumeDefaultValue = 1f;
+
// [VIDEO] 0..1, vanilla 0.5 = neutral (the menu's Brightness slider).
public const string VideoBrightness = "zVidBrightness";
public const float VideoBrightnessDefaultValue = 0.5f;
diff --git a/Assets/Gothic-Core/Scripts/Domain/Npc/Actions/AnimationActions/Output.cs b/Assets/Gothic-Core/Scripts/Domain/Npc/Actions/AnimationActions/Output.cs
index c7dccd9be..b20a444cb 100644
--- a/Assets/Gothic-Core/Scripts/Domain/Npc/Actions/AnimationActions/Output.cs
+++ b/Assets/Gothic-Core/Scripts/Domain/Npc/Actions/AnimationActions/Output.cs
@@ -119,7 +119,8 @@ private AudioSource GetVoiceSource()
var voiceGo = new GameObject(voiceName);
voiceGo.transform.SetParent(npcSound.transform, false);
voice = voiceGo.AddComponent();
- voice.outputAudioMixerGroup = npcSound.outputAudioMixerGroup;
+ // No mixer group: NpcSound plays through the sound effects group, a voice mustn't follow that slider.
+ voice.outputAudioMixerGroup = null;
voice.spatialBlend = npcSound.spatialBlend;
voice.volume = npcSound.volume;
voice.priority = npcSound.priority;
diff --git a/Assets/Gothic-Core/Scripts/Domain/Npc/Actions/AnimationActions/StandUp.cs b/Assets/Gothic-Core/Scripts/Domain/Npc/Actions/AnimationActions/StandUp.cs
index d0d69c66d..dd0a757ae 100644
--- a/Assets/Gothic-Core/Scripts/Domain/Npc/Actions/AnimationActions/StandUp.cs
+++ b/Assets/Gothic-Core/Scripts/Domain/Npc/Actions/AnimationActions/StandUp.cs
@@ -17,12 +17,7 @@ public override void Start()
{
// Ends the mob usage. After AI_StandUp's back transitions the NPC already stands; AI_StandUpQuick pops.
if (PrefabProps.CurrentInteractable != null)
- {
- PrefabProps.CurrentInteractable = null;
- PrefabProps.CurrentInteractableSlot = null;
- Props.CurrentInteractableStateId = -1;
- Props.BodyState = VmGothicEnums.BodyState.BsStand;
- }
+ _npcService.ReleaseMob(NpcContainer);
// Like the engine's AI_StandUp, an item in the hand (food, beer) is put away - B_FullStop on aggro
// left it there.
diff --git a/Assets/Gothic-Core/Scripts/Domain/Npc/Actions/AnimationActions/UseMob.cs b/Assets/Gothic-Core/Scripts/Domain/Npc/Actions/AnimationActions/UseMob.cs
index b3bad2097..07c5bcbca 100644
--- a/Assets/Gothic-Core/Scripts/Domain/Npc/Actions/AnimationActions/UseMob.cs
+++ b/Assets/Gothic-Core/Scripts/Domain/Npc/Actions/AnimationActions/UseMob.cs
@@ -2,7 +2,9 @@
using Gothic.Core.Adapters.Vob;
using Gothic.Core.Models.Container;
using Gothic.Core.Models.Vm;
+using Gothic.Core.Models.Vob;
using Gothic.Core.Services.Npc;
+using Gothic.Core.Services.Vobs;
using Gothic.Core.Extensions;
using JetBrains.Annotations;
using MyBox;
@@ -15,9 +17,9 @@ namespace Gothic.Core.Domain.Npc.Actions.AnimationActions
public class UseMob : AbstractWalkAnimationAction2
{
[Inject] private readonly NpcHelperService _npcHelperService;
+ [Inject] private readonly NpcService _npcService;
+ [Inject] private readonly MobAnimationService _mobAnimationService;
- private const string _mobTransitionAnimationString = "T_{0}{1}{2}_2_{3}";
- private const string _mobLoopAnimationString = "S_{0}{1}S{2}";
private VobContainer _mobContainer;
private GameObject _slotGo;
private Vector3 _destination;
@@ -102,7 +104,7 @@ private void StartNow()
if (slot == null)
{
- // The reservation from Start goes - no free slot.
+ // The reservation from Start goes - no free slot. Not a usage yet (state -1), so no ReleaseMob.
if (Props.CurrentInteractableStateId == -1 && PrefabProps.CurrentInteractable == _mobContainer)
PrefabProps.CurrentInteractable = null;
IsFinishedFlag = true;
@@ -191,10 +193,8 @@ private void TickMobUsage()
// Mobsi isn't in use any longer
if (Props.CurrentInteractableStateId == -1)
{
- PrefabProps.CurrentInteractable = null;
- PrefabProps.CurrentInteractableSlot = null;
+ _npcService.ReleaseMob(NpcContainer);
Props.CurrentItem = -1;
- Props.BodyState = VmGothicEnums.BodyState.BsStand;
PhysicsService.EnablePhysicsForNpc(PrefabProps);
}
@@ -202,7 +202,7 @@ private void TickMobUsage()
else
{
// Loop animations carry the slot position as well (e.g. s_Bed_Front_S1 vs. s_Cauldron_S1).
- var animName = GetMobAnimationName(tag => string.Format(_mobLoopAnimationString, _mobsiScheme, tag, TargetState));
+ var animName = GetMobAnimationName(tag => MobStateNames.GetUserLoopName(_mobsiScheme, tag, TargetState));
PrefabProps.AnimationSystem.PlayAnimation(animName);
}
@@ -346,15 +346,15 @@ private void PlayTransitionAnimation()
var current = Props.CurrentInteractableStateId;
var next = current + (TargetState > current ? +1 : -1);
- // -1 is the not-in-use state and is named Stand inside the animations.
+ // -1 is the not-in-use state and is named STAND inside the animations (MobStateNames, lookups ignore case).
// Both directions exist as own animations (e.g. t_Cauldron_Stand_2_S0, t_Cauldron_S0_2_S1, t_Cauldron_S1_2_S0).
- var from = current == -1 ? "Stand" : $"S{current}";
- var to = next == -1 ? "Stand" : $"S{next}";
-
- var animName = GetMobAnimationName(tag => string.Format(_mobTransitionAnimationString, _mobsiScheme, tag, from, to));
+ var animName = GetMobAnimationName(tag => MobStateNames.GetUserTransitionName(_mobsiScheme, tag, current, next));
_currentMobAnimation = animName;
PrefabProps.AnimationSystem.PlayAnimation(animName);
+
+ // Like the engine, the mob plays its own transition with the user's (the anvil's sparks, a turning wheel).
+ _mobAnimationService.OnStateChanged(_mobContainer, NpcContainer, current, next);
}
}
}
diff --git a/Assets/Gothic-Core/Scripts/Domain/Npc/NpcDeathDomain.cs b/Assets/Gothic-Core/Scripts/Domain/Npc/NpcDeathDomain.cs
index dcb43edeb..e4279bf59 100644
--- a/Assets/Gothic-Core/Scripts/Domain/Npc/NpcDeathDomain.cs
+++ b/Assets/Gothic-Core/Scripts/Domain/Npc/NpcDeathDomain.cs
@@ -30,6 +30,10 @@ public class NpcDeathDomain
public void Die(NpcContainer npc)
{
+ // Killed at a mob (a smith at the anvil): the usage ends there, the mob stops and is free for others.
+ if (npc.PrefabProps?.CurrentInteractable != null)
+ _npcService.ReleaseMob(npc);
+
npc.Props.BodyState = VmGothicEnums.BodyState.BsDead;
Logger.Log($"[NpcDeath] {npc.Instance.GetName(NpcNameSlot.Slot0)} is dead.", LogCat.Npc);
diff --git a/Assets/Gothic-Core/Scripts/Domain/Npc/NpcKnockoutDomain.cs b/Assets/Gothic-Core/Scripts/Domain/Npc/NpcKnockoutDomain.cs
index 546602fa4..cdf710831 100644
--- a/Assets/Gothic-Core/Scripts/Domain/Npc/NpcKnockoutDomain.cs
+++ b/Assets/Gothic-Core/Scripts/Domain/Npc/NpcKnockoutDomain.cs
@@ -74,6 +74,11 @@ public bool IsInKnockoutGraceTime(NpcContainer npc)
public void KnockOutNpc(NpcContainer npc, NpcContainer attacker)
{
+ // Like death (engine: Npc::onNoHealth quits the interaction either way), a smith knocked out at the anvil
+ // lets go of it: the mob stops and is free for others.
+ if (npc.PrefabProps?.CurrentInteractable != null)
+ _npcService.ReleaseMob(npc);
+
// The hit already showed its number - no "+X HP" for going up to 1.
_npcService.SetAttribute(npc, NpcAttribute.HitPoints, 1, cause: AttributeChangeCause.Knockout);
diff --git a/Assets/Gothic-Core/Scripts/Domain/Vobs/VobInitializerDomain.cs b/Assets/Gothic-Core/Scripts/Domain/Vobs/VobInitializerDomain.cs
index 4fad0242a..afdddad20 100644
--- a/Assets/Gothic-Core/Scripts/Domain/Vobs/VobInitializerDomain.cs
+++ b/Assets/Gothic-Core/Scripts/Domain/Vobs/VobInitializerDomain.cs
@@ -811,7 +811,9 @@ private GameObject CreateSoundDaytime(SoundDaytime vob, GameObject parent)
private void PrepareAudioSource(AudioSource source, Sound soundData, string soundName)
{
source.maxDistance = soundData.Radius / 100f; // Gothic's values are in cm, Unity's in m.
- source.volume = soundData.Volume / 100f; // Gothic's volume is 0...100, Unity's is 0...1.
+ // The VOB's own volume (Gothic's 0...100, Unity's 0...1). The player's sound effects slider works on top of
+ // it through the prefab's SoundEffects mixer group (AudioService), also on a loop that plays.
+ source.volume = soundData.Volume / 100f;
// Random sounds shouldn't play initially, but after certain time.
source.playOnAwake = soundData.InitiallyPlaying && soundData.Mode != SoundMode.Random;
diff --git a/Assets/Gothic-Core/Scripts/Extensions/ZenKitExtension.cs b/Assets/Gothic-Core/Scripts/Extensions/ZenKitExtension.cs
index e7de044f3..e5d599b95 100644
--- a/Assets/Gothic-Core/Scripts/Extensions/ZenKitExtension.cs
+++ b/Assets/Gothic-Core/Scripts/Extensions/ZenKitExtension.cs
@@ -112,10 +112,18 @@ public static byte[] GetR5G6B5MipmapRgba(this ITexture zkTexture, int level)
/// CHESTBIG_ORCMUMMY.ASC). It's used like other mobs and looted like a body.
///
public static bool IsLidlessContainer([CanBeNull] this IVirtualObject vob)
+ {
+ return vob is IContainer && !string.IsNullOrEmpty(vob.Visual?.Name) && !vob.HasModelScriptVisual();
+ }
+
+ ///
+ /// The visual is a model script (.MDS) - the mob has animations of its own. Plain meshes (.MDL, .ASC) don't.
+ ///
+ public static bool HasModelScriptVisual([CanBeNull] this IVirtualObject vob)
{
var visualName = vob?.Visual?.Name;
- return vob is IContainer && !string.IsNullOrEmpty(visualName) &&
- !visualName.EndsWith(".MDS", StringComparison.OrdinalIgnoreCase);
+ return !string.IsNullOrEmpty(visualName) &&
+ visualName.EndsWith(".MDS", StringComparison.OrdinalIgnoreCase);
}
///
@@ -128,6 +136,15 @@ public static bool IsBed([CanBeNull] this IVirtualObject vob)
visualName.StartsWith("BED", StringComparison.OrdinalIgnoreCase);
}
+ ///
+ /// A door or a chest: in VR it swings on a physical hinge when grabbed (VRMobHinge), it isn't used like other
+ /// mobs (AI_UseMob, the mob grab, its own state animations). Beds are oCMobDoors too, but no hinge (IsBed).
+ ///
+ public static bool IsHingeMob([CanBeNull] this IVirtualObject vob)
+ {
+ return (vob is IDoor && !vob.IsBed()) || vob is IContainer;
+ }
+
///
/// oCMobLockable's fields: doors and chests are both lockable, but ZenKit has no common interface for them.
/// Returns false if the vob is neither.
diff --git a/Assets/Gothic-Core/Scripts/GlobalEventDispatcher.cs b/Assets/Gothic-Core/Scripts/GlobalEventDispatcher.cs
index 809aa3177..2aa0bfb5e 100644
--- a/Assets/Gothic-Core/Scripts/GlobalEventDispatcher.cs
+++ b/Assets/Gothic-Core/Scripts/GlobalEventDispatcher.cs
@@ -341,6 +341,10 @@ public enum HandSide
// opened submenu.
public static readonly UnityEvent MenuOpened = new();
+ // The hero's mob dialog (a MOBSI's choices at the anvil, a shrine, a bookstand) closed, or the mob's
+ // [onStateFunc]_S1 opened none (DialogService). The mob he used rests again (MobAnimationService).
+ public static readonly UnityEvent MobDialogEnded = new();
+
// Trading (TradeService) started with this NPC: the VR trade counter opens, the dialog goes on.
public static readonly UnityEvent TradeStarted = new();
// Trading with this NPC ended (closed, the dialog ended, the world left) - the offers went back.
diff --git a/Assets/Gothic-Core/Scripts/Models/Animations/AnimationPoseJob.cs b/Assets/Gothic-Core/Scripts/Models/Animations/AnimationPoseJob.cs
index 32320d0d7..e4897bf57 100644
--- a/Assets/Gothic-Core/Scripts/Models/Animations/AnimationPoseJob.cs
+++ b/Assets/Gothic-Core/Scripts/Models/Animations/AnimationPoseJob.cs
@@ -150,9 +150,8 @@ private void ApplyTrack(AnimationStream stream, AnimationPoseJobTrack track,
if (track.Weight <= 0f || track.BoneCount == 0)
return;
- var frame0 = Mathf.Clamp((int)track.Frame, 0, track.FrameCount - 1);
- var frame1 = Mathf.Min(frame0 + 1, track.FrameCount - 1);
- var frameBlend = Mathf.Clamp01(track.Frame - frame0);
+ AnimationSampling.GetFrames(track.Frame, track.FrameCount, out var frame0, out var frame1,
+ out var frameBlend);
for (var bone = 0; bone < track.BoneCount; bone++)
{
@@ -160,42 +159,19 @@ private void ApplyTrack(AnimationStream stream, AnimationPoseJobTrack track,
if (!handle.IsValid(stream))
continue;
- // Keys are hemisphere-aligned at bake time, so the normalized lerp takes the short way.
- var position = Vector3.Lerp(
- positions[frame0 * track.BoneCount + bone], positions[frame1 * track.BoneCount + bone], frameBlend);
- var rotation = Nlerp(
- rotations[frame0 * track.BoneCount + bone], rotations[frame1 * track.BoneCount + bone], frameBlend);
+ AnimationSampling.SampleBone(positions, rotations, track.BoneCount, frame0, frame1, frameBlend, bone,
+ out var position, out var rotation);
if (track.Weight < 1f)
{
// Blend over whatever lower layers (or the rest pose) wrote before us.
position = Vector3.Lerp(handle.GetLocalPosition(stream), position, track.Weight);
- rotation = Nlerp(handle.GetLocalRotation(stream), rotation, track.Weight);
+ rotation = AnimationSampling.Nlerp(handle.GetLocalRotation(stream), rotation, track.Weight);
}
handle.SetLocalPosition(stream, position);
handle.SetLocalRotation(stream, rotation);
}
}
-
- ///
- /// Normalized lerp instead of slerp: between consecutive .man frames the angles are tiny and for
- /// blend ramps both endpoints are the same poses - the angular deviation stays invisible, while a
- /// dot + sqrt replaces the per-bone trigonometry (this runs per bone, per track, per NPC, per frame).
- ///
- private static Quaternion Nlerp(Quaternion from, Quaternion to, float weight)
- {
- // Take the short way around - blend sources aren't hemisphere-aligned with each other.
- var dot = from.x * to.x + from.y * to.y + from.z * to.z + from.w * to.w;
- var sign = dot < 0f ? -1f : 1f;
-
- var x = from.x + (to.x * sign - from.x) * weight;
- var y = from.y + (to.y * sign - from.y) * weight;
- var z = from.z + (to.z * sign - from.z) * weight;
- var w = from.w + (to.w * sign - from.w) * weight;
-
- var scale = 1f / Mathf.Sqrt(x * x + y * y + z * z + w * w);
- return new Quaternion(x * scale, y * scale, z * scale, w * scale);
- }
}
}
diff --git a/Assets/Gothic-Core/Scripts/Models/Animations/AnimationSampling.cs b/Assets/Gothic-Core/Scripts/Models/Animations/AnimationSampling.cs
new file mode 100644
index 000000000..40cea28d4
--- /dev/null
+++ b/Assets/Gothic-Core/Scripts/Models/Animations/AnimationSampling.cs
@@ -0,0 +1,58 @@
+using Unity.Collections;
+using UnityEngine;
+
+namespace Gothic.Core.Models.Animations
+{
+ ///
+ /// Reads the pose of one bone out of a baked AnimationTrack (Positions/Rotations, layout [frame * BoneCount +
+ /// bone]) at a fractional frame, interpolating linearly between the two neighbouring samples like the original
+ /// engine. Used by AnimationPoseJob (NPCs, Burst, animation worker threads) and MobAnimator (the few rigid nodes of
+ /// a used mob, main thread). Static and allocation free, so Burst compiles it into the job.
+ ///
+ public static class AnimationSampling
+ {
+ ///
+ /// The two samples around a fractional frame and the blend between them. Done once per track and frame, the
+ /// bones of the track share it.
+ ///
+ public static void GetFrames(float frame, int frameCount, out int frame0, out int frame1, out float frameBlend)
+ {
+ frame0 = Mathf.Clamp((int)frame, 0, frameCount - 1);
+ frame1 = Mathf.Min(frame0 + 1, frameCount - 1);
+ frameBlend = Mathf.Clamp01(frame - frame0);
+ }
+
+ ///
+ /// Local position and rotation of one track bone between two samples (see GetFrames).
+ /// Keys are hemisphere-aligned at bake time, so the normalized lerp takes the short way.
+ ///
+ public static void SampleBone(NativeArray positions, NativeArray rotations, int boneCount,
+ int frame0, int frame1, float frameBlend, int bone, out Vector3 position, out Quaternion rotation)
+ {
+ position = Vector3.Lerp(
+ positions[frame0 * boneCount + bone], positions[frame1 * boneCount + bone], frameBlend);
+ rotation = Nlerp(
+ rotations[frame0 * boneCount + bone], rotations[frame1 * boneCount + bone], frameBlend);
+ }
+
+ ///
+ /// Normalized lerp instead of slerp: between consecutive .man frames the angles are tiny and for
+ /// blend ramps both endpoints are the same poses - the angular deviation stays invisible, while a
+ /// dot + sqrt replaces the per-bone trigonometry (this runs per bone, per track, per NPC, per frame).
+ ///
+ public static Quaternion Nlerp(Quaternion from, Quaternion to, float weight)
+ {
+ // Take the short way around - blend sources aren't hemisphere-aligned with each other.
+ var dot = from.x * to.x + from.y * to.y + from.z * to.z + from.w * to.w;
+ var sign = dot < 0f ? -1f : 1f;
+
+ var x = from.x + (to.x * sign - from.x) * weight;
+ var y = from.y + (to.y * sign - from.y) * weight;
+ var z = from.z + (to.z * sign - from.z) * weight;
+ var w = from.w + (to.w * sign - from.w) * weight;
+
+ var scale = 1f / Mathf.Sqrt(x * x + y * y + z * z + w * w);
+ return new Quaternion(x * scale, y * scale, z * scale, w * scale);
+ }
+ }
+}
diff --git a/Assets/Gothic-Core/Scripts/Models/Animations/AnimationSampling.cs.meta b/Assets/Gothic-Core/Scripts/Models/Animations/AnimationSampling.cs.meta
new file mode 100644
index 000000000..dad8959fb
--- /dev/null
+++ b/Assets/Gothic-Core/Scripts/Models/Animations/AnimationSampling.cs.meta
@@ -0,0 +1,2 @@
+fileFormatVersion: 2
+guid: 1599da8ae3ff80845ae9b9239c929b38
\ No newline at end of file
diff --git a/Assets/Gothic-Core/Scripts/Models/Audio/AnimationSfx.cs b/Assets/Gothic-Core/Scripts/Models/Audio/AnimationSfx.cs
new file mode 100644
index 000000000..46b39222b
--- /dev/null
+++ b/Assets/Gothic-Core/Scripts/Models/Audio/AnimationSfx.cs
@@ -0,0 +1,28 @@
+using UnityEngine;
+
+namespace Gothic.Core.Models.Audio
+{
+ ///
+ /// What an animation sound event (*eventSFX, *eventSFXGrnd) plays with, decided by AudioService.GetAnimationSfx().
+ /// Nothing to play if Clip is null (footsteps off, no sound by that name).
+ ///
+ public readonly struct AnimationSfx
+ {
+ /// The sound to play, null if there is none.
+ public readonly AudioClip Clip;
+ /// Gothic's volume of the picked sound (0..1).
+ public readonly float Volume;
+ /// Range in which the sound is audible, in meters.
+ public readonly float RangeMeters;
+ /// A footstep: plays as a one-shot on top of other sounds instead of as the source's clip.
+ public readonly bool IsStep;
+
+ public AnimationSfx(AudioClip clip, float volume, float rangeMeters, bool isStep)
+ {
+ Clip = clip;
+ Volume = volume;
+ RangeMeters = rangeMeters;
+ IsStep = isStep;
+ }
+ }
+}
diff --git a/Assets/Gothic-Core/Scripts/Models/Audio/AnimationSfx.cs.meta b/Assets/Gothic-Core/Scripts/Models/Audio/AnimationSfx.cs.meta
new file mode 100644
index 000000000..d7a935b1f
--- /dev/null
+++ b/Assets/Gothic-Core/Scripts/Models/Audio/AnimationSfx.cs.meta
@@ -0,0 +1,2 @@
+fileFormatVersion: 2
+guid: fffdd8b355b30ad6199396a0d544d822
\ No newline at end of file
diff --git a/Assets/Gothic-Core/Scripts/Models/Audio/SfxModel.cs b/Assets/Gothic-Core/Scripts/Models/Audio/SfxModel.cs
index f6105f5c3..a690095b6 100644
--- a/Assets/Gothic-Core/Scripts/Models/Audio/SfxModel.cs
+++ b/Assets/Gothic-Core/Scripts/Models/Audio/SfxModel.cs
@@ -22,8 +22,13 @@ public class SfxModel
// TODO - Injecting in a Model wasn't intended. Try to use it without injecting.
[Inject] private readonly GameStateService _gameStateService;
+ // C_SFX_DEF vol is 0..127 (the prototype's default 127).
+ private const float _maxGothicVolume = 127f;
+
private string soundKey;
private SoundEffectInstance[] _soundEffects;
+ // Gothic's volume of each instance (vol, 0..1), same index as _soundEffects.
+ private float[] _volumes;
public int Count => _soundEffects.Length;
@@ -45,16 +50,27 @@ public SoundEffectInstance GetFirstSound()
[CanBeNull]
public SoundEffectInstance GetRandomSound()
+ {
+ return GetRandomSound(out _);
+ }
+
+ ///
+ /// Like GetRandomSound(), with Gothic's volume of the picked instance (vol as 0..1): a random variant
+ /// (BreathBubbles_A1) has its own. 1 if there's none.
+ ///
+ [CanBeNull]
+ public SoundEffectInstance GetRandomSound(out float volume)
{
if (_soundEffects == null)
LoadSoundEffects();
+ volume = 1f;
if (_soundEffects.IsEmpty())
return null;
- else if (_soundEffects!.Length == 1)
- return _soundEffects.First();
- else
- return _soundEffects.GetRandom();
+
+ var index = _soundEffects!.Length == 1 ? 0 : UnityEngine.Random.Range(0, _soundEffects.Length);
+ volume = _volumes[index];
+ return _soundEffects[index];
}
private void LoadSoundEffects()
@@ -71,6 +87,7 @@ private void LoadSoundEffects()
// SFX symbol missing from Gothic's SFX scripts — expected for some broken VOBs (e.g. Wood_Night2 was never defined).
Logger.LogWarning($"SFX symbol not found in VM: '{soundKey}' — no sound will play.", LogCat.Audio);
_soundEffects = Array.Empty();
+ _volumes = Array.Empty();
return;
}
@@ -109,6 +126,10 @@ private void LoadSoundEffects()
}
_soundEffects = sounds.ToArray();
+
+ _volumes = new float[_soundEffects.Length];
+ for (var i = 0; i < _soundEffects.Length; i++)
+ _volumes[i] = UnityEngine.Mathf.Clamp01(_soundEffects[i].Volume / _maxGothicVolume);
}
}
}
diff --git a/Assets/Gothic-Core/Scripts/Models/Config/DeveloperConfig.cs b/Assets/Gothic-Core/Scripts/Models/Config/DeveloperConfig.cs
index c47400a2d..e12d14fa1 100644
--- a/Assets/Gothic-Core/Scripts/Models/Config/DeveloperConfig.cs
+++ b/Assets/Gothic-Core/Scripts/Models/Config/DeveloperConfig.cs
@@ -46,6 +46,11 @@ public class DebugChannelTypesCollection : CollectionWrapper
+ /// How a mob's states are named inside model scripts: -1 (not in use) is STAND, the others S0, S1, ... The mob's
+ /// own tracks are T_S0_2_S1 / S_S1; an NPC's tracks put the mob's scheme (and a slot position) in front of the
+ /// states: T_CAULDRON_S0_2_S1, S_BED_FRONT_S1. Docs/mobs.md.
+ ///
+ public static class MobStateNames
+ {
+ private const string _standStateName = "STAND";
+
+ public static string GetStateName(int state)
+ {
+ return state < 0 ? _standStateName : "S" + state;
+ }
+
+ ///
+ /// The mob's own transition track, e.g. T_S0_2_S1.
+ ///
+ public static string GetTransitionName(int from, int to)
+ {
+ return "T_" + GetStateName(from) + "_2_" + GetStateName(to);
+ }
+
+ ///
+ /// The mob's own loop track, e.g. S_S1.
+ ///
+ public static string GetLoopName(int state)
+ {
+ return "S_" + GetStateName(state);
+ }
+
+ ///
+ /// A state animation of the mob's own model script: a loop (S_S1) or a transition between two states
+ /// (T_S0_2_S1, T_STAND_2_S0). Not the NPCs' tracks with a scheme in front (T_CAULDRON_S0_2_S1).
+ ///
+ public static bool IsOwnStateAnimation(string animationName)
+ {
+ if (animationName == null)
+ return false;
+
+ var name = animationName.ToUpperInvariant();
+ if (name.StartsWith("S_", StringComparison.Ordinal))
+ return IsStateName(name.Substring(2));
+ if (!name.StartsWith("T_", StringComparison.Ordinal))
+ return false;
+
+ var states = name.Substring(2).Split(new[] { "_2_" }, StringSplitOptions.None);
+ return states.Length == 2 && IsStateName(states[0]) && IsStateName(states[1]);
+ }
+
+ // STAND or S0, S1, ...
+ private static bool IsStateName(string name)
+ {
+ if (name == _standStateName)
+ return true;
+
+ return name.Length > 1 && name[0] == 'S' && name.Skip(1).All(char.IsDigit);
+ }
+
+ ///
+ /// The NPC's transition track at a mob, e.g. T_CAULDRON_S0_2_S1. The position tag is "_" or e.g. "_FRONT_".
+ ///
+ public static string GetUserTransitionName(string scheme, string positionTag, int from, int to)
+ {
+ return "T_" + scheme + positionTag + GetStateName(from) + "_2_" + GetStateName(to);
+ }
+
+ ///
+ /// The NPC's loop track at a mob, e.g. S_BED_FRONT_S1.
+ ///
+ public static string GetUserLoopName(string scheme, string positionTag, int state)
+ {
+ return "S_" + scheme + positionTag + GetStateName(state);
+ }
+ }
+}
diff --git a/Assets/Gothic-Core/Scripts/Models/Vob/MobStateNames.cs.meta b/Assets/Gothic-Core/Scripts/Models/Vob/MobStateNames.cs.meta
new file mode 100644
index 000000000..1e511756f
--- /dev/null
+++ b/Assets/Gothic-Core/Scripts/Models/Vob/MobStateNames.cs.meta
@@ -0,0 +1,2 @@
+fileFormatVersion: 2
+guid: 1b1dbd4cd087a92eb934081b3cf11211
\ No newline at end of file
diff --git a/Assets/Gothic-Core/Scripts/ReflexProjectInstaller.cs b/Assets/Gothic-Core/Scripts/ReflexProjectInstaller.cs
index cfae28cac..abd91ffc1 100644
--- a/Assets/Gothic-Core/Scripts/ReflexProjectInstaller.cs
+++ b/Assets/Gothic-Core/Scripts/ReflexProjectInstaller.cs
@@ -76,6 +76,7 @@ public void InstallBindings(ContainerBuilder containerBuilder)
containerBuilder.AddSingleton(typeof(ContextGameVersionService));
containerBuilder.AddSingleton(typeof(ContextMeleeDamageRuleService));
containerBuilder.AddSingleton(typeof(ContextRangedCombatService));
+ containerBuilder.AddSingleton(typeof(ContextSoundRangeService));
containerBuilder.AddSingleton(typeof(ContextHeroBlockService));
containerBuilder.AddSingleton(typeof(NpcMeshCullingService));
@@ -91,6 +92,7 @@ public void InstallBindings(ContainerBuilder containerBuilder)
containerBuilder.AddSingleton(typeof(TouchDamageService));
containerBuilder.AddSingleton(typeof(MobInteractionService));
containerBuilder.AddSingleton(typeof(MobLockService));
+ containerBuilder.AddSingleton(typeof(MobAnimationService));
containerBuilder.AddSingleton(typeof(ParticleService));
// Player
@@ -124,6 +126,7 @@ public void InstallBindings(ContainerBuilder containerBuilder)
containerBuilder.AddSingleton(typeof(VisualFxLightFactory), typeof(IVisualFxLightFactory));
containerBuilder.AddSingleton(typeof(NpcJumpFallFactory), typeof(INpcJumpFallFactory));
containerBuilder.AddSingleton(typeof(NpcBurnEffectFactory), typeof(INpcBurnEffectFactory));
+ containerBuilder.AddSingleton(typeof(MobAnimatorFactory), typeof(IMobAnimatorFactory));
// Caches
containerBuilder.AddSingleton(typeof(ResourceCacheService));
diff --git a/Assets/Gothic-Core/Scripts/Services/Audio/AudioService.cs b/Assets/Gothic-Core/Scripts/Services/Audio/AudioService.cs
index c45056171..d9a09a596 100644
--- a/Assets/Gothic-Core/Scripts/Services/Audio/AudioService.cs
+++ b/Assets/Gothic-Core/Scripts/Services/Audio/AudioService.cs
@@ -1,20 +1,27 @@
using System;
+using System.Collections.Generic;
using System.Threading.Tasks;
+using Gothic.Core.Const;
using Gothic.Core.Domain.Audio;
using Gothic.Core.Logging;
+using Gothic.Core.Models.Audio;
using Gothic.Core.Models.Container;
using Gothic.Core.Models.Vm;
using Gothic.Core.Services;
+using Gothic.Core.Services.Audio;
using Gothic.Core.Services.Caches;
using Gothic.Core.Services.Culling;
using Gothic.Core.Services.Config;
+using Gothic.Core.Services.Context;
using Gothic.Core.Services.World;
using Gothic.Core.Extensions;
using JetBrains.Annotations;
using Reflex.Attributes;
using UnityEngine;
+using UnityEngine.Audio;
using ZenKit.Daedalus;
using Logger = Gothic.Core.Logging.Logger;
+using Object = UnityEngine.Object;
namespace Gothic.Core.Manager
{
@@ -25,6 +32,8 @@ public class AudioService
[Inject] private readonly GameStateService _gameStateService;
[Inject] private readonly NpcMeshCullingService _npcMeshCullingService;
[Inject] private readonly GameTimeService _gameTimeService;
+ [Inject] private readonly GroundSoundService _groundSoundService;
+ [Inject] private readonly ContextSoundRangeService _contextSoundRangeService;
// #503: the last music situation, logged when it changes.
private MusicDomain.MusicTagsMode _lastMusicMode;
@@ -41,10 +50,29 @@ public class AudioService
private readonly SoundDomain _soundDomain = new SoundDomain().Inject();
private AudioSource _scriptSoundSource;
+ // Sound names without a C_SFX_DEF, warned about once each (animations ask for them on every frame crossed).
+ private readonly HashSet _missingSfxNames = new(StringComparer.OrdinalIgnoreCase);
+
+ // Resources/AudioMixer.mixer: its SoundEffects group gets every sound effect source, the options' sound effects
+ // slider (Gothic.ini soundVolume) sets the group's exposed volume.
+ private const string _mixerResourcePath = "AudioMixer";
+ private const string _soundEffectsGroupName = "SoundEffects";
+ private const string _soundEffectsVolumeParameter = "SoundEffectsVolume";
+ // The slider at 0 is silent: -80 dB, the mixer's bottom (log10(0) has none).
+ private const float _minSoundVolume = 0.0001f;
+ private AudioMixer _mixer;
+ private AudioMixerGroup _soundEffectsGroup;
+ private bool _isMixerLoaded;
public SoundEffectInstance InvOpen => _vmCacheService.TryGetSfxData("INV_OPEN").GetFirstSound();
public SoundEffectInstance InvClose => _vmCacheService.TryGetSfxData("INV_CLOSE").GetFirstSound();
-
+
+ public AudioService()
+ {
+ GlobalEventDispatcher.GothicInisInitialized.AddListener(ApplySoundVolume);
+ GlobalEventDispatcher.PlayerPrefUpdated.AddListener(OnSoundOptionUpdated);
+ }
+
//
// Music
//
@@ -169,6 +197,115 @@ public void SetScriptSoundSource(AudioSource audioSource)
_scriptSoundSource = audioSource;
}
+ ///
+ /// The mixer group every sound effect source plays through (prefab sources are routed in the prefab): the
+ /// options' sound effects slider turns it up and down. A source's own volume stays Gothic's of the sound
+ /// (C_SFX_DEF vol, a VOB's volume). Voices and music aren't in it. Null if the mixer is missing.
+ ///
+ [CanBeNull]
+ public AudioMixerGroup SoundEffectsGroup
+ {
+ get
+ {
+ LoadMixer();
+ return _soundEffectsGroup;
+ }
+ }
+
+ ///
+ /// Adds an AudioSource for sound effects to the GameObject, routed to SoundEffectsGroup.
+ ///
+ public AudioSource AddSfxSource(GameObject go)
+ {
+ var source = go.AddComponent();
+ source.outputAudioMixerGroup = SoundEffectsGroup;
+ return source;
+ }
+
+ ///
+ /// Like AudioSource.PlayClipAtPoint() (a 3D one-shot on a temporary GameObject), through SoundEffectsGroup.
+ ///
+ public void PlaySfxAtPoint(AudioClip clip, Vector3 position, float volume = 1f)
+ {
+ if (clip == null)
+ return;
+
+ var go = new GameObject("One shot audio");
+ go.transform.position = position;
+ var source = AddSfxSource(go);
+ source.clip = clip;
+ source.spatialBlend = 1f;
+ source.volume = volume;
+ source.Play();
+ Object.Destroy(go, clip.length * (Time.timeScale < 0.01f ? 0.01f : Time.timeScale));
+ }
+
+ private void LoadMixer()
+ {
+ if (_isMixerLoaded)
+ return;
+
+ _isMixerLoaded = true;
+ _mixer = Resources.Load(_mixerResourcePath);
+ var groups = _mixer != null ? _mixer.FindMatchingGroups(_soundEffectsGroupName) : null;
+ _soundEffectsGroup = groups is { Length: > 0 } ? groups[0] : null;
+ if (_soundEffectsGroup == null)
+ Logger.LogError($"[SoundVolume] Resources/{_mixerResourcePath} or its {_soundEffectsGroupName} group " +
+ "is missing: sound effects play without the sound effects slider.", LogCat.Audio);
+ }
+
+ private void OnSoundOptionUpdated(string key, object value)
+ {
+ if (key == Constants.IniNames.SoundVolume)
+ ApplySoundVolume();
+ }
+
+ ///
+ /// Sets the SoundEffects group's volume from Gothic.ini [SOUND] soundVolume (0..1, the options' slider): 1 is
+ /// Gothic's own volume of each sound (0 dB) like the engine's default, 0 is silent.
+ ///
+ private void ApplySoundVolume()
+ {
+ LoadMixer();
+ if (_mixer == null)
+ return;
+
+ var volume = Mathf.Clamp01(_configService.GetGothicOption(Constants.IniNames.SoundVolume,
+ Constants.IniNames.SoundVolumeDefaultValue));
+ var decibel = 20f * Mathf.Log10(Mathf.Max(volume, _minSoundVolume));
+ _mixer.SetFloat(_soundEffectsVolumeParameter, decibel);
+ Logger.Log($"[SoundVolume] Sound effects slider {volume:0.##} (Gothic.ini soundVolume): {decibel:0.#} dB.",
+ LogCat.Audio);
+ }
+
+ ///
+ /// Decides what an animation sound event plays with. A step (*eventSFXGrnd, name with
+ /// GroundSoundDomain.GroundEventPrefix) takes its sound from the ground below stepOrigin (RUN_EARTH, RUN_STONE)
+ /// and is silent if the player turned footsteps off (Gothic.ini footstepSounds). Any other sound brings
+ /// Gothic's volume and Gothic's range (R:, in meters) - unless the game version module changes the range
+ /// (ContextSoundRangeService). Clip is null if there is nothing to play.
+ ///
+ /// Daedalus instance index of the NPC playing the sound, -1 if none (a mob).
+ ///
+ public AnimationSfx GetAnimationSfx(int npcInstanceIndex, string sfxName, float gothicRangeMeters,
+ Vector3 stepOrigin)
+ {
+ if (sfxName.StartsWith(GroundSoundDomain.GroundEventPrefix, StringComparison.Ordinal))
+ {
+ if (!_groundSoundService.IsEnabled)
+ return default;
+
+ var stepName = _groundSoundService.GetSoundName(
+ sfxName.Substring(GroundSoundDomain.GroundEventPrefix.Length), stepOrigin);
+ var stepClip = GetRandomSoundClip(stepName, out var stepVolume);
+ return new AnimationSfx(stepClip, stepVolume, gothicRangeMeters, true);
+ }
+
+ var clip = GetRandomSoundClip(sfxName, out var volume);
+ var rangeMeters = _contextSoundRangeService.GetRangeMeters(npcInstanceIndex, sfxName, gothicRangeMeters);
+ return new AnimationSfx(clip, volume, rangeMeters, false);
+ }
+
///
/// Non-positional sound, e.g. Daedalus Snd_Play("LogEntry").
///
@@ -232,8 +369,18 @@ public Task CreateAudioClipAsync(string fileName)
/// This method caches the AudioClips itself automatically. No performance penalty when re-running this method.
///
public AudioClip GetRandomSoundClip(string soundName)
+ {
+ return GetRandomSoundClip(soundName, out _);
+ }
+
+ ///
+ /// Like GetRandomSoundClip(), with Gothic's volume of the picked sound (its C_SFX_DEF vol as 0..1 - a random
+ /// variant _A1, _A2 has its own, Forge_Sharpen is quiet). A .wav file name has none: 1.
+ ///
+ public AudioClip GetRandomSoundClip(string soundName, out float volume)
{
AudioClip clip;
+ volume = 1f;
if (soundName.EqualsIgnoreCase(NoSoundName))
{
@@ -253,14 +400,28 @@ public AudioClip GetRandomSoundClip(string soundName)
if (sfxContainer == null)
return null;
+ // A name without C_SFX_DEF has no sound at all.
+ if (sfxContainer.GetFirstSound() == null)
+ {
+ WarnMissingSfxOnce(soundName);
+ return null;
+ }
+
// Instead of decoding nosound.wav which might be decoded incorrectly, just return null.
- if (sfxContainer.GetFirstSound() == null || sfxContainer.GetFirstSound()!.File.EqualsIgnoreCase(NoSoundName))
+ if (sfxContainer.GetFirstSound()!.File.EqualsIgnoreCase(NoSoundName))
return null;
- clip = CreateAudioClip(sfxContainer.GetRandomSound());
+ clip = CreateAudioClip(sfxContainer.GetRandomSound(out volume));
}
return clip;
}
+
+ private void WarnMissingSfxOnce(string soundName)
+ {
+ if (_missingSfxNames.Add(soundName))
+ Logger.LogWarning($"[Sfx] No sound effect {soundName} (C_SFX_DEF missing) - it stays silent.",
+ LogCat.Audio);
+ }
}
}
diff --git a/Assets/Gothic-Core/Scripts/Services/BootstrapService.cs b/Assets/Gothic-Core/Scripts/Services/BootstrapService.cs
index 078d36092..8abc79496 100644
--- a/Assets/Gothic-Core/Scripts/Services/BootstrapService.cs
+++ b/Assets/Gothic-Core/Scripts/Services/BootstrapService.cs
@@ -61,6 +61,7 @@ public class BootstrapService
[Inject] private readonly NpcNavMeshService _npcNavMeshService;
[Inject] private readonly NpcWaterService _npcWaterService;
[Inject] private readonly ParticleService _particleService;
+ [Inject] private readonly MobAnimationService _mobAnimationService;
[Inject] private readonly DialogService _dialogService;
[Inject] private readonly GameEndingService _gameEndingService;
@@ -118,6 +119,7 @@ public void InitPhase1()
_npcNavMeshService.Init();
_npcWaterService.Init();
_particleService.Init();
+ _mobAnimationService.Init();
_dialogService.Init();
_saveGameService.Init();
_gameEndingService.Init();
diff --git a/Assets/Gothic-Core/Scripts/Services/Context/ContextSoundRangeService.cs b/Assets/Gothic-Core/Scripts/Services/Context/ContextSoundRangeService.cs
new file mode 100644
index 000000000..6bd2eee5a
--- /dev/null
+++ b/Assets/Gothic-Core/Scripts/Services/Context/ContextSoundRangeService.cs
@@ -0,0 +1,23 @@
+namespace Gothic.Core.Services.Context
+{
+ ///
+ /// The sound range rule the game version module registered (G2ContextBootstrap). Without one, every sound keeps
+ /// Gothic's range.
+ ///
+ public class ContextSoundRangeService : IContextSoundRangeService
+ {
+ private IContextSoundRangeService _impl;
+
+ public void SetImpl(IContextSoundRangeService impl)
+ {
+ _impl = impl;
+ }
+
+ public float GetRangeMeters(int npcInstanceIndex, string sfxName, float gothicRangeMeters)
+ {
+ return _impl == null
+ ? gothicRangeMeters
+ : _impl.GetRangeMeters(npcInstanceIndex, sfxName, gothicRangeMeters);
+ }
+ }
+}
diff --git a/Assets/Gothic-Core/Scripts/Services/Context/ContextSoundRangeService.cs.meta b/Assets/Gothic-Core/Scripts/Services/Context/ContextSoundRangeService.cs.meta
new file mode 100644
index 000000000..3d926e665
--- /dev/null
+++ b/Assets/Gothic-Core/Scripts/Services/Context/ContextSoundRangeService.cs.meta
@@ -0,0 +1,2 @@
+fileFormatVersion: 2
+guid: 091a18fc139214118bf535a5b0daefb4
\ No newline at end of file
diff --git a/Assets/Gothic-Core/Scripts/Services/Context/IContextSoundRangeService.cs b/Assets/Gothic-Core/Scripts/Services/Context/IContextSoundRangeService.cs
new file mode 100644
index 000000000..9d4808281
--- /dev/null
+++ b/Assets/Gothic-Core/Scripts/Services/Context/IContextSoundRangeService.cs
@@ -0,0 +1,15 @@
+namespace Gothic.Core.Services.Context
+{
+ ///
+ /// The range (m) in which an animation sound (*eventSFX) is heard. Core (AudioService) asks, a game version module
+ /// may answer differently than Gothic's own range (R:), e.g. an improvement for a single NPC.
+ ///
+ public interface IContextSoundRangeService
+ {
+ /// Daedalus instance index of the NPC playing the sound, -1 if none (a mob).
+ ///
+ /// Name of the sound (C_SFX_DEF instance), e.g. HAMMER.
+ /// Gothic's range of the sound event (R:, in meters).
+ float GetRangeMeters(int npcInstanceIndex, string sfxName, float gothicRangeMeters);
+ }
+}
diff --git a/Assets/Gothic-Core/Scripts/Services/Context/IContextSoundRangeService.cs.meta b/Assets/Gothic-Core/Scripts/Services/Context/IContextSoundRangeService.cs.meta
new file mode 100644
index 000000000..292c48ca5
--- /dev/null
+++ b/Assets/Gothic-Core/Scripts/Services/Context/IContextSoundRangeService.cs.meta
@@ -0,0 +1,2 @@
+fileFormatVersion: 2
+guid: 5c801b98360b1a190b19dc157f8f5efe
\ No newline at end of file
diff --git a/Assets/Gothic-Core/Scripts/Services/Meshes/ParticleService.cs b/Assets/Gothic-Core/Scripts/Services/Meshes/ParticleService.cs
index 7401bde50..d6e6b2904 100644
--- a/Assets/Gothic-Core/Scripts/Services/Meshes/ParticleService.cs
+++ b/Assets/Gothic-Core/Scripts/Services/Meshes/ParticleService.cs
@@ -125,7 +125,7 @@ private void PlayVisualFx(string fxName, Vector3 position, Transform follow, boo
{
var clip = _audioService.GetRandomSoundClip(fx.SfxId);
if (clip != null)
- AudioSource.PlayClipAtPoint(clip, position);
+ _audioService.PlaySfxAtPoint(clip, position);
}
PlayVisualFx(fx.EmFxCreateS, position, follow, isLooping, skippedSfx, ownerMesh, created, depth + 1);
@@ -193,7 +193,7 @@ private void PlayGlobalFx(string fxName, Vector3 position)
{
var clip = _audioService.GetRandomSoundClip(fx.SfxId);
if (clip != null)
- AudioSource.PlayClipAtPoint(clip, position);
+ _audioService.PlaySfxAtPoint(clip, position);
}
Logger.Log($"[VisualFx] {fxName}: earthquake {radius:F0} m, {seconds:F1} s", LogCat.Mesh);
GlobalEventDispatcher.VisualFxEarthquake.Invoke(position, radius, seconds);
diff --git a/Assets/Gothic-Core/Scripts/Services/Npc/AnimationService.cs b/Assets/Gothic-Core/Scripts/Services/Npc/AnimationService.cs
index 784563d8f..6141bb931 100644
--- a/Assets/Gothic-Core/Scripts/Services/Npc/AnimationService.cs
+++ b/Assets/Gothic-Core/Scripts/Services/Npc/AnimationService.cs
@@ -539,7 +539,10 @@ private AnimationSkeleton GetSkeleton(string mdhName, IModelHierarchy mdh)
}
///
- /// Skeleton of the given model script - used by AnimationSystem to build its stream handles and job data.
+ /// Skeleton of the given model script - used by AnimationSystem to build its stream handles and job data, and
+ /// by MobAnimationService for the nodes of a mob. A model can keep its hierarchy inside its .MDL (hierarchy
+ /// and mesh in one file) instead of an .MDH, like VobInitializerDomain builds such meshes. Once cached here,
+ /// GetTrack finds the skeleton under the same name.
///
[CanBeNull]
public AnimationSkeleton GetSkeleton(string mdsName)
@@ -549,7 +552,8 @@ public AnimationSkeleton GetSkeleton(string mdsName)
return null;
}
- var mdh = _resourceCacheService.TryGetModelHierarchy(mdsName, false);
+ var mdh = _resourceCacheService.TryGetModelHierarchy(mdsName, false) ??
+ _resourceCacheService.TryGetModel(mdsName, false)?.Hierarchy;
return mdh == null ? null : GetSkeleton(mdsName, mdh);
}
diff --git a/Assets/Gothic-Core/Scripts/Services/Npc/NpcService.cs b/Assets/Gothic-Core/Scripts/Services/Npc/NpcService.cs
index 78a44b9ea..6b3504d6a 100644
--- a/Assets/Gothic-Core/Scripts/Services/Npc/NpcService.cs
+++ b/Assets/Gothic-Core/Scripts/Services/Npc/NpcService.cs
@@ -53,6 +53,7 @@ public class NpcService : ILazyInitQueue
[Inject] private readonly VobService _vobService;
[Inject] private readonly NpcInventoryService _npcInventoryService;
[Inject] private readonly NpcLookService _npcLookService;
+ [Inject] private readonly MobAnimationService _mobAnimationService;
// Supporter class where the whole Init() logic is outsourced for better readability.
@@ -896,6 +897,34 @@ private void EventNpcMeshCullingChanged(NpcContainer npcContainer, NpcLoader npc
}
}
+ ///
+ /// The NPC is no longer the user of its mob: no mob, no slot, the not-in-use state (-1), standing, and the
+ /// mob's own animation stops (MobAnimationService). The one place where a mob usage ends - after the last back
+ /// transition of AI_UseMob(-1), at AI_StandUp(Quick), at death, when knocked out and when the NPC starts over
+ /// (culled, re-enabled: AiHandler). A world change or load drops the NPCs and mobs together, so nothing is
+ /// released there. The last user who was in one of the mob's states leaves it at -1 (Wld_GetMobState
+ /// reads 0, a save doesn't keep it) - a smith killed at the anvil frees it. An NPC only walking there
+ /// doesn't touch it (a lever the hero switched keeps its state).
+ ///
+ public void ReleaseMob(NpcContainer npc)
+ {
+ var prefabProps = npc?.PrefabProps;
+ if (prefabProps == null)
+ return;
+
+ var mob = prefabProps.CurrentInteractable;
+ _mobAnimationService.Stop(mob, npc);
+
+ if (mob != null && npc.Props.CurrentInteractableStateId >= 0 &&
+ !_vobService.GetOtherMobUsers(mob, npc).Any())
+ mob.MobState = -1;
+
+ prefabProps.CurrentInteractable = null;
+ prefabProps.CurrentInteractableSlot = null;
+ npc.Props.CurrentInteractableStateId = -1;
+ npc.Props.BodyState = VmGothicEnums.BodyState.BsStand;
+ }
+
///
/// An item the NPC holds from AI_UseItemToState (food, a torch, ...) is put away: its mesh in the slot goes,
/// the item state resets. Like the engine's clearState/AI_StandUp - an NPC interrupted while eating (aggro)
diff --git a/Assets/Gothic-Core/Scripts/Services/Player/DialogService.cs b/Assets/Gothic-Core/Scripts/Services/Player/DialogService.cs
index a5f64d131..d3c4a1cea 100644
--- a/Assets/Gothic-Core/Scripts/Services/Player/DialogService.cs
+++ b/Assets/Gothic-Core/Scripts/Services/Player/DialogService.cs
@@ -453,7 +453,7 @@ public void PrepareMobDialog(GameObject anchor)
}
if (MobDialogAnchor != null)
- Object.Destroy(MobDialogAnchor);
+ DestroyMobDialogAnchor();
MobDialogAnchor = anchor;
_isHeroQueueRunning = false;
@@ -471,8 +471,17 @@ public void ReleaseUnusedMobDialogAnchor()
if (MobDialogAnchor == null || isDialogPending)
return;
+ DestroyMobDialogAnchor();
+ }
+
+ ///
+ /// The mob dialog is over (or never opened): its anchor goes, the mob the hero used rests again.
+ ///
+ private void DestroyMobDialogAnchor()
+ {
Object.Destroy(MobDialogAnchor);
MobDialogAnchor = null;
+ GlobalEventDispatcher.MobDialogEnded.Invoke();
}
///
@@ -607,10 +616,7 @@ public void StopDialog(NpcContainer npc)
// EndDialog moved the dialog box away from the anchor - it can go now.
if (IsMobDialog(npc))
- {
- Object.Destroy(MobDialogAnchor);
- MobDialogAnchor = null;
- }
+ DestroyMobDialogAnchor();
// Hide subtitles from both dialog partners. A destroyed NPC took its subtitles with it.
_npcService.GetHeroContainer().PrefabProps.NpcSubtitles.HideSubtitles();
diff --git a/Assets/Gothic-Core/Scripts/Services/Vm/VmService.cs b/Assets/Gothic-Core/Scripts/Services/Vm/VmService.cs
index 6234f3a0d..f872faaab 100644
--- a/Assets/Gothic-Core/Scripts/Services/Vm/VmService.cs
+++ b/Assets/Gothic-Core/Scripts/Services/Vm/VmService.cs
@@ -114,8 +114,7 @@ public List InventoryCategories
"MENUITEM_GRA_TEXQUAL", "MENUITEM_GRA_TEXQUAL_SLIDER",
"MENUITEM_GRA_MODEL_DETAIL", "MENUITEM_GRA_MODEL_DETAIL_SLIDER",
"MENUITEM_GRA_SKY_EFFECTS", "MENUITEM_GRA_SKY_EFFECTS_CHOICE",
- // Parts of AUDIO menu
- "MENUITEM_AUDIO_SFXVOL", "MENUITEM_AUDIO_SFXVOL_SLIDER",
+ // Parts of AUDIO menu (the sound effects volume works: AudioService.SoundEffectsGroup)
"MENUITEM_AUDIO_PROVIDER", "MENUITEM_AUDIO_PROVIDER_CHOICE",
"MENUITEM_AUDIO_SPEEKER", "MENUITEM_AUDIO_SPEEKER_CHOICE",
"MENUITEM_AUDIO_REVERB", "MENUITEM_AUDIO_REVERB_CHOICE",
diff --git a/Assets/Gothic-Core/Scripts/Services/Vobs/IMobAnimator.cs b/Assets/Gothic-Core/Scripts/Services/Vobs/IMobAnimator.cs
new file mode 100644
index 000000000..0843d19aa
--- /dev/null
+++ b/Assets/Gothic-Core/Scripts/Services/Vobs/IMobAnimator.cs
@@ -0,0 +1,29 @@
+using Gothic.Core.Models.Animations;
+
+namespace Gothic.Core.Services.Vobs
+{
+ ///
+ /// Plays a mob's own animations (the MobAnimator adapter on the mob). MobAnimationService decides what to play and
+ /// gets it from IMobAnimatorFactory. It only plays: who uses the mob is the NPCs' state, the service asks that.
+ /// Docs/mobs.md.
+ ///
+ public interface IMobAnimator
+ {
+ ///
+ /// The mob state the animation is in or plays towards. 0 while the mob rests.
+ ///
+ int State { get; }
+
+ ///
+ /// Plays the transition into the state (e.g. T_S0_2_S1), then its loop (S_S1). Either may be null: without a
+ /// loop the mob rests in the transition's last pose (a lever stays down).
+ ///
+ void Play(int state, AnimationTrack transition, AnimationTrack loop);
+
+ ///
+ /// Lets a running transition end, plays the transition back (e.g. T_S1_2_S0, may be null) and rests. Its
+ /// particles fade out.
+ ///
+ void PlayBackAndStop(AnimationTrack backTransition);
+ }
+}
diff --git a/Assets/Gothic-Core/Scripts/Services/Vobs/IMobAnimator.cs.meta b/Assets/Gothic-Core/Scripts/Services/Vobs/IMobAnimator.cs.meta
new file mode 100644
index 000000000..3ee3bc110
--- /dev/null
+++ b/Assets/Gothic-Core/Scripts/Services/Vobs/IMobAnimator.cs.meta
@@ -0,0 +1,2 @@
+fileFormatVersion: 2
+guid: 1a6f7a761f3bf134d877417042cac37d
\ No newline at end of file
diff --git a/Assets/Gothic-Core/Scripts/Services/Vobs/IMobAnimatorFactory.cs b/Assets/Gothic-Core/Scripts/Services/Vobs/IMobAnimatorFactory.cs
new file mode 100644
index 000000000..fbae31dfe
--- /dev/null
+++ b/Assets/Gothic-Core/Scripts/Services/Vobs/IMobAnimatorFactory.cs
@@ -0,0 +1,21 @@
+using Gothic.Core.Models.Animations;
+using Gothic.Core.Models.Container;
+
+namespace Gothic.Core.Services.Vobs
+{
+ ///
+ /// Gives a mob's animator. Implemented in Adapters/ (MobAnimatorFactory), registered in ReflexProjectInstaller.
+ ///
+ public interface IMobAnimatorFactory
+ {
+ ///
+ /// The mob's animator, created on first use with the nodes of the skeleton. Null without a GameObject.
+ ///
+ IMobAnimator GetOrCreate(VobContainer mob, AnimationSkeleton skeleton);
+
+ ///
+ /// The mob's animator if it has one, else null (nothing is created).
+ ///
+ IMobAnimator TryGet(VobContainer mob);
+ }
+}
diff --git a/Assets/Gothic-Core/Scripts/Services/Vobs/IMobAnimatorFactory.cs.meta b/Assets/Gothic-Core/Scripts/Services/Vobs/IMobAnimatorFactory.cs.meta
new file mode 100644
index 000000000..1d30cdb9b
--- /dev/null
+++ b/Assets/Gothic-Core/Scripts/Services/Vobs/IMobAnimatorFactory.cs.meta
@@ -0,0 +1,2 @@
+fileFormatVersion: 2
+guid: d6bf575df473a76428786e96cf562f4f
\ No newline at end of file
diff --git a/Assets/Gothic-Core/Scripts/Services/Vobs/MobAnimationService.cs b/Assets/Gothic-Core/Scripts/Services/Vobs/MobAnimationService.cs
new file mode 100644
index 000000000..2f5ee9a56
--- /dev/null
+++ b/Assets/Gothic-Core/Scripts/Services/Vobs/MobAnimationService.cs
@@ -0,0 +1,313 @@
+using System;
+using System.Collections.Generic;
+using System.Diagnostics;
+using System.Linq;
+using System.Text;
+using System.Threading.Tasks;
+using Gothic.Core.Extensions;
+using Gothic.Core.Logging;
+using Gothic.Core.Manager;
+using Gothic.Core.Models.Animations;
+using Gothic.Core.Models.Container;
+using Gothic.Core.Models.Vob;
+using Gothic.Core.Services.Caches;
+using Gothic.Core.Services.Npc;
+using JetBrains.Annotations;
+using Reflex.Attributes;
+using ZenKit.Daedalus;
+using ZenKit.Vobs;
+using Logger = Gothic.Core.Logging.Logger;
+
+namespace Gothic.Core.Services.Vobs
+{
+ ///
+ /// Like the engine's oCMobInter (OpenGothic Interactive::setState), a mob plays its own state animations while an
+ /// NPC or the hero changes its state: the anvil rings and sparks, the forge roars, the grindstone turns, a lever
+ /// swings. They live in the mob's own model script (BSANVIL_OC.MDS: T_S0_2_S1, S_S1, T_S1_2_S0), not in the
+ /// user's. This service looks the tracks up and decides; the MobAnimator adapter on the mob plays them.
+ /// Docs/mobs.md.
+ ///
+ public class MobAnimationService
+ {
+ [Inject] private readonly AnimationService _animationService;
+ [Inject] private readonly AudioService _audioService;
+ [Inject] private readonly FrameSkipperService _frameSkipperService;
+ [Inject] private readonly GameStateService _gameStateService;
+ [Inject] private readonly IMobAnimatorFactory _mobAnimatorFactory;
+ [Inject] private readonly ResourceCacheService _resourceCacheService;
+ [Inject] private readonly VobService _vobService;
+
+
+ // Model scripts (visual names, any casing) whose tracks are looked up already.
+ private readonly HashSet _warmedModels = new(StringComparer.OrdinalIgnoreCase);
+ // One-shot logs: a model without a hierarchy, an animation a model doesn't have.
+ private readonly HashSet _loggedMissingSkeletons = new(StringComparer.OrdinalIgnoreCase);
+ private readonly HashSet _loggedMissingTracks = new(StringComparer.OrdinalIgnoreCase);
+
+ // The mob the hero uses while his mob dialog is open (the smithy), see StartHeroUse.
+ private VobContainer _heroMob;
+ private NpcContainer _hero;
+
+
+ public void Init()
+ {
+ GlobalEventDispatcher.MobDialogEnded.AddListener(StopHeroUse);
+ GlobalEventDispatcher.LoadGameStart.AddListener(ForgetHeroUse);
+ GlobalEventDispatcher.LoadingSceneLoaded.AddListener(ForgetHeroUse);
+ }
+
+ ///
+ /// The mob plays state animations of its own: an oCMobInter family member with an .MDS visual. Not doors,
+ /// chests and beds (the VR hand moves them, IsHingeMob/IsBed) and no fireplaces (FireService burns them).
+ /// Mobs with a plain mesh (Fellan's REPAIR_PLANK.MDL) have no animation file.
+ ///
+ public bool IsAnimated([CanBeNull] VobContainer mob)
+ {
+ var vob = mob?.Vob;
+ if (vob is not IInteractiveObject || vob is IFire || vob.IsHingeMob() || vob.IsBed())
+ return false;
+
+ return vob.HasModelScriptVisual();
+ }
+
+ ///
+ /// The mob's state changed (from -> to, -1 = not used). With a user (an NPC at the mob, the hero at his smithy)
+ /// the transition plays, then the state's loop while the user stays; -1 ends the user's usage (Stop). Without
+ /// a user (the hero pulled a lever) only the transition plays and the mob rests in its last pose.
+ /// A second user of a mob already in the state (or higher) just joins it - the mob goes on for the others.
+ /// Who uses the mob isn't kept here: it's the NPCs' CurrentInteractable and state (HasOtherUser).
+ ///
+ public void OnStateChanged([CanBeNull] VobContainer mob, [CanBeNull] NpcContainer user, int from, int to)
+ {
+ if (!IsAnimated(mob))
+ return;
+
+ if (to < 0)
+ {
+ StopIfLastUser(mob, user);
+ return;
+ }
+
+ var animator = _mobAnimatorFactory.TryGet(mob);
+ if (user != null && animator != null && to <= animator.State && HasOtherUser(mob, user))
+ return;
+
+ var visualName = mob.Vob.Visual.Name;
+ var skeleton = GetSkeleton(visualName);
+ if (skeleton == null)
+ return;
+
+ var transition = GetTrack(visualName, MobStateNames.GetTransitionName(from, to));
+ var loop = user != null ? GetTrack(visualName, MobStateNames.GetLoopName(to)) : null;
+ if (transition == null && loop == null)
+ return;
+
+ animator ??= _mobAnimatorFactory.GetOrCreate(mob, skeleton);
+ if (animator == null)
+ return;
+
+ animator.Play(to, transition, loop);
+ Logger.LogEditor($"[MobAnimation] {mob.Vob.Name} ({visualName}): {MobStateNames.GetStateName(from)} -> " +
+ $"{MobStateNames.GetStateName(to)} by {user?.Instance?.GetName(NpcNameSlot.Slot0) ?? "nobody"}",
+ LogCat.Vob);
+ }
+
+ ///
+ /// The NPC's usage of the mob ends (NpcService.ReleaseMob, before it clears the NPC's mob and state). The last
+ /// user stops the mob's animation. An NPC that only walked there (state -1) never started it - a lever the
+ /// hero switched stays. After AI_UseMob(-1) the state is -1 already: its S0 -> Stand stopped it before.
+ ///
+ public void Stop([CanBeNull] VobContainer mob, [CanBeNull] NpcContainer user)
+ {
+ if (user == null || !user.IsUsingMob())
+ return;
+
+ StopIfLastUser(mob, user);
+ }
+
+ ///
+ /// The user leaves the mob. Without another one the mob stops: a running transition ends, the transition back
+ /// plays (T_S1_2_S0, a lever swings back), then the mob rests.
+ ///
+ private void StopIfLastUser([CanBeNull] VobContainer mob, [CanBeNull] NpcContainer user)
+ {
+ if (mob == null || user == null)
+ return;
+
+ var animator = _mobAnimatorFactory.TryGet(mob);
+ if (animator == null || HasOtherUser(mob, user))
+ return;
+
+ var state = animator.State;
+ var back = state > 0 ? GetTrack(mob.Vob.Visual.Name, MobStateNames.GetTransitionName(state, state - 1)) : null;
+ animator.PlayBackAndStop(back);
+ Logger.LogEditor($"[MobAnimation] {mob.Vob.Name}: last user left - stopping from {MobStateNames.GetStateName(state)}.",
+ LogCat.Vob);
+ }
+
+ ///
+ /// 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. 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)
+ {
+ StopHeroUse();
+ if (hero == null || !IsAnimated(mob))
+ return;
+
+ _heroMob = mob;
+ _hero = hero;
+ 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)
+ return;
+
+ var mob = _heroMob;
+ var hero = _hero;
+ _heroMob = null;
+ _hero = null;
+ StopIfLastUser(mob, hero);
+ }
+
+ ///
+ /// The world is left (world change, a loaded game): its mobs are gone with it, so the hero's mob is just
+ /// forgotten - a dialog anchor that went with the world never raised MobDialogEnded.
+ ///
+ private void ForgetHeroUse()
+ {
+ _heroMob = null;
+ _hero = null;
+ }
+
+ ///
+ /// Someone else uses the mob: the hero while his mob dialog is open, or another NPC in one of its states
+ /// (IsUsingMob, Docs/mobs.md "Who uses a mob"). An NPC still walking there doesn't keep it going.
+ ///
+ private bool HasOtherUser(VobContainer mob, NpcContainer user)
+ {
+ if (mob == _heroMob && user != _hero)
+ return true;
+
+ return _vobService.GetOtherMobUsers(mob, user).Any(i => i.IsUsingMob());
+ }
+
+ ///
+ /// The skeleton of the mob's model (its nodes). Null (logged once) if the model has no hierarchy.
+ ///
+ [CanBeNull]
+ private AnimationSkeleton GetSkeleton(string visualName)
+ {
+ var skeleton = _animationService.GetSkeleton(visualName);
+ if (skeleton == null && _loggedMissingSkeletons.Add(visualName))
+ Logger.LogWarning($"[MobAnimation] {visualName} has no model hierarchy - it won't animate.",
+ LogCat.Vob);
+ return skeleton;
+ }
+
+ ///
+ /// A track of the mob's own model script. AnimationService strips the extension and remembers missing names.
+ /// Most mobs miss some names (T_STAND_2_S0): logged once, in the Editor only.
+ ///
+ [CanBeNull]
+ private AnimationTrack GetTrack(string visualName, string animationName)
+ {
+ var track = _animationService.GetTrack(animationName, visualName, null);
+ if (track == null && _loggedMissingTracks.Add(visualName + "/" + animationName))
+ Logger.LogEditor($"[MobAnimation] {visualName} has no {animationName}.", LogCat.Vob);
+ return track;
+ }
+
+ ///
+ /// The tracks of the world's mobs are baked while the world loads (P3, WorldScene after the VOBs, the loading
+ /// screen is still shown): the first anvil hit or lever pull would read and bake the model's .MAN files in the
+ /// middle of the game otherwise. Their sounds are decoded too. Each model only once per game session
+ /// (AnimationService keeps the baked tracks). One track per step, the frame skipper yields in between.
+ ///
+ public async Task WarmWorldMobsAsync()
+ {
+ var watch = Stopwatch.StartNew();
+
+ // Collected first: the dictionary may change while we yield.
+ var visualNames = new List();
+ foreach (var mobs in _gameStateService.VobsInteractable.Values)
+ {
+ foreach (var mob in mobs)
+ {
+ if (IsAnimated(mob) && _warmedModels.Add(mob.Vob.Visual.Name))
+ visualNames.Add(mob.Vob.Visual.Name);
+ }
+ }
+
+ var trackCount = 0;
+ foreach (var visualName in visualNames)
+ {
+ trackCount += await WarmModelAsync(visualName);
+ await _frameSkipperService.TrySkipToNextFrame();
+ }
+
+ if (visualNames.Count > 0)
+ Logger.Log($"[MobAnimation] {trackCount} animations of {visualNames.Count} mob models baked in " +
+ $"{watch.ElapsedMilliseconds} ms.", LogCat.Vob);
+ }
+
+ ///
+ /// Bakes every state animation the model script has (MobStateNames.IsOwnStateAnimation: T_S0_2_S1, S_S2,
+ /// T_STAND_2_S0, ...), not a guessed list - a mob can reach S2 or more.
+ ///
+ private async Task WarmModelAsync(string visualName)
+ {
+ if (GetSkeleton(visualName) == null)
+ return 0;
+
+ var mds = _resourceCacheService.TryGetModelScript(visualName, false);
+ if (mds == null)
+ return 0;
+
+ var animationNames = mds.Animations.Select(i => i.Name)
+ .Concat(mds.AnimationAliases.Select(i => i.Name))
+ .Concat(mds.AnimationCombines.Select(i => i.Name))
+ .Where(MobStateNames.IsOwnStateAnimation)
+ .Distinct(StringComparer.OrdinalIgnoreCase)
+ .ToList();
+
+ var found = new StringBuilder();
+ foreach (var animationName in animationNames)
+ {
+ WarmTrack(visualName, animationName, found);
+ await _frameSkipperService.TrySkipToNextFrame();
+ }
+
+ var foundNames = found.Length > 0 ? found.ToString() : "no state animations";
+ Logger.LogEditor($"[MobAnimation] {visualName}: {foundNames}", LogCat.Vob);
+ return animationNames.Count;
+ }
+
+ private void WarmTrack(string visualName, string animationName, StringBuilder found)
+ {
+ var track = GetTrack(visualName, animationName);
+ if (track == null)
+ return;
+
+ found.Append(found.Length > 0 ? ", " : string.Empty).Append(animationName);
+ if (track.SoundEffects == null)
+ return;
+
+ foreach (var sfx in track.SoundEffects)
+ _audioService.GetRandomSoundClip(sfx.Name);
+ }
+ }
+}
diff --git a/Assets/Gothic-Core/Scripts/Services/Vobs/MobAnimationService.cs.meta b/Assets/Gothic-Core/Scripts/Services/Vobs/MobAnimationService.cs.meta
new file mode 100644
index 000000000..10e9c3f74
--- /dev/null
+++ b/Assets/Gothic-Core/Scripts/Services/Vobs/MobAnimationService.cs.meta
@@ -0,0 +1,2 @@
+fileFormatVersion: 2
+guid: df843125a346e9246a590599bba8eb8e
\ No newline at end of file
diff --git a/Assets/Gothic-Core/Scripts/Services/Vobs/MobInteractionService.cs b/Assets/Gothic-Core/Scripts/Services/Vobs/MobInteractionService.cs
index 5e56177f9..d8bac4359 100644
--- a/Assets/Gothic-Core/Scripts/Services/Vobs/MobInteractionService.cs
+++ b/Assets/Gothic-Core/Scripts/Services/Vobs/MobInteractionService.cs
@@ -35,6 +35,7 @@ public class MobInteractionService
[Inject] private readonly ConfigService _configService;
[Inject] private readonly ResourceCacheService _resourceCacheService;
[Inject] private readonly FireService _fireService;
+ [Inject] private readonly MobAnimationService _mobAnimationService;
///
/// Doors use VR hinge physics and chests their lid physics - not the mob/trigger path.
@@ -45,7 +46,7 @@ public bool ShouldHandleGrab(IVirtualObject vob)
if (vob is not IInteractiveObject)
return false;
- return !((vob is IDoor && !vob.IsBed()) || vob is IContainer);
+ return !vob.IsHingeMob();
}
///
@@ -125,6 +126,7 @@ public void HandleMobGrab(VobLoader loader, Func createDialogAnchor,
// stateNum (the number of its states), which a save game must keep.
var container = loader.Container;
var senderName = container.Vob.Name;
+ var previousState = container.MobState;
if (container.MobState > 0)
{
container.MobState = 0;
@@ -135,6 +137,9 @@ public void HandleMobGrab(VobLoader loader, Func createDialogAnchor,
container.MobState = 1;
_vobService.DispatchTrigger(target, senderName);
}
+
+ // The lever or wheel swings into its new state and stays there (no user keeps it busy).
+ _mobAnimationService.OnStateChanged(container, null, Math.Max(0, previousState), container.MobState);
}
///
@@ -178,6 +183,13 @@ private bool TryUseMobStateFunction(VobLoader loader, IInteractiveObject mob,
try
{
_dialogService.PrepareMobDialog(createDialogAnchor());
+
+ // The mob works while its dialog is open (the anvil sparks while the hero chooses what to forge), like
+ // for a smith. It rests when the dialog closes, or right after its transition if _S1 opens none
+ // (GlobalEventDispatcher.MobDialogEnded). Only after PrepareMobDialog: it ends an old anchor, whose
+ // MobDialogEnded -> StopHeroUse would stop this use at once.
+ _mobAnimationService.StartHeroUse(loader.Container, hero);
+
_vmService.CallAsHero(functionName, LogCat.Dialog);
Logger.Log($"[MobDialog] Called '{functionName}' for '{loader.name}'.", LogCat.Dialog);
}
@@ -254,9 +266,16 @@ private bool TryUseMobWithItemEvents(VobLoader loader, IInteractiveObject mob,
handItem = tag.Item;
}
- if (!string.IsNullOrEmpty(mob.OnStateChangeFunction))
+ var isStateFunctionUsed = !string.IsNullOrEmpty(mob.OnStateChangeFunction) &&
TryUseMobStateFunction(loader, mob, createDialogAnchor, beginStateFunction, isItemInHand: true);
+ // Without a dialog (the forge turns the raw steel into hot steel) the mob works once: there and back.
+ if (!isStateFunctionUsed)
+ {
+ _mobAnimationService.StartHeroUse(loader.Container, hero);
+ _mobAnimationService.StopHeroUse();
+ }
+
var leaveAnim = mds.Animations.FirstOrDefault(a => a.Name.EqualsIgnoreCase($"T_{scheme}_S1_2_S0"));
var isPutBack = leaveAnim?.EventTags.Any(e => e.Type == EventType.ItemRemove) ?? false;
if (isPutBack)
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-Core/Scripts/Services/World/BarrierService.cs b/Assets/Gothic-Core/Scripts/Services/World/BarrierService.cs
index 07be91fe4..282d4333c 100644
--- a/Assets/Gothic-Core/Scripts/Services/World/BarrierService.cs
+++ b/Assets/Gothic-Core/Scripts/Services/World/BarrierService.cs
@@ -80,7 +80,7 @@ private void CreateBarrier()
for (var i = 0; i < _thunderSoundSources.Length; i++)
{
- _thunderSoundSources[i] = _barrier.AddComponent();
+ _thunderSoundSources[i] = _audioService.AddSfxSource(_barrier);
_thunderSoundSources[i].volume = 0.3f; // We reduce its sound, as it's too noisy with 100%. Like music, we start with 0.3f.
// AddThunder(i);
}
diff --git a/Assets/Gothic-VR/Resources/VR/Prefabs/VR - Player XRI.prefab b/Assets/Gothic-VR/Resources/VR/Prefabs/VR - Player XRI.prefab
index 14b3ea400..ed82b67fa 100644
--- a/Assets/Gothic-VR/Resources/VR/Prefabs/VR - Player XRI.prefab
+++ b/Assets/Gothic-VR/Resources/VR/Prefabs/VR - Player XRI.prefab
@@ -111,7 +111,7 @@ AudioSource:
m_GameObject: {fileID: 267875144165424739}
m_Enabled: 1
serializedVersion: 4
- OutputAudioMixerGroup: {fileID: 0}
+ OutputAudioMixerGroup: {fileID: 6160132109742411210, guid: 118dcb5485ad4894fb619aab7e1f8708, type: 2}
m_audioClip: {fileID: 0}
m_Resource: {fileID: 0}
m_PlayOnAwake: 0
diff --git a/Assets/Gothic-VR/Resources/VR/Prefabs/Vobs/oCMobContainer.prefab b/Assets/Gothic-VR/Resources/VR/Prefabs/Vobs/oCMobContainer.prefab
index 1519bc1d7..cc9888f7d 100644
--- a/Assets/Gothic-VR/Resources/VR/Prefabs/Vobs/oCMobContainer.prefab
+++ b/Assets/Gothic-VR/Resources/VR/Prefabs/Vobs/oCMobContainer.prefab
@@ -141,7 +141,7 @@ AudioSource:
m_GameObject: {fileID: 4312441289917667731}
m_Enabled: 1
serializedVersion: 4
- OutputAudioMixerGroup: {fileID: 0}
+ OutputAudioMixerGroup: {fileID: 6160132109742411210, guid: 118dcb5485ad4894fb619aab7e1f8708, type: 2}
m_audioClip: {fileID: 0}
m_Resource: {fileID: 0}
m_PlayOnAwake: 1
@@ -488,6 +488,7 @@ MonoBehaviour:
m_MaxAngularVelocityDelta: 20
_heldInterpolation: 1
_isOneHandOnly: 0
+ _rightHandAttachTransform: {fileID: 0}
--- !u!114 &7588009683243012385
MonoBehaviour:
m_ObjectHideFlags: 0
diff --git a/Assets/Gothic-VR/Resources/VR/Prefabs/Vobs/oCMobDoor.prefab b/Assets/Gothic-VR/Resources/VR/Prefabs/Vobs/oCMobDoor.prefab
index e1b14f159..57a5606fd 100644
--- a/Assets/Gothic-VR/Resources/VR/Prefabs/Vobs/oCMobDoor.prefab
+++ b/Assets/Gothic-VR/Resources/VR/Prefabs/Vobs/oCMobDoor.prefab
@@ -246,6 +246,7 @@ MonoBehaviour:
m_MaxAngularVelocityDelta: 20
_heldInterpolation: 1
_isOneHandOnly: 0
+ _rightHandAttachTransform: {fileID: 0}
--- !u!114 &786056569404290700
MonoBehaviour:
m_ObjectHideFlags: 0
@@ -337,7 +338,7 @@ AudioSource:
m_GameObject: {fileID: 1222579370199367537}
m_Enabled: 1
serializedVersion: 4
- OutputAudioMixerGroup: {fileID: 0}
+ OutputAudioMixerGroup: {fileID: 6160132109742411210, guid: 118dcb5485ad4894fb619aab7e1f8708, type: 2}
m_audioClip: {fileID: 0}
m_Resource: {fileID: 0}
m_PlayOnAwake: 1
diff --git a/Assets/Gothic-VR/Resources/VR/Prefabs/Vobs/oCNpc.prefab b/Assets/Gothic-VR/Resources/VR/Prefabs/Vobs/oCNpc.prefab
index 6f5f5a323..5ced93ad0 100644
--- a/Assets/Gothic-VR/Resources/VR/Prefabs/Vobs/oCNpc.prefab
+++ b/Assets/Gothic-VR/Resources/VR/Prefabs/Vobs/oCNpc.prefab
@@ -1,5 +1,134 @@
%YAML 1.1
%TAG !u! tag:unity3d.com,2011:
+--- !u!1 &572506100184511426
+GameObject:
+ m_ObjectHideFlags: 0
+ m_CorrespondingSourceObject: {fileID: 0}
+ m_PrefabInstance: {fileID: 0}
+ m_PrefabAsset: {fileID: 0}
+ serializedVersion: 6
+ m_Component:
+ - component: {fileID: 3304720018996019096}
+ - component: {fileID: 1586037810186681885}
+ m_Layer: 0
+ m_Name: _AnimationSfx
+ m_TagString: Untagged
+ m_Icon: {fileID: 0}
+ m_NavMeshLayer: 0
+ m_StaticEditorFlags: 0
+ m_IsActive: 1
+--- !u!4 &3304720018996019096
+Transform:
+ m_ObjectHideFlags: 0
+ m_CorrespondingSourceObject: {fileID: 0}
+ m_PrefabInstance: {fileID: 0}
+ m_PrefabAsset: {fileID: 0}
+ m_GameObject: {fileID: 572506100184511426}
+ serializedVersion: 2
+ m_LocalRotation: {x: 0, y: 0, z: 0, w: 1}
+ m_LocalPosition: {x: 0, y: 0, z: 0}
+ m_LocalScale: {x: 1, y: 1, z: 1}
+ m_ConstrainProportionsScale: 0
+ m_Children: []
+ m_Father: {fileID: 8679908380237941234}
+ m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0}
+--- !u!82 &1586037810186681885
+AudioSource:
+ m_ObjectHideFlags: 0
+ m_CorrespondingSourceObject: {fileID: 0}
+ m_PrefabInstance: {fileID: 0}
+ m_PrefabAsset: {fileID: 0}
+ m_GameObject: {fileID: 572506100184511426}
+ m_Enabled: 1
+ serializedVersion: 4
+ OutputAudioMixerGroup: {fileID: 6160132109742411210, guid: 118dcb5485ad4894fb619aab7e1f8708, type: 2}
+ m_audioClip: {fileID: 0}
+ m_Resource: {fileID: 0}
+ m_PlayOnAwake: 0
+ m_Volume: 1
+ m_Pitch: 1
+ Loop: 0
+ Mute: 0
+ Spatialize: 0
+ SpatializePostEffects: 0
+ Priority: 128
+ DopplerLevel: 1
+ MinDistance: 0
+ MaxDistance: 10
+ Pan2D: 0
+ rolloffMode: 1
+ BypassEffects: 0
+ BypassListenerEffects: 0
+ BypassReverbZones: 0
+ rolloffCustomCurve:
+ serializedVersion: 2
+ m_Curve:
+ - serializedVersion: 3
+ time: 0
+ value: 1
+ inSlope: 0
+ outSlope: 0
+ tangentMode: 0
+ weightedMode: 0
+ inWeight: 0.33333334
+ outWeight: 0.33333334
+ - serializedVersion: 3
+ time: 1
+ value: 0
+ inSlope: 0
+ outSlope: 0
+ tangentMode: 0
+ weightedMode: 0
+ inWeight: 0.33333334
+ outWeight: 0.33333334
+ m_PreInfinity: 2
+ m_PostInfinity: 2
+ m_RotationOrder: 4
+ panLevelCustomCurve:
+ serializedVersion: 2
+ m_Curve:
+ - serializedVersion: 3
+ time: 0
+ value: 1
+ inSlope: 0
+ outSlope: 0
+ tangentMode: 0
+ weightedMode: 0
+ inWeight: 0.33333334
+ outWeight: 0.33333334
+ m_PreInfinity: 2
+ m_PostInfinity: 2
+ m_RotationOrder: 4
+ spreadCustomCurve:
+ serializedVersion: 2
+ m_Curve:
+ - serializedVersion: 3
+ time: 0
+ value: 0
+ inSlope: 0
+ outSlope: 0
+ tangentMode: 0
+ weightedMode: 0
+ inWeight: 0.33333334
+ outWeight: 0.33333334
+ m_PreInfinity: 2
+ m_PostInfinity: 2
+ m_RotationOrder: 4
+ reverbZoneMixCustomCurve:
+ serializedVersion: 2
+ m_Curve:
+ - serializedVersion: 3
+ time: 0
+ value: 1
+ inSlope: 0
+ outSlope: 0
+ tangentMode: 0
+ weightedMode: 0
+ inWeight: 0.33333334
+ outWeight: 0.33333334
+ m_PreInfinity: 2
+ m_PostInfinity: 2
+ m_RotationOrder: 4
--- !u!1 &2202926895728732233
GameObject:
m_ObjectHideFlags: 0
@@ -55,6 +184,7 @@ MonoBehaviour:
m_EditorClassIdentifier:
_isHero: 0
NpcSound: {fileID: 3405042143443336336}
+ AnimationSfxSound: {fileID: 1586037810186681885}
Bip01: {fileID: 8679908380237941234}
ColliderRootMotion: {fileID: 6115383017936816660}
AiHandler: {fileID: 3046509075852218844}
@@ -200,6 +330,7 @@ Transform:
- {fileID: 4224993087751750351}
- {fileID: 1729239900852249070}
- {fileID: 8661861277319438176}
+ - {fileID: 3304720018996019096}
m_Father: {fileID: 1199752534748503035}
m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0}
--- !u!82 &3405042143443336336
@@ -211,7 +342,7 @@ AudioSource:
m_GameObject: {fileID: 2815092147823170342}
m_Enabled: 1
serializedVersion: 4
- OutputAudioMixerGroup: {fileID: 0}
+ OutputAudioMixerGroup: {fileID: 6160132109742411210, guid: 118dcb5485ad4894fb619aab7e1f8708, type: 2}
m_audioClip: {fileID: 0}
m_Resource: {fileID: 0}
m_PlayOnAwake: 0
diff --git a/Assets/Gothic-VR/Scripts/Adapters/Player/VRBackpack.cs b/Assets/Gothic-VR/Scripts/Adapters/Player/VRBackpack.cs
index eec0bbb39..9e32089a3 100644
--- a/Assets/Gothic-VR/Scripts/Adapters/Player/VRBackpack.cs
+++ b/Assets/Gothic-VR/Scripts/Adapters/Player/VRBackpack.cs
@@ -259,7 +259,7 @@ public void OnTakeAllClick()
var itemCount = _inventoryTransferService.TakeAll(_owner);
var clip = _audioService.CreateAudioClip(_audioService.InvOpen.File);
if (clip != null)
- AudioSource.PlayClipAtPoint(clip, transform.position);
+ _audioService.PlaySfxAtPoint(clip, transform.position);
if (itemCount > 0 && !_vmService.PrintItemsTaken(itemCount))
Logger.LogWarning("[VRBackpack] No items taken text in the scripts - take all without message.",
LogCat.VR);
diff --git a/Assets/Gothic-VR/Scripts/Adapters/Player/VRHeroBody.cs b/Assets/Gothic-VR/Scripts/Adapters/Player/VRHeroBody.cs
index b713ff5bf..73051426f 100644
--- a/Assets/Gothic-VR/Scripts/Adapters/Player/VRHeroBody.cs
+++ b/Assets/Gothic-VR/Scripts/Adapters/Player/VRHeroBody.cs
@@ -494,7 +494,7 @@ private void OnBodySoundEvent(ZenKit.IEventSoundEffect sfx)
return;
if (_bodySoundSource == null)
{
- _bodySoundSource = gameObject.AddComponent();
+ _bodySoundSource = _audioService.AddSfxSource(gameObject);
_bodySoundSource.playOnAwake = false;
// The player's own body: right with him, no distance falloff.
_bodySoundSource.spatialBlend = 0f;
diff --git a/Assets/Gothic-VR/Scripts/Adapters/Player/VRHeroMovement.cs b/Assets/Gothic-VR/Scripts/Adapters/Player/VRHeroMovement.cs
index 4672d4360..89e36cb21 100644
--- a/Assets/Gothic-VR/Scripts/Adapters/Player/VRHeroMovement.cs
+++ b/Assets/Gothic-VR/Scripts/Adapters/Player/VRHeroMovement.cs
@@ -287,7 +287,7 @@ private void UpdateHeroFootsteps()
_silentStepReason = null;
if (_stepSource == null)
{
- _stepSource = gameObject.AddComponent();
+ _stepSource = _audioService.AddSfxSource(gameObject);
_stepSource.playOnAwake = false;
// The player's own feet: right below him, no distance falloff.
_stepSource.spatialBlend = 0f;
diff --git a/Assets/Gothic-VR/Scripts/Adapters/Player/VRPickpocket.cs b/Assets/Gothic-VR/Scripts/Adapters/Player/VRPickpocket.cs
index 21079e0c2..96594c61b 100644
--- a/Assets/Gothic-VR/Scripts/Adapters/Player/VRPickpocket.cs
+++ b/Assets/Gothic-VR/Scripts/Adapters/Player/VRPickpocket.cs
@@ -574,7 +574,7 @@ private IEnumerator PutPocketsIntoHand(VrHandSide side, string victimName, Vecto
var clip = _audioService.CreateAudioClip(_audioService.InvOpen.File);
if (clip != null)
- AudioSource.PlayClipAtPoint(clip, soundPosition);
+ _audioService.PlaySfxAtPoint(clip, soundPosition);
_hapticsService.Vibrate(side, VrHapticPreset.Success);
Logger.Log($"[Pickpocket] Robbing {victimName}", LogCat.VR);
}
diff --git a/Assets/Gothic-VR/Scripts/Adapters/Trade/VRTradeCounter.cs b/Assets/Gothic-VR/Scripts/Adapters/Trade/VRTradeCounter.cs
index 30c28ba32..1e5fa8e3b 100644
--- a/Assets/Gothic-VR/Scripts/Adapters/Trade/VRTradeCounter.cs
+++ b/Assets/Gothic-VR/Scripts/Adapters/Trade/VRTradeCounter.cs
@@ -740,7 +740,7 @@ private void PlaySound(SoundEffectInstance sound)
{
var clip = sound != null ? _audioService.CreateAudioClip(sound) : null;
if (clip != null)
- AudioSource.PlayClipAtPoint(clip, transform.position);
+ _audioService.PlaySfxAtPoint(clip, transform.position);
}
}
}
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/VRBow.cs b/Assets/Gothic-VR/Scripts/Adapters/Vob/VobItem/VRBow.cs
index 9a994ef56..9302088df 100644
--- a/Assets/Gothic-VR/Scripts/Adapters/Vob/VobItem/VRBow.cs
+++ b/Assets/Gothic-VR/Scripts/Adapters/Vob/VobItem/VRBow.cs
@@ -499,7 +499,7 @@ private void PlaySfx(string sfxName)
{
var clip = _audioService.GetRandomSoundClip(sfxName);
if (clip != null)
- AudioSource.PlayClipAtPoint(clip, transform.position);
+ _audioService.PlaySfxAtPoint(clip, transform.position);
}
}
}
diff --git a/Assets/Gothic-VR/Scripts/Adapters/Vob/VobItem/VRCrossbow.cs b/Assets/Gothic-VR/Scripts/Adapters/Vob/VobItem/VRCrossbow.cs
index ba22bcf4d..9df3950d4 100644
--- a/Assets/Gothic-VR/Scripts/Adapters/Vob/VobItem/VRCrossbow.cs
+++ b/Assets/Gothic-VR/Scripts/Adapters/Vob/VobItem/VRCrossbow.cs
@@ -434,7 +434,7 @@ private void PlaySfx(string sfxName)
{
var clip = _audioService.GetRandomSoundClip(sfxName);
if (clip != null)
- AudioSource.PlayClipAtPoint(clip, transform.position);
+ _audioService.PlaySfxAtPoint(clip, transform.position);
}
}
}
diff --git a/Assets/Gothic-VR/Scripts/Adapters/Vob/VobItem/VRMouth.cs b/Assets/Gothic-VR/Scripts/Adapters/Vob/VobItem/VRMouth.cs
index 8caa17e7b..c45254a72 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))
@@ -90,7 +97,7 @@ private void OnTriggerEnter(Collider other)
Logger.Log($"Eating item: {go.name}", LogCat.VR);
var destroyTime = 1f;
- if (TryExtractSfx(item, out var clip))
+ if (TryExtractSfx(item, out var clip, out var volume))
destroyTime = clip.length;
else
Logger.LogWarning("No SFX for eating/drinking item found. Removing item anyways after 1 second.", LogCat.VR);
@@ -98,10 +105,22 @@ private void OnTriggerEnter(Collider other)
_objectsInDestroyGracePeriod.Add(rootGo);
// Smoking: a drag first, then the sound and the smoke (_smokeStartDelay).
var startDelay = IsSmokable(item) ? Mathf.Max(0f, _smokeStartDelay) : 0f;
- StartCoroutine(ConsumeObject(rootGo, clip, destroyTime, startDelay));
+ StartCoroutine(ConsumeObject(rootGo, clip, volume, 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++)
{
@@ -196,9 +234,11 @@ private bool TryGetItemToEat(GameObject go, out ItemInstance item)
return true;
}
- private bool TryExtractSfx(ItemInstance item, out AudioClip clip)
+ /// Gothic's volume of the sound (SMOKE_JOINT 20 of 127), 0..1.
+ private bool TryExtractSfx(ItemInstance item, out AudioClip clip, out float volume)
{
clip = null;
+ volume = 1f;
var animationName = string.Format(_animationSchemeWithSfx, item.SchemeName);
var anim = TryGetUseAnimation(item);
@@ -226,7 +266,7 @@ private bool TryExtractSfx(ItemInstance item, out AudioClip clip)
return false;
}
- clip = _audioService.CreateAudioClip(sfxContainer.GetRandomSound());
+ clip = _audioService.CreateAudioClip(sfxContainer.GetRandomSound(out volume));
if (clip == null)
return false;
@@ -235,19 +275,24 @@ 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));
}
- private IEnumerator ConsumeObject(GameObject go, [CanBeNull] AudioClip clip, float destroyDelay,
+ private IEnumerator ConsumeObject(GameObject go, [CanBeNull] AudioClip clip, float volume, float destroyDelay,
float startDelay = 0f)
{
if (startDelay > 0f)
yield return new WaitForSeconds(startDelay);
if (clip != null)
- _mouthAudio.PlayOneShot(clip);
+ _mouthAudio.PlayOneShot(clip, volume);
yield return new WaitForSeconds(destroyDelay);
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/Adapters/Vob/VobItem/VRSpellFx.cs b/Assets/Gothic-VR/Scripts/Adapters/Vob/VobItem/VRSpellFx.cs
index 6ef730ab4..806805b85 100644
--- a/Assets/Gothic-VR/Scripts/Adapters/Vob/VobItem/VRSpellFx.cs
+++ b/Assets/Gothic-VR/Scripts/Adapters/Vob/VobItem/VRSpellFx.cs
@@ -128,8 +128,7 @@ public void PlayInvestLevelSound(string sfxId)
var clip = _audioService.GetRandomSoundClip(sfxId);
if (clip == null)
return;
- _investAudioSource.clip = clip;
- _investAudioSource.Play();
+ PlayInvestClip(clip);
}
public void SpawnHandVfx(VrHandSide handSide, string pfxNameOverride = null)
@@ -414,7 +413,7 @@ public void SpawnCollideFx(string fxName, int level, Vector3 position, Vector3 n
{
var clip = _audioService.GetRandomSoundClip(sfxName);
if (clip != null)
- AudioSource.PlayClipAtPoint(clip, position);
+ _audioService.PlaySfxAtPoint(clip, position);
}
// emFXCreate_S of the collide effect (e.g. fire storm: SPREAD -> burning area).
@@ -452,6 +451,13 @@ public void StartInvestSound()
if (mfxName == null) return;
var clip = _audioService.GetRandomSoundClip($"MFX_{mfxName}_Invest");
if (clip == null) return;
+ PlayInvestClip(clip);
+ }
+
+ // Created in the constructor, before the injection: routed to the sound effects slider's group here.
+ private void PlayInvestClip(AudioClip clip)
+ {
+ _investAudioSource.outputAudioMixerGroup = _audioService.SoundEffectsGroup;
_investAudioSource.clip = clip;
_investAudioSource.Play();
}
@@ -472,14 +478,14 @@ public void PlayCastSound()
if (clip == null)
clip = _audioService.GetRandomSoundClip("MFX_Thunderbolt_Cast");
if (clip != null)
- AudioSource.PlayClipAtPoint(clip, _owner.transform.position);
+ _audioService.PlaySfxAtPoint(clip, _owner.transform.position);
}
public void PlayOneShot(string sfxName)
{
var clip = _audioService.GetRandomSoundClip(sfxName);
if (clip != null)
- AudioSource.PlayClipAtPoint(clip, _owner.transform.position);
+ _audioService.PlaySfxAtPoint(clip, _owner.transform.position);
}
///
diff --git a/Assets/Gothic-VR/Scripts/Adapters/Vob/VobItem/VRTorch.cs b/Assets/Gothic-VR/Scripts/Adapters/Vob/VobItem/VRTorch.cs
index 156535c15..89e8366ba 100644
--- a/Assets/Gothic-VR/Scripts/Adapters/Vob/VobItem/VRTorch.cs
+++ b/Assets/Gothic-VR/Scripts/Adapters/Vob/VobItem/VRTorch.cs
@@ -100,7 +100,7 @@ private void Light()
var clip = _audioService.GetRandomSoundClip(Constants.SfxTorchLight);
if (clip != null)
- AudioSource.PlayClipAtPoint(clip, tip.transform.position);
+ _audioService.PlaySfxAtPoint(clip, tip.transform.position);
Logger.Log($"[VRTorch] {name} lit", LogCat.VR);
}
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/Backends/Xri/XriSfxPlayer.cs b/Assets/Gothic-VR/Scripts/Interaction/Backends/Xri/XriSfxPlayer.cs
index 967621237..dda0e58f1 100644
--- a/Assets/Gothic-VR/Scripts/Interaction/Backends/Xri/XriSfxPlayer.cs
+++ b/Assets/Gothic-VR/Scripts/Interaction/Backends/Xri/XriSfxPlayer.cs
@@ -1,25 +1,33 @@
using System;
using System.Collections.Generic;
+using Gothic.Core.Manager;
using Gothic.VR.Interaction.Ports;
using UnityEngine;
namespace Gothic.VR.Interaction.Backends.Xri
{
///
- /// Minimal 3D one-shot player via AudioSource.PlayClipAtPoint (fully spatial, default rolloff, no mixer group).
+ /// Minimal 3D one-shot player via AudioService.PlaySfxAtPoint (fully spatial, default rolloff, the sound effects
+ /// mixer group).
/// HVR's pool used a reference AudioSource from HVRGlobal.prefab; an own pool with the same settings is a later
/// phase.
///
public class XriSfxPlayer : IVrSfxPlayer
{
+ private readonly AudioService _audioService;
private readonly Dictionary _lastPlayTimes = new();
+ public XriSfxPlayer(AudioService audioService)
+ {
+ _audioService = audioService;
+ }
+
public void Play(AudioClip clip, Vector3 position)
{
if (clip == null)
return;
- AudioSource.PlayClipAtPoint(clip, position);
+ _audioService.PlaySfxAtPoint(clip, position);
}
public void PlayWithCooldown(AudioClip clip, Vector3 position, Guid sourceId, float cooldownTime)
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/Assets/Gothic2/Scripts/Adapters/Context/G2ContextBootstrap.cs b/Assets/Gothic2/Scripts/Adapters/Context/G2ContextBootstrap.cs
index 543aeb847..d70737be1 100644
--- a/Assets/Gothic2/Scripts/Adapters/Context/G2ContextBootstrap.cs
+++ b/Assets/Gothic2/Scripts/Adapters/Context/G2ContextBootstrap.cs
@@ -1,6 +1,8 @@
using Gothic.Core.Adapters.Context;
using Gothic.Core.Models.Context;
+using Gothic.Core.Services.Config;
using Gothic.Core.Services.Context;
+using Gothic.G2.Services.Audio;
using Gothic.G2.Services.Context;
using Gothic.G2.Services.Fight;
using Gothic.Core;
@@ -18,6 +20,8 @@ public class G2ContextBootstrap : AbstractContextBootstrap
[Inject] private readonly ContextGameVersionService _contextGameVersionService;
[Inject] private readonly ContextMeleeDamageRuleService _contextMeleeDamageRuleService;
[Inject] private readonly ContextRangedCombatService _contextRangedCombatService;
+ [Inject] private readonly ContextSoundRangeService _contextSoundRangeService;
+ [Inject] private readonly ConfigService _configService;
protected override void RegisterControlModule(Controls controls)
@@ -33,6 +37,10 @@ protected override void RegisterGameVersionModule(GameVersion version)
_contextGameVersionService.SetImpl(new G2ContextService().Inject());
_contextMeleeDamageRuleService.SetImpl(new G2MeleeDamageRule().Inject());
_contextRangedCombatService.SetImpl(new G2RangedCombatService().Inject());
+
+ // Improvements beyond the original game: vanilla G2 only, a mod keeps its own world.
+ if (_configService.Dev.EnableImprovements && !_configService.IsModActive)
+ _contextSoundRangeService.SetImpl(new G2SoundRangeService().Inject());
}
}
}
diff --git a/Assets/Gothic2/Scripts/Services/Audio.meta b/Assets/Gothic2/Scripts/Services/Audio.meta
new file mode 100644
index 000000000..f11f60de3
--- /dev/null
+++ b/Assets/Gothic2/Scripts/Services/Audio.meta
@@ -0,0 +1,8 @@
+fileFormatVersion: 2
+guid: ee2331ee7e5ada2739ef4df4ed5963f8
+folderAsset: yes
+DefaultImporter:
+ externalObjects: {}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/Assets/Gothic2/Scripts/Services/Audio/G2SoundRangeService.cs b/Assets/Gothic2/Scripts/Services/Audio/G2SoundRangeService.cs
new file mode 100644
index 000000000..2a683688c
--- /dev/null
+++ b/Assets/Gothic2/Scripts/Services/Audio/G2SoundRangeService.cs
@@ -0,0 +1,62 @@
+using System;
+using Gothic.Core.Logging;
+using Gothic.Core.Services;
+using Gothic.Core.Services.Context;
+using Reflex.Attributes;
+using Logger = Gothic.Core.Logging.Logger;
+
+namespace Gothic.G2.Services.Audio
+{
+ ///
+ /// An improvement beyond the original game, gated by DeveloperConfig.EnableImprovements (G2 without a mod only):
+ /// Fellan's hammering carries 24 m instead of Gothic's 10 m. Every other sound keeps Gothic's range.
+ ///
+ public class G2SoundRangeService : IContextSoundRangeService
+ {
+ [Inject] private readonly GameStateService _gameStateService;
+
+ // Alwin asks "Hörst du nicht das Hämmern?" (DIA_Alwin_Fellan_12_02), but Fellan's HAMMER (R:1000 = 10 m) isn't
+ // heard at Alwin's sheep pen ~18 m away. Chosen in play: 24 m reaches the pen, 60 m was heard across the
+ // whole harbour.
+ private const string _fellanInstanceName = "VLK_480_Fellan";
+ private const string _hammerSfxName = "HAMMER";
+ private const float _hammerRangeMeters = 24f;
+
+ // Not resolved yet: the VM is loaded after the game version module is registered.
+ private const int _unresolvedIndex = -2;
+ // -1 if Fellan isn't in the scripts: no NPC matches then (mobs pass -1 and are skipped before the compare).
+ private int _fellanIndex = _unresolvedIndex;
+
+
+ public float GetRangeMeters(int npcInstanceIndex, string sfxName, float gothicRangeMeters)
+ {
+ if (_fellanIndex == _unresolvedIndex)
+ ResolveFellanIndex();
+
+ if (npcInstanceIndex < 0 || npcInstanceIndex != _fellanIndex)
+ return gothicRangeMeters;
+
+ return string.Equals(sfxName, _hammerSfxName, StringComparison.OrdinalIgnoreCase)
+ ? _hammerRangeMeters
+ : gothicRangeMeters;
+ }
+
+ private void ResolveFellanIndex()
+ {
+ var vm = _gameStateService.GothicVm;
+ if (vm == null)
+ return;
+
+ var symbol = vm.GetSymbolByName(_fellanInstanceName);
+ if (symbol == null)
+ {
+ _fellanIndex = -1;
+ Logger.LogWarning($"[SoundRange] {_fellanInstanceName} not found in the scripts - his hammering " +
+ "keeps Gothic's range.", LogCat.Audio);
+ return;
+ }
+
+ _fellanIndex = symbol.Index;
+ }
+ }
+}
diff --git a/Assets/Gothic2/Scripts/Services/Audio/G2SoundRangeService.cs.meta b/Assets/Gothic2/Scripts/Services/Audio/G2SoundRangeService.cs.meta
new file mode 100644
index 000000000..db94b2609
--- /dev/null
+++ b/Assets/Gothic2/Scripts/Services/Audio/G2SoundRangeService.cs.meta
@@ -0,0 +1,2 @@
+fileFormatVersion: 2
+guid: 49245c8f6f24857e8a8109f01a4e3343
\ No newline at end of file
diff --git a/Docs/adr/2026-11-25-mob-animations.md b/Docs/adr/2026-11-25-mob-animations.md
new file mode 100644
index 000000000..5e5b422cc
--- /dev/null
+++ b/Docs/adr/2026-11-25-mob-animations.md
@@ -0,0 +1,27 @@
+# ADR: Mobs play their own animations, sounds and particles while they are used
+
+- Date: 2026-11-25
+- Technical details: Docs/mobs.md
+
+## Context
+
+In Gothic, a mob (an anvil, a forge, a grindstone, a water bucket, a lever) has its own animations for its states, not only the person using it. While a smith works, the anvil throws sparks and rings, the forge roars and glows, the grindstone turns and sparks, the bucket steams.
+
+We only played the person's animations. The mobs stood still and silent: no turning grindstone, no sparks, no sound of the smithy in Khorinis.
+
+## Decisions
+
+1. **Every mob whose state an NPC or the hero changes plays its own state animation, with its sounds and particles.** That is what the engine does, and it covers the smithy, stoves, cauldrons, levers and the like at once. Not chosen: only the smithy's four mobs, which would leave the other working places silent.
+2. **When the hero forges himself, the anvil, forge and grindstone work while his smithing window is open.** They start when it opens and stop when it closes, as if he were one of the smiths. Not chosen: leaving the hero's own forging silent.
+3. **Doors, chests and beds stay as they are.** In VR they move physically when the player grabs them; playing their recorded animation as well would fight the hand. Not chosen: all mobs including doors and chests.
+4. **The forge gives no extra light while used, like in the original.** Its particles don't light anything in Gothic either; the room's light comes from the world's lamps. Not chosen: a glowing light added while the forge is in use; it can still come later if the smithy looks too dark.
+5. **It works in Gothic 1 and 2, in VR and on the flat screen, without a switch.** It is the original's behaviour, not an option.
+6. **A mob only animates while it is being used, with a small player of its own.** An unused mob costs nothing, and a used one only moves its few rigid parts and plays its effects, so many working places in a town stay cheap on the headset. Not chosen: giving every mob the full animation system the characters use, which is built for skinned bodies and costs far more per object.
+
+## Consequences
+
+- The smithy in Khorinis (and the smiths in Gothic 1) can be heard and seen working: sparks, steam, a turning grindstone.
+- Nothing new is saved: the mob's state already is, and its animation starts again with the next use after a load.
+- Mobs without their own animation file (Fellan's planks) don't change.
+- An NPC killed at a mob, or gone out of sight, lets go of it at once: the mob falls silent and is free for others. Before, a dead smith kept his anvil.
+- A lever or wheel left in its other state shows its resting pose after a load until it is used again; that is still open.
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/adr/2026-12-03-sound-effects-volume.md b/Docs/adr/2026-12-03-sound-effects-volume.md
new file mode 100644
index 000000000..06f5d91bc
--- /dev/null
+++ b/Docs/adr/2026-12-03-sound-effects-volume.md
@@ -0,0 +1,24 @@
+# ADR: The sound effects slider is Gothic's own volume, and sounds keep Gothic's range
+
+- Date: 2026-12-03
+
+## Context
+
+Gothic's options menu has a sound effects slider, stored in Gothic.ini as the sound volume. In the original game it sets how loud every sound effect plays, and it is at full by default.
+
+Our first version tried to give the slider its own scale: a position at three quarters meant Gothic's own loudness, and the top end was louder. Loud sounds could not get louder than their own level, so the top end did nothing for them. The slider also missed some sounds, because every sound had to be found and turned down by hand.
+
+## Decisions
+
+1. **The slider is Gothic's own global volume: 1 plays every sound at its own Gothic loudness, lower values turn all sound effects down together.** It defaults to 1, like the original and the slider in the menu. Not chosen: a scale where three quarters means Gothic's loudness and the top end is louder; loud sounds cannot get louder than they are, so the top end was silent in practice.
+2. **All sound effects go through one sound effects channel, and the slider sets that channel.** Every sound effect follows it, whether it plays on a world object, an animation, a spell or the hero. Not chosen: keeping a list of every sound and multiplying each one's loudness by the slider; a sound that was forgotten ignored the slider, and the list kept growing.
+3. **A sound keeps its own Gothic loudness, and the slider only turns it down.** The loudness of an animation sound or a world sound stays what Gothic gives it.
+4. **Voices and music are not part of the slider.** Dialog voices of NPCs keep their own level, and music is controlled by its own settings. The hero's hit sounds are still open: they play on the hero's voice for now and do not follow the slider. Interface and video sounds are not in the slider either.
+5. **Sounds keep Gothic's range.** A sound's range is Gothic's R: value (centimeters, converted to meters), and it fades linearly to silence at that range, like OpenGothic (OpenAL linear distance model, max distance = range). The only exception is an improvement beyond the original in G2: Fellan's hammering carries 24 m instead of 10 m, so it is heard at Alwin's sheep pen about 18 m away, where Alwin asks whether you hear the hammering. It applies to Fellan's HAMMER only, in G2 without a mod, and can be turned off with DeveloperConfig.EnableImprovements. Not chosen: 60 m, which was heard across the whole harbour, and a longer range for every NPC's hammering.
+
+## Consequences
+
+- Moving the slider in the menu changes every sound effect at once, without a restart, and the value is kept in Gothic.ini like the original's settings.
+- A sound effect that is added later follows the slider as soon as it uses the sound effects channel; nothing has to be registered.
+- The hero's hit sounds and the interface sounds are not yet under the slider.
+- Every animation sound fades linearly to silence at its Gothic range, except Fellan's hammering in G2 (24 m).
diff --git a/Docs/architecture.md b/Docs/architecture.md
index a2e44992d..b8d437c91 100644
--- a/Docs/architecture.md
+++ b/Docs/architecture.md
@@ -121,7 +121,7 @@ time on every change.
**Example:** `SaveGameService` orchestrates, the details live in `Domain/SaveGames/*`, the design in
`Docs/save-game.md`. The NPC AI and fight classes are mapped in `Docs/npc-ai.md`, the VR melee ones in
`Docs/vr-melee.md`, the VR ranged ones in `Docs/vr-ranged.md`, the lightmaps, lights and fires in
-`Docs/world-lighting.md`.
+`Docs/world-lighting.md`, the mob states and animations in `Docs/mobs.md`.
### 9. Leave it better, don't rewrite
@@ -165,6 +165,7 @@ removed from the baseline. Rule 5 is enforced by the asmdef references.
| change VR melee (swings, fists, block, stab finish) | see the map in `Docs/vr-melee.md` |
| change VR bows/crossbows (draw, shot, reload) | see the map in `Docs/vr-ranged.md` |
| change world lights, lightmaps, fires, indoor sky | see the map in `Docs/world-lighting.md` |
+| change mobs: their state, who uses them, their own animations | see the map in `Docs/mobs.md` |
| add a rule about an NPC, item or VOB | a property on its model or an extension in `Extensions/` |
| add a use case with state (loading, saving, dialogs) | a service in `Services//`, registered in `ReflexProjectInstaller` |
| move a big piece of logic out of a service | `Domain//Domain.cs`, created by the service |
diff --git a/Docs/mobs.md b/Docs/mobs.md
new file mode 100644
index 000000000..c12b6eee2
--- /dev/null
+++ b/Docs/mobs.md
@@ -0,0 +1,121 @@
+# Mobs
+
+How mobs (Gothic's `oCMobInter` family: anvils, forges, grindstones, cauldrons, benches, levers, wheels, beds,
+doors, chests) keep their state and play their own animations. Why the animations are built this way:
+Docs/adr/2026-11-25-mob-animations.md. The NPC AI in general is mapped in `Docs/npc-ai.md`.
+
+## The mob state
+
+A mob has a current state: 0 at rest, 1 (or higher) while used or switched, -1 while an NPC leaves it. It lives in
+`VobContainer.MobState`, not in the VOB's `State` (that is Gothic's `stateNum`, the number of states, which the save
+format keeps). Scripts read it with `Wld_GetMobState` (never below 0).
+
+| Who | Writes `MobState` when |
+|---|---|
+| `UseMob` (`AI_UseMob`) | each finished transition of its user moves the state one step towards the target (`UpdateState`), a linked mover is opened/closed |
+| `NpcService.ReleaseMob` | the last NPC still in one of the mob's states leaves it without `AI_UseMob(-1)` (`AI_StandUp`, death, starting over when culled or re-enabled): -1 |
+| `MobInteractionService` | the hero uses a lever/wheel with a target: 0 -> 1 triggers, 1 -> 0 untriggers (the trigger branch) |
+| `VRMobHinge` (VR) | the hand opens (1) or closes (0) a door or chest lid |
+| `MobStatesSaveSection` | a loaded game restores the states > 0 (section `core.mobStates`, per world, by type and position) |
+
+Saving: only the state is saved. Nothing about a mob's animation is: it starts again with the next use after a load.
+
+## Who uses a mob
+
+An NPC uses a mob while `NpcPrefabProperties.CurrentInteractable` is the mob and
+`NpcProperties.CurrentInteractableStateId` is >= 0 (`NpcContainerExtension.IsUsingMob`). `UseMob` reserves the mob
+before walking there, so two NPCs don't pick the same one (`VobService.GetOtherMobUsers`, a mob with several slots
+takes several).
+
+The usage ends in one place: `NpcService.ReleaseMob` clears mob, slot, state and body state, stops the mob's
+animation and, for the last user, sets the mob's state to -1. It runs after `AI_UseMob(-1)`'s last back transition,
+at `AI_StandUp(Quick)` (`StandUp`), at death (`NpcDeathDomain.Die`: a killed smith frees his anvil), when knocked out
+(`NpcKnockoutDomain.KnockOutNpc`, like the engine's `onNoHealth`) and when the NPC starts over (`AiHandler`). A world
+change or load drops NPCs and mobs together - nothing is released there. `UseMob` dropping its walk reservation (no
+free slot) isn't a usage yet.
+
+The hero doesn't set `CurrentInteractable`. He uses a mob through `MobInteractionService` (the VR grab,
+`VRMobUseService`): its condition function, then either the item swap of crafting mobs, the mob's dialog
+(`[onStateFunc]_S1`) or the trigger branch.
+
+## A mob's own animations
+
+Like the engine (OpenGothic `Interactive::setState`), a mob with an `.MDS` visual plays animations of its own model
+script while its state changes: `T_S0_2_S1`, then the loop `S_S1`, and `T_S1_2_S0` back. They carry their own
+events: G2's smithy has `BSANVIL_OC.MDS` `S_S1` with `FORGE_ANVIL` and `ANVIL_SPARKS`, `BSFIRE_OC.MDS` `T_S0_2_S1`
+with `FIRE_HOT`, `BSSHARP_OC.MDS` turning its wheel with `SHARPSTONE_SPARKS`, `BSCOOL_OC.MDS` with `WATERVAPOUR`.
+State -1 is called `STAND` in the names (`T_STAND_2_S0` - most mobs don't have it).
+
+| Class | Owns |
+|---|---|
+| `MobAnimationService` (Services/Vobs) | which mobs animate (`IsAnimated`: an `.MDS` visual, no door, chest, bed or fireplace), the track names, whether someone else still uses the mob (`HasOtherUser`: the NPCs' `IsUsingMob`, the hero's dialog use), baking the world's mob tracks at load |
+| `IMobAnimator` / `IMobAnimatorFactory` (Services/Vobs) | the port; `MobAnimatorFactory` (Adapters/Vob) adds a `MobAnimator` on first use, bound in `ReflexProjectInstaller` |
+| `MobAnimator` (Adapters/Vob) | plays: maps the model's nodes once, samples them on the CPU, transition -> loop -> way back. It doesn't know who uses the mob |
+| `AnimationEffectPlayer` (Adapters/Animations) | the sound and particle events of a track instance - shared with `AnimationSystem` (NPCs) |
+| `AnimationSampling` (Models/Animations) | the frame interpolation of a baked track - shared with `AnimationPoseJob` (NPCs, Burst) |
+
+### Data flow
+
+1. World load: right after the VOBs, while the loading screen is still shown, `WorldScene` awaits
+ `MobAnimationService.WarmWorldMobsAsync`. It bakes every state animation each animated mob model in
+ `GameStateService.VobsInteractable` has (`MobStateNames.IsOwnStateAnimation`: `T_S0_2_S1`, `S_S2`,
+ `T_STAND_2_S0`, ...) and decodes their sounds (P3), one track per step with `FrameSkipperService` yielding in
+ between. The log gives the time and model count, the Editor log the tracks found per model.
+2. An NPC's `UseMob` plays its own transition and calls `OnStateChanged(mob, npc, from, to)`. The mob's transition
+ starts with it, then its loop runs while the NPC stays.
+3. A second NPC on the same mob (another slot) joins: the mob doesn't restart; a user leaving while others stay
+ doesn't stop it. "Others" are read from the existing state, not kept in a list of their own: other NPCs with the
+ mob as `CurrentInteractable` in one of its states (`VobService.GetOtherMobUsers` + `IsUsingMob`), and the hero
+ while his mob dialog is open. An NPC still walking there doesn't count.
+4. The last user leaves (`to == -1`, or `ReleaseMob` -> `Stop` while the NPC is still in a state): a running
+ transition ends, the transition back plays (a lever swings back), the particles fade out, `MobAnimator` turns
+ itself off. `Stop` runs before `ReleaseMob` clears the NPC's mob, so the leaving NPC is excluded by name, not by
+ its cleared state. A loop runs until then - there is no polling: every path that ends a usage goes through
+ `ReleaseMob`.
+
+The hero: a lever or wheel plays only its transition into the new state and rests there (no user). A mob with a
+dialog (anvil, grindstone, rune table) works like for a smith while its dialog is open: `StartHeroUse` before
+`[onStateFunc]_S1`, `StopHeroUse` on `GlobalEventDispatcher.MobDialogEnded` (DialogService raises it where it drops
+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,
+root motion. A mob moves a few rigid nodes (a grindstone's wheel, a lever's arm), so `MobAnimator` samples them on
+the main thread with `AnimationSampling` and writes the node transforms, no blending. It reuses Gothic's clock and
+event timeline (`AnimationTrackInstance`) and the baked tracks of `AnimationService` (`GetTrack(name, mds, null)`,
+`GetSkeleton(mds)`, which also reads a hierarchy from an `.MDL`).
+
+- Node mapping: the skeleton's paths (MDH order, `AnimationTrack.BoneToNode`) below the root node's parent; the root
+ node is found once by its Gothic name (architecture.md rule C exception).
+- Root node: tracks pin the root's X/Z to zero and store Y relative to the rest height. That matches mobs: the mesh
+ builder rests their root node at zero.
+- Sounds: one 3D `AudioSource` on the mob, linear fall-off to the event's range (`FORGE_ANVIL` R:2500 = 25 m), like an
+ NPC's sound.
+- Particles: built once per effect on its first event and replayed (an anvil hit twice per loop doesn't rebuild its
+ sparks), destroyed after fading when the mob rests. Effects not attached to a node are parented to the mob, so they
+ are culled with it.
+- Per frame: `Update` only while a transition or loop plays, nothing allocates. A mob culled with its VOB pauses and
+ goes on when visible again.
+
+Not done (follow-ups): a lever's or wheel's pose after a load or a stop in the middle of a transition (it shows its
+rest pose until used again), idle loops of unused mobs (`S_S0`), a light from the forge (the original has none),
+doors, chests and beds (the VR hand moves them), `oCMobFire` (FireService).
+
+## Where does my change go?
+
+| You want to ... | Go to |
+|---|---|
+| change which mobs play their own animations | `MobAnimationService.IsAnimated` |
+| change which tracks a state change plays, or how users join and leave | `MobAnimationService.OnStateChanged` / `Stop` |
+| change playback or node mapping | `MobAnimator` |
+| change mob sounds or particles (also for NPCs) | `AnimationEffectPlayer` |
+| end an NPC's mob usage on a new path | call `NpcService.ReleaseMob` - never clear `CurrentInteractable` by hand |
+| change what the hero's grab of a mob does | `MobInteractionService.HandleMobGrab` |
+| save more mob state | `MobStatesSaveSection` (`Docs/save-game.md`) |