From 5e903d62bedfb6142477d1d3344e365ad442158a Mon Sep 17 00:00:00 2001 From: BoroBongo Date: Wed, 25 Nov 2026 22:58:33 +0000 Subject: [PATCH 01/29] refactor: animation sound/particle events and bone sampling are reusable outside AnimationSystem - no behaviour change - AnimationEffectPlayer (Adapters/Animations) plays a track instance's *eventSFX/*eventPFX/*eventPFXStop; AnimationSystem owns one (one-off particles, as before), mobs will own one that builds each effect once and replays it - AnimationSampling (Models/Animations, static, Burst) holds the frame interpolation and Nlerp of AnimationPoseJob - IVirtualObject.IsHingeMob(): the door/chest rule of the VR grab (MobInteractionService.ShouldHandleGrab) in one place Co-Authored-By: Claude Opus 5.5 --- .../Animations/AnimationEffectPlayer.cs | 289 ++++++++++++++++++ .../Adapters/Animations/AnimationSystem.cs | 126 +------- .../Scripts/Extensions/ZenKitExtension.cs | 9 + .../Models/Animations/AnimationPoseJob.cs | 34 +-- .../Models/Animations/AnimationSampling.cs | 58 ++++ .../Services/Vobs/MobInteractionService.cs | 2 +- 6 files changed, 372 insertions(+), 146 deletions(-) create mode 100644 Assets/Gothic-Core/Scripts/Adapters/Animations/AnimationEffectPlayer.cs create mode 100644 Assets/Gothic-Core/Scripts/Models/Animations/AnimationSampling.cs 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..e0833ef99 --- /dev/null +++ b/Assets/Gothic-Core/Scripts/Adapters/Animations/AnimationEffectPlayer.cs @@ -0,0 +1,289 @@ +using System.Collections.Generic; +using Gothic.Core.Domain.Audio; +using Gothic.Core.Extensions; +using Gothic.Core.Logging; +using Gothic.Core.Manager; +using Gothic.Core.Models.Animations; +using Gothic.Core.Services.Audio; +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; + [Inject] private readonly GroundSoundService _groundSoundService; + + // *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 _sound; + 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 *eventSFX sounds (one at a time, like the engine's model sound). + /// Build each effect once and replay it (mobs), see class summary. + public AnimationEffectPlayer(Transform boneRoot, Transform stepOrigin, AudioSource sound, bool isReusingPfx) + { + _boneRoot = boneRoot; + _stepOrigin = stepOrigin; + _sound = sound; + _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) + { + // 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(GroundSoundDomain.GroundEventPrefix)) + { + if (!_groundSoundService.IsEnabled) + continue; + var stepName = _groundSoundService.GetSoundName( + sfx.Name.Substring(GroundSoundDomain.GroundEventPrefix.Length), _stepOrigin.position); + var stepClip = _audioService.GetRandomSoundClip(stepName); + if (stepClip != null) + _sound.PlayOneShot(stepClip); + continue; + } + + var clip = _audioService.GetRandomSoundClip(sfx.Name); + _sound.clip = clip; + _sound.maxDistance = _audioService.GetSfxRangeMeters(sfx.Name, sfx.Range.ToMeter()); + _sound.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/AnimationSystem.cs b/Assets/Gothic-Core/Scripts/Adapters/Animations/AnimationSystem.cs index dcc5c5551..c3b20f852 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, 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/Extensions/ZenKitExtension.cs b/Assets/Gothic-Core/Scripts/Extensions/ZenKitExtension.cs index e7de044f3..758712560 100644 --- a/Assets/Gothic-Core/Scripts/Extensions/ZenKitExtension.cs +++ b/Assets/Gothic-Core/Scripts/Extensions/ZenKitExtension.cs @@ -128,6 +128,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/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/Services/Vobs/MobInteractionService.cs b/Assets/Gothic-Core/Scripts/Services/Vobs/MobInteractionService.cs index 9553fb6b0..ad02f21dd 100644 --- a/Assets/Gothic-Core/Scripts/Services/Vobs/MobInteractionService.cs +++ b/Assets/Gothic-Core/Scripts/Services/Vobs/MobInteractionService.cs @@ -45,7 +45,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(); } /// From f855023417c10bd76706761ca2185c99067ca094 Mon Sep 17 00:00:00 2001 From: BoroBongo Date: Wed, 25 Nov 2026 22:59:29 +0000 Subject: [PATCH 02/29] refactor: an NPC's mob usage ends in one place (NpcService.ReleaseMob) - no behaviour change UseMob's last back transition, AI_StandUp(Quick) and AiHandler.ReEnableNpc cleared the mob, slot, state and body state each on their own. The mob's own animation will stop there. Co-Authored-By: Claude Opus 5.5 --- .../Scripts/Adapters/Npc/AiHandler.cs | 5 +---- .../Npc/Actions/AnimationActions/StandUp.cs | 7 +------ .../Npc/Actions/AnimationActions/UseMob.cs | 5 ++--- .../Scripts/Services/Npc/NpcService.cs | 17 +++++++++++++++++ 4 files changed, 21 insertions(+), 13 deletions(-) diff --git a/Assets/Gothic-Core/Scripts/Adapters/Npc/AiHandler.cs b/Assets/Gothic-Core/Scripts/Adapters/Npc/AiHandler.cs index 3290640ef..30ff2424e 100644 --- a/Assets/Gothic-Core/Scripts/Adapters/Npc/AiHandler.cs +++ b/Assets/Gothic-Core/Scripts/Adapters/Npc/AiHandler.cs @@ -798,10 +798,7 @@ public void ReEnableNpc() if (PrefabProps.CurrentInteractable != null) PrefabProps.CurrentInteractable.MobState = -1; - PrefabProps.CurrentInteractable = null; - PrefabProps.CurrentInteractableSlot = null; - Properties.CurrentInteractableStateId = -1; - Properties.BodyState = VmGothicEnums.BodyState.BsStand; + _npcService.ReleaseMob(NpcData); } // WayNet handling 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..e3bd317c7 100644 --- a/Assets/Gothic-Core/Scripts/Domain/Npc/Actions/AnimationActions/UseMob.cs +++ b/Assets/Gothic-Core/Scripts/Domain/Npc/Actions/AnimationActions/UseMob.cs @@ -15,6 +15,7 @@ namespace Gothic.Core.Domain.Npc.Actions.AnimationActions public class UseMob : AbstractWalkAnimationAction2 { [Inject] private readonly NpcHelperService _npcHelperService; + [Inject] private readonly NpcService _npcService; private const string _mobTransitionAnimationString = "T_{0}{1}{2}_2_{3}"; private const string _mobLoopAnimationString = "S_{0}{1}S{2}"; @@ -191,10 +192,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); } diff --git a/Assets/Gothic-Core/Scripts/Services/Npc/NpcService.cs b/Assets/Gothic-Core/Scripts/Services/Npc/NpcService.cs index 78a44b9ea..613257355 100644 --- a/Assets/Gothic-Core/Scripts/Services/Npc/NpcService.cs +++ b/Assets/Gothic-Core/Scripts/Services/Npc/NpcService.cs @@ -896,6 +896,23 @@ 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. The one place + /// where a mob usage ends - after the last back transition of AI_UseMob(-1), at AI_StandUp(Quick) and when the + /// NPC starts over (AiHandler.ReEnableNpc). + /// + public void ReleaseMob(NpcContainer npc) + { + var prefabProps = npc?.PrefabProps; + if (prefabProps == null) + return; + + 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) From ddfbb62a2de1a5f509965a20deadf39ce50608e6 Mon Sep 17 00:00:00 2001 From: BoroBongo Date: Wed, 25 Nov 2026 23:02:19 +0000 Subject: [PATCH 03/29] feat: mob state animations are looked up and baked while the world loads (MobAnimationService) - MobAnimationService (Services/Vobs): which mobs animate (an oCMobInter family member with an .MDS visual - no doors, chests, beds, fireplaces), the track names of a state change (T_S0_2_S1, S_S1, T_S1_2_S0) in the mob's own model script, one-shot logs for missing models/tracks (missing tracks Editor only) - At WorldSceneLoaded the world's mob models are baked and their sounds decoded (P3), with an Editor log of the tracks found per model - IMobAnimator / IMobAnimatorFactory: the port the MobAnimator adapter will implement - AnimationService.GetSkeleton also takes the hierarchy from an .MDL (hierarchy and mesh in one file), like the mesh builder Co-Authored-By: Claude Opus 5.5 --- .../Scripts/ReflexProjectInstaller.cs | 1 + .../Scripts/Services/BootstrapService.cs | 2 + .../Scripts/Services/Npc/AnimationService.cs | 8 +- .../Scripts/Services/Vobs/IMobAnimator.cs | 40 +++++ .../Services/Vobs/IMobAnimatorFactory.cs | 21 +++ .../Services/Vobs/MobAnimationService.cs | 169 ++++++++++++++++++ 6 files changed, 239 insertions(+), 2 deletions(-) create mode 100644 Assets/Gothic-Core/Scripts/Services/Vobs/IMobAnimator.cs create mode 100644 Assets/Gothic-Core/Scripts/Services/Vobs/IMobAnimatorFactory.cs create mode 100644 Assets/Gothic-Core/Scripts/Services/Vobs/MobAnimationService.cs diff --git a/Assets/Gothic-Core/Scripts/ReflexProjectInstaller.cs b/Assets/Gothic-Core/Scripts/ReflexProjectInstaller.cs index 519b69f0f..cc3a002a2 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 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/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/Vobs/IMobAnimator.cs b/Assets/Gothic-Core/Scripts/Services/Vobs/IMobAnimator.cs new file mode 100644 index 000000000..86534a389 --- /dev/null +++ b/Assets/Gothic-Core/Scripts/Services/Vobs/IMobAnimator.cs @@ -0,0 +1,40 @@ +using Gothic.Core.Models.Animations; +using Gothic.Core.Models.Container; + +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. Docs/mobs.md. + /// + public interface IMobAnimator + { + /// + /// The mob state the animation is in or plays towards. 0 while the mob rests. + /// + int State { get; } + + /// + /// NPCs (or the hero) using the mob right now - several on a mob with several slots. + /// + int UserCount { get; } + + bool HasUser(NpcContainer user); + + void AddUser(NpcContainer user); + + void RemoveUser(NpcContainer user); + + /// + /// 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/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/MobAnimationService.cs b/Assets/Gothic-Core/Scripts/Services/Vobs/MobAnimationService.cs new file mode 100644 index 000000000..359c9f47a --- /dev/null +++ b/Assets/Gothic-Core/Scripts/Services/Vobs/MobAnimationService.cs @@ -0,0 +1,169 @@ +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Text; +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.Services.Npc; +using JetBrains.Annotations; +using Reflex.Attributes; +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 GameStateService _gameStateService; + + private const string _mdsExtension = ".MDS"; + private const string _standStateName = "STAND"; + + // The states a used mob plays in nearly every model script - looked up at world load (see WarmWorldMobs). + private static readonly (int From, int To)[] _warmedStateChanges = { (0, 1), (1, 0) }; + private static readonly int[] _warmedLoops = { 1 }; + + // 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); + + + public void Init() + { + GlobalEventDispatcher.WorldSceneLoaded.AddListener(WarmWorldMobs); + } + + /// + /// 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; + + var visualName = vob.Visual?.Name; + return !string.IsNullOrEmpty(visualName) && + visualName.EndsWith(_mdsExtension, StringComparison.OrdinalIgnoreCase); + } + + /// + /// The name of a mob state inside its animations: -1 (not used) is STAND, the others S0, S1, ... + /// + private static string GetStateName(int state) + { + return state < 0 ? _standStateName : "S" + state; + } + + private static string GetTransitionName(int from, int to) + { + return "T_" + GetStateName(from) + "_2_" + GetStateName(to); + } + + private static string GetLoopName(int state) + { + return "S_" + GetStateName(state); + } + + /// + /// 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): 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). + /// + private void WarmWorldMobs() + { + var watch = Stopwatch.StartNew(); + var modelCount = 0; + foreach (var mobs in _gameStateService.VobsInteractable.Values) + { + foreach (var mob in mobs) + { + if (!IsAnimated(mob)) + continue; + + var visualName = mob.Vob.Visual.Name; + if (!_warmedModels.Add(visualName)) + continue; + + WarmModel(visualName); + modelCount++; + } + } + + if (modelCount > 0) + Logger.Log($"[MobAnimation] Animations of {modelCount} mob models baked in " + + $"{watch.ElapsedMilliseconds} ms.", LogCat.Vob); + } + + private void WarmModel(string visualName) + { + if (GetSkeleton(visualName) == null) + return; + + var found = new StringBuilder(); + foreach (var (from, to) in _warmedStateChanges) + WarmTrack(visualName, GetTransitionName(from, to), found); + foreach (var state in _warmedLoops) + WarmTrack(visualName, GetLoopName(state), found); + + var foundNames = found.Length > 0 ? found.ToString() : "no state animations"; + Logger.LogEditor($"[MobAnimation] {visualName}: {foundNames}", LogCat.Vob); + } + + 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); + } + } +} From 313465c4f06d9cac403757ab3fb5068879492bf1 Mon Sep 17 00:00:00 2001 From: BoroBongo Date: Wed, 25 Nov 2026 23:05:13 +0000 Subject: [PATCH 04/29] feat: a mob can play its own state animation with its sounds and particles (MobAnimator) - nothing calls it yet - MobAnimator (Adapters/Vob, added on first use by MobAnimatorFactory): maps the model's nodes once, samples the rigid nodes on the CPU (AnimationSampling), plays a transition then the state's loop, events through its own AnimationEffectPlayer (one 3D sound, linear to the event's range; particles built once and replayed); Update only while something plays - users per mob (slots): the last one leaving lets a running transition end, plays the way back (T_S1_2_S0) and rests - safety net once per loop round: a user that is gone, culled, dead or no longer at the mob stops it - MobAnimationService: OnStateChanged / Stop / StartHeroUse / StopHeroUse / IsStillUsing; IMobAnimatorFactory bound in ReflexProjectInstaller Co-Authored-By: Claude Opus 5.5 --- .../Scripts/Adapters/Vob/MobAnimator.cs | 280 ++++++++++++++++++ .../Adapters/Vob/MobAnimatorFactory.cs | 35 +++ .../Scripts/ReflexProjectInstaller.cs | 1 + .../Services/Vobs/MobAnimationService.cs | 122 ++++++++ 4 files changed, 438 insertions(+) create mode 100644 Assets/Gothic-Core/Scripts/Adapters/Vob/MobAnimator.cs create mode 100644 Assets/Gothic-Core/Scripts/Adapters/Vob/MobAnimatorFactory.cs 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..80e648f80 --- /dev/null +++ b/Assets/Gothic-Core/Scripts/Adapters/Vob/MobAnimator.cs @@ -0,0 +1,280 @@ +using System.Collections.Generic; +using Gothic.Core.Adapters.Animations; +using Gothic.Core.Extensions; +using Gothic.Core.Logging; +using Gothic.Core.Models.Animations; +using Gothic.Core.Models.Container; +using Gothic.Core.Services.Vobs; +using Reflex.Attributes; +using UnityEngine; +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. + /// + public class MobAnimator : MonoBehaviour, IMobAnimator + { + [Inject] private readonly MobAnimationService _mobAnimationService; + + private VobContainer _mob; + // The mob's node transforms, index == mdh node index (AnimationTrack.BoneToNode). Null if not found. + private Transform[] _nodes; + private AnimationEffectPlayer _effectPlayer; + private readonly List _users = new(); + + private AnimationTrackInstance _current; + private bool _isCurrentLoop; + private float _previousTime; + // 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; } + + public int UserCount => _users.Count; + + + /// + /// 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). + /// + public void Init(VobContainer mob, AnimationSkeleton skeleton) + { + _mob = mob; + MapNodes(skeleton); + + var sound = gameObject.AddComponent(); + sound.playOnAwake = false; + sound.spatialBlend = 1f; + sound.rolloffMode = AudioRolloffMode.Linear; + sound.minDistance = 0f; + _effectPlayer = new AnimationEffectPlayer(transform, transform, sound, isReusingPfx: true).Inject(); + + enabled = false; + } + + /// + /// 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) + 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 bool HasUser(NpcContainer user) + { + return _users.Contains(user); + } + + public void AddUser(NpcContainer user) + { + if (user != null && !_users.Contains(user)) + _users.Add(user); + } + + public void RemoveUser(NpcContainer user) + { + _users.Remove(user); + } + + 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(); + } + + 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(); + } + + private void StartTrack(AnimationTrack track, bool isLoop) + { + _current = new AnimationTrackInstance(track); + _isCurrentLoop = isLoop; + _previousTime = 0f; + enabled = true; + } + + /// + /// Nothing plays any more: the nodes keep their last pose, the particles fade out, Update is off. + /// + private void Rest() + { + _current = null; + _isCurrentLoop = false; + _nextLoop = null; + _isStopPending = false; + _pendingBack = null; + _effectPlayer?.StopAllPfx(); + 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 AnimationState.BlendOut or AnimationState.Stop) + { + if (_isCurrentLoop) + OnLoopWrapped(restartTrack: true); + else + OnTransitionEnded(); + return; + } + + if (_isCurrentLoop && _current.CurrentTime < _previousTime) + { + OnLoopWrapped(restartTrack: false); + return; + } + + _previousTime = _current.CurrentTime; + } + + private void OnTransitionEnded() + { + if (_pendingBack != null) + { + var back = _pendingBack; + _pendingBack = null; + StartTrack(back, isLoop: false); + return; + } + + if (_isStopPending || _nextLoop == null) + { + Rest(); + return; + } + + StartTrack(_nextLoop, isLoop: true); + } + + /// + /// The safety net, once per loop round (not per frame): a user who left without the mob being released (a + /// path that doesn't end the usage, a culled or killed NPC) stops the animation. + /// + private void OnLoopWrapped(bool restartTrack) + { + if (restartTrack) + StartTrack(_current.Track, isLoop: true); + else + _previousTime = _current.CurrentTime; + + for (var i = _users.Count - 1; i >= 0; i--) + { + // Stop() removes exactly this user, the ones below stay at their index. + var user = _users[i]; + if (_mobAnimationService.IsStillUsing(_mob, user)) + continue; + + Logger.Log($"[MobAnimation] {name}: a user left without releasing it - stopping.", LogCat.Vob); + _mobAnimationService.Stop(_mob, user); + } + + if (_users.Count == 0 && _isCurrentLoop) + Rest(); + } + + 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/MobAnimatorFactory.cs b/Assets/Gothic-Core/Scripts/Adapters/Vob/MobAnimatorFactory.cs new file mode 100644 index 000000000..5497bd0f8 --- /dev/null +++ b/Assets/Gothic-Core/Scripts/Adapters/Vob/MobAnimatorFactory.cs @@ -0,0 +1,35 @@ +using Gothic.Core.Extensions; +using Gothic.Core.Models.Animations; +using Gothic.Core.Models.Container; +using Gothic.Core.Services.Vobs; + +namespace Gothic.Core.Adapters.Vob +{ + public class MobAnimatorFactory : IMobAnimatorFactory + { + 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) + return null; + + animator = mob.Go.AddComponent().Inject(); + animator.Init(mob, skeleton); + 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/ReflexProjectInstaller.cs b/Assets/Gothic-Core/Scripts/ReflexProjectInstaller.cs index cc3a002a2..74035bf12 100644 --- a/Assets/Gothic-Core/Scripts/ReflexProjectInstaller.cs +++ b/Assets/Gothic-Core/Scripts/ReflexProjectInstaller.cs @@ -124,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/Vobs/MobAnimationService.cs b/Assets/Gothic-Core/Scripts/Services/Vobs/MobAnimationService.cs index 359c9f47a..ace397f74 100644 --- a/Assets/Gothic-Core/Scripts/Services/Vobs/MobAnimationService.cs +++ b/Assets/Gothic-Core/Scripts/Services/Vobs/MobAnimationService.cs @@ -10,6 +10,7 @@ using Gothic.Core.Services.Npc; using JetBrains.Annotations; using Reflex.Attributes; +using ZenKit.Daedalus; using ZenKit.Vobs; using Logger = Gothic.Core.Logging.Logger; @@ -27,6 +28,7 @@ public class MobAnimationService [Inject] private readonly AnimationService _animationService; [Inject] private readonly AudioService _audioService; [Inject] private readonly GameStateService _gameStateService; + [Inject] private readonly IMobAnimatorFactory _mobAnimatorFactory; private const string _mdsExtension = ".MDS"; private const string _standStateName = "STAND"; @@ -41,6 +43,10 @@ public class MobAnimationService 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() { @@ -63,6 +69,122 @@ public bool IsAnimated([CanBeNull] VobContainer mob) visualName.EndsWith(_mdsExtension, StringComparison.OrdinalIgnoreCase); } + /// + /// 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. + /// + public void OnStateChanged([CanBeNull] VobContainer mob, [CanBeNull] NpcContainer user, int from, int to) + { + if (!IsAnimated(mob)) + return; + + if (to < 0) + { + Stop(mob, user); + return; + } + + var animator = _mobAnimatorFactory.TryGet(mob); + if (user != null && animator != null && HasOtherUser(animator, user) && to <= animator.State) + { + animator.AddUser(user); + return; + } + + var visualName = mob.Vob.Visual.Name; + var skeleton = GetSkeleton(visualName); + if (skeleton == null) + return; + + var transition = GetTrack(visualName, GetTransitionName(from, to)); + var loop = user != null ? GetTrack(visualName, GetLoopName(to)) : null; + if (transition == null && loop == null) + return; + + animator ??= _mobAnimatorFactory.GetOrCreate(mob, skeleton); + if (animator == null) + return; + + animator.AddUser(user); + animator.Play(to, transition, loop); + Logger.LogEditor($"[MobAnimation] {mob.Vob.Name} ({visualName}): {GetStateName(from)} -> " + + $"{GetStateName(to)} by {user?.Instance?.GetName(NpcNameSlot.Slot0) ?? "nobody"}", + LogCat.Vob); + } + + /// + /// The user doesn't use the mob any more. The last one stops its animation: a running transition ends, the + /// transition back plays (T_S1_2_S0, a lever swings back), then the mob rests. + /// + public void Stop([CanBeNull] VobContainer mob, [CanBeNull] NpcContainer user) + { + if (mob == null || user == null) + return; + + var animator = _mobAnimatorFactory.TryGet(mob); + if (animator == null || !animator.HasUser(user)) + return; + + animator.RemoveUser(user); + if (animator.UserCount > 0) + return; + + var state = animator.State; + var back = state > 0 ? GetTrack(mob.Vob.Visual.Name, GetTransitionName(state, state - 1)) : null; + animator.PlayBackAndStop(back); + Logger.LogEditor($"[MobAnimation] {mob.Vob.Name}: last user left - stopping from {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; + Stop(mob, hero); + } + + /// + /// The user still uses the mob: the hero while his mob dialog is open, an NPC while it's there (active, alive, + /// the mob is its CurrentInteractable). MobAnimator asks once per loop round. + /// + public bool IsStillUsing([CanBeNull] VobContainer mob, [CanBeNull] NpcContainer user) + { + if (mob == null || user?.Props == null || user.Props.IsDead) + return false; + + if (mob == _heroMob && user == _hero) + return true; + + return user.Go != null && user.Go.activeInHierarchy && user.PrefabProps?.CurrentInteractable == mob; + } + + private static bool HasOtherUser(IMobAnimator animator, NpcContainer user) + { + return animator.UserCount > (animator.HasUser(user) ? 1 : 0); + } + /// /// The name of a mob state inside its animations: -1 (not used) is STAND, the others S0, S1, ... /// From ce77fa613fd2edafa75523528b570dcc78b5c772 Mon Sep 17 00:00:00 2001 From: BoroBongo Date: Wed, 25 Nov 2026 23:07:47 +0000 Subject: [PATCH 05/29] feat: mobs play their own state animations, sounds and particles while an NPC or the hero uses them - the smithy rings, sparks and steams - UseMob: every transition of the user also plays the mob's own (T_S0_2_S1 then S_S1, ...) - NpcService.ReleaseMob stops it; ReleaseMob now also runs at death (NpcDeathDomain.Die - a killed smith frees the anvil) and when a culled NPC is moved to its routine waypoint (AiHandler.DisableNpc, like ReEnableNpc: mob state -1) - the hero: levers/wheels swing into their new state (trigger branch 0 <-> 1); a mob with a dialog (anvil, grindstone, rune table) works while its dialog is open (new GlobalEventDispatcher.MobDialogEnded, raised where DialogService drops the mob dialog anchor); without a dialog (the forge's item swap) it works once, there and back - the safety net also stops for a knocked out user (IsDown) Co-Authored-By: Claude Opus 5.5 --- .../Scripts/Adapters/Npc/AiHandler.cs | 30 ++++++++++++------- .../Npc/Actions/AnimationActions/UseMob.cs | 5 ++++ .../Scripts/Domain/Npc/NpcDeathDomain.cs | 4 +++ .../Scripts/GlobalEventDispatcher.cs | 4 +++ .../Scripts/Services/Npc/NpcService.cs | 10 +++++-- .../Scripts/Services/Player/DialogService.cs | 16 ++++++---- .../Services/Vobs/MobAnimationService.cs | 7 +++-- .../Services/Vobs/MobInteractionService.cs | 20 ++++++++++++- 8 files changed, 74 insertions(+), 22 deletions(-) diff --git a/Assets/Gothic-Core/Scripts/Adapters/Npc/AiHandler.cs b/Assets/Gothic-Core/Scripts/Adapters/Npc/AiHandler.cs index 30ff2424e..9adc6c201 100644 --- a/Assets/Gothic-Core/Scripts/Adapters/Npc/AiHandler.cs +++ b/Assets/Gothic-Core/Scripts/Adapters/Npc/AiHandler.cs @@ -790,16 +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; - - _npcService.ReleaseMob(NpcData); - } + LeaveMobToStartOver(); // WayNet handling // Nothing to do -> Even a despawned NPC (based on culling) needs to stick with its WPs/FPs. @@ -882,11 +873,30 @@ 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; + + if (PrefabProps.CurrentInteractable != null) + PrefabProps.CurrentInteractable.MobState = -1; + + _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/Domain/Npc/Actions/AnimationActions/UseMob.cs b/Assets/Gothic-Core/Scripts/Domain/Npc/Actions/AnimationActions/UseMob.cs index e3bd317c7..ce07933c5 100644 --- a/Assets/Gothic-Core/Scripts/Domain/Npc/Actions/AnimationActions/UseMob.cs +++ b/Assets/Gothic-Core/Scripts/Domain/Npc/Actions/AnimationActions/UseMob.cs @@ -3,6 +3,7 @@ using Gothic.Core.Models.Container; using Gothic.Core.Models.Vm; using Gothic.Core.Services.Npc; +using Gothic.Core.Services.Vobs; using Gothic.Core.Extensions; using JetBrains.Annotations; using MyBox; @@ -16,6 +17,7 @@ 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}"; @@ -354,6 +356,9 @@ private void PlayTransitionAnimation() _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/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/Services/Npc/NpcService.cs b/Assets/Gothic-Core/Scripts/Services/Npc/NpcService.cs index 613257355..ad85d7a81 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. @@ -897,9 +898,10 @@ 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. The one place - /// where a mob usage ends - after the last back transition of AI_UseMob(-1), at AI_StandUp(Quick) and when the - /// NPC starts over (AiHandler.ReEnableNpc). + /// 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 and when the NPC starts over (culled, + /// re-enabled: AiHandler). /// public void ReleaseMob(NpcContainer npc) { @@ -907,6 +909,8 @@ public void ReleaseMob(NpcContainer npc) if (prefabProps == null) return; + _mobAnimationService.Stop(prefabProps.CurrentInteractable, npc); + prefabProps.CurrentInteractable = null; prefabProps.CurrentInteractableSlot = null; npc.Props.CurrentInteractableStateId = -1; 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/Vobs/MobAnimationService.cs b/Assets/Gothic-Core/Scripts/Services/Vobs/MobAnimationService.cs index ace397f74..7656885c3 100644 --- a/Assets/Gothic-Core/Scripts/Services/Vobs/MobAnimationService.cs +++ b/Assets/Gothic-Core/Scripts/Services/Vobs/MobAnimationService.cs @@ -51,6 +51,7 @@ public class MobAnimationService public void Init() { GlobalEventDispatcher.WorldSceneLoaded.AddListener(WarmWorldMobs); + GlobalEventDispatcher.MobDialogEnded.AddListener(StopHeroUse); } /// @@ -166,12 +167,12 @@ public void StopHeroUse() } /// - /// The user still uses the mob: the hero while his mob dialog is open, an NPC while it's there (active, alive, - /// the mob is its CurrentInteractable). MobAnimator asks once per loop round. + /// The user still uses the mob: the hero while his mob dialog is open, an NPC while it's there (active, not + /// dead or knocked out, the mob is its CurrentInteractable). MobAnimator asks once per loop round. /// public bool IsStillUsing([CanBeNull] VobContainer mob, [CanBeNull] NpcContainer user) { - if (mob == null || user?.Props == null || user.Props.IsDead) + if (mob == null || user?.Props == null || user.IsDown()) return false; if (mob == _heroMob && user == _hero) diff --git a/Assets/Gothic-Core/Scripts/Services/Vobs/MobInteractionService.cs b/Assets/Gothic-Core/Scripts/Services/Vobs/MobInteractionService.cs index ad02f21dd..fad14f860 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. @@ -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,12 @@ 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). + _mobAnimationService.StartHeroUse(loader.Container, hero); + _vmService.CallAsHero(functionName, LogCat.Dialog); Logger.Log($"[MobDialog] Called '{functionName}' for '{loader.name}'.", LogCat.Dialog); } @@ -252,9 +263,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) From 36ec125a4fe110e963bd337f049171d110c3c5ee Mon Sep 17 00:00:00 2001 From: BoroBongo Date: Wed, 25 Nov 2026 23:09:11 +0000 Subject: [PATCH 06/29] docs: mobs - who writes the mob state, who uses a mob, saving, the mobs' own animations (Docs/mobs.md, ADR) - Docs/mobs.md: MobState writers (UseMob, AiHandler, MobInteractionService, VRMobHinge, MobStatesSaveSection), NpcService.ReleaseMob as the one end of a usage, the animation classes and data flow, the light player, follow-ups, a "where does my change go" table - architecture.md: "Where does my code go?" row and principle 8 point to Docs/mobs.md - ADR 2026-11-25-mob-animations: why mobs animate, the hero's smithy, no doors/chests/beds, no forge light, no switch, the own light player (not AnimationSystem per mob) Co-Authored-By: Claude Opus 5.5 --- Docs/adr/2026-11-25-mob-animations.md | 27 +++++++ Docs/architecture.md | 3 +- Docs/mobs.md | 108 ++++++++++++++++++++++++++ 3 files changed, 137 insertions(+), 1 deletion(-) create mode 100644 Docs/adr/2026-11-25-mob-animations.md create mode 100644 Docs/mobs.md 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/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..a7428cef2 --- /dev/null +++ b/Docs/mobs.md @@ -0,0 +1,108 @@ +# 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 | +| `AiHandler` (`LeaveMobToStartOver`) | an NPC starts over at its routine waypoint (culled out, 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 and stops the mob's +animation. 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) and when the NPC starts over (`AiHandler`). + +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, users, the hero's dialog use, the safety net rule (`IsStillUsing`), 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, the users, the per-loop safety net | +| `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: `MobAnimationService` bakes `T_S0_2_S1`, `S_S1`, `T_S1_2_S0` of every animated mob model in + `GameStateService.VobsInteractable` and decodes their sounds (P3). The Editor log lists 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. +4. The last user leaves (`to == -1`, or `ReleaseMob` -> `Stop`): a running transition ends, the transition back plays + (a lever swings back), the particles fade out, `MobAnimator` turns itself off. +5. Safety net: once per loop round (never per frame) `MobAnimator` asks `IsStillUsing` for each user. A user that is + gone, culled, dead, knocked out or at another mob is stopped - a path that ends a usage without `ReleaseMob` + can't leave an anvil sparking forever. + +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, node mapping or the safety net round | `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`) | From a1d6059663adc83a9255a307ebe2d0b0f5a14ec7 Mon Sep 17 00:00:00 2001 From: BoroBongo Date: Wed, 25 Nov 2026 23:12:35 +0000 Subject: [PATCH 07/29] chore: meta files of the new mob animation scripts (generated by Unity on import) Co-Authored-By: Claude Opus 5.5 --- .../Scripts/Adapters/Animations/AnimationEffectPlayer.cs.meta | 2 ++ Assets/Gothic-Core/Scripts/Adapters/Vob/MobAnimator.cs.meta | 2 ++ .../Gothic-Core/Scripts/Adapters/Vob/MobAnimatorFactory.cs.meta | 2 ++ .../Scripts/Models/Animations/AnimationSampling.cs.meta | 2 ++ Assets/Gothic-Core/Scripts/Services/Vobs/IMobAnimator.cs.meta | 2 ++ .../Scripts/Services/Vobs/IMobAnimatorFactory.cs.meta | 2 ++ .../Scripts/Services/Vobs/MobAnimationService.cs.meta | 2 ++ 7 files changed, 14 insertions(+) create mode 100644 Assets/Gothic-Core/Scripts/Adapters/Animations/AnimationEffectPlayer.cs.meta create mode 100644 Assets/Gothic-Core/Scripts/Adapters/Vob/MobAnimator.cs.meta create mode 100644 Assets/Gothic-Core/Scripts/Adapters/Vob/MobAnimatorFactory.cs.meta create mode 100644 Assets/Gothic-Core/Scripts/Models/Animations/AnimationSampling.cs.meta create mode 100644 Assets/Gothic-Core/Scripts/Services/Vobs/IMobAnimator.cs.meta create mode 100644 Assets/Gothic-Core/Scripts/Services/Vobs/IMobAnimatorFactory.cs.meta create mode 100644 Assets/Gothic-Core/Scripts/Services/Vobs/MobAnimationService.cs.meta 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/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.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/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/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.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.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 From 7744022370f550a2501fa68127fc4302da2e3596 Mon Sep 17 00:00:00 2001 From: BoroBongo Date: Wed, 25 Nov 2026 23:35:45 +0000 Subject: [PATCH 08/29] fix: a mob's sound stops with it when the last user leaves - the forge fire no longer roars on after the smith walked away A lever pull without a user still lets its sound play out. Co-Authored-By: Claude Opus 5.5 --- .../Scripts/Adapters/Vob/MobAnimator.cs | 29 +++++++++++-------- 1 file changed, 17 insertions(+), 12 deletions(-) diff --git a/Assets/Gothic-Core/Scripts/Adapters/Vob/MobAnimator.cs b/Assets/Gothic-Core/Scripts/Adapters/Vob/MobAnimator.cs index 80e648f80..06ce24153 100644 --- a/Assets/Gothic-Core/Scripts/Adapters/Vob/MobAnimator.cs +++ b/Assets/Gothic-Core/Scripts/Adapters/Vob/MobAnimator.cs @@ -32,6 +32,7 @@ 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 readonly List _users = new(); private AnimationTrackInstance _current; @@ -57,14 +58,14 @@ public void Init(VobContainer mob, AnimationSkeleton skeleton) _mob = mob; MapNodes(skeleton); - var sound = gameObject.AddComponent(); - sound.playOnAwake = false; - sound.spatialBlend = 1f; - sound.rolloffMode = AudioRolloffMode.Linear; - sound.minDistance = 0f; - _effectPlayer = new AnimationEffectPlayer(transform, transform, sound, isReusingPfx: true).Inject(); + _sound = gameObject.AddComponent(); + _sound.playOnAwake = false; + _sound.spatialBlend = 1f; + _sound.rolloffMode = AudioRolloffMode.Linear; + _sound.minDistance = 0f; + _effectPlayer = new AnimationEffectPlayer(transform, transform, _sound, isReusingPfx: true).Inject(); - enabled = false; + Rest(isSoundStopped: true); } /// @@ -127,7 +128,7 @@ public void Play(int state, AnimationTrack transition, AnimationTrack loop) else if (loop != null) StartTrack(loop, isLoop: true); else - Rest(); + Rest(isSoundStopped: true); } public void PlayBackAndStop(AnimationTrack backTransition) @@ -146,7 +147,7 @@ public void PlayBackAndStop(AnimationTrack backTransition) if (backTransition != null) StartTrack(backTransition, isLoop: false); else - Rest(); + Rest(isSoundStopped: true); } private void StartTrack(AnimationTrack track, bool isLoop) @@ -159,8 +160,10 @@ private void StartTrack(AnimationTrack track, bool isLoop) /// /// 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() + private void Rest(bool isSoundStopped) { _current = null; _isCurrentLoop = false; @@ -168,6 +171,8 @@ private void Rest() _isStopPending = false; _pendingBack = null; _effectPlayer?.StopAllPfx(); + if (isSoundStopped && _sound != null) + _sound.Stop(); enabled = false; } @@ -219,7 +224,7 @@ private void OnTransitionEnded() if (_isStopPending || _nextLoop == null) { - Rest(); + Rest(isSoundStopped: _isStopPending); return; } @@ -249,7 +254,7 @@ private void OnLoopWrapped(bool restartTrack) } if (_users.Count == 0 && _isCurrentLoop) - Rest(); + Rest(isSoundStopped: true); } private void ApplyPose(AnimationTrackInstance instance) From e7054ccfe35142904785b9538a0abd35cd3be181 Mon Sep 17 00:00:00 2001 From: BoroBongo Date: Wed, 25 Nov 2026 23:36:55 +0000 Subject: [PATCH 09/29] fix: a smith killed or stood up at the anvil leaves it free - the last user's release resets the mob state in NpcService.ReleaseMob Wld_GetMobState then reads 0 and a save no longer keeps the anvil as used. Before, only a culled NPC reset it (AiHandler). An NPC only walking to the mob doesn't touch its state. Co-Authored-By: Claude Opus 5.5 --- Assets/Gothic-Core/Scripts/Adapters/Npc/AiHandler.cs | 3 --- Assets/Gothic-Core/Scripts/Services/Npc/NpcService.cs | 11 +++++++++-- Docs/mobs.md | 9 +++++---- 3 files changed, 14 insertions(+), 9 deletions(-) diff --git a/Assets/Gothic-Core/Scripts/Adapters/Npc/AiHandler.cs b/Assets/Gothic-Core/Scripts/Adapters/Npc/AiHandler.cs index 9adc6c201..483215623 100644 --- a/Assets/Gothic-Core/Scripts/Adapters/Npc/AiHandler.cs +++ b/Assets/Gothic-Core/Scripts/Adapters/Npc/AiHandler.cs @@ -883,9 +883,6 @@ private void LeaveMobToStartOver() if (Properties.CurrentInteractableStateId < 0) return; - if (PrefabProps.CurrentInteractable != null) - PrefabProps.CurrentInteractable.MobState = -1; - _npcService.ReleaseMob(NpcData); } diff --git a/Assets/Gothic-Core/Scripts/Services/Npc/NpcService.cs b/Assets/Gothic-Core/Scripts/Services/Npc/NpcService.cs index ad85d7a81..411e19050 100644 --- a/Assets/Gothic-Core/Scripts/Services/Npc/NpcService.cs +++ b/Assets/Gothic-Core/Scripts/Services/Npc/NpcService.cs @@ -901,7 +901,9 @@ 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 and when the NPC starts over (culled, - /// re-enabled: AiHandler). + /// re-enabled: AiHandler). 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) { @@ -909,7 +911,12 @@ public void ReleaseMob(NpcContainer npc) if (prefabProps == null) return; - _mobAnimationService.Stop(prefabProps.CurrentInteractable, npc); + 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; diff --git a/Docs/mobs.md b/Docs/mobs.md index a7428cef2..5437c4088 100644 --- a/Docs/mobs.md +++ b/Docs/mobs.md @@ -13,7 +13,7 @@ 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 | -| `AiHandler` (`LeaveMobToStartOver`) | an NPC starts over at its routine waypoint (culled out, re-enabled): -1 | +| `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) | @@ -27,9 +27,10 @@ An NPC uses a mob while `NpcPrefabProperties.CurrentInteractable` is the mob and 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 and stops the mob's -animation. 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) and when the NPC starts over (`AiHandler`). +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) and when the NPC +starts over (`AiHandler`). 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 From 34923ac24eb3632b5f1e67365ad9debe3b95f26d Mon Sep 17 00:00:00 2001 From: BoroBongo Date: Wed, 25 Nov 2026 23:37:08 +0000 Subject: [PATCH 10/29] docs: why the hero's mob use starts only after the mob dialog is prepared (MobInteractionService) Co-Authored-By: Claude Opus 5.5 --- .../Gothic-Core/Scripts/Services/Vobs/MobInteractionService.cs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Assets/Gothic-Core/Scripts/Services/Vobs/MobInteractionService.cs b/Assets/Gothic-Core/Scripts/Services/Vobs/MobInteractionService.cs index fad14f860..b7504963b 100644 --- a/Assets/Gothic-Core/Scripts/Services/Vobs/MobInteractionService.cs +++ b/Assets/Gothic-Core/Scripts/Services/Vobs/MobInteractionService.cs @@ -186,7 +186,8 @@ private bool TryUseMobStateFunction(VobLoader loader, IInteractiveObject mob, // 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). + // (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); From c8eaf5c3a2faf75bd2c863b2752a209b63bcc476 Mon Sep 17 00:00:00 2001 From: BoroBongo Date: Thu, 26 Nov 2026 19:25:04 +0000 Subject: [PATCH 11/29] fix: a skipped mob animation is logged, and the hero's mob is forgotten when the world is left (MobAnimationService) A mob that isn't loaded yet gets no animator - the hero's lever pull then plays no animation, now with an Editor log. On a world change or a loaded game the hero's mob dialog use is cleared, so it never points at a destroyed mob. Co-Authored-By: Claude Opus 5.5 --- .../Scripts/Adapters/Vob/MobAnimatorFactory.cs | 6 ++++++ .../Scripts/Services/Vobs/MobAnimationService.cs | 12 ++++++++++++ 2 files changed, 18 insertions(+) diff --git a/Assets/Gothic-Core/Scripts/Adapters/Vob/MobAnimatorFactory.cs b/Assets/Gothic-Core/Scripts/Adapters/Vob/MobAnimatorFactory.cs index 5497bd0f8..791b6b60b 100644 --- a/Assets/Gothic-Core/Scripts/Adapters/Vob/MobAnimatorFactory.cs +++ b/Assets/Gothic-Core/Scripts/Adapters/Vob/MobAnimatorFactory.cs @@ -1,7 +1,9 @@ using Gothic.Core.Extensions; +using Gothic.Core.Logging; using Gothic.Core.Models.Animations; using Gothic.Core.Models.Container; using Gothic.Core.Services.Vobs; +using Logger = Gothic.Core.Logging.Logger; namespace Gothic.Core.Adapters.Vob { @@ -17,7 +19,11 @@ public IMobAnimator GetOrCreate(VobContainer mob, AnimationSkeleton skeleton) // 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().Inject(); animator.Init(mob, skeleton); diff --git a/Assets/Gothic-Core/Scripts/Services/Vobs/MobAnimationService.cs b/Assets/Gothic-Core/Scripts/Services/Vobs/MobAnimationService.cs index 7656885c3..1e16875c3 100644 --- a/Assets/Gothic-Core/Scripts/Services/Vobs/MobAnimationService.cs +++ b/Assets/Gothic-Core/Scripts/Services/Vobs/MobAnimationService.cs @@ -52,6 +52,8 @@ public void Init() { GlobalEventDispatcher.WorldSceneLoaded.AddListener(WarmWorldMobs); GlobalEventDispatcher.MobDialogEnded.AddListener(StopHeroUse); + GlobalEventDispatcher.LoadGameStart.AddListener(ForgetHeroUse); + GlobalEventDispatcher.LoadingSceneLoaded.AddListener(ForgetHeroUse); } /// @@ -166,6 +168,16 @@ public void StopHeroUse() Stop(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; + } + /// /// The user still uses the mob: the hero while his mob dialog is open, an NPC while it's there (active, not /// dead or knocked out, the mob is its CurrentInteractable). MobAnimator asks once per loop round. From 8a1723379d0a35e5985f4eb1ecfc6efe934b13f9 Mon Sep 17 00:00:00 2001 From: BoroBongo Date: Thu, 26 Nov 2026 22:14:45 +0000 Subject: [PATCH 12/29] fix: animation sounds play at Gothic's own volume of each sound - the anvil, grindstone, quench and water pipe are no longer all at full volume - SfxModel caches each instance's C_SFX_DEF vol (0..127 as 0..1); a random variant (_A1, _A2) has its own - AudioService.GetRandomSoundClip(name, out volume): the picked sound's volume, 1 for a plain .wav name - AnimationEffectPlayer: a clip plays at it, a footstep one-shot gets it as volumeScale - an NPC's animation clips play on an own source next to NpcSound (_AnimationSfx, created on the first clip with NpcSound's settings): hits, weapon draws and steps play on NpcSound as one-shots and were turned down by the last clip's volume (and range) otherwise; a mob's source is its own already - VRMouth: eating, drinking and smoking at the VR mouth use it too (SMOKE_JOINT 20) Co-Authored-By: Claude Opus 5.5 --- .../Animations/AnimationEffectPlayer.cs | 64 +++++++++++++++++-- .../Adapters/Animations/AnimationSystem.cs | 4 +- .../Scripts/Adapters/Vob/MobAnimator.cs | 3 +- .../Scripts/Models/Audio/SfxModel.cs | 29 +++++++-- .../Scripts/Services/Audio/AudioService.cs | 12 +++- .../Scripts/Adapters/Vob/VobItem/VRMouth.cs | 14 ++-- 6 files changed, 105 insertions(+), 21 deletions(-) diff --git a/Assets/Gothic-Core/Scripts/Adapters/Animations/AnimationEffectPlayer.cs b/Assets/Gothic-Core/Scripts/Adapters/Animations/AnimationEffectPlayer.cs index e0833ef99..68320b6e3 100644 --- a/Assets/Gothic-Core/Scripts/Adapters/Animations/AnimationEffectPlayer.cs +++ b/Assets/Gothic-Core/Scripts/Adapters/Animations/AnimationEffectPlayer.cs @@ -46,10 +46,17 @@ private struct ReusedPfx public ParticleSystem[] Systems; } + private const string _clipSourceName = "_AnimationSfx"; + private readonly Transform _boneRoot; private readonly Transform _stepOrigin; private readonly AudioSource _sound; + private readonly bool _isSoundShared; + // The volume the given source had: Gothic's volume of each sound is applied on top of it. + private readonly float _soundBaseVolume; private readonly bool _isReusingPfx; + // Plays the *eventSFX clips: the given source, or an own one next to it if that's shared (see GetClipSource). + private AudioSource _clipSource; // One-off mode: effects with an index, until their *eventPFXStop. private readonly Dictionary _activePfx = new(); @@ -63,13 +70,20 @@ private struct ReusedPfx /// /// Where a step sound (*eventSFXGrnd) asks for the ground below. /// Plays the *eventSFX sounds (one at a time, like the engine's model sound). + /// Others play on the source too (an NPC's NpcSound): its clips get an own source + /// next to it, see GetClipSource(). /// Build each effect once and replay it (mobs), see class summary. - public AnimationEffectPlayer(Transform boneRoot, Transform stepOrigin, AudioSource sound, bool isReusingPfx) + public AnimationEffectPlayer(Transform boneRoot, Transform stepOrigin, AudioSource sound, bool isSoundShared, + bool isReusingPfx) { _boneRoot = boneRoot; _stepOrigin = stepOrigin; _sound = sound; + _isSoundShared = isSoundShared; + _soundBaseVolume = sound != null ? sound.volume : 1f; _isReusingPfx = isReusingPfx; + if (!isSoundShared) + _clipSource = sound; } /// @@ -91,21 +105,57 @@ public bool ApplySfxEvents(AnimationTrackInstance trackInstance) continue; var stepName = _groundSoundService.GetSoundName( sfx.Name.Substring(GroundSoundDomain.GroundEventPrefix.Length), _stepOrigin.position); - var stepClip = _audioService.GetRandomSoundClip(stepName); + var stepClip = _audioService.GetRandomSoundClip(stepName, out var stepVolume); if (stepClip != null) - _sound.PlayOneShot(stepClip); + _sound.PlayOneShot(stepClip, stepVolume); continue; } - var clip = _audioService.GetRandomSoundClip(sfx.Name); - _sound.clip = clip; - _sound.maxDistance = _audioService.GetSfxRangeMeters(sfx.Name, sfx.Range.ToMeter()); - _sound.Play(); + // Gothic's volume of the sound (Forge_Sharpen 40 of 127): its source plays one clip at a time. + var clip = _audioService.GetRandomSoundClip(sfx.Name, out var volume); + var clipSource = GetClipSource(); + clipSource.clip = clip; + clipSource.volume = _soundBaseVolume * volume; + clipSource.maxDistance = _audioService.GetSfxRangeMeters(sfx.Name, sfx.Range.ToMeter()); + clipSource.Play(); } return sfxEvents.Count > 0; } + /// + /// The source of the *eventSFX clips. An NPC's NpcSound is shared - hits, weapon draws and steps play on it as + /// one-shots, which a clip's volume (Gothic's of each sound) would turn down, and so would its range. Its clips + /// get an own source next to it instead, created on the first one with NpcSound's settings. + /// + private AudioSource GetClipSource() + { + if (_clipSource != null || !_isSoundShared) + return _clipSource; + + var existing = _sound.transform.Find(_clipSourceName); + if (existing != null && existing.TryGetComponent(out _clipSource)) + return _clipSource; + + var clipGo = new GameObject(_clipSourceName); + clipGo.transform.SetParent(_sound.transform, false); + _clipSource = clipGo.AddComponent(); + _clipSource.playOnAwake = false; + _clipSource.outputAudioMixerGroup = _sound.outputAudioMixerGroup; + _clipSource.spatialBlend = _sound.spatialBlend; + _clipSource.priority = _sound.priority; + _clipSource.dopplerLevel = _sound.dopplerLevel; + _clipSource.spread = _sound.spread; + _clipSource.reverbZoneMix = _sound.reverbZoneMix; + _clipSource.rolloffMode = _sound.rolloffMode; + _clipSource.minDistance = _sound.minDistance; + _clipSource.maxDistance = _sound.maxDistance; + if (_sound.rolloffMode == AudioRolloffMode.Custom) + _clipSource.SetCustomCurve(AudioSourceCurveType.CustomRolloff, + _sound.GetCustomCurve(AudioSourceCurveType.CustomRolloff)); + return _clipSource; + } + /// /// *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, ... diff --git a/Assets/Gothic-Core/Scripts/Adapters/Animations/AnimationSystem.cs b/Assets/Gothic-Core/Scripts/Adapters/Animations/AnimationSystem.cs index c3b20f852..f330c8fa4 100644 --- a/Assets/Gothic-Core/Scripts/Adapters/Animations/AnimationSystem.cs +++ b/Assets/Gothic-Core/Scripts/Adapters/Animations/AnimationSystem.cs @@ -139,8 +139,8 @@ 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, isReusingPfx: false) - .Inject(); + _effectPlayer = new AnimationEffectPlayer(Go.transform, transform, PrefabProps.NpcSound, + isSoundShared: true, isReusingPfx: false).Inject(); CreateGraph(); ResizeRootCollider(); diff --git a/Assets/Gothic-Core/Scripts/Adapters/Vob/MobAnimator.cs b/Assets/Gothic-Core/Scripts/Adapters/Vob/MobAnimator.cs index 06ce24153..ae24d30af 100644 --- a/Assets/Gothic-Core/Scripts/Adapters/Vob/MobAnimator.cs +++ b/Assets/Gothic-Core/Scripts/Adapters/Vob/MobAnimator.cs @@ -63,7 +63,8 @@ public void Init(VobContainer mob, AnimationSkeleton skeleton) _sound.spatialBlend = 1f; _sound.rolloffMode = AudioRolloffMode.Linear; _sound.minDistance = 0f; - _effectPlayer = new AnimationEffectPlayer(transform, transform, _sound, isReusingPfx: true).Inject(); + _effectPlayer = new AnimationEffectPlayer(transform, transform, _sound, isSoundShared: false, + isReusingPfx: true).Inject(); Rest(isSoundStopped: true); } 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/Services/Audio/AudioService.cs b/Assets/Gothic-Core/Scripts/Services/Audio/AudioService.cs index 306e5d4e4..3a5767889 100644 --- a/Assets/Gothic-Core/Scripts/Services/Audio/AudioService.cs +++ b/Assets/Gothic-Core/Scripts/Services/Audio/AudioService.cs @@ -254,8 +254,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)) { @@ -279,7 +289,7 @@ public AudioClip GetRandomSoundClip(string soundName) if (sfxContainer.GetFirstSound() == null || sfxContainer.GetFirstSound()!.File.EqualsIgnoreCase(NoSoundName)) return null; - clip = CreateAudioClip(sfxContainer.GetRandomSound()); + clip = CreateAudioClip(sfxContainer.GetRandomSound(out volume)); } return clip; 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); From 4746ca78f98b03c9df008455e006cd6080a88a8a Mon Sep 17 00:00:00 2001 From: BoroBongo Date: Thu, 26 Nov 2026 22:16:18 +0000 Subject: [PATCH 13/29] fix: the options' sound effects slider works - world sounds, NPC and mob animation sounds follow it, a playing loop at once Gothic.ini [SOUND] soundVolume (MENU_OPT_AUDIO) was written by the menu but applied to nothing. - AudioService.SoundVolume: the option 0..1, read on first use and again when the menu changes it (logged, LogCat.Audio) - AudioService.SetSfxVolume(source, volume): Gothic's volume of the sound times the slider; the source is remembered and set again on the option change (no polling), destroyed ones are dropped on the next world - VOB sounds and day/night sounds (VobInitializerDomain), NPC and mob animation clips (AnimationEffectPlayer) use it; footsteps, eating/drinking/smoking at the VR mouth and Snd_Play sounds get it when they play - voices and music are untouched (music has its own slider) Co-Authored-By: Claude Opus 5.5 --- .../Animations/AnimationEffectPlayer.cs | 7 +- Assets/Gothic-Core/Scripts/Const/Constants.cs | 4 + .../Domain/Vobs/VobInitializerDomain.cs | 3 +- .../Scripts/Services/Audio/AudioService.cs | 80 ++++++++++++++++++- .../Scripts/Adapters/Vob/VobItem/VRMouth.cs | 2 +- 5 files changed, 89 insertions(+), 7 deletions(-) diff --git a/Assets/Gothic-Core/Scripts/Adapters/Animations/AnimationEffectPlayer.cs b/Assets/Gothic-Core/Scripts/Adapters/Animations/AnimationEffectPlayer.cs index 68320b6e3..b151d2ba2 100644 --- a/Assets/Gothic-Core/Scripts/Adapters/Animations/AnimationEffectPlayer.cs +++ b/Assets/Gothic-Core/Scripts/Adapters/Animations/AnimationEffectPlayer.cs @@ -107,15 +107,16 @@ public bool ApplySfxEvents(AnimationTrackInstance trackInstance) sfx.Name.Substring(GroundSoundDomain.GroundEventPrefix.Length), _stepOrigin.position); var stepClip = _audioService.GetRandomSoundClip(stepName, out var stepVolume); if (stepClip != null) - _sound.PlayOneShot(stepClip, stepVolume); + _sound.PlayOneShot(stepClip, stepVolume * _audioService.SoundVolume); continue; } - // Gothic's volume of the sound (Forge_Sharpen 40 of 127): its source plays one clip at a time. + // Gothic's volume of the sound (Forge_Sharpen 40 of 127) and the player's sound volume, which a + // long clip (FORGE_FIRE) follows while it plays. Its source plays one clip at a time. var clip = _audioService.GetRandomSoundClip(sfx.Name, out var volume); var clipSource = GetClipSource(); clipSource.clip = clip; - clipSource.volume = _soundBaseVolume * volume; + _audioService.SetSfxVolume(clipSource, _soundBaseVolume * volume); clipSource.maxDistance = _audioService.GetSfxRangeMeters(sfx.Name, sfx.Range.ToMeter()); clipSource.Play(); } diff --git a/Assets/Gothic-Core/Scripts/Const/Constants.cs b/Assets/Gothic-Core/Scripts/Const/Constants.cs index be0547dfb..10242886c 100644 --- a/Assets/Gothic-Core/Scripts/Const/Constants.cs +++ b/Assets/Gothic-Core/Scripts/Const/Constants.cs @@ -31,6 +31,10 @@ 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 (AudioService.SoundVolume). + 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/Vobs/VobInitializerDomain.cs b/Assets/Gothic-Core/Scripts/Domain/Vobs/VobInitializerDomain.cs index beb1ff979..7b8347a88 100644 --- a/Assets/Gothic-Core/Scripts/Domain/Vobs/VobInitializerDomain.cs +++ b/Assets/Gothic-Core/Scripts/Domain/Vobs/VobInitializerDomain.cs @@ -808,7 +808,8 @@ 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. + // Gothic's volume is 0...100, Unity's is 0...1. Times the player's sound volume, a loop follows the slider. + _audioService.SetSfxVolume(source, 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/Services/Audio/AudioService.cs b/Assets/Gothic-Core/Scripts/Services/Audio/AudioService.cs index 3a5767889..8df9c8f9f 100644 --- a/Assets/Gothic-Core/Scripts/Services/Audio/AudioService.cs +++ b/Assets/Gothic-Core/Scripts/Services/Audio/AudioService.cs @@ -1,6 +1,7 @@ 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.Container; @@ -50,9 +51,23 @@ public class AudioService private AudioSource _scriptSoundSource; + // Gothic.ini soundVolume, read on first use and again when the menu changes it. Stays unset while Gothic.ini + // isn't loaded (the player scene runs before a game was picked): the default would stick otherwise. + private float? _soundVolume; + // Sound effect sources that follow the slider (SetSfxVolume): their volume without it. + private readonly Dictionary _sfxSources = new(); + private readonly List _destroyedSfxSources = new(); + public SoundEffectInstance InvOpen => _vmCacheService.TryGetSfxData("INV_OPEN").GetFirstSound(); public SoundEffectInstance InvClose => _vmCacheService.TryGetSfxData("INV_CLOSE").GetFirstSound(); - + + public AudioService() + { + GlobalEventDispatcher.PlayerPrefUpdated.AddListener(OnSoundOptionUpdated); + // The old world's sources are gone by now. + GlobalEventDispatcher.WorldSceneLoaded.AddListener(RemoveDestroyedSfxSources); + } + // // Music // @@ -177,6 +192,67 @@ public void SetScriptSoundSource(AudioSource audioSource) _scriptSoundSource = audioSource; } + /// + /// The player's sound effects volume (options slider, Gothic.ini [SOUND] soundVolume), 0..1. Voices and music + /// have their own. + /// + public float SoundVolume + { + get + { + if (_soundVolume.HasValue) + return _soundVolume.Value; + + var volume = Mathf.Clamp01(_configService.GetGothicOption(Constants.IniNames.SoundVolume, + Constants.IniNames.SoundVolumeDefaultValue)); + if (_configService.Gothic == null) + return volume; + + _soundVolume = volume; + Logger.Log($"[SoundVolume] Sound effects at {volume:0.##} (Gothic.ini soundVolume).", LogCat.Audio); + return volume; + } + } + + /// + /// Sets a sound effect source's volume: the sound's own (Gothic's, 0..1) times the player's SoundVolume. The + /// source follows the slider from now on - a loop that plays (a VOB's campfire, the forge fire) changes at + /// once. Call it again when the source plays another sound with another volume. + /// + public void SetSfxVolume(AudioSource source, float soundVolume) + { + _sfxSources[source] = soundVolume; + source.volume = soundVolume * SoundVolume; + } + + private void OnSoundOptionUpdated(string key, object value) + { + if (key != Constants.IniNames.SoundVolume) + return; + + _soundVolume = null; + var volume = SoundVolume; + foreach (var (source, soundVolume) in _sfxSources) + { + if (source != null) + source.volume = soundVolume * volume; + } + RemoveDestroyedSfxSources(); + } + + private void RemoveDestroyedSfxSources() + { + foreach (var (source, _) in _sfxSources) + { + if (source == null) + _destroyedSfxSources.Add(source); + } + + foreach (var source in _destroyedSfxSources) + _sfxSources.Remove(source); + _destroyedSfxSources.Clear(); + } + /// /// 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. @@ -201,7 +277,7 @@ public void PlaySound2D(string soundName) var clip = GetRandomSoundClip(soundName); if (clip != null) - _scriptSoundSource.PlayOneShot(clip); + _scriptSoundSource.PlayOneShot(clip, SoundVolume); } [CanBeNull] diff --git a/Assets/Gothic-VR/Scripts/Adapters/Vob/VobItem/VRMouth.cs b/Assets/Gothic-VR/Scripts/Adapters/Vob/VobItem/VRMouth.cs index 34b7c4834..d6ac3c223 100644 --- a/Assets/Gothic-VR/Scripts/Adapters/Vob/VobItem/VRMouth.cs +++ b/Assets/Gothic-VR/Scripts/Adapters/Vob/VobItem/VRMouth.cs @@ -249,7 +249,7 @@ private IEnumerator ConsumeObject(GameObject go, [CanBeNull] AudioClip clip, flo if (startDelay > 0f) yield return new WaitForSeconds(startDelay); if (clip != null) - _mouthAudio.PlayOneShot(clip, volume); + _mouthAudio.PlayOneShot(clip, volume * _audioService.SoundVolume); yield return new WaitForSeconds(destroyDelay); From 46b9e74d59b006eb5c0c60520d8904819a32f4f0 Mon Sep 17 00:00:00 2001 From: BoroBongo Date: Thu, 26 Nov 2026 22:27:53 +0000 Subject: [PATCH 14/29] fix: the sound effects volume slider shows in the sound options again - it was hidden as unsupported Co-Authored-By: Claude Opus 5.5 --- Assets/Gothic-Core/Scripts/Services/Vm/VmService.cs | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/Assets/Gothic-Core/Scripts/Services/Vm/VmService.cs b/Assets/Gothic-Core/Scripts/Services/Vm/VmService.cs index 6234f3a0d..dc587ddc8 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.SoundVolume) "MENUITEM_AUDIO_PROVIDER", "MENUITEM_AUDIO_PROVIDER_CHOICE", "MENUITEM_AUDIO_SPEEKER", "MENUITEM_AUDIO_SPEEKER_CHOICE", "MENUITEM_AUDIO_REVERB", "MENUITEM_AUDIO_REVERB_CHOICE", From efd3a8ffdb5f83cbdf3e3b23d5940229afe7a114 Mon Sep 17 00:00:00 2001 From: BoroBongo Date: Thu, 26 Nov 2026 22:31:07 +0000 Subject: [PATCH 15/29] fix: the sound effects slider plays Gothic's own volume at 75% - the top end is a third louder for who wants more Co-Authored-By: Claude Opus 5.5 --- Assets/Gothic-Core/Scripts/Const/Constants.cs | 2 +- .../Scripts/Services/Audio/AudioService.cs | 14 ++++++++++---- 2 files changed, 11 insertions(+), 5 deletions(-) diff --git a/Assets/Gothic-Core/Scripts/Const/Constants.cs b/Assets/Gothic-Core/Scripts/Const/Constants.cs index 10242886c..30b9aad27 100644 --- a/Assets/Gothic-Core/Scripts/Const/Constants.cs +++ b/Assets/Gothic-Core/Scripts/Const/Constants.cs @@ -33,7 +33,7 @@ public static class IniNames // Gothic's own [SOUND] 0..1, the options' sound effects slider (AudioService.SoundVolume). public const string SoundVolume = "soundVolume"; - public const float SoundVolumeDefaultValue = 1f; + public const float SoundVolumeDefaultValue = 0.75f; // Gothic's own volume (AudioService) // [VIDEO] 0..1, vanilla 0.5 = neutral (the menu's Brightness slider). public const string VideoBrightness = "zVidBrightness"; diff --git a/Assets/Gothic-Core/Scripts/Services/Audio/AudioService.cs b/Assets/Gothic-Core/Scripts/Services/Audio/AudioService.cs index 8df9c8f9f..c9b003179 100644 --- a/Assets/Gothic-Core/Scripts/Services/Audio/AudioService.cs +++ b/Assets/Gothic-Core/Scripts/Services/Audio/AudioService.cs @@ -192,9 +192,12 @@ public void SetScriptSoundSource(AudioSource audioSource) _scriptSoundSource = audioSource; } + // The slider position that plays the sounds at Gothic's own volume: the slider's top end is louder (1/0.75). + private const float _ownVolumeSliderPosition = 0.75f; + /// - /// The player's sound effects volume (options slider, Gothic.ini [SOUND] soundVolume), 0..1. Voices and music - /// have their own. + /// The player's sound effects gain (options slider, Gothic.ini [SOUND] soundVolume 0..1): the slider at 0.75 + /// plays Gothic's own volume, the top end a third louder. Voices and music have their own. /// public float SoundVolume { @@ -203,13 +206,16 @@ public float SoundVolume if (_soundVolume.HasValue) return _soundVolume.Value; - var volume = Mathf.Clamp01(_configService.GetGothicOption(Constants.IniNames.SoundVolume, + var slider = Mathf.Clamp01(_configService.GetGothicOption(Constants.IniNames.SoundVolume, Constants.IniNames.SoundVolumeDefaultValue)); + var volume = slider / _ownVolumeSliderPosition; if (_configService.Gothic == null) return volume; _soundVolume = volume; - Logger.Log($"[SoundVolume] Sound effects at {volume:0.##} (Gothic.ini soundVolume).", LogCat.Audio); + Logger.Log($"[SoundVolume] Sound effects slider {slider:0.##} (Gothic.ini soundVolume), gain " + + $"{volume:0.##}.", + LogCat.Audio); return volume; } } From b1a444a0749fafb0f0dad049cda27e459c8bed26 Mon Sep 17 00:00:00 2001 From: JaXt0r Date: Thu, 3 Dec 2026 06:08:30 +0100 Subject: [PATCH 16/29] fix: a mob works exactly as long as an NPC or the hero uses it - who uses it is read from the NPCs' own mob state, no second user list MobAnimationService asks VobService.GetOtherMobUsers (+ IsUsingMob) and the hero's dialog mob to decide whether a user joins or the last one left. MobAnimator only plays tracks; its user list, the per-loop IsStillUsing safety net and the adapter's call back into the service are gone. Co-Authored-By: Claude Opus 5.5 --- .../Scripts/Adapters/Vob/MobAnimator.cs | 78 ++----------------- .../Adapters/Vob/MobAnimatorFactory.cs | 5 +- .../Scripts/Services/Vobs/IMobAnimator.cs | 15 +--- .../Services/Vobs/MobAnimationService.cs | 54 ++++++------- Docs/mobs.md | 20 ++--- 5 files changed, 50 insertions(+), 122 deletions(-) diff --git a/Assets/Gothic-Core/Scripts/Adapters/Vob/MobAnimator.cs b/Assets/Gothic-Core/Scripts/Adapters/Vob/MobAnimator.cs index ae24d30af..9e28135ca 100644 --- a/Assets/Gothic-Core/Scripts/Adapters/Vob/MobAnimator.cs +++ b/Assets/Gothic-Core/Scripts/Adapters/Vob/MobAnimator.cs @@ -1,11 +1,8 @@ -using System.Collections.Generic; using Gothic.Core.Adapters.Animations; using Gothic.Core.Extensions; using Gothic.Core.Logging; using Gothic.Core.Models.Animations; -using Gothic.Core.Models.Container; using Gothic.Core.Services.Vobs; -using Reflex.Attributes; using UnityEngine; using AnimationState = Gothic.Core.Models.Animations.AnimationState; using Logger = Gothic.Core.Logging.Logger; @@ -22,22 +19,18 @@ namespace Gothic.Core.Adapters.Vob /// 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. + /// 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 { - [Inject] private readonly MobAnimationService _mobAnimationService; - - private VobContainer _mob; // 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 readonly List _users = new(); private AnimationTrackInstance _current; private bool _isCurrentLoop; - private float _previousTime; // 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. @@ -46,16 +39,13 @@ public class MobAnimator : MonoBehaviour, IMobAnimator public int State { get; private set; } - public int UserCount => _users.Count; - /// /// 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). /// - public void Init(VobContainer mob, AnimationSkeleton skeleton) + public void Init(AnimationSkeleton skeleton) { - _mob = mob; MapNodes(skeleton); _sound = gameObject.AddComponent(); @@ -101,22 +91,6 @@ private void MapNodes(AnimationSkeleton skeleton) LogCat.Vob); } - public bool HasUser(NpcContainer user) - { - return _users.Contains(user); - } - - public void AddUser(NpcContainer user) - { - if (user != null && !_users.Contains(user)) - _users.Add(user); - } - - public void RemoveUser(NpcContainer user) - { - _users.Remove(user); - } - public void Play(int state, AnimationTrack transition, AnimationTrack loop) { State = state; @@ -155,7 +129,6 @@ private void StartTrack(AnimationTrack track, bool isLoop) { _current = new AnimationTrackInstance(track); _isCurrentLoop = isLoop; - _previousTime = 0f; enabled = true; } @@ -195,22 +168,13 @@ private void Update() } // A track without a loop of its own reached its last frame (it starts blending out). - if (stateChange is AnimationState.BlendOut or AnimationState.Stop) - { - if (_isCurrentLoop) - OnLoopWrapped(restartTrack: true); - else - OnTransitionEnded(); - return; - } - - if (_isCurrentLoop && _current.CurrentTime < _previousTime) - { - OnLoopWrapped(restartTrack: false); + if (stateChange is not (AnimationState.BlendOut or AnimationState.Stop)) return; - } - _previousTime = _current.CurrentTime; + if (_isCurrentLoop) + StartTrack(_current.Track, isLoop: true); + else + OnTransitionEnded(); } private void OnTransitionEnded() @@ -232,32 +196,6 @@ private void OnTransitionEnded() StartTrack(_nextLoop, isLoop: true); } - /// - /// The safety net, once per loop round (not per frame): a user who left without the mob being released (a - /// path that doesn't end the usage, a culled or killed NPC) stops the animation. - /// - private void OnLoopWrapped(bool restartTrack) - { - if (restartTrack) - StartTrack(_current.Track, isLoop: true); - else - _previousTime = _current.CurrentTime; - - for (var i = _users.Count - 1; i >= 0; i--) - { - // Stop() removes exactly this user, the ones below stay at their index. - var user = _users[i]; - if (_mobAnimationService.IsStillUsing(_mob, user)) - continue; - - Logger.Log($"[MobAnimation] {name}: a user left without releasing it - stopping.", LogCat.Vob); - _mobAnimationService.Stop(_mob, user); - } - - if (_users.Count == 0 && _isCurrentLoop) - Rest(isSoundStopped: true); - } - private void ApplyPose(AnimationTrackInstance instance) { var track = instance.Track; diff --git a/Assets/Gothic-Core/Scripts/Adapters/Vob/MobAnimatorFactory.cs b/Assets/Gothic-Core/Scripts/Adapters/Vob/MobAnimatorFactory.cs index 791b6b60b..58344c086 100644 --- a/Assets/Gothic-Core/Scripts/Adapters/Vob/MobAnimatorFactory.cs +++ b/Assets/Gothic-Core/Scripts/Adapters/Vob/MobAnimatorFactory.cs @@ -1,4 +1,3 @@ -using Gothic.Core.Extensions; using Gothic.Core.Logging; using Gothic.Core.Models.Animations; using Gothic.Core.Models.Container; @@ -25,8 +24,8 @@ public IMobAnimator GetOrCreate(VobContainer mob, AnimationSkeleton skeleton) return null; } - animator = mob.Go.AddComponent().Inject(); - animator.Init(mob, skeleton); + animator = mob.Go.AddComponent(); + animator.Init(skeleton); return animator; } diff --git a/Assets/Gothic-Core/Scripts/Services/Vobs/IMobAnimator.cs b/Assets/Gothic-Core/Scripts/Services/Vobs/IMobAnimator.cs index 86534a389..0843d19aa 100644 --- a/Assets/Gothic-Core/Scripts/Services/Vobs/IMobAnimator.cs +++ b/Assets/Gothic-Core/Scripts/Services/Vobs/IMobAnimator.cs @@ -1,11 +1,11 @@ using Gothic.Core.Models.Animations; -using Gothic.Core.Models.Container; 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. Docs/mobs.md. + /// 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 { @@ -14,17 +14,6 @@ public interface IMobAnimator /// int State { get; } - /// - /// NPCs (or the hero) using the mob right now - several on a mob with several slots. - /// - int UserCount { get; } - - bool HasUser(NpcContainer user); - - void AddUser(NpcContainer user); - - void RemoveUser(NpcContainer user); - /// /// 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). diff --git a/Assets/Gothic-Core/Scripts/Services/Vobs/MobAnimationService.cs b/Assets/Gothic-Core/Scripts/Services/Vobs/MobAnimationService.cs index 1e16875c3..60b8a2c00 100644 --- a/Assets/Gothic-Core/Scripts/Services/Vobs/MobAnimationService.cs +++ b/Assets/Gothic-Core/Scripts/Services/Vobs/MobAnimationService.cs @@ -1,6 +1,7 @@ using System; using System.Collections.Generic; using System.Diagnostics; +using System.Linq; using System.Text; using Gothic.Core.Extensions; using Gothic.Core.Logging; @@ -29,6 +30,7 @@ public class MobAnimationService [Inject] private readonly AudioService _audioService; [Inject] private readonly GameStateService _gameStateService; [Inject] private readonly IMobAnimatorFactory _mobAnimatorFactory; + [Inject] private readonly VobService _vobService; private const string _mdsExtension = ".MDS"; private const string _standStateName = "STAND"; @@ -77,6 +79,7 @@ public bool IsAnimated([CanBeNull] VobContainer mob) /// 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) { @@ -85,16 +88,13 @@ public void OnStateChanged([CanBeNull] VobContainer mob, [CanBeNull] NpcContaine if (to < 0) { - Stop(mob, user); + StopIfLastUser(mob, user); return; } var animator = _mobAnimatorFactory.TryGet(mob); - if (user != null && animator != null && HasOtherUser(animator, user) && to <= animator.State) - { - animator.AddUser(user); + if (user != null && animator != null && to <= animator.State && HasOtherUser(mob, user)) return; - } var visualName = mob.Vob.Visual.Name; var skeleton = GetSkeleton(visualName); @@ -110,7 +110,6 @@ public void OnStateChanged([CanBeNull] VobContainer mob, [CanBeNull] NpcContaine if (animator == null) return; - animator.AddUser(user); animator.Play(to, transition, loop); Logger.LogEditor($"[MobAnimation] {mob.Vob.Name} ({visualName}): {GetStateName(from)} -> " + $"{GetStateName(to)} by {user?.Instance?.GetName(NpcNameSlot.Slot0) ?? "nobody"}", @@ -118,20 +117,29 @@ public void OnStateChanged([CanBeNull] VobContainer mob, [CanBeNull] NpcContaine } /// - /// The user doesn't use the mob any more. The last one stops its animation: a running transition ends, the - /// transition back plays (T_S1_2_S0, a lever swings back), then the mob rests. + /// 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 (mob == null || user == null) + if (user == null || !user.IsUsingMob()) return; - var animator = _mobAnimatorFactory.TryGet(mob); - if (animator == null || !animator.HasUser(user)) + 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; - animator.RemoveUser(user); - if (animator.UserCount > 0) + var animator = _mobAnimatorFactory.TryGet(mob); + if (animator == null || HasOtherUser(mob, user)) return; var state = animator.State; @@ -165,7 +173,7 @@ public void StopHeroUse() var hero = _hero; _heroMob = null; _hero = null; - Stop(mob, hero); + StopIfLastUser(mob, hero); } /// @@ -179,23 +187,15 @@ private void ForgetHeroUse() } /// - /// The user still uses the mob: the hero while his mob dialog is open, an NPC while it's there (active, not - /// dead or knocked out, the mob is its CurrentInteractable). MobAnimator asks once per loop round. + /// 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. /// - public bool IsStillUsing([CanBeNull] VobContainer mob, [CanBeNull] NpcContainer user) + private bool HasOtherUser(VobContainer mob, NpcContainer user) { - if (mob == null || user?.Props == null || user.IsDown()) - return false; - - if (mob == _heroMob && user == _hero) + if (mob == _heroMob && user != _hero) return true; - return user.Go != null && user.Go.activeInHierarchy && user.PrefabProps?.CurrentInteractable == mob; - } - - private static bool HasOtherUser(IMobAnimator animator, NpcContainer user) - { - return animator.UserCount > (animator.HasUser(user) ? 1 : 0); + return _vobService.GetOtherMobUsers(mob, user).Any(i => i.IsUsingMob()); } /// diff --git a/Docs/mobs.md b/Docs/mobs.md index 5437c4088..bdd48c574 100644 --- a/Docs/mobs.md +++ b/Docs/mobs.md @@ -46,9 +46,9 @@ State -1 is called `STAND` in the names (`T_STAND_2_S0` - most mobs don't have i | Class | Owns | |---|---| -| `MobAnimationService` (Services/Vobs) | which mobs animate (`IsAnimated`: an `.MDS` visual, no door, chest, bed or fireplace), the track names, users, the hero's dialog use, the safety net rule (`IsStillUsing`), baking the world's mob tracks at load | +| `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, the users, the per-loop safety net | +| `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) | @@ -59,12 +59,14 @@ State -1 is called `STAND` in the names (`T_STAND_2_S0` - most mobs don't have i 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. -4. The last user leaves (`to == -1`, or `ReleaseMob` -> `Stop`): a running transition ends, the transition back plays - (a lever swings back), the particles fade out, `MobAnimator` turns itself off. -5. Safety net: once per loop round (never per frame) `MobAnimator` asks `IsStillUsing` for each user. A user that is - gone, culled, dead, knocked out or at another mob is stopped - a path that ends a usage without `ReleaseMob` - can't leave an anvil sparking forever. + 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 @@ -102,7 +104,7 @@ doors, chests and beds (the VR hand moves them), `oCMobFire` (FireService). |---|---| | 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, node mapping or the safety net round | `MobAnimator` | +| 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` | From dded03a542bccb56cdd1cf3c1b0cbe4b19930fb5 Mon Sep 17 00:00:00 2001 From: JaXt0r Date: Thu, 3 Dec 2026 06:08:48 +0100 Subject: [PATCH 17/29] fix: a smith knocked out at the anvil lets go of it like a killed one - the anvil stops and is free for others (NpcKnockoutDomain -> ReleaseMob) Like the engine's Npc::onNoHealth, which quits the interaction for death and unconsciousness. Before, only the removed per-loop safety net stopped the mob's animation, and the NPC kept the mob reserved while lying there. ReleaseMob's doc and Docs/mobs.md name the paths; world change/load and UseMob's dropped walk reservation need no release. Co-Authored-By: Claude Opus 5.5 --- .../Scripts/Domain/Npc/Actions/AnimationActions/UseMob.cs | 2 +- Assets/Gothic-Core/Scripts/Domain/Npc/NpcKnockoutDomain.cs | 5 +++++ Assets/Gothic-Core/Scripts/Services/Npc/NpcService.cs | 5 +++-- Docs/mobs.md | 6 ++++-- 4 files changed, 13 insertions(+), 5 deletions(-) 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 ce07933c5..f601b53e9 100644 --- a/Assets/Gothic-Core/Scripts/Domain/Npc/Actions/AnimationActions/UseMob.cs +++ b/Assets/Gothic-Core/Scripts/Domain/Npc/Actions/AnimationActions/UseMob.cs @@ -105,7 +105,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; 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/Services/Npc/NpcService.cs b/Assets/Gothic-Core/Scripts/Services/Npc/NpcService.cs index 411e19050..6b3504d6a 100644 --- a/Assets/Gothic-Core/Scripts/Services/Npc/NpcService.cs +++ b/Assets/Gothic-Core/Scripts/Services/Npc/NpcService.cs @@ -900,8 +900,9 @@ 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 and when the NPC starts over (culled, - /// re-enabled: AiHandler). The last user who was in one of the mob's states leaves it at -1 (Wld_GetMobState + /// 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). /// diff --git a/Docs/mobs.md b/Docs/mobs.md index bdd48c574..8a087627e 100644 --- a/Docs/mobs.md +++ b/Docs/mobs.md @@ -29,8 +29,10 @@ 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) and when the NPC -starts over (`AiHandler`). +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 From 4bc4df4fa6b98b5a4963d40e406f567a4ed7fcca Mon Sep 17 00:00:00 2001 From: JaXt0r Date: Thu, 3 Dec 2026 06:08:54 +0100 Subject: [PATCH 18/29] fix: a mob whose model has no root node logs why it won't move instead of staying silent (MobAnimator) Co-Authored-By: Claude Opus 5.5 --- Assets/Gothic-Core/Scripts/Adapters/Vob/MobAnimator.cs | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/Assets/Gothic-Core/Scripts/Adapters/Vob/MobAnimator.cs b/Assets/Gothic-Core/Scripts/Adapters/Vob/MobAnimator.cs index 9e28135ca..0202a466a 100644 --- a/Assets/Gothic-Core/Scripts/Adapters/Vob/MobAnimator.cs +++ b/Assets/Gothic-Core/Scripts/Adapters/Vob/MobAnimator.cs @@ -67,7 +67,11 @@ 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); From 8041949c45b29d1aa967f66253f84d46d8b5aaab Mon Sep 17 00:00:00 2001 From: JaXt0r Date: Thu, 3 Dec 2026 06:14:34 +0100 Subject: [PATCH 19/29] fix: the sound effects slider works through the SoundEffects mixer group - every sound effect follows it, a voice doesn't All sound effect sources play through AudioMixer's SoundEffects group; Gothic.ini soundVolume sets its exposed SoundEffectsVolume (20*log10, 0 = -80 dB) at Gothic.ini load and when the menu changes it. A source's volume keeps only Gothic's own (C_SFX_DEF vol, a VOB's volume): the per-source registry (SetSfxVolume) and the "* SoundVolume" multiplications are gone, and so is its leak and the clamp at 1. - Prefabs (via UnityMCP): NPC sound (Core + VR oCNpc BIP01), VR door/chest lock picking, the player's mouth. - Runtime sources: AudioService.AddSfxSource (mob animator, burning NPC, barrier thunder, hero body/steps, spell invest loop) and AudioService.PlaySfxAtPoint instead of AudioSource.PlayClipAtPoint (particles, movers, bow, crossbow, torch, backpack, pickpocket, trade, spells, XriSfxPlayer). - NPC dialog voices get no mixer group instead of copying NpcSound's. Co-Authored-By: Claude Opus 5.5 --- .../Resources/Prefabs/Vobs/oCNpc.prefab | 10 +- .../Animations/AnimationEffectPlayer.cs | 8 +- .../Scripts/Adapters/Npc/NpcBurnEffect.cs | 2 +- .../Scripts/Adapters/Vob/MobAnimator.cs | 7 +- .../Adapters/Vob/MobAnimatorFactory.cs | 6 +- .../Scripts/Adapters/Vob/MoverAdapter.cs | 2 +- .../Npc/Actions/AnimationActions/Output.cs | 3 +- .../Domain/Vobs/VobInitializerDomain.cs | 5 +- .../Scripts/Services/Audio/AudioService.cs | 127 ++++++++++-------- .../Services/Meshes/ParticleService.cs | 4 +- .../Scripts/Services/Vm/VmService.cs | 2 +- .../Scripts/Services/World/BarrierService.cs | 2 +- .../VR/Prefabs/VR - Player XRI.prefab | 2 +- .../VR/Prefabs/Vobs/oCMobContainer.prefab | 3 +- .../VR/Prefabs/Vobs/oCMobDoor.prefab | 3 +- .../Resources/VR/Prefabs/Vobs/oCNpc.prefab | 2 +- .../Scripts/Adapters/Player/VRBackpack.cs | 2 +- .../Scripts/Adapters/Player/VRHeroBody.cs | 2 +- .../Scripts/Adapters/Player/VRHeroMovement.cs | 2 +- .../Scripts/Adapters/Player/VRPickpocket.cs | 2 +- .../Scripts/Adapters/Trade/VRTradeCounter.cs | 2 +- .../Scripts/Adapters/Vob/VobItem/VRBow.cs | 2 +- .../Adapters/Vob/VobItem/VRCrossbow.cs | 2 +- .../Scripts/Adapters/Vob/VobItem/VRMouth.cs | 2 +- .../Scripts/Adapters/Vob/VobItem/VRSpellFx.cs | 16 ++- .../Scripts/Adapters/Vob/VobItem/VRTorch.cs | 2 +- .../Interaction/Backends/Xri/XriSfxPlayer.cs | 12 +- 27 files changed, 139 insertions(+), 95 deletions(-) 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 index b151d2ba2..12c5fd896 100644 --- a/Assets/Gothic-Core/Scripts/Adapters/Animations/AnimationEffectPlayer.cs +++ b/Assets/Gothic-Core/Scripts/Adapters/Animations/AnimationEffectPlayer.cs @@ -107,16 +107,16 @@ public bool ApplySfxEvents(AnimationTrackInstance trackInstance) sfx.Name.Substring(GroundSoundDomain.GroundEventPrefix.Length), _stepOrigin.position); var stepClip = _audioService.GetRandomSoundClip(stepName, out var stepVolume); if (stepClip != null) - _sound.PlayOneShot(stepClip, stepVolume * _audioService.SoundVolume); + _sound.PlayOneShot(stepClip, stepVolume); continue; } - // Gothic's volume of the sound (Forge_Sharpen 40 of 127) and the player's sound volume, which a - // long clip (FORGE_FIRE) follows while it plays. Its source plays one clip at a time. + // 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. var clip = _audioService.GetRandomSoundClip(sfx.Name, out var volume); var clipSource = GetClipSource(); clipSource.clip = clip; - _audioService.SetSfxVolume(clipSource, _soundBaseVolume * volume); + clipSource.volume = _soundBaseVolume * volume; clipSource.maxDistance = _audioService.GetSfxRangeMeters(sfx.Name, sfx.Range.ToMeter()); clipSource.Play(); } 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/Vob/MobAnimator.cs b/Assets/Gothic-Core/Scripts/Adapters/Vob/MobAnimator.cs index 0202a466a..aae5275ee 100644 --- a/Assets/Gothic-Core/Scripts/Adapters/Vob/MobAnimator.cs +++ b/Assets/Gothic-Core/Scripts/Adapters/Vob/MobAnimator.cs @@ -4,6 +4,7 @@ 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; @@ -42,13 +43,15 @@ public class MobAnimator : MonoBehaviour, IMobAnimator /// /// 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). + /// 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) + 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; diff --git a/Assets/Gothic-Core/Scripts/Adapters/Vob/MobAnimatorFactory.cs b/Assets/Gothic-Core/Scripts/Adapters/Vob/MobAnimatorFactory.cs index 58344c086..c8543a005 100644 --- a/Assets/Gothic-Core/Scripts/Adapters/Vob/MobAnimatorFactory.cs +++ b/Assets/Gothic-Core/Scripts/Adapters/Vob/MobAnimatorFactory.cs @@ -1,13 +1,17 @@ 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) @@ -25,7 +29,7 @@ public IMobAnimator GetOrCreate(VobContainer mob, AnimationSkeleton skeleton) } animator = mob.Go.AddComponent(); - animator.Init(skeleton); + animator.Init(skeleton, _audioService.SoundEffectsGroup); return animator; } 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/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/Vobs/VobInitializerDomain.cs b/Assets/Gothic-Core/Scripts/Domain/Vobs/VobInitializerDomain.cs index 7b8347a88..fb9a2f512 100644 --- a/Assets/Gothic-Core/Scripts/Domain/Vobs/VobInitializerDomain.cs +++ b/Assets/Gothic-Core/Scripts/Domain/Vobs/VobInitializerDomain.cs @@ -808,8 +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. - // Gothic's volume is 0...100, Unity's is 0...1. Times the player's sound volume, a loop follows the slider. - _audioService.SetSfxVolume(source, soundData.Volume / 100f); + // 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/Services/Audio/AudioService.cs b/Assets/Gothic-Core/Scripts/Services/Audio/AudioService.cs index c9b003179..5fcb84daf 100644 --- a/Assets/Gothic-Core/Scripts/Services/Audio/AudioService.cs +++ b/Assets/Gothic-Core/Scripts/Services/Audio/AudioService.cs @@ -15,8 +15,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 { @@ -51,21 +53,24 @@ public class AudioService private AudioSource _scriptSoundSource; - // Gothic.ini soundVolume, read on first use and again when the menu changes it. Stays unset while Gothic.ini - // isn't loaded (the player scene runs before a game was picked): the default would stick otherwise. - private float? _soundVolume; - // Sound effect sources that follow the slider (SetSfxVolume): their volume without it. - private readonly Dictionary _sfxSources = new(); - private readonly List _destroyedSfxSources = new(); + // 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); - // The old world's sources are gone by now. - GlobalEventDispatcher.WorldSceneLoaded.AddListener(RemoveDestroyedSfxSources); } // @@ -192,71 +197,85 @@ public void SetScriptSoundSource(AudioSource audioSource) _scriptSoundSource = audioSource; } - // The slider position that plays the sounds at Gothic's own volume: the slider's top end is louder (1/0.75). - private const float _ownVolumeSliderPosition = 0.75f; - /// - /// The player's sound effects gain (options slider, Gothic.ini [SOUND] soundVolume 0..1): the slider at 0.75 - /// plays Gothic's own volume, the top end a third louder. Voices and music have their own. + /// 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. /// - public float SoundVolume + [CanBeNull] + public AudioMixerGroup SoundEffectsGroup { get { - if (_soundVolume.HasValue) - return _soundVolume.Value; - - var slider = Mathf.Clamp01(_configService.GetGothicOption(Constants.IniNames.SoundVolume, - Constants.IniNames.SoundVolumeDefaultValue)); - var volume = slider / _ownVolumeSliderPosition; - if (_configService.Gothic == null) - return volume; - - _soundVolume = volume; - Logger.Log($"[SoundVolume] Sound effects slider {slider:0.##} (Gothic.ini soundVolume), gain " + - $"{volume:0.##}.", - LogCat.Audio); - return volume; + LoadMixer(); + return _soundEffectsGroup; } } /// - /// Sets a sound effect source's volume: the sound's own (Gothic's, 0..1) times the player's SoundVolume. The - /// source follows the slider from now on - a loop that plays (a VOB's campfire, the forge fire) changes at - /// once. Call it again when the source plays another sound with another volume. + /// Adds an AudioSource for sound effects to the GameObject, routed to SoundEffectsGroup. /// - public void SetSfxVolume(AudioSource source, float soundVolume) + public AudioSource AddSfxSource(GameObject go) { - _sfxSources[source] = soundVolume; - source.volume = soundVolume * SoundVolume; + var source = go.AddComponent(); + source.outputAudioMixerGroup = SoundEffectsGroup; + return source; } - private void OnSoundOptionUpdated(string key, object value) + /// + /// Like AudioSource.PlayClipAtPoint() (a 3D one-shot on a temporary GameObject), through SoundEffectsGroup. + /// + public void PlaySfxAtPoint(AudioClip clip, Vector3 position, float volume = 1f) { - if (key != Constants.IniNames.SoundVolume) + if (clip == null) return; - _soundVolume = null; - var volume = SoundVolume; - foreach (var (source, soundVolume) in _sfxSources) - { - if (source != null) - source.volume = soundVolume * volume; - } - RemoveDestroyedSfxSources(); + 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 RemoveDestroyedSfxSources() + private void LoadMixer() { - foreach (var (source, _) in _sfxSources) - { - if (source == null) - _destroyedSfxSources.Add(source); - } + if (_isMixerLoaded) + return; + + _isMixerLoaded = true; + _mixer = Resources.Load(_mixerResourcePath); + var groups = _mixer != null ? _mixer.FindMatchingGroups(_soundEffectsGroupName) : null; + _soundEffectsGroup = groups is { Length: > 0 } ? groups[0] : null; + if (_soundEffectsGroup == null) + Logger.LogError($"[SoundVolume] Resources/{_mixerResourcePath} or its {_soundEffectsGroupName} group " + + "is missing: sound effects play without the sound effects slider.", LogCat.Audio); + } + + private void OnSoundOptionUpdated(string key, object value) + { + if (key == Constants.IniNames.SoundVolume) + ApplySoundVolume(); + } + + /// + /// Sets the SoundEffects group's volume from Gothic.ini [SOUND] soundVolume (0..1, the options' slider): 1 is + /// Gothic's own volume of each sound (0 dB) like the engine's default, 0 is silent. + /// + private void ApplySoundVolume() + { + LoadMixer(); + if (_mixer == null) + return; - foreach (var source in _destroyedSfxSources) - _sfxSources.Remove(source); - _destroyedSfxSources.Clear(); + 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); } /// @@ -283,7 +302,7 @@ public void PlaySound2D(string soundName) var clip = GetRandomSoundClip(soundName); if (clip != null) - _scriptSoundSource.PlayOneShot(clip, SoundVolume); + _scriptSoundSource.PlayOneShot(clip); } [CanBeNull] 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/Vm/VmService.cs b/Assets/Gothic-Core/Scripts/Services/Vm/VmService.cs index dc587ddc8..f872faaab 100644 --- a/Assets/Gothic-Core/Scripts/Services/Vm/VmService.cs +++ b/Assets/Gothic-Core/Scripts/Services/Vm/VmService.cs @@ -114,7 +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 (the sound effects volume works: AudioService.SoundVolume) + // 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/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..1f524010c 100644 --- a/Assets/Gothic-VR/Resources/VR/Prefabs/Vobs/oCNpc.prefab +++ b/Assets/Gothic-VR/Resources/VR/Prefabs/Vobs/oCNpc.prefab @@ -211,7 +211,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 d6ac3c223..34b7c4834 100644 --- a/Assets/Gothic-VR/Scripts/Adapters/Vob/VobItem/VRMouth.cs +++ b/Assets/Gothic-VR/Scripts/Adapters/Vob/VobItem/VRMouth.cs @@ -249,7 +249,7 @@ private IEnumerator ConsumeObject(GameObject go, [CanBeNull] AudioClip clip, flo if (startDelay > 0f) yield return new WaitForSeconds(startDelay); if (clip != null) - _mouthAudio.PlayOneShot(clip, volume * _audioService.SoundVolume); + _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) From 1b3391be3dd1ccf68e71270f01cd9dbdfe98134d Mon Sep 17 00:00:00 2001 From: JaXt0r Date: Thu, 3 Dec 2026 06:14:37 +0100 Subject: [PATCH 20/29] fix: the sound effects slider defaults to 1 like Gothic - its top end is Gothic's own volume of each sound Gothic.ini soundVolume missing = 1 (the engine's default and the menu slider's), 0 dB on the SoundEffects group. The 0.75 "own volume" position and the louder top end are gone. Co-Authored-By: Claude Opus 5.5 --- Assets/Gothic-Core/Scripts/Const/Constants.cs | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/Assets/Gothic-Core/Scripts/Const/Constants.cs b/Assets/Gothic-Core/Scripts/Const/Constants.cs index 30b9aad27..a9568473b 100644 --- a/Assets/Gothic-Core/Scripts/Const/Constants.cs +++ b/Assets/Gothic-Core/Scripts/Const/Constants.cs @@ -31,9 +31,10 @@ 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 (AudioService.SoundVolume). + // 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 = 0.75f; // Gothic's own volume (AudioService) + public const float SoundVolumeDefaultValue = 1f; // [VIDEO] 0..1, vanilla 0.5 = neutral (the menu's Brightness slider). public const string VideoBrightness = "zVidBrightness"; From 9c736adf454924eb2cadc99629880c217bda5465 Mon Sep 17 00:00:00 2001 From: JaXt0r Date: Thu, 3 Dec 2026 06:17:07 +0100 Subject: [PATCH 21/29] fix: an NPC's animation sound effects play on an animation sound source that sits in its prefab - no source built at runtime, a new NpcSound setting can't be forgotten (AnimationEffectPlayer) Co-Authored-By: Claude Opus 5.5 --- .../Animations/AnimationEffectPlayer.cs | 74 +++------- .../Adapters/Animations/AnimationSystem.cs | 2 +- .../Adapters/Npc/NpcPrefabProperties.cs | 3 + .../Scripts/Adapters/Vob/MobAnimator.cs | 2 +- .../Resources/VR/Prefabs/Vobs/oCNpc.prefab | 131 ++++++++++++++++++ 5 files changed, 154 insertions(+), 58 deletions(-) diff --git a/Assets/Gothic-Core/Scripts/Adapters/Animations/AnimationEffectPlayer.cs b/Assets/Gothic-Core/Scripts/Adapters/Animations/AnimationEffectPlayer.cs index 12c5fd896..6a5a549f9 100644 --- a/Assets/Gothic-Core/Scripts/Adapters/Animations/AnimationEffectPlayer.cs +++ b/Assets/Gothic-Core/Scripts/Adapters/Animations/AnimationEffectPlayer.cs @@ -46,17 +46,13 @@ private struct ReusedPfx public ParticleSystem[] Systems; } - private const string _clipSourceName = "_AnimationSfx"; - private readonly Transform _boneRoot; private readonly Transform _stepOrigin; - private readonly AudioSource _sound; - private readonly bool _isSoundShared; - // The volume the given source had: Gothic's volume of each sound is applied on top of it. + 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; - // Plays the *eventSFX clips: the given source, or an own one next to it if that's shared (see GetClipSource). - private AudioSource _clipSource; // One-off mode: effects with an index, until their *eventPFXStop. private readonly Dictionary _activePfx = new(); @@ -69,21 +65,21 @@ private struct ReusedPfx /// 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 *eventSFX sounds (one at a time, like the engine's model sound). - /// Others play on the source too (an NPC's NpcSound): its clips get an own source - /// next to it, see GetClipSource(). + /// 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 sound, bool isSoundShared, - bool isReusingPfx) + public AnimationEffectPlayer(Transform boneRoot, Transform stepOrigin, AudioSource stepSound, + AudioSource clipSound, bool isReusingPfx) { _boneRoot = boneRoot; _stepOrigin = stepOrigin; - _sound = sound; - _isSoundShared = isSoundShared; - _soundBaseVolume = sound != null ? sound.volume : 1f; + _stepSound = stepSound; + _clipSound = clipSound; + _soundBaseVolume = clipSound != null ? clipSound.volume : 1f; _isReusingPfx = isReusingPfx; - if (!isSoundShared) - _clipSource = sound; } /// @@ -107,56 +103,22 @@ public bool ApplySfxEvents(AnimationTrackInstance trackInstance) sfx.Name.Substring(GroundSoundDomain.GroundEventPrefix.Length), _stepOrigin.position); var stepClip = _audioService.GetRandomSoundClip(stepName, out var stepVolume); if (stepClip != null) - _sound.PlayOneShot(stepClip, stepVolume); + _stepSound.PlayOneShot(stepClip, stepVolume); 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. var clip = _audioService.GetRandomSoundClip(sfx.Name, out var volume); - var clipSource = GetClipSource(); - clipSource.clip = clip; - clipSource.volume = _soundBaseVolume * volume; - clipSource.maxDistance = _audioService.GetSfxRangeMeters(sfx.Name, sfx.Range.ToMeter()); - clipSource.Play(); + _clipSound.clip = clip; + _clipSound.volume = _soundBaseVolume * volume; + _clipSound.maxDistance = _audioService.GetSfxRangeMeters(sfx.Name, sfx.Range.ToMeter()); + _clipSound.Play(); } return sfxEvents.Count > 0; } - /// - /// The source of the *eventSFX clips. An NPC's NpcSound is shared - hits, weapon draws and steps play on it as - /// one-shots, which a clip's volume (Gothic's of each sound) would turn down, and so would its range. Its clips - /// get an own source next to it instead, created on the first one with NpcSound's settings. - /// - private AudioSource GetClipSource() - { - if (_clipSource != null || !_isSoundShared) - return _clipSource; - - var existing = _sound.transform.Find(_clipSourceName); - if (existing != null && existing.TryGetComponent(out _clipSource)) - return _clipSource; - - var clipGo = new GameObject(_clipSourceName); - clipGo.transform.SetParent(_sound.transform, false); - _clipSource = clipGo.AddComponent(); - _clipSource.playOnAwake = false; - _clipSource.outputAudioMixerGroup = _sound.outputAudioMixerGroup; - _clipSource.spatialBlend = _sound.spatialBlend; - _clipSource.priority = _sound.priority; - _clipSource.dopplerLevel = _sound.dopplerLevel; - _clipSource.spread = _sound.spread; - _clipSource.reverbZoneMix = _sound.reverbZoneMix; - _clipSource.rolloffMode = _sound.rolloffMode; - _clipSource.minDistance = _sound.minDistance; - _clipSource.maxDistance = _sound.maxDistance; - if (_sound.rolloffMode == AudioRolloffMode.Custom) - _clipSource.SetCustomCurve(AudioSourceCurveType.CustomRolloff, - _sound.GetCustomCurve(AudioSourceCurveType.CustomRolloff)); - return _clipSource; - } - /// /// *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, ... diff --git a/Assets/Gothic-Core/Scripts/Adapters/Animations/AnimationSystem.cs b/Assets/Gothic-Core/Scripts/Adapters/Animations/AnimationSystem.cs index f330c8fa4..65596f56c 100644 --- a/Assets/Gothic-Core/Scripts/Adapters/Animations/AnimationSystem.cs +++ b/Assets/Gothic-Core/Scripts/Adapters/Animations/AnimationSystem.cs @@ -140,7 +140,7 @@ private void Start() _initialMeshBoneRot = _bones.Select(i => i.localRotation).ToArray(); _effectPlayer = new AnimationEffectPlayer(Go.transform, transform, PrefabProps.NpcSound, - isSoundShared: true, isReusingPfx: false).Inject(); + PrefabProps.AnimationSfxSound, isReusingPfx: false).Inject(); CreateGraph(); ResizeRootCollider(); 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/Vob/MobAnimator.cs b/Assets/Gothic-Core/Scripts/Adapters/Vob/MobAnimator.cs index aae5275ee..06d1a7a45 100644 --- a/Assets/Gothic-Core/Scripts/Adapters/Vob/MobAnimator.cs +++ b/Assets/Gothic-Core/Scripts/Adapters/Vob/MobAnimator.cs @@ -56,7 +56,7 @@ public void Init(AnimationSkeleton skeleton, AudioMixerGroup soundGroup) _sound.spatialBlend = 1f; _sound.rolloffMode = AudioRolloffMode.Linear; _sound.minDistance = 0f; - _effectPlayer = new AnimationEffectPlayer(transform, transform, _sound, isSoundShared: false, + _effectPlayer = new AnimationEffectPlayer(transform, transform, _sound, _sound, isReusingPfx: true).Inject(); Rest(isSoundStopped: true); diff --git a/Assets/Gothic-VR/Resources/VR/Prefabs/Vobs/oCNpc.prefab b/Assets/Gothic-VR/Resources/VR/Prefabs/Vobs/oCNpc.prefab index 1f524010c..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 From 470c8443b60a8c356c0e3b3d32f556ed17f32c6d Mon Sep 17 00:00:00 2001 From: JaXt0r Date: Thu, 3 Dec 2026 06:17:50 +0100 Subject: [PATCH 22/29] fix: ground sound events are recognised by their prefix independent of the system culture (AnimationEffectPlayer) Co-Authored-By: Claude Opus 5.5 --- .../Scripts/Adapters/Animations/AnimationEffectPlayer.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Assets/Gothic-Core/Scripts/Adapters/Animations/AnimationEffectPlayer.cs b/Assets/Gothic-Core/Scripts/Adapters/Animations/AnimationEffectPlayer.cs index 6a5a549f9..dec97c5b0 100644 --- a/Assets/Gothic-Core/Scripts/Adapters/Animations/AnimationEffectPlayer.cs +++ b/Assets/Gothic-Core/Scripts/Adapters/Animations/AnimationEffectPlayer.cs @@ -95,7 +95,7 @@ public bool ApplySfxEvents(AnimationTrackInstance trackInstance) { // 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(GroundSoundDomain.GroundEventPrefix)) + if (sfx.Name.StartsWith(GroundSoundDomain.GroundEventPrefix, System.StringComparison.Ordinal)) { if (!_groundSoundService.IsEnabled) continue; From 2044ff914c9cc97c7b29d50b4a41b1d56ceafd43 Mon Sep 17 00:00:00 2001 From: JaXt0r Date: Thu, 3 Dec 2026 06:18:04 +0100 Subject: [PATCH 23/29] fix: an animation sound that doesn't exist no longer cuts the sound still playing on the source (a forge fire loop) and is logged once (AnimationEffectPlayer, AudioService) Co-Authored-By: Claude Opus 5.5 --- .../Animations/AnimationEffectPlayer.cs | 3 +++ .../Scripts/Services/Audio/AudioService.cs | 18 +++++++++++++++++- 2 files changed, 20 insertions(+), 1 deletion(-) diff --git a/Assets/Gothic-Core/Scripts/Adapters/Animations/AnimationEffectPlayer.cs b/Assets/Gothic-Core/Scripts/Adapters/Animations/AnimationEffectPlayer.cs index dec97c5b0..2bf288a7d 100644 --- a/Assets/Gothic-Core/Scripts/Adapters/Animations/AnimationEffectPlayer.cs +++ b/Assets/Gothic-Core/Scripts/Adapters/Animations/AnimationEffectPlayer.cs @@ -110,6 +110,9 @@ public bool ApplySfxEvents(AnimationTrackInstance trackInstance) // 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. var clip = _audioService.GetRandomSoundClip(sfx.Name, out var volume); + // No clip (missing or nosound): a clip still playing on the source (a fire loop) keeps playing. + if (clip == null) + continue; _clipSound.clip = clip; _clipSound.volume = _soundBaseVolume * volume; _clipSound.maxDistance = _audioService.GetSfxRangeMeters(sfx.Name, sfx.Range.ToMeter()); diff --git a/Assets/Gothic-Core/Scripts/Services/Audio/AudioService.cs b/Assets/Gothic-Core/Scripts/Services/Audio/AudioService.cs index 5fcb84daf..9352c42dc 100644 --- a/Assets/Gothic-Core/Scripts/Services/Audio/AudioService.cs +++ b/Assets/Gothic-Core/Scripts/Services/Audio/AudioService.cs @@ -52,6 +52,8 @@ public class AudioService }; 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. @@ -386,8 +388,15 @@ public AudioClip GetRandomSoundClip(string soundName, out float volume) 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(out volume)); @@ -395,5 +404,12 @@ public AudioClip GetRandomSoundClip(string soundName, out float 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); + } } } From 239568f3a9c808e48d3aff8866e8d8f6c9689367 Mon Sep 17 00:00:00 2001 From: JaXt0r Date: Thu, 3 Dec 2026 06:18:54 +0100 Subject: [PATCH 24/29] fix: which sound an animation event plays (footstep by ground, Gothic's volume and range) is decided in AudioService, the adapter only plays it (AnimationEffectPlayer, AudioService.GetAnimationSfx) Co-Authored-By: Claude Opus 5.5 --- .../Animations/AnimationEffectPlayer.cs | 33 ++++++++----------- .../Scripts/Models/Audio/AnimationSfx.cs | 28 ++++++++++++++++ .../Scripts/Models/Audio/AnimationSfx.cs.meta | 2 ++ .../Scripts/Services/Audio/AudioService.cs | 26 +++++++++++++++ 4 files changed, 69 insertions(+), 20 deletions(-) create mode 100644 Assets/Gothic-Core/Scripts/Models/Audio/AnimationSfx.cs create mode 100644 Assets/Gothic-Core/Scripts/Models/Audio/AnimationSfx.cs.meta diff --git a/Assets/Gothic-Core/Scripts/Adapters/Animations/AnimationEffectPlayer.cs b/Assets/Gothic-Core/Scripts/Adapters/Animations/AnimationEffectPlayer.cs index 2bf288a7d..a09602275 100644 --- a/Assets/Gothic-Core/Scripts/Adapters/Animations/AnimationEffectPlayer.cs +++ b/Assets/Gothic-Core/Scripts/Adapters/Animations/AnimationEffectPlayer.cs @@ -1,10 +1,8 @@ using System.Collections.Generic; -using Gothic.Core.Domain.Audio; using Gothic.Core.Extensions; using Gothic.Core.Logging; using Gothic.Core.Manager; using Gothic.Core.Models.Animations; -using Gothic.Core.Services.Audio; using Gothic.Core.Services.Meshes; using Reflex.Attributes; using UnityEngine; @@ -28,7 +26,6 @@ public class AnimationEffectPlayer { [Inject] private readonly AudioService _audioService; [Inject] private readonly MeshService _meshService; - [Inject] private readonly GroundSoundService _groundSoundService; // *eventPFX effects that run until their *eventPFXStop (same index). Safety: gone after this time anyway. private const float _pfxMaxSeconds = 12f; @@ -93,29 +90,25 @@ public bool ApplySfxEvents(AnimationTrackInstance trackInstance) 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(GroundSoundDomain.GroundEventPrefix, System.StringComparison.Ordinal)) + // 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) { - if (!_groundSoundService.IsEnabled) - continue; - var stepName = _groundSoundService.GetSoundName( - sfx.Name.Substring(GroundSoundDomain.GroundEventPrefix.Length), _stepOrigin.position); - var stepClip = _audioService.GetRandomSoundClip(stepName, out var stepVolume); - if (stepClip != null) - _stepSound.PlayOneShot(stepClip, stepVolume); + _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. - var clip = _audioService.GetRandomSoundClip(sfx.Name, out var volume); - // No clip (missing or nosound): a clip still playing on the source (a fire loop) keeps playing. - if (clip == null) - continue; - _clipSound.clip = clip; - _clipSound.volume = _soundBaseVolume * volume; - _clipSound.maxDistance = _audioService.GetSfxRangeMeters(sfx.Name, sfx.Range.ToMeter()); + _clipSound.clip = toPlay.Clip; + _clipSound.volume = _soundBaseVolume * toPlay.Volume; + _clipSound.maxDistance = toPlay.RangeMeters; _clipSound.Play(); } 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/Services/Audio/AudioService.cs b/Assets/Gothic-Core/Scripts/Services/Audio/AudioService.cs index 9352c42dc..276dcdb9f 100644 --- a/Assets/Gothic-Core/Scripts/Services/Audio/AudioService.cs +++ b/Assets/Gothic-Core/Scripts/Services/Audio/AudioService.cs @@ -4,9 +4,11 @@ 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; @@ -29,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; @@ -280,6 +283,29 @@ private void ApplySoundVolume() 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 its range (GetSfxRangeMeters). 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, GetSfxRangeMeters(sfxName, gothicRangeMeters), false); + } + /// /// 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. From 3518fe9fc9604639eee7e1ea8f46f0b0333db552 Mon Sep 17 00:00:00 2001 From: JaXt0r Date: Thu, 3 Dec 2026 06:19:53 +0100 Subject: [PATCH 25/29] fix: the hammering range override is a tuning value in Constants.Audio, not a private literal in AudioService (behaviour unchanged) Co-Authored-By: Claude Opus 5.5 --- Assets/Gothic-Core/Scripts/Const/Constants.cs | 19 +++++++++++++++++++ .../Scripts/Services/Audio/AudioService.cs | 9 +-------- 2 files changed, 20 insertions(+), 8 deletions(-) diff --git a/Assets/Gothic-Core/Scripts/Const/Constants.cs b/Assets/Gothic-Core/Scripts/Const/Constants.cs index a9568473b..8914aba82 100644 --- a/Assets/Gothic-Core/Scripts/Const/Constants.cs +++ b/Assets/Gothic-Core/Scripts/Const/Constants.cs @@ -1,3 +1,5 @@ +using System; +using System.Collections.Generic; using Gothic.Core.Extensions; using Gothic.Core.Services; using UnityEngine; @@ -98,6 +100,23 @@ public static class Fires public const float IndoorRadius = 3f; } + /// + /// Tuning values of animation sounds (AudioService). + /// + public static class Audio + { + // Animation sounds that carry further than their *eventSFX range (R:). Finite list, all others keep theirs. + // 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. It applies to every NPC's + // HAMMER. Unity's linear rolloff is quiet long before Gothic's range is felt; a general rolloff change is a + // follow-up. + public static readonly IReadOnlyDictionary SfxRangeOverridesMeters = + new Dictionary(StringComparer.OrdinalIgnoreCase) + { + { "HAMMER", 24f } + }; + } + // Unity shaders public static readonly Shader ShaderUnlit = Shader.Find("Universal Render Pipeline/Unlit"); public static readonly Shader ShaderUnlitParticles = Shader.Find("Universal Render Pipeline/Particles/Unlit"); diff --git a/Assets/Gothic-Core/Scripts/Services/Audio/AudioService.cs b/Assets/Gothic-Core/Scripts/Services/Audio/AudioService.cs index 276dcdb9f..b35c5e0a4 100644 --- a/Assets/Gothic-Core/Scripts/Services/Audio/AudioService.cs +++ b/Assets/Gothic-Core/Scripts/Services/Audio/AudioService.cs @@ -47,13 +47,6 @@ 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); @@ -315,7 +308,7 @@ public AnimationSfx GetAnimationSfx(string sfxName, float gothicRangeMeters, Vec /// public float GetSfxRangeMeters(string sfxName, float gothicRangeMeters) { - return _sfxRangeOverridesMeters.TryGetValue(sfxName, out var overrideMeters) + return Constants.Audio.SfxRangeOverridesMeters.TryGetValue(sfxName, out var overrideMeters) ? overrideMeters : gothicRangeMeters; } From f6af5d0ed6bca5de4c0a1000d03aff5874efce04 Mon Sep 17 00:00:00 2001 From: JaXt0r Date: Thu, 3 Dec 2026 06:21:12 +0100 Subject: [PATCH 26/29] fix: one place decides "visual is a model script" (ZenKitExtension.HasModelScriptVisual) and one names a mob's states and their animations (MobStateNames), used by MobAnimationService and UseMob (behaviour unchanged) Co-Authored-By: Claude Opus 5.5 --- .../Npc/Actions/AnimationActions/UseMob.cs | 12 ++--- .../Scripts/Extensions/ZenKitExtension.cs | 12 ++++- .../Scripts/Models/Vob/MobStateNames.cs | 49 +++++++++++++++++++ .../Scripts/Models/Vob/MobStateNames.cs.meta | 2 + .../Services/Vobs/MobAnimationService.cs | 41 ++++------------ 5 files changed, 75 insertions(+), 41 deletions(-) create mode 100644 Assets/Gothic-Core/Scripts/Models/Vob/MobStateNames.cs create mode 100644 Assets/Gothic-Core/Scripts/Models/Vob/MobStateNames.cs.meta 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 f601b53e9..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,6 +2,7 @@ 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; @@ -19,8 +20,6 @@ public class UseMob : AbstractWalkAnimationAction2 [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; @@ -203,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); } @@ -347,12 +346,9 @@ 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); diff --git a/Assets/Gothic-Core/Scripts/Extensions/ZenKitExtension.cs b/Assets/Gothic-Core/Scripts/Extensions/ZenKitExtension.cs index 758712560..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); } /// 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..821fa86ae --- /dev/null +++ b/Assets/Gothic-Core/Scripts/Models/Vob/MobStateNames.cs @@ -0,0 +1,49 @@ +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); + } + + /// + /// 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/Services/Vobs/MobAnimationService.cs b/Assets/Gothic-Core/Scripts/Services/Vobs/MobAnimationService.cs index 60b8a2c00..4bb4bc6ee 100644 --- a/Assets/Gothic-Core/Scripts/Services/Vobs/MobAnimationService.cs +++ b/Assets/Gothic-Core/Scripts/Services/Vobs/MobAnimationService.cs @@ -8,6 +8,7 @@ using Gothic.Core.Manager; using Gothic.Core.Models.Animations; using Gothic.Core.Models.Container; +using Gothic.Core.Models.Vob; using Gothic.Core.Services.Npc; using JetBrains.Annotations; using Reflex.Attributes; @@ -32,8 +33,6 @@ public class MobAnimationService [Inject] private readonly IMobAnimatorFactory _mobAnimatorFactory; [Inject] private readonly VobService _vobService; - private const string _mdsExtension = ".MDS"; - private const string _standStateName = "STAND"; // The states a used mob plays in nearly every model script - looked up at world load (see WarmWorldMobs). private static readonly (int From, int To)[] _warmedStateChanges = { (0, 1), (1, 0) }; @@ -69,9 +68,7 @@ public bool IsAnimated([CanBeNull] VobContainer mob) if (vob is not IInteractiveObject || vob is IFire || vob.IsHingeMob() || vob.IsBed()) return false; - var visualName = vob.Visual?.Name; - return !string.IsNullOrEmpty(visualName) && - visualName.EndsWith(_mdsExtension, StringComparison.OrdinalIgnoreCase); + return vob.HasModelScriptVisual(); } /// @@ -101,8 +98,8 @@ public void OnStateChanged([CanBeNull] VobContainer mob, [CanBeNull] NpcContaine if (skeleton == null) return; - var transition = GetTrack(visualName, GetTransitionName(from, to)); - var loop = user != null ? GetTrack(visualName, GetLoopName(to)) : null; + var transition = GetTrack(visualName, MobStateNames.GetTransitionName(from, to)); + var loop = user != null ? GetTrack(visualName, MobStateNames.GetLoopName(to)) : null; if (transition == null && loop == null) return; @@ -111,8 +108,8 @@ public void OnStateChanged([CanBeNull] VobContainer mob, [CanBeNull] NpcContaine return; animator.Play(to, transition, loop); - Logger.LogEditor($"[MobAnimation] {mob.Vob.Name} ({visualName}): {GetStateName(from)} -> " + - $"{GetStateName(to)} by {user?.Instance?.GetName(NpcNameSlot.Slot0) ?? "nobody"}", + Logger.LogEditor($"[MobAnimation] {mob.Vob.Name} ({visualName}): {MobStateNames.GetStateName(from)} -> " + + $"{MobStateNames.GetStateName(to)} by {user?.Instance?.GetName(NpcNameSlot.Slot0) ?? "nobody"}", LogCat.Vob); } @@ -143,9 +140,9 @@ private void StopIfLastUser([CanBeNull] VobContainer mob, [CanBeNull] NpcContain return; var state = animator.State; - var back = state > 0 ? GetTrack(mob.Vob.Visual.Name, GetTransitionName(state, state - 1)) : null; + 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 {GetStateName(state)}.", + Logger.LogEditor($"[MobAnimation] {mob.Vob.Name}: last user left - stopping from {MobStateNames.GetStateName(state)}.", LogCat.Vob); } @@ -198,24 +195,6 @@ private bool HasOtherUser(VobContainer mob, NpcContainer user) return _vobService.GetOtherMobUsers(mob, user).Any(i => i.IsUsingMob()); } - /// - /// The name of a mob state inside its animations: -1 (not used) is STAND, the others S0, S1, ... - /// - private static string GetStateName(int state) - { - return state < 0 ? _standStateName : "S" + state; - } - - private static string GetTransitionName(int from, int to) - { - return "T_" + GetStateName(from) + "_2_" + GetStateName(to); - } - - private static string GetLoopName(int state) - { - return "S_" + GetStateName(state); - } - /// /// The skeleton of the mob's model (its nodes). Null (logged once) if the model has no hierarchy. /// @@ -279,9 +258,9 @@ private void WarmModel(string visualName) var found = new StringBuilder(); foreach (var (from, to) in _warmedStateChanges) - WarmTrack(visualName, GetTransitionName(from, to), found); + WarmTrack(visualName, MobStateNames.GetTransitionName(from, to), found); foreach (var state in _warmedLoops) - WarmTrack(visualName, GetLoopName(state), found); + WarmTrack(visualName, MobStateNames.GetLoopName(state), found); var foundNames = found.Length > 0 ? found.ToString() : "no state animations"; Logger.LogEditor($"[MobAnimation] {visualName}: {foundNames}", LogCat.Vob); From 80e7ada4c0d503217ad55f897f93e8b5c6b26e75 Mon Sep 17 00:00:00 2001 From: JaXt0r Date: Thu, 3 Dec 2026 06:23:41 +0100 Subject: [PATCH 27/29] fix: mob animations are baked during world loading behind the loading screen, frame by frame, and all of a mob's state tracks are baked, not only S0/S1 (MobAnimationService.WarmWorldMobsAsync, WorldScene, MobStateNames.IsOwnStateAnimation) Before, the warm-up ran synchronously in the WorldSceneLoaded listener (~115 ms in the Editor for G2 Khorinis, more on Quest 2) and only baked T_S0_2_S1, S_S1, T_S1_2_S0 - mobs reaching S2 or STAND<->S0 still baked on first use. Now WorldScene awaits it right after the VOBs; FrameSkipperService yields between tracks. Every state animation in the mob's model script (T__2_, S_) is baked and its sounds decoded. Co-Authored-By: Claude Opus 5.5 --- .../Scripts/Adapters/Scenes/WorldScene.cs | 8 ++ .../Scripts/Models/Vob/MobStateNames.cs | 31 ++++++++ .../Services/Vobs/MobAnimationService.cs | 73 ++++++++++++------- Docs/mobs.md | 7 +- 4 files changed, 90 insertions(+), 29 deletions(-) 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/Models/Vob/MobStateNames.cs b/Assets/Gothic-Core/Scripts/Models/Vob/MobStateNames.cs index 821fa86ae..8a7519b4b 100644 --- a/Assets/Gothic-Core/Scripts/Models/Vob/MobStateNames.cs +++ b/Assets/Gothic-Core/Scripts/Models/Vob/MobStateNames.cs @@ -1,3 +1,6 @@ +using System; +using System.Linq; + namespace Gothic.Core.Models.Vob { /// @@ -30,6 +33,34 @@ 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_". /// diff --git a/Assets/Gothic-Core/Scripts/Services/Vobs/MobAnimationService.cs b/Assets/Gothic-Core/Scripts/Services/Vobs/MobAnimationService.cs index 4bb4bc6ee..8d909cec8 100644 --- a/Assets/Gothic-Core/Scripts/Services/Vobs/MobAnimationService.cs +++ b/Assets/Gothic-Core/Scripts/Services/Vobs/MobAnimationService.cs @@ -3,12 +3,14 @@ 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; @@ -29,15 +31,13 @@ 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; - // The states a used mob plays in nearly every model script - looked up at world load (see WarmWorldMobs). - private static readonly (int From, int To)[] _warmedStateChanges = { (0, 1), (1, 0) }; - private static readonly int[] _warmedLoops = { 1 }; - // 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. @@ -51,7 +51,6 @@ public class MobAnimationService public void Init() { - GlobalEventDispatcher.WorldSceneLoaded.AddListener(WarmWorldMobs); GlobalEventDispatcher.MobDialogEnded.AddListener(StopHeroUse); GlobalEventDispatcher.LoadGameStart.AddListener(ForgetHeroUse); GlobalEventDispatcher.LoadingSceneLoaded.AddListener(ForgetHeroUse); @@ -222,48 +221,68 @@ private AnimationTrack GetTrack(string visualName, string animationName) } /// - /// The tracks of the world's mobs are baked while the world loads (P3): 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). + /// 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. /// - private void WarmWorldMobs() + public async Task WarmWorldMobsAsync() { var watch = Stopwatch.StartNew(); - var modelCount = 0; + + // 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)) - continue; - - var visualName = mob.Vob.Visual.Name; - if (!_warmedModels.Add(visualName)) - continue; - - WarmModel(visualName); - modelCount++; + if (IsAnimated(mob) && _warmedModels.Add(mob.Vob.Visual.Name)) + visualNames.Add(mob.Vob.Visual.Name); } } - if (modelCount > 0) - Logger.Log($"[MobAnimation] Animations of {modelCount} mob models baked in " + + 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); } - private void WarmModel(string visualName) + /// + /// 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; + 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 (from, to) in _warmedStateChanges) - WarmTrack(visualName, MobStateNames.GetTransitionName(from, to), found); - foreach (var state in _warmedLoops) - WarmTrack(visualName, MobStateNames.GetLoopName(state), found); + 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) diff --git a/Docs/mobs.md b/Docs/mobs.md index 8a087627e..88c91926a 100644 --- a/Docs/mobs.md +++ b/Docs/mobs.md @@ -56,8 +56,11 @@ State -1 is called `STAND` in the names (`T_STAND_2_S0` - most mobs don't have i ### Data flow -1. World load: `MobAnimationService` bakes `T_S0_2_S1`, `S_S1`, `T_S1_2_S0` of every animated mob model in - `GameStateService.VobsInteractable` and decodes their sounds (P3). The Editor log lists the tracks found per model. +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 From 6cfd2e6e912e4c86540b5c6434e01a7808909ead Mon Sep 17 00:00:00 2001 From: JaXt0r Date: Thu, 3 Dec 2026 06:24:40 +0100 Subject: [PATCH 28/29] docs: ADR for the sound effects slider (Gothic's own volume, default 1) and the hammering range The sound effects slider is Gothic's global volume: 1 plays each sound at its own Gothic loudness, lower values turn all sound effects down together. Voices and music are not part of it. Hammering reaches 24 m instead of Gothic's 10 m so Fellan's hammering is heard at Alwin's sheep pen. Co-Authored-By: Claude Opus 5.5 --- Docs/adr/2026-12-03-sound-effects-volume.md | 24 +++++++++++++++++++++ 1 file changed, 24 insertions(+) create mode 100644 Docs/adr/2026-12-03-sound-effects-volume.md 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..14acad796 --- /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 hammering carries farther + +- 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. **Hammering is heard up to 24 m away, not 10 m.** Gothic's range for hammering is 10 m. Fellan's hammering has to reach Alwin's sheep pen about 18 m away for his quest, so the hammering range is raised for that sound only. Not chosen: 60 m, which was heard across the whole harbour. Not chosen either: changing how all sounds fade with distance; that is a separate question for later. + +## 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. +- Other sounds keep Unity's standard fade with distance, which is quiet long before Gothic's range ends. Only hammering has its own range for now. From 745812cdc1e6a39e33dc737dc91d1296251c9577 Mon Sep 17 00:00:00 2001 From: JaXt0r Date: Thu, 3 Dec 2026 06:57:56 +0100 Subject: [PATCH 29/29] fix: animation sounds carry exactly their Gothic range like in OpenGothic - the hammering override is gone (#569) Every animation sound now fades linearly to silence at its own Gothic R: range (cm -> m), as OpenGothic does with OpenAL linear distance, max distance = range. The per-sound override (HAMMER 24 m, Constants.Audio) is removed, so Fellan's hammering is heard up to 10 m again. Whether the original fades more gently is open in #569. Co-Authored-By: Claude Opus 5.5 --- Assets/Gothic-Core/Scripts/Const/Constants.cs | 19 ------------------- .../Scripts/Services/Audio/AudioService.cs | 18 ++---------------- Docs/adr/2026-12-03-sound-effects-volume.md | 6 +++--- 3 files changed, 5 insertions(+), 38 deletions(-) diff --git a/Assets/Gothic-Core/Scripts/Const/Constants.cs b/Assets/Gothic-Core/Scripts/Const/Constants.cs index 8914aba82..a9568473b 100644 --- a/Assets/Gothic-Core/Scripts/Const/Constants.cs +++ b/Assets/Gothic-Core/Scripts/Const/Constants.cs @@ -1,5 +1,3 @@ -using System; -using System.Collections.Generic; using Gothic.Core.Extensions; using Gothic.Core.Services; using UnityEngine; @@ -100,23 +98,6 @@ public static class Fires public const float IndoorRadius = 3f; } - /// - /// Tuning values of animation sounds (AudioService). - /// - public static class Audio - { - // Animation sounds that carry further than their *eventSFX range (R:). Finite list, all others keep theirs. - // 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. It applies to every NPC's - // HAMMER. Unity's linear rolloff is quiet long before Gothic's range is felt; a general rolloff change is a - // follow-up. - public static readonly IReadOnlyDictionary SfxRangeOverridesMeters = - new Dictionary(StringComparer.OrdinalIgnoreCase) - { - { "HAMMER", 24f } - }; - } - // Unity shaders public static readonly Shader ShaderUnlit = Shader.Find("Universal Render Pipeline/Unlit"); public static readonly Shader ShaderUnlitParticles = Shader.Find("Universal Render Pipeline/Particles/Unlit"); diff --git a/Assets/Gothic-Core/Scripts/Services/Audio/AudioService.cs b/Assets/Gothic-Core/Scripts/Services/Audio/AudioService.cs index b35c5e0a4..3c2e2f1df 100644 --- a/Assets/Gothic-Core/Scripts/Services/Audio/AudioService.cs +++ b/Assets/Gothic-Core/Scripts/Services/Audio/AudioService.cs @@ -280,7 +280,7 @@ private void ApplySoundVolume() /// 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 its range (GetSfxRangeMeters). Clip is null if there is nothing to play. + /// 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) { @@ -296,21 +296,7 @@ public AnimationSfx GetAnimationSfx(string sfxName, float gothicRangeMeters, Vec } var clip = GetRandomSoundClip(sfxName, out var volume); - return new AnimationSfx(clip, volume, GetSfxRangeMeters(sfxName, gothicRangeMeters), false); - } - - /// - /// 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. - /// - public float GetSfxRangeMeters(string sfxName, float gothicRangeMeters) - { - return Constants.Audio.SfxRangeOverridesMeters.TryGetValue(sfxName, out var overrideMeters) - ? overrideMeters - : gothicRangeMeters; + return new AnimationSfx(clip, volume, gothicRangeMeters, false); } /// diff --git a/Docs/adr/2026-12-03-sound-effects-volume.md b/Docs/adr/2026-12-03-sound-effects-volume.md index 14acad796..64e2f013d 100644 --- a/Docs/adr/2026-12-03-sound-effects-volume.md +++ b/Docs/adr/2026-12-03-sound-effects-volume.md @@ -1,4 +1,4 @@ -# ADR: The sound effects slider is Gothic's own volume, and hammering carries farther +# ADR: The sound effects slider is Gothic's own volume, and sounds keep Gothic's range - Date: 2026-12-03 @@ -14,11 +14,11 @@ Our first version tried to give the slider its own scale: a position at three qu 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. **Hammering is heard up to 24 m away, not 10 m.** Gothic's range for hammering is 10 m. Fellan's hammering has to reach Alwin's sheep pen about 18 m away for his quest, so the hammering range is raised for that sound only. Not chosen: 60 m, which was heard across the whole harbour. Not chosen either: changing how all sounds fade with distance; that is a separate question for later. +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. -- Other sounds keep Unity's standard fade with distance, which is quiet long before Gothic's range ends. Only hammering has its own range for now. +- 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.