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..a09602275
--- /dev/null
+++ b/Assets/Gothic-Core/Scripts/Adapters/Animations/AnimationEffectPlayer.cs
@@ -0,0 +1,298 @@
+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;
+ 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.
+ /// Build each effect once and replay it (mobs), see class summary.
+ public AnimationEffectPlayer(Transform boneRoot, Transform stepOrigin, AudioSource stepSound,
+ AudioSource clipSound, bool isReusingPfx)
+ {
+ _boneRoot = boneRoot;
+ _stepOrigin = stepOrigin;
+ _stepSound = stepSound;
+ _clipSound = clipSound;
+ _soundBaseVolume = clipSound != null ? clipSound.volume : 1f;
+ _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(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 dcc5c5551..65596f56c 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, 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 = _audioService.GetSfxRangeMeters(sfx.Name, 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 a8dc6ecc6..9c4cbf814 100644
--- a/Assets/Gothic-Core/Scripts/Adapters/Scenes/WorldScene.cs
+++ b/Assets/Gothic-Core/Scripts/Adapters/Scenes/WorldScene.cs
@@ -47,6 +47,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;
private Vector3? _spawnPosition;
@@ -68,6 +69,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
///
@@ -133,6 +135,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..06d1a7a45
--- /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,
+ 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 be0547dfb..a9568473b 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 6b59adcea..ca1385492 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 beb1ff979..fb9a2f512 100644
--- a/Assets/Gothic-Core/Scripts/Domain/Vobs/VobInitializerDomain.cs
+++ b/Assets/Gothic-Core/Scripts/Domain/Vobs/VobInitializerDomain.cs
@@ -808,7 +808,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 e5ef283d2..b4619ee25 100644
--- a/Assets/Gothic-Core/Scripts/GlobalEventDispatcher.cs
+++ b/Assets/Gothic-Core/Scripts/GlobalEventDispatcher.cs
@@ -340,6 +340,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/Vob/MobStateNames.cs b/Assets/Gothic-Core/Scripts/Models/Vob/MobStateNames.cs
new file mode 100644
index 000000000..8a7519b4b
--- /dev/null
+++ b/Assets/Gothic-Core/Scripts/Models/Vob/MobStateNames.cs
@@ -0,0 +1,80 @@
+using System;
+using System.Linq;
+
+namespace Gothic.Core.Models.Vob
+{
+ ///
+ /// 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 519b69f0f..74035bf12 100644
--- a/Assets/Gothic-Core/Scripts/ReflexProjectInstaller.cs
+++ b/Assets/Gothic-Core/Scripts/ReflexProjectInstaller.cs
@@ -90,6 +90,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
@@ -123,6 +124,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 306e5d4e4..3c2e2f1df 100644
--- a/Assets/Gothic-Core/Scripts/Services/Audio/AudioService.cs
+++ b/Assets/Gothic-Core/Scripts/Services/Audio/AudioService.cs
@@ -1,11 +1,14 @@
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;
@@ -14,8 +17,10 @@
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
{
@@ -26,6 +31,7 @@ public class AudioService
[Inject] private readonly GameStateService _gameStateService;
[Inject] private readonly NpcMeshCullingService _npcMeshCullingService;
[Inject] private readonly GameTimeService _gameTimeService;
+ [Inject] private readonly GroundSoundService _groundSoundService;
// #503: the last music situation, logged when it changes.
private MusicDomain.MusicTagsMode _lastMusicMode;
@@ -41,18 +47,30 @@ public class AudioService
private readonly SoundDomain _soundDomain = new SoundDomain().Inject();
- // Animation sounds that carry further than their *eventSFX range (R:). Finite list, all others keep theirs.
- private static readonly Dictionary _sfxRangeOverridesMeters =
- new(StringComparer.OrdinalIgnoreCase)
- {
- { "HAMMER", 24f }
- };
-
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
//
@@ -178,17 +196,107 @@ public void SetScriptSoundSource(AudioSource audioSource)
}
///
- /// Range (m) in which an animation sound (*eventSFX) is audible: the override of the few sounds that carry
- /// further than Gothic's range, else Gothic's own.
- /// Chosen in play: Fellan's hammering (R:1000 = 10 m) must reach Alwin's sheep pen ~18 m away (his quest asks
- /// whether you hear it); 60 m was heard across the harbour, 24 m reaches the pen. Unity's linear rolloff is
- /// quiet long before Gothic's range is felt; a general rolloff change is a follow-up.
+ /// 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.
///
- public float GetSfxRangeMeters(string sfxName, float gothicRangeMeters)
+ private void ApplySoundVolume()
{
- return _sfxRangeOverridesMeters.TryGetValue(sfxName, out var overrideMeters)
- ? overrideMeters
- : gothicRangeMeters;
+ 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 exactly Gothic's range (R:, in meters). Clip is null if there is nothing to play.
+ ///
+ public AnimationSfx GetAnimationSfx(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);
+ return new AnimationSfx(clip, volume, gothicRangeMeters, false);
}
///
@@ -254,8 +362,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))
{
@@ -275,14 +393,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 9e2c8e3c1..a82f83439 100644
--- a/Assets/Gothic-Core/Scripts/Services/BootstrapService.cs
+++ b/Assets/Gothic-Core/Scripts/Services/BootstrapService.cs
@@ -60,6 +60,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;
@@ -116,6 +117,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/Meshes/ParticleService.cs b/Assets/Gothic-Core/Scripts/Services/Meshes/ParticleService.cs
index 296c62b1e..c87443e78 100644
--- a/Assets/Gothic-Core/Scripts/Services/Meshes/ParticleService.cs
+++ b/Assets/Gothic-Core/Scripts/Services/Meshes/ParticleService.cs
@@ -123,7 +123,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);
@@ -191,7 +191,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 05796abfd..5cba1e86a 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..8d909cec8
--- /dev/null
+++ b/Assets/Gothic-Core/Scripts/Services/Vobs/MobAnimationService.cs
@@ -0,0 +1,302 @@
+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.
+ ///
+ 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);
+ }
+
+ 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 9553fb6b0..b7504963b 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);
}
@@ -252,9 +264,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/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 dde896027..edd522da4 100644
--- a/Assets/Gothic-VR/Scripts/Adapters/Player/VRHeroMovement.cs
+++ b/Assets/Gothic-VR/Scripts/Adapters/Player/VRHeroMovement.cs
@@ -285,7 +285,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/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..34b7c4834 100644
--- a/Assets/Gothic-VR/Scripts/Adapters/Vob/VobItem/VRMouth.cs
+++ b/Assets/Gothic-VR/Scripts/Adapters/Vob/VobItem/VRMouth.cs
@@ -90,7 +90,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,7 +98,7 @@ 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));
@@ -196,9 +196,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 +228,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;
@@ -241,13 +243,13 @@ private IAnimation TryGetUseAnimation(ItemInstance item)
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/VRSpellFx.cs b/Assets/Gothic-VR/Scripts/Adapters/Vob/VobItem/VRSpellFx.cs
index ba14a048c..55c1500f3 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)
@@ -413,7 +412,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).
@@ -451,6 +450,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();
}
@@ -471,14 +477,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/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/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-12-03-sound-effects-volume.md b/Docs/adr/2026-12-03-sound-effects-volume.md
new file mode 100644
index 000000000..64e2f013d
--- /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. **No per-sound range overrides.** 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). Hammering keeps its Gothic range of 10 m. An earlier override raised hammering to 24 m so Fellan's hammering would reach Alwin's sheep pen about 18 m away; that override was removed. Not chosen: 60 m, which was heard across the whole harbour. Whether the original engine fades more gently than a linear fade is open in issue #569.
+
+## 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. Hammering is heard up to 10 m, so it no longer reaches Alwin's sheep pen about 18 m away; whether the original fades more gently is open in issue #569.
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..88c91926a
--- /dev/null
+++ b/Docs/mobs.md
@@ -0,0 +1,116 @@
+# 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.
+
+### 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`) |