diff --git a/Assets/Gothic-Core/Scripts/Adapters/Npc/NpcAnimationSequence.cs b/Assets/Gothic-Core/Scripts/Adapters/Npc/NpcAnimationSequence.cs new file mode 100644 index 000000000..0f6253a16 --- /dev/null +++ b/Assets/Gothic-Core/Scripts/Adapters/Npc/NpcAnimationSequence.cs @@ -0,0 +1,105 @@ +using UnityEngine; + +namespace Gothic.Core.Adapters.Npc +{ + /// + /// Animations played on an NPC one after another, each for its own duration - a landing (NpcJumpFall) or a climb + /// (NpcLedgeClimb). Animations the model doesn't have are skipped. Can't move any more (died, swimming): the rest + /// plays none of them (the death's or swimming's animations take over), the time still runs to the end. + /// + internal class NpcAnimationSequence + { + private readonly NpcMoveBody _body; + + public NpcAnimationSequence(NpcMoveBody body) + { + _body = body; + } + + public string[] Animations { get; private set; } + + /// + /// s per animation, 0 for one the model doesn't have. + /// + public float[] Durations { get; private set; } + + /// + /// The animation playing now; Animations.Length when all are done. + /// + public int Index { get; private set; } + + /// + /// s since the current animation began. + /// + public float AnimationTime { get; private set; } + + /// + /// s since the sequence began. + /// + public float Elapsed { get; private set; } + + /// + /// s the whole sequence lasts - the sum of the animations, a climb may set its own. + /// + public float Duration { get; set; } + + public bool IsDone => Elapsed >= Duration; + + /// + /// 0..1 of Duration. + /// + public float Progress => Mathf.Clamp01(Elapsed / Duration); + + public void Start(string[] animations) + { + Animations = animations; + Durations = new float[animations.Length]; + Duration = 0f; + for (var i = 0; i < animations.Length; i++) + { + Durations[i] = _body.HasTrack(animations[i]) + ? _body.Animations.GetAnimationDuration(animations[i]) + : 0f; + Duration += Durations[i]; + } + + Index = -1; + AnimationTime = 0f; + Elapsed = 0f; + Next(); + } + + public void Tick(float deltaTime) + { + Elapsed += deltaTime; + AnimationTime += deltaTime; + if (Index < Animations.Length && AnimationTime >= Durations[Index]) + Next(); + } + + /// + /// Stops the animation playing now - the sequence is over. + /// + public void Stop() + { + if (Animations != null && Index >= 0 && Index < Animations.Length) + _body.Animations.StopAnimation(Animations[Index]); + Animations = null; + } + + private void Next() + { + if (Index >= 0 && Index < Animations.Length) + _body.Animations.StopAnimation(Animations[Index]); + + Index++; + AnimationTime = 0f; + while (Index < Animations.Length && Durations[Index] <= 0f) + Index++; + + // Can't move any more: the move ends without our animations (the death's or swimming's play). + if (Index < Animations.Length && _body.CanMove()) + _body.Animations.PlayAnimation(Animations[Index]); + } + } +} diff --git a/Assets/Gothic-Core/Scripts/Adapters/Npc/NpcAnimationSequence.cs.meta b/Assets/Gothic-Core/Scripts/Adapters/Npc/NpcAnimationSequence.cs.meta new file mode 100644 index 000000000..128931628 --- /dev/null +++ b/Assets/Gothic-Core/Scripts/Adapters/Npc/NpcAnimationSequence.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 942fe2213bb48d1469cd59dbcc163b97 \ No newline at end of file diff --git a/Assets/Gothic-Core/Scripts/Adapters/Npc/NpcJumpFall.cs b/Assets/Gothic-Core/Scripts/Adapters/Npc/NpcJumpFall.cs index 279390f44..37c93daa1 100644 --- a/Assets/Gothic-Core/Scripts/Adapters/Npc/NpcJumpFall.cs +++ b/Assets/Gothic-Core/Scripts/Adapters/Npc/NpcJumpFall.cs @@ -7,9 +7,6 @@ using Gothic.Core.Models.Vm; using Gothic.Core.Services; using Gothic.Core.Services.Config; -using Gothic.Core.Services.Movement; -using Gothic.Core.Services.Npc; -using Gothic.Core.Services.World; using Reflex.Attributes; using UnityEngine; using Logger = Gothic.Core.Logging.Logger; @@ -17,16 +14,25 @@ namespace Gothic.Core.Adapters.Npc { /// - /// V1: NPCs fall off ledges and climb onto ledges like the engine. + /// V1: NPCs fall off ledges, climb onto ledges and slide down steep slopes like the engine. /// - Falling: no ground within STEP_HEIGHT below the feet -> S_FALLDN (S_FALL when deeper), the direction and speed /// of the run are kept (no steering in the air), landing T_FALLDN_2_STAND or T_FALL_2_FALLEN + T_FALLEN_2_STAND. /// Fall damage like the engine: FALLDOWN_DAMAGE per meter above FALLDOWN_HEIGHT (Species.d), minus PROT_FALL. - /// - Climbing (chasing NPCs only, called by AttackPlayAni): a ledge in front between STEP_HEIGHT and JUMPMID_HEIGHT - /// is climbed with the JumpUpLow/JumpUpMid animations - only if the model has them (most monsters don't). + /// - Climbing (NpcLedgeClimb): a chasing NPC climbs a ledge in front between STEP_HEIGHT and JUMPMID_HEIGHT with + /// the JumpUpLow/JumpUpMid animations (only if the model has them), a NavMesh ladder link with the ladder ones. + /// - Sliding (NpcSlopeSlide, the guild's SLIDE_ANGLE): down or across steep ground with S_SLIDE / S_SLIDEB, until + /// walkable ground (it walks on), a block, or an edge (it falls). + /// Can't move any more (dead, unconscious, swimming - NpcFallDomain.CanMove): a fall still lands and a climb still + /// reaches its end (nobody hangs in the air), a slide ends at once (it's on the ground) - with no more of our + /// animations, the death or the swimming takes over. Dead and unconscious bodies stay kinematic (their domains + /// made them so), all others get their physics back. /// Lives on the NPC (added on demand), not in an AI action: ZS_Attack_Loop clears the AI queue every ~2 s, an action /// would leave the NPC hanging in the air. /// Not saved - a loaded NPC stands on the ground anyway. - /// The rules live elsewhere: climbing values and the ledge probe in LedgeService, falling in NpcFallDomain. + /// The rules live elsewhere: climbing values and the ledge probe in LedgeService, falling in NpcFallDomain, sliding + /// in SlopeSlideDomain. This class keeps the state switch, the fall and the landing; its workers do the rest: the + /// slide NpcSlopeSlide, the climbs NpcLedgeClimb, the landing's and climbs' animations NpcAnimationSequence, what + /// they all ask of the body (rest height, guild values, ground below, physics) NpcMoveBody. /// Disabled while nothing happens (standing, far from the hero); Get/Wake enable it again when the NPC walks, attacks, /// is hit or pushed. /// @@ -34,25 +40,9 @@ public class NpcJumpFall : MonoBehaviour, INpcJumpFall { [Inject] private readonly GameStateService _gameStateService; [Inject] private readonly ConfigService _configService; - [Inject] private readonly AnimationService _animationService; - [Inject] private readonly PhysicsService _physicsService; - [Inject] private readonly LedgeService _ledgeService; - [Inject] private readonly NpcNavMeshService _npcNavMeshService; - private const float _gravity = 9.81f; private const float _maxFallSpeedH = 6f; private const float _outOfWorldFallHeight = 100f; - private const float _groundProbeExtra = 0.1f; - private const float _climbMinSeconds = 0.6f; - private const float _climbMaxSeconds = 2f; - private const float _climbRisePart = 0.65f; - private const float _ladderSpeed = 1.5f; - private const float _ladderExtraSeconds = 0.6f; - // HUMANS.MDS: one climb cycle t_Ladder_S0_2_S1 (frames 15-45), down = the same played backwards (aliases R). - private static readonly string[] _ladderUp = { "T_LADDER_STAND_2_S0", "T_LADDER_S0_2_S1", "T_LADDER_S1_2_STAND" }; - private static readonly string[] _ladderDown = { "T_LADDER_STAND_2_S1", "T_LADDER_S1_2_S0", "T_LADDER_S0_2_STAND" }; - // Fallback if the climb cycle doesn't lift the root bone itself (0.9 climbed a few cycles too many). - private const float _ladderMetersPerCycle = 1.2f; // Unloaded vobs (bridges, platforms) far from the hero have no colliders yet - nobody falls through them there. private const float _fallCheckMaxHeroDistance = 40f; // Standing (or far from the hero) this long: the component sleeps until Get/Wake. @@ -63,10 +53,15 @@ private enum State None, Falling, Landing, - Climbing + Climbing, + Sliding } private NpcContainer _npc; + private NpcMoveBody _body; + private NpcSlopeSlide _slide; + private NpcAnimationSequence _sequence; + private NpcLedgeClimb _climb; private State _state; private Vector3 _previousPosition; private bool _hasPreviousPosition; @@ -80,30 +75,6 @@ private enum State // Thrown by a spell - lands lying and gets up. private bool _isThrown; - // Landing / climbing: a sequence of animations played one after another. - private string[] _sequence; - private float[] _sequenceDurations; - private int _sequenceIndex; - private float _sequenceTime; - private float _stateTime; - private float _stateDuration; - private Vector3 _climbFrom; - private Vector3 _climbTo; - // Ladders: step to the ladder during the first animation, change height only during the climb cycles, step off - // during the last one (start/end as parts of the whole climb). - private bool _isLadder; - private static bool _hasLoggedLadderCycle; - private Vector3 _ladderColumn; - private float _ladderRiseStart; - private float _ladderRiseEnd; - // The climb animations lift the root bone themselves (pose offset): per animation the NPC's base height, so each - // one starts where the previous one ended - no double lift ("hiccup"). Null: no usable root lift (plain lerp). - private float[] _ladderBases; - private float[] _ladderBlendIns; - // What's left to the ladder's end after the last animation - spread over the whole climb. - private float _ladderEndError; - private const float _ladderMaxEndError = 1.5f; - public bool IsBusy => _state != State.None; public static NpcJumpFall Get(NpcContainer npc) @@ -113,7 +84,8 @@ public static NpcJumpFall Get(NpcContainer npc) if (!npc.Go.TryGetComponent(out var jumpFall)) jumpFall = npc.Go.AddComponent(); - jumpFall._npc = npc; + if (jumpFall._npc != npc) + jumpFall.Bind(npc); jumpFall.WakeUp(); return jumpFall; } @@ -139,6 +111,15 @@ private void Awake() this.Inject(); } + private void Bind(NpcContainer npc) + { + _npc = npc; + _body = new NpcMoveBody(npc, transform).Inject(); + _slide = new NpcSlopeSlide(_body); + _sequence = new NpcAnimationSequence(_body); + _climb = new NpcLedgeClimb(_body, _sequence).Inject(); + } + private void Update() { if (_npc?.PrefabProps?.AnimationSystem == null) @@ -156,12 +137,16 @@ private void Update() TickFall(); break; case State.Landing: - TickSequence(); - if (_stateTime >= _stateDuration) + _sequence.Tick(Time.deltaTime); + if (_sequence.IsDone) Finish(); break; case State.Climbing: - TickClimb(); + if (_climb.Tick()) + Finish(); + break; + case State.Sliding: + TickSlide(); break; } @@ -169,12 +154,9 @@ private void Update() _hasPreviousPosition = true; } - private float RestHeight => _npc.PrefabProps.AnimationSystem.RestRootHeight; - private int Guild => _npc.Instance.GetValuesGuild(); + private float RestHeight => _body.RestHeight; - private LedgeRules Rules => _ledgeService.GetRules(Guild); - - private bool CanMove() => NpcFallDomain.CanMove(_gameStateService.GuildValues, _npc); + private bool CanMove() => _body.CanMove(); /// /// Walked off a ledge: start falling. False if the NPC stands still or isn't checked (far from the hero, @@ -182,24 +164,68 @@ private void Update() /// private bool CheckFall() { - if (!_hasPreviousPosition || RestHeight <= 0f || !CanMove() || !IsNearHero()) + if (!_hasPreviousPosition || RestHeight <= 0f) + return false; + + // The slide's steep time counts only while it moves over steep ground - not in bursts with breaks between. + if (!CanMove() || !IsNearHero()) + { + _slide.Hold(); return false; + } // Only NPCs that move walk off a ledge (an idle NPC on a vob that isn't loaded yet must not drop). var moved = transform.position - _previousPosition; moved.y = 0f; if (moved.sqrMagnitude < 0.0001f) + { + _slide.Rest(); return false; + } - var probe = RestHeight + Rules.StepHeight + _groundProbeExtra; - if (Physics.Raycast(transform.position, Vector3.down, probe, 1 << Constants.DefaultLayer, - QueryTriggerInteraction.Ignore)) + if (_body.TryGetGround(transform.position, out var ground)) + { + if (_slide.TryStart(ground, moved)) + Enter(State.Sliding); return true; + } StartFall(moved / Mathf.Max(Time.deltaTime, 0.001f)); return true; } + private void Enter(State state) + { + enabled = true; + _state = state; + } + + /// + /// Can't move any more: the slide ends at once (it's on the ground). Off an edge it falls on with the slide's + /// speed. + /// + private void TickSlide() + { + if (!CanMove()) + { + _slide.Stop("can't move"); + Finish(); + return; + } + + switch (_slide.Tick(out var fallVelocity)) + { + case SlopeSlideEvent.LostGround: + StartFall(new Vector3(fallVelocity.x, 0f, fallVelocity.z)); + _fallVelocityY = Mathf.Min(fallVelocity.y, 0f); + break; + case SlopeSlideEvent.Stopped: + case SlopeSlideEvent.Blocked: + Finish(); + break; + } + } + private bool IsNearHero() { var hero = _gameStateService.GothicVm?.GlobalHero as ZenKit.Daedalus.NpcInstance; @@ -210,17 +236,15 @@ private bool IsNearHero() private void StartFall(Vector3 velocityH) { - enabled = true; - _state = State.Falling; + Enter(State.Falling); _fallVelocityH = Vector3.ClampMagnitude(velocityH, _maxFallSpeedH); _fallVelocityY = 0f; _fallStartFeetY = transform.position.y - RestHeight; _npc.Props.BodyState = VmGothicEnums.BodyState.BsFall; - _physicsService.DisablePhysicsForNpc(_npc.PrefabProps); - _npc.PrefabProps.AnimationSystem.StopAllAnimations(); + _body.TakeOver(); _fallAnimName = FallPose.FallDown; - PlayIfExists(_fallAnimName); + _body.PlayIfExists(_fallAnimName); Logger.Log($"[NpcJumpFall] {_npc.Go.name} falls (speed {_fallVelocityH.magnitude:F1} m/s).", LogCat.Ai); } @@ -247,14 +271,13 @@ public bool TryThrow(Vector3 velocityH, float velocityY) private void TickFall() { var dt = Time.deltaTime; - _fallVelocityY -= _gravity * dt; + _fallVelocityY -= NpcMoveBody.Gravity * dt; var position = transform.position; var moveH = _fallVelocityH * dt; - if (moveH.sqrMagnitude > 0f && Physics.Raycast(position, moveH.normalized, moveH.magnitude + 0.3f, - 1 << Constants.DefaultLayer, QueryTriggerInteraction.Ignore)) + if (_body.IsWallAhead(position, moveH)) { - // Against a wall: slide down it. + // Against a wall: slide down it. A slope rising ahead is no wall - the fall lands on it. _fallVelocityH = Vector3.zero; moveH = Vector3.zero; } @@ -276,12 +299,12 @@ private void TickFall() { _npc.PrefabProps.AnimationSystem.StopAnimation(_fallAnimName); _fallAnimName = FallPose.Front.Flight; - PlayIfExists(_fallAnimName); + _body.PlayIfExists(_fallAnimName); } - else if (!_npc.PrefabProps.AnimationSystem.IsPlaying(_fallAnimName)) + else if (!_npc.PrefabProps.AnimationSystem.IsPlaying(_fallAnimName) && CanMove()) { - // Npc_ClearAIQueue stops all animations every ~2 s. - PlayIfExists(_fallAnimName); + // Npc_ClearAIQueue stops all animations every ~2 s (a death's animation stays). + _body.PlayIfExists(_fallAnimName); } if (fallen > _outOfWorldFallHeight) @@ -296,9 +319,15 @@ private void Land(float height) _npc.PrefabProps.AnimationSystem.StopAnimation(_fallAnimName); var isDeep = height > NpcFallDomain.LyingFallHeight || _isThrown; _isThrown = false; - StartSequence(State.Landing, isDeep - ? new[] { FallPose.Front.Landing, FallPose.Front.StandUp } - : new[] { FallPose.FallDownToStand }); + var canMove = CanMove(); + // Can't move (died in the air, landed in water): no landing animations. + if (canMove) + { + _sequence.Start(isDeep + ? new[] { FallPose.Front.Landing, FallPose.Front.StandUp } + : new[] { FallPose.FallDownToStand }); + Enter(State.Landing); + } // NPCs' fall damage comes with the combat system, the hero's always (HeroFallService). var damage = NpcFallDomain.GetFallDamage(_gameStateService.GuildValues, _npc, height); @@ -306,7 +335,10 @@ private void Land(float height) if (isDamageOn && damage > 0) GlobalEventDispatcher.FallDamage.Invoke(_npc, damage); Logger.Log($"[NpcJumpFall] {_npc.Go.name} landed after {height:F1} m, fall damage {damage}" + - (isDamageOn || damage <= 0 ? "" : " - not applied (EnableCombatSystem off)"), LogCat.Ai); + (isDamageOn || damage <= 0 ? "" : " - not applied (EnableCombatSystem off)") + + (canMove ? "" : $" ({_npc.Props.BodyState}, no landing)"), LogCat.Ai); + if (!canMove) + Finish(); } /// @@ -314,36 +346,10 @@ private void Land(float height) /// public bool TryStartClimb(Vector3 direction) { - if (IsBusy || RestHeight <= 0f || !CanMove()) + if (IsBusy || RestHeight <= 0f || !CanMove() || !_climb.TryStartLedge(direction)) return false; - direction.y = 0f; - if (direction.sqrMagnitude < 0.0001f) - return false; - direction.Normalize(); - - var position = transform.position; - var ledge = _ledgeService.ProbeNpcClimb(position, RestHeight, direction, Rules); - if (ledge.Band is not (LedgeBand.Low or LedgeBand.Mid)) - return false; - - var sequence = ledge.Band == LedgeBand.Low - ? new[] { "T_STAND_2_JUMPUPLOW", "S_JUMPUPLOW", "T_JUMPUPLOW_2_STAND" } - : new[] { "T_STAND_2_JUMPUPMID", "S_JUMPUPMID", "T_JUMPUPMID_2_STAND" }; - if (!HasTrack(sequence[0])) - return false; - - var height = ledge.Height; - _climbFrom = position; - _climbTo = ledge.StandPoint + Vector3.up * RestHeight; - _physicsService.DisablePhysicsForNpc(_npc.PrefabProps); - _npc.PrefabProps.AnimationSystem.StopAllAnimations(); - transform.rotation = Quaternion.LookRotation(direction); - _npc.Props.BodyState = VmGothicEnums.BodyState.BsJump; - _isLadder = false; - StartSequence(State.Climbing, sequence); - - Logger.Log($"[NpcJumpFall] {_npc.Go.name} climbs a {height:F2} m ledge.", LogCat.Ai); + Enter(State.Climbing); return true; } @@ -355,56 +361,8 @@ public bool TryStartLadder(Vector3 ladderStart, Vector3 ladderEnd) if (IsBusy || RestHeight <= 0f || !CanMove()) return false; - var isUp = ladderEnd.y > ladderStart.y; - var names = isUp ? _ladderUp : _ladderDown; - var cycles = Mathf.Max(1, Mathf.RoundToInt(GetLadderClimbHeight(ladderStart, ladderEnd) / - GetLadderMetersPerCycle())); - var sequence = new System.Collections.Generic.List { names[0] }; - for (var i = 0; i < cycles; i++) - sequence.Add(names[1]); - sequence.Add(names[2]); - - _climbFrom = transform.position; - _climbTo = ladderEnd + Vector3.up * RestHeight; - _isLadder = true; - Vector3 flat; - if (_npcNavMeshService.TryGetLadderStance(ladderStart, ladderEnd, out var column, out var facing)) - { - // In front of the rungs, looking at them - up and down at the same spot (like the engine). - _ladderColumn = new Vector3(column.x, 0f, column.z); - flat = facing; - } - else - { - var middle = (ladderStart + ladderEnd) * 0.5f; - _ladderColumn = new Vector3(middle.x, 0f, middle.z); - var bottom = isUp ? ladderStart : ladderEnd; - var top = isUp ? ladderEnd : ladderStart; - flat = top - bottom; - } - flat.y = 0f; - if (flat.sqrMagnitude > 0.0001f) - transform.rotation = Quaternion.LookRotation(flat); - - _physicsService.DisablePhysicsForNpc(_npc.PrefabProps); - _npc.PrefabProps.AnimationSystem.StopAllAnimations(); - _npc.Props.BodyState = VmGothicEnums.BodyState.BsClimb; - StartSequence(State.Climbing, sequence.ToArray()); - // Without the animations (other models): a plain climb at ladder speed. - if (_stateDuration <= _climbMinSeconds) - { - _stateDuration = Mathf.Abs(ladderEnd.y - ladderStart.y) / _ladderSpeed + _ladderExtraSeconds; - _ladderRiseStart = 0.1f; - _ladderRiseEnd = 0.9f; - } - else - { - _ladderRiseStart = Mathf.Clamp01(_sequenceDurations[0] / _stateDuration); - _ladderRiseEnd = Mathf.Clamp(1f - _sequenceDurations[^1] / _stateDuration, _ladderRiseStart + 0.01f, 1f); - } - PrepareLadderBases(); - - Logger.Log($"[NpcJumpFall] {_npc.Go.name} takes a ladder ({ladderStart.y:F1} -> {ladderEnd.y:F1}).", LogCat.Ai); + _climb.StartLadder(ladderStart, ladderEnd); + Enter(State.Climbing); return true; } @@ -418,216 +376,24 @@ public bool IsSafeDropAhead(Vector3 direction) direction); } - private void TickClimb() - { - TickSequence(); - - var t = Mathf.Clamp01(_stateTime / _stateDuration); - if (_isLadder) - { - TickLadder(t); - return; - } - - // Up first, then forward onto the ledge. - var rise = Mathf.Clamp01(t / _climbRisePart); - var forward = Mathf.Clamp01((t - _climbRisePart * 0.5f) / (1f - _climbRisePart * 0.5f)); - var horizontal = Vector3.Lerp(new Vector3(_climbFrom.x, 0f, _climbFrom.z), new Vector3(_climbTo.x, 0f, _climbTo.z), forward); - transform.position = new Vector3(horizontal.x, Mathf.Lerp(_climbFrom.y, _climbTo.y, rise), horizontal.z); - - if (t >= 1f) - Finish(); - } - - /// - /// Height the climb cycles have to cover: the whole ladder minus what getting on and off lift already. - /// - private float GetLadderClimbHeight(Vector3 ladderStart, Vector3 ladderEnd) - { - var height = Mathf.Abs(ladderEnd.y - ladderStart.y); - var transitions = Mathf.Abs(RootHeightChange(_ladderUp[0])) + Mathf.Abs(RootHeightChange(_ladderUp[2])); - return transitions < height * 0.5f ? height - transitions : height; - } - - /// - /// One t_Ladder_S0_2_S1 cycle lifts the root this far in HUMANS.MDS (fallback if the track has no root lift). - /// - private float GetLadderMetersPerCycle() - { - var perCycle = Mathf.Abs(RootHeightChange(_ladderUp[1])); - if (!_hasLoggedLadderCycle) - { - _hasLoggedLadderCycle = true; - Logger.Log($"[NpcJumpFall] Ladder cycle lifts {perCycle:F2} m (getting on " + - $"{RootHeightChange(_ladderUp[0]):F2}, off {RootHeightChange(_ladderUp[2]):F2}).", LogCat.Ai); - } - return perCycle > 0.2f ? perCycle : _ladderMetersPerCycle; - } - - private float RootHeightChange(string animation) => - _animationService.GetRootHeightChange(animation, _npc.Props.MdsNameBase, _npc.Props.MdsNameOverlay); - - /// - /// base[i] + firstOffset[i] = base[i-1] + lastOffset[i-1]: every animation continues at the height the previous - /// one left the body. Starts at the NPC's own height. - /// - private void PrepareLadderBases() - { - _ladderBases = null; - if (_sequence == null || _sequence.Length == 0) - return; - - var bases = new float[_sequence.Length]; - var blendIns = new float[_sequence.Length]; - var baseY = _climbFrom.y; - float? previousLast = null; - for (var i = 0; i < _sequence.Length; i++) - { - if (_sequenceDurations[i] <= 0f || - !_animationService.TryGetRootHeightOffsets(_sequence[i], _npc.Props.MdsNameBase, - _npc.Props.MdsNameOverlay, out var first, out var last)) - { - bases[i] = baseY; - continue; - } - - if (previousLast != null) - baseY += previousLast.Value - first; - bases[i] = baseY; - blendIns[i] = _animationService.GetTrack(_sequence[i], _npc.Props.MdsNameBase, - _npc.Props.MdsNameOverlay)?.BlendIn ?? 0f; - previousLast = last; - } - - if (previousLast == null) - return; - var endError = _climbTo.y - (baseY + previousLast.Value); - if (Mathf.Abs(endError) > _ladderMaxEndError) - { - Logger.LogWarning($"[NpcJumpFall] Ladder root lift doesn't fit ({endError:F2} m off) - plain climb.", - LogCat.Ai); - return; - } - - _ladderBases = bases; - _ladderBlendIns = blendIns; - _ladderEndError = endError; - } - - /// - /// Base height of the running animation. While it blends in, the pose offset still blends from the previous - /// animation's - the base moves along, so the body doesn't hop. - /// - private float GetLadderBaseY(float t) - { - var index = Mathf.Clamp(_sequenceIndex, 0, _ladderBases.Length - 1); - var baseY = _ladderBases[index]; - if (index > 0 && _ladderBlendIns[index] > 0f) - baseY = Mathf.Lerp(_ladderBases[index - 1], baseY, Mathf.Clamp01(_sequenceTime / _ladderBlendIns[index])); - return baseY + _ladderEndError * t; - } - - /// - /// Onto the ladder (first animation), up/down along it (climb cycles), off it (last animation). - /// - private void TickLadder(float t) - { - var fromFlat = new Vector3(_climbFrom.x, 0f, _climbFrom.z); - var toFlat = new Vector3(_climbTo.x, 0f, _climbTo.z); - Vector3 horizontal; - if (t < _ladderRiseStart) - horizontal = Vector3.Lerp(fromFlat, _ladderColumn, t / _ladderRiseStart); - else if (t <= _ladderRiseEnd) - horizontal = _ladderColumn; - else - horizontal = Vector3.Lerp(_ladderColumn, toFlat, (t - _ladderRiseEnd) / Mathf.Max(1f - _ladderRiseEnd, 0.001f)); - - var rise = Mathf.Clamp01((t - _ladderRiseStart) / (_ladderRiseEnd - _ladderRiseStart)); - var y = _ladderBases != null ? GetLadderBaseY(t) : Mathf.Lerp(_climbFrom.y, _climbTo.y, rise); - transform.position = new Vector3(horizontal.x, y, horizontal.z); - - if (t >= 1f) - Finish(); - } - - private void StartSequence(State state, string[] animations) - { - enabled = true; - _state = state; - _sequence = animations; - _sequenceDurations = new float[animations.Length]; - _stateDuration = 0f; - for (var i = 0; i < animations.Length; i++) - { - _sequenceDurations[i] = HasTrack(animations[i]) - ? _npc.PrefabProps.AnimationSystem.GetAnimationDuration(animations[i]) - : 0f; - _stateDuration += _sequenceDurations[i]; - } - - // Ledges: short; ladders (more than 3 animations) take as long as their climb cycles. - if (state == State.Climbing && animations.Length <= 3) - _stateDuration = Mathf.Clamp(_stateDuration, _climbMinSeconds, _climbMaxSeconds); - - _sequenceIndex = -1; - _sequenceTime = 0f; - _stateTime = 0f; - NextInSequence(); - } - - private void TickSequence() - { - _stateTime += Time.deltaTime; - _sequenceTime += Time.deltaTime; - if (_sequenceIndex < _sequence.Length && _sequenceTime >= _sequenceDurations[_sequenceIndex]) - NextInSequence(); - } - - private void NextInSequence() - { - if (_sequenceIndex >= 0 && _sequenceIndex < _sequence.Length) - _npc.PrefabProps.AnimationSystem.StopAnimation(_sequence[_sequenceIndex]); - - _sequenceIndex++; - _sequenceTime = 0f; - while (_sequenceIndex < _sequence.Length && _sequenceDurations[_sequenceIndex] <= 0f) - _sequenceIndex++; - - if (_sequenceIndex < _sequence.Length) - _npc.PrefabProps.AnimationSystem.PlayAnimation(_sequence[_sequenceIndex]); - } - private void Finish() { - // Ladder: off it exactly at its end point (the base height + last pose offset left it mid-air/inside). - if (_isLadder && _state == State.Climbing) - transform.position = _climbTo; + if (_state == State.Climbing) + _climb.End(); - if (_sequence != null && _sequenceIndex >= 0 && _sequenceIndex < _sequence.Length) - _npc.PrefabProps.AnimationSystem.StopAnimation(_sequence[_sequenceIndex]); + _sequence.Stop(); if (_fallAnimName != null) _npc.PrefabProps.AnimationSystem.StopAnimation(_fallAnimName); + _slide.StopAnimation(); _state = State.None; - _isLadder = false; - _sequence = null; _fallAnimName = null; if (_npc.Props.BodyState is VmGothicEnums.BodyState.BsFall or VmGothicEnums.BodyState.BsJump or VmGothicEnums.BodyState.BsClimb) _npc.Props.BodyState = VmGothicEnums.BodyState.BsStand; - _physicsService.EnablePhysicsForNpc(_npc.PrefabProps); - _npc.PrefabProps.AnimationSystem.PlayIdleAnimation(); - } - - private void PlayIfExists(string animationName) - { - if (HasTrack(animationName)) - _npc.PrefabProps.AnimationSystem.PlayAnimation(animationName); - } - - private bool HasTrack(string animationName) - { - return _animationService.GetTrack(animationName, _npc.Props.MdsNameBase, _npc.Props.MdsNameOverlay) != null; + _body.Release(); + if (CanMove()) + _npc.PrefabProps.AnimationSystem.PlayIdleAnimation(); } } } diff --git a/Assets/Gothic-Core/Scripts/Adapters/Npc/NpcLedgeClimb.cs b/Assets/Gothic-Core/Scripts/Adapters/Npc/NpcLedgeClimb.cs new file mode 100644 index 000000000..028f1ec26 --- /dev/null +++ b/Assets/Gothic-Core/Scripts/Adapters/Npc/NpcLedgeClimb.cs @@ -0,0 +1,319 @@ +using System.Collections.Generic; +using Gothic.Core.Logging; +using Gothic.Core.Models.Movement; +using Gothic.Core.Models.Vm; +using Gothic.Core.Services.Movement; +using Gothic.Core.Services.Npc; +using Reflex.Attributes; +using UnityEngine; +using Logger = Gothic.Core.Logging.Logger; + +namespace Gothic.Core.Adapters.Npc +{ + /// + /// An NPC's climbs, worker of NpcJumpFall (new().Inject()) - NpcJumpFall decides the state, this moves the body + /// along the climb's animations (NpcAnimationSequence). + /// - Ledges (chasing NPCs only, called by AttackPlayAni): a ledge in front between STEP_HEIGHT and JUMPMID_HEIGHT + /// (LedgeService.ProbeNpcClimb) is climbed with the JumpUpLow/JumpUpMid animations - only if the model has them + /// (most monsters don't). Up first, then forward onto the ledge. + /// - Ladders (a NavMesh ladder link): onto the ladder, as many climb cycles as its height takes, off it - the + /// animations' own root lift carries the body where they have one, else a plain climb. + /// + internal class NpcLedgeClimb + { + [Inject] private readonly AnimationService _animationService; + [Inject] private readonly LedgeService _ledgeService; + [Inject] private readonly NpcNavMeshService _npcNavMeshService; + + private const float _climbMinSeconds = 0.6f; + private const float _climbMaxSeconds = 2f; + private const float _climbRisePart = 0.65f; + private const float _ladderSpeed = 1.5f; + private const float _ladderExtraSeconds = 0.6f; + // HUMANS.MDS: one climb cycle t_Ladder_S0_2_S1 (frames 15-45), down = the same played backwards (aliases R). + private static readonly string[] _ladderUp = + { "T_LADDER_STAND_2_S0", "T_LADDER_S0_2_S1", "T_LADDER_S1_2_STAND" }; + private static readonly string[] _ladderDown = + { "T_LADDER_STAND_2_S1", "T_LADDER_S1_2_S0", "T_LADDER_S0_2_STAND" }; + // Fallback if the climb cycle doesn't lift the root bone itself (0.9 climbed a few cycles too many). + private const float _ladderMetersPerCycle = 1.2f; + private const float _ladderMaxEndError = 1.5f; + + private static bool _hasLoggedLadderCycle; + + private readonly NpcMoveBody _body; + private readonly NpcAnimationSequence _sequence; + + private Vector3 _climbFrom; + private Vector3 _climbTo; + // Ladders: step to the ladder during the first animation, change height only during the climb cycles, step off + // during the last one (start/end as parts of the whole climb). + private bool _isLadder; + private Vector3 _ladderColumn; + private float _ladderRiseStart; + private float _ladderRiseEnd; + // The climb animations lift the root bone themselves (pose offset): per animation the NPC's base height, so each + // one starts where the previous one ended - no double lift ("hiccup"). Null: no usable root lift (plain lerp). + private float[] _ladderBases; + private float[] _ladderBlendIns; + // What's left to the ladder's end after the last animation - spread over the whole climb. + private float _ladderEndError; + + public NpcLedgeClimb(NpcMoveBody body, NpcAnimationSequence sequence) + { + _body = body; + _sequence = sequence; + } + + private Transform Transform => _body.Transform; + + /// + /// A chasing NPC runs into a ledge: climb it if it's higher than a step and not higher than JUMPMID_HEIGHT. + /// true: the climb began. + /// + public bool TryStartLedge(Vector3 direction) + { + direction.y = 0f; + if (direction.sqrMagnitude < 0.0001f) + return false; + direction.Normalize(); + + var position = Transform.position; + var restHeight = _body.RestHeight; + var ledge = _ledgeService.ProbeNpcClimb(position, restHeight, direction, _body.Rules); + if (ledge.Band is not (LedgeBand.Low or LedgeBand.Mid)) + return false; + + var animations = ledge.Band == LedgeBand.Low + ? new[] { "T_STAND_2_JUMPUPLOW", "S_JUMPUPLOW", "T_JUMPUPLOW_2_STAND" } + : new[] { "T_STAND_2_JUMPUPMID", "S_JUMPUPMID", "T_JUMPUPMID_2_STAND" }; + if (!_body.HasTrack(animations[0])) + return false; + + _climbFrom = position; + _climbTo = ledge.StandPoint + Vector3.up * restHeight; + _body.TakeOver(); + Transform.rotation = Quaternion.LookRotation(direction); + _body.Npc.Props.BodyState = VmGothicEnums.BodyState.BsJump; + _isLadder = false; + _sequence.Start(animations); + // Ledges are short. + _sequence.Duration = Mathf.Clamp(_sequence.Duration, _climbMinSeconds, _climbMaxSeconds); + + Logger.Log($"[NpcJumpFall] {_body.Name} climbs a {ledge.Height:F2} m ledge.", LogCat.Ai); + return true; + } + + /// + /// The NavMesh path goes over a ladder link: climb it from start to end (up or down). + /// + public void StartLadder(Vector3 ladderStart, Vector3 ladderEnd) + { + var isUp = ladderEnd.y > ladderStart.y; + var names = isUp ? _ladderUp : _ladderDown; + var cycles = Mathf.Max(1, Mathf.RoundToInt(GetLadderClimbHeight(ladderStart, ladderEnd) / + GetLadderMetersPerCycle())); + var animations = new List { names[0] }; + for (var i = 0; i < cycles; i++) + animations.Add(names[1]); + animations.Add(names[2]); + + _climbFrom = Transform.position; + _climbTo = ladderEnd + Vector3.up * _body.RestHeight; + _isLadder = true; + Vector3 flat; + if (_npcNavMeshService.TryGetLadderStance(ladderStart, ladderEnd, out var column, out var facing)) + { + // In front of the rungs, looking at them - up and down at the same spot (like the engine). + _ladderColumn = new Vector3(column.x, 0f, column.z); + flat = facing; + } + else + { + var middle = (ladderStart + ladderEnd) * 0.5f; + _ladderColumn = new Vector3(middle.x, 0f, middle.z); + var bottom = isUp ? ladderStart : ladderEnd; + var top = isUp ? ladderEnd : ladderStart; + flat = top - bottom; + } + flat.y = 0f; + if (flat.sqrMagnitude > 0.0001f) + Transform.rotation = Quaternion.LookRotation(flat); + + _body.TakeOver(); + _body.Npc.Props.BodyState = VmGothicEnums.BodyState.BsClimb; + _sequence.Start(animations.ToArray()); + // Ladders take as long as their climb cycles - one of a single cycle (three animations) is timed like a + // ledge. + if (animations.Count <= 3) + _sequence.Duration = Mathf.Clamp(_sequence.Duration, _climbMinSeconds, _climbMaxSeconds); + // Without the animations (other models): a plain climb at ladder speed. + if (_sequence.Duration <= _climbMinSeconds) + { + _sequence.Duration = Mathf.Abs(ladderEnd.y - ladderStart.y) / _ladderSpeed + _ladderExtraSeconds; + _ladderRiseStart = 0.1f; + _ladderRiseEnd = 0.9f; + } + else + { + var durations = _sequence.Durations; + _ladderRiseStart = Mathf.Clamp01(durations[0] / _sequence.Duration); + _ladderRiseEnd = Mathf.Clamp(1f - durations[^1] / _sequence.Duration, _ladderRiseStart + 0.01f, 1f); + } + PrepareLadderBases(); + + Logger.Log($"[NpcJumpFall] {_body.Name} takes a ladder ({ladderStart.y:F1} -> {ladderEnd.y:F1}).", + LogCat.Ai); + } + + /// + /// One frame of the climb. true: it's over (NpcJumpFall finishes it). + /// + public bool Tick() + { + _sequence.Tick(Time.deltaTime); + + var t = _sequence.Progress; + if (_isLadder) + { + TickLadder(t); + return t >= 1f; + } + + // Up first, then forward onto the ledge. + var rise = Mathf.Clamp01(t / _climbRisePart); + var forward = Mathf.Clamp01((t - _climbRisePart * 0.5f) / (1f - _climbRisePart * 0.5f)); + var horizontal = Vector3.Lerp(new Vector3(_climbFrom.x, 0f, _climbFrom.z), + new Vector3(_climbTo.x, 0f, _climbTo.z), forward); + Transform.position = new Vector3(horizontal.x, Mathf.Lerp(_climbFrom.y, _climbTo.y, rise), horizontal.z); + return t >= 1f; + } + + /// + /// The climb is over (or cut short): a ladder leaves the body exactly at its end point (the base height + last + /// pose offset left it mid-air/inside). + /// + public void End() + { + if (_isLadder) + Transform.position = _climbTo; + _isLadder = false; + } + + /// + /// Height the climb cycles have to cover: the whole ladder minus what getting on and off lift already. + /// + private float GetLadderClimbHeight(Vector3 ladderStart, Vector3 ladderEnd) + { + var height = Mathf.Abs(ladderEnd.y - ladderStart.y); + var transitions = Mathf.Abs(RootHeightChange(_ladderUp[0])) + Mathf.Abs(RootHeightChange(_ladderUp[2])); + return transitions < height * 0.5f ? height - transitions : height; + } + + /// + /// One t_Ladder_S0_2_S1 cycle lifts the root this far in HUMANS.MDS (fallback if the track has no root lift). + /// + private float GetLadderMetersPerCycle() + { + var perCycle = Mathf.Abs(RootHeightChange(_ladderUp[1])); + if (!_hasLoggedLadderCycle) + { + _hasLoggedLadderCycle = true; + Logger.Log($"[NpcJumpFall] Ladder cycle lifts {perCycle:F2} m (getting on " + + $"{RootHeightChange(_ladderUp[0]):F2}, off {RootHeightChange(_ladderUp[2]):F2}).", LogCat.Ai); + } + return perCycle > 0.2f ? perCycle : _ladderMetersPerCycle; + } + + private float RootHeightChange(string animation) + { + var props = _body.Npc.Props; + return _animationService.GetRootHeightChange(animation, props.MdsNameBase, props.MdsNameOverlay); + } + + /// + /// base[i] + firstOffset[i] = base[i-1] + lastOffset[i-1]: every animation continues at the height the previous + /// one left the body. Starts at the NPC's own height. + /// + private void PrepareLadderBases() + { + _ladderBases = null; + var animations = _sequence.Animations; + if (animations == null || animations.Length == 0) + return; + + var props = _body.Npc.Props; + var durations = _sequence.Durations; + var bases = new float[animations.Length]; + var blendIns = new float[animations.Length]; + var baseY = _climbFrom.y; + float? previousLast = null; + for (var i = 0; i < animations.Length; i++) + { + if (durations[i] <= 0f || + !_animationService.TryGetRootHeightOffsets(animations[i], props.MdsNameBase, props.MdsNameOverlay, + out var first, out var last)) + { + bases[i] = baseY; + continue; + } + + if (previousLast != null) + baseY += previousLast.Value - first; + bases[i] = baseY; + blendIns[i] = _animationService.GetTrack(animations[i], props.MdsNameBase, props.MdsNameOverlay) + ?.BlendIn ?? 0f; + previousLast = last; + } + + if (previousLast == null) + return; + var endError = _climbTo.y - (baseY + previousLast.Value); + if (Mathf.Abs(endError) > _ladderMaxEndError) + { + Logger.LogWarning($"[NpcJumpFall] Ladder root lift doesn't fit ({endError:F2} m off) - plain climb.", + LogCat.Ai); + return; + } + + _ladderBases = bases; + _ladderBlendIns = blendIns; + _ladderEndError = endError; + } + + /// + /// Base height of the running animation. While it blends in, the pose offset still blends from the previous + /// animation's - the base moves along, so the body doesn't hop. + /// + private float GetLadderBaseY(float t) + { + var index = Mathf.Clamp(_sequence.Index, 0, _ladderBases.Length - 1); + var baseY = _ladderBases[index]; + if (index > 0 && _ladderBlendIns[index] > 0f) + baseY = Mathf.Lerp(_ladderBases[index - 1], baseY, + Mathf.Clamp01(_sequence.AnimationTime / _ladderBlendIns[index])); + return baseY + _ladderEndError * t; + } + + /// + /// Onto the ladder (first animation), up/down along it (climb cycles), off it (last animation). + /// + private void TickLadder(float t) + { + var fromFlat = new Vector3(_climbFrom.x, 0f, _climbFrom.z); + var toFlat = new Vector3(_climbTo.x, 0f, _climbTo.z); + Vector3 horizontal; + if (t < _ladderRiseStart) + horizontal = Vector3.Lerp(fromFlat, _ladderColumn, t / _ladderRiseStart); + else if (t <= _ladderRiseEnd) + horizontal = _ladderColumn; + else + horizontal = Vector3.Lerp(_ladderColumn, toFlat, + (t - _ladderRiseEnd) / Mathf.Max(1f - _ladderRiseEnd, 0.001f)); + + var rise = Mathf.Clamp01((t - _ladderRiseStart) / (_ladderRiseEnd - _ladderRiseStart)); + var y = _ladderBases != null ? GetLadderBaseY(t) : Mathf.Lerp(_climbFrom.y, _climbTo.y, rise); + Transform.position = new Vector3(horizontal.x, y, horizontal.z); + } + } +} diff --git a/Assets/Gothic-Core/Scripts/Adapters/Npc/NpcLedgeClimb.cs.meta b/Assets/Gothic-Core/Scripts/Adapters/Npc/NpcLedgeClimb.cs.meta new file mode 100644 index 000000000..e8babaf78 --- /dev/null +++ b/Assets/Gothic-Core/Scripts/Adapters/Npc/NpcLedgeClimb.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: e14f7828e3f9a6143be54faa354fdedf \ No newline at end of file diff --git a/Assets/Gothic-Core/Scripts/Adapters/Npc/NpcMoveBody.cs b/Assets/Gothic-Core/Scripts/Adapters/Npc/NpcMoveBody.cs new file mode 100644 index 000000000..a22ba4e89 --- /dev/null +++ b/Assets/Gothic-Core/Scripts/Adapters/Npc/NpcMoveBody.cs @@ -0,0 +1,122 @@ +using Gothic.Core.Adapters.Animations; +using Gothic.Core.Const; +using Gothic.Core.Domain.Npc; +using Gothic.Core.Extensions; +using Gothic.Core.Models.Container; +using Gothic.Core.Models.Movement; +using Gothic.Core.Models.Vm; +using Gothic.Core.Services; +using Gothic.Core.Services.Movement; +using Gothic.Core.Services.Npc; +using Gothic.Core.Services.World; +using Reflex.Attributes; +using UnityEngine; + +namespace Gothic.Core.Adapters.Npc +{ + /// + /// The NPC's body as NpcJumpFall and its workers (NpcSlopeSlide, NpcLedgeClimb, NpcAnimationSequence) move it: + /// its rest height, its guild's ledge and slide values, whether it can move, its animations, the ground below. + /// Created by NpcJumpFall per NPC (new().Inject()) and shared with its workers - one place for what they all ask. + /// + internal class NpcMoveBody + { + [Inject] private readonly GameStateService _gameStateService; + [Inject] private readonly AnimationService _animationService; + [Inject] private readonly PhysicsService _physicsService; + [Inject] private readonly LedgeService _ledgeService; + + /// + /// m/s^2 of a fall and a slide. + /// + public const float Gravity = 9.81f; + + /// + /// m the wall ray of a fall or slide reaches beyond this frame's move. + /// + public const float WallLookAhead = 0.3f; + + private const float _groundProbeExtra = 0.1f; + // A wall ray hit with a normal.y above this (~80 deg) is a slope rising ahead or beside, not a wall. + private const float _wallMaxNormalY = 0.17f; + + public readonly NpcContainer Npc; + public readonly Transform Transform; + + public NpcMoveBody(NpcContainer npc, Transform transform) + { + Npc = npc; + Transform = transform; + } + + public string Name => Npc.Go.name; + + public AnimationSystem Animations => Npc.PrefabProps.AnimationSystem; + + public float RestHeight => Animations.RestRootHeight; + + public Vector3 Feet => Transform.position - Vector3.up * RestHeight; + + public LedgeRules Rules => _ledgeService.GetRules(Npc.Instance.GetValuesGuild()); + + public bool CanMove() => NpcFallDomain.CanMove(_gameStateService.GuildValues, Npc); + + /// + /// NpcDeathDomain / NpcKnockoutDomain made the body kinematic: it stays so. + /// + public bool IsDown => Npc.Props.BodyState is VmGothicEnums.BodyState.BsDead + or VmGothicEnums.BodyState.BsUnconscious; + + /// + /// Ground within STEP_HEIGHT under the feet of a root at position - a ray straight down, so stair risers and + /// walls beside the NPC don't count. + /// + public bool TryGetGround(Vector3 position, out RaycastHit hit) + { + var probe = RestHeight + Rules.StepHeight + _groundProbeExtra; + return Physics.Raycast(position, Vector3.down, out hit, probe, 1 << Constants.DefaultLayer, + QueryTriggerInteraction.Ignore); + } + + /// + /// A wall in the way of this frame's horizontal move from a root at position (WallLookAhead beyond it) - for a + /// fall and a slide alike. Only near-vertical hits are walls: a slope rising ahead or beside is no wall, the + /// move goes on until the ground ray finds it. + /// + public bool IsWallAhead(Vector3 position, Vector3 moveH) + { + return moveH.sqrMagnitude > 0f && Physics.Raycast(position, moveH.normalized, out var hit, + moveH.magnitude + WallLookAhead, 1 << Constants.DefaultLayer, QueryTriggerInteraction.Ignore) && + hit.normal.y <= _wallMaxNormalY; + } + + /// + /// A fall, climb or slide takes the body: no physics, none of the other animations. + /// + public void TakeOver() + { + _physicsService.DisablePhysicsForNpc(Npc.PrefabProps); + Animations.StopAllAnimations(); + } + + /// + /// The move is over: physics again - unless dead or unconscious (kinematic, as their domains left it). + /// + public void Release() + { + if (!IsDown) + _physicsService.EnablePhysicsForNpc(Npc.PrefabProps); + } + + public void PlayIfExists(string animationName) + { + if (HasTrack(animationName)) + Animations.PlayAnimation(animationName); + } + + public bool HasTrack(string animationName) + { + return _animationService.GetTrack(animationName, Npc.Props.MdsNameBase, Npc.Props.MdsNameOverlay) != null; + } + } +} diff --git a/Assets/Gothic-Core/Scripts/Adapters/Npc/NpcMoveBody.cs.meta b/Assets/Gothic-Core/Scripts/Adapters/Npc/NpcMoveBody.cs.meta new file mode 100644 index 000000000..dfcbbb182 --- /dev/null +++ b/Assets/Gothic-Core/Scripts/Adapters/Npc/NpcMoveBody.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 2f1ccd6e4cccfbf40919246e924d11eb \ No newline at end of file diff --git a/Assets/Gothic-Core/Scripts/Adapters/Npc/NpcSlopeSlide.cs b/Assets/Gothic-Core/Scripts/Adapters/Npc/NpcSlopeSlide.cs new file mode 100644 index 000000000..122e21807 --- /dev/null +++ b/Assets/Gothic-Core/Scripts/Adapters/Npc/NpcSlopeSlide.cs @@ -0,0 +1,155 @@ +using Gothic.Core.Const; +using Gothic.Core.Domain.Movement; +using Gothic.Core.Logging; +using Gothic.Core.Models.Movement; +using Gothic.Core.Models.Vm; +using UnityEngine; +using Logger = Gothic.Core.Logging.Logger; + +namespace Gothic.Core.Adapters.Npc +{ + /// + /// An NPC's slide down a steep slope (SlopeSlideDomain, the guild's SLIDE_ANGLE), worker of NpcJumpFall: going down + /// or across ground steeper than it slides the NPC down with S_SLIDE / S_SLIDEB, BS_STAND, until walkable ground, + /// a block, or an edge (NpcJumpFall's fall takes over with the slide's speed). Walking up such a slope stays + /// walking (ours - Gothic stops it like at a wall): waypoint routes over steep ground don't loop between walking up + /// and sliding down. + /// Moves the body itself (a wall ray ahead, held on the ground below) - NpcJumpFall decides the state. + /// + internal class NpcSlopeSlide + { + private readonly NpcMoveBody _body; + private readonly SlopeSlideState _state = new(); + private string _animationName; + + public NpcSlopeSlide(NpcMoveBody body) + { + _body = body; + } + + /// + /// Not checked (can't move, far from the hero) or walking up the slope: the steep time starts again. + /// + public void Hold() + { + SlopeSlideDomain.Hold(_state, _body.Feet); + } + + /// + /// Stands still: the steep time starts again, a block stays (SlopeSlideDomain.Rest). + /// + public void Rest() + { + SlopeSlideDomain.Rest(_state, _body.Feet); + } + + /// + /// Steep ground under a moving NPC long enough: the slide begins (the body taken, its animation playing) - not + /// while it walks up the slope. moved: its horizontal move this frame. + /// + public bool TryStart(RaycastHit ground, Vector3 moved) + { + if (SlopeSlideDomain.IsMovingUphill(moved, ground.normal)) + { + Hold(); + return false; + } + + if (SlopeSlideDomain.Tick(_state, _body.Feet, true, ground.normal, _body.Rules, + NpcMoveBody.Gravity, Time.deltaTime) != SlopeSlideEvent.Started) + return false; + + _body.Npc.Props.BodyState = VmGothicEnums.BodyState.BsStand; + _body.TakeOver(); + _animationName = null; + PlayAnimation(); + + Logger.Log($"[NpcSlide] {_body.Name} slides down a {_state.GroundAngle:F0} deg slope (SLIDE_ANGLE " + + $"{_body.Rules.SlideAngle:F0}).", LogCat.Ai); + return true; + } + + /// + /// Down the slope at the slide's speed, along walls, held on the ground below. None: it slides on. Stopped / + /// Blocked: it stands (logged). LostGround: off an edge, it's moved there and falls on with fallVelocity (a + /// fall from here - the slide itself is no drop). + /// + public SlopeSlideEvent Tick(out Vector3 fallVelocity) + { + fallVelocity = Vector3.zero; + var dt = Time.deltaTime; + var position = _body.Transform.position; + var move = _state.Velocity * dt; + var moveH = new Vector3(move.x, 0f, move.z); + // Against a wall: the slide gets nowhere and ends as blocked. Across a slope the ray may hit the slope + // rising beside the NPC - no wall (NpcMoveBody.IsWallAhead). + if (_body.IsWallAhead(position, moveH)) + move = Vector3.zero; + + var next = position + move; + if (!_body.TryGetGround(next, out var ground)) + { + fallVelocity = _state.Velocity; + Hold(); + StopAnimation(); + Logger.Log($"[NpcSlide] {_body.Name} slides off an edge.", LogCat.Ai); + _body.Transform.position = next; + return SlopeSlideEvent.LostGround; + } + + _body.Transform.position = ground.point + Vector3.up * _body.RestHeight; + var slideEvent = SlopeSlideDomain.Tick(_state, ground.point, true, ground.normal, _body.Rules, + NpcMoveBody.Gravity, dt); + if (slideEvent != SlopeSlideEvent.None) + { + LogEnd(slideEvent == SlopeSlideEvent.Blocked ? "blocked" : "walkable ground"); + return slideEvent; + } + + PlayAnimation(); + return SlopeSlideEvent.None; + } + + /// + /// The NPC can't move any more: the slide ends at once (logged). + /// + public void Stop(string reason) + { + Hold(); + LogEnd(reason); + } + + public void StopAnimation() + { + if (_animationName != null) + _body.Animations.StopAnimation(_animationName); + _animationName = null; + } + + /// + /// S_SLIDE facing downhill, S_SLIDEB backwards (S_SLIDE if the model has no S_SLIDEB) - again when the + /// direction changed or Npc_ClearAIQueue stopped it. + /// + private void PlayAnimation() + { + var animationName = SlopeSlideDomain.GetAnimation(_state.Velocity, _body.Transform.forward, + _body.HasTrack(DaedalusConst.AniSlideBack), _body.HasTrack(DaedalusConst.AniSlide)); + if (animationName == null) + return; + + var animations = _body.Animations; + if (animationName == _animationName && animations.IsPlaying(animationName)) + return; + + StopAnimation(); + _animationName = animationName; + animations.PlayAnimation(animationName); + } + + private void LogEnd(string reason) + { + Logger.Log($"[NpcSlide] {_body.Name} slide ended ({reason}) after " + + $"{SlopeSlideDomain.GetSlidDistance(_state, _body.Feet):F1} m.", LogCat.Ai); + } + } +} diff --git a/Assets/Gothic-Core/Scripts/Adapters/Npc/NpcSlopeSlide.cs.meta b/Assets/Gothic-Core/Scripts/Adapters/Npc/NpcSlopeSlide.cs.meta new file mode 100644 index 000000000..2be840289 --- /dev/null +++ b/Assets/Gothic-Core/Scripts/Adapters/Npc/NpcSlopeSlide.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: d178c864e4e3e644c94526dc7b8adfcd \ No newline at end of file diff --git a/Assets/Gothic-Core/Scripts/Const/DaedalusConst.cs b/Assets/Gothic-Core/Scripts/Const/DaedalusConst.cs index 5adfa229a..da7bc2a5b 100644 --- a/Assets/Gothic-Core/Scripts/Const/DaedalusConst.cs +++ b/Assets/Gothic-Core/Scripts/Const/DaedalusConst.cs @@ -39,6 +39,10 @@ public class DaedalusConst public const string AniSwimForward = "S_SWIMF"; public const string AniSwimBack = "S_SWIMB"; + // Sliding down a slope, facing downhill and backwards (SlopeSlideDomain.GetAnimation). + public const string AniSlide = "S_SLIDE"; + public const string AniSlideBack = "S_SLIDEB"; + // Ammunition an NPC shoots when its inventory names none of the bow's/crossbow's munition (G1, G2). public static readonly string[] FallbackArrowInstances = { "ItAmArrow", "ItRw_Arrow" }; public static readonly string[] FallbackBoltInstances = { "ItAmBolt", "ItRw_Bolt" }; diff --git a/Assets/Gothic-Core/Scripts/Domain/Movement/HeroAirborneDomain.cs b/Assets/Gothic-Core/Scripts/Domain/Movement/HeroAirborneDomain.cs index 3da5e4ee5..8c2541c69 100644 --- a/Assets/Gothic-Core/Scripts/Domain/Movement/HeroAirborneDomain.cs +++ b/Assets/Gothic-Core/Scripts/Domain/Movement/HeroAirborneDomain.cs @@ -5,7 +5,7 @@ namespace Gothic.Core.Domain.Movement { /// - /// The hero's airborne phases from per-frame measurements (HeroFallSample): jump, fall, fall flat, landing, and + /// The hero's airborne phases from per-frame measurements (HeroBodySample): jump, fall, fall flat, landing, and /// the drop of each landing - from the highest point of the phase down to the landing point (like OpenGothic, which /// derives it from the impact speed: a jump on flat ground adds only its own small height). Pure rules, no Unity /// objects - worker of HeroFallService, which decides what is ignored (water, climbing, teleports) and what a @@ -17,11 +17,11 @@ namespace Gothic.Core.Domain.Movement /// below where it started; a jump only deeper than the guild's FALLDOWN_HEIGHT (5 m human) below its take-off, /// like OpenGothic - the jump's own rise doesn't count, and a jump down a steep slope lands on his feet. A jump /// stays a jump (its pose in the air, the jump's landing) until that deep. - /// - A jump taken at running speed (HeroFallSample.RunSpeed) is Gothic's running jump (IsRunningJump), the + /// - A jump taken at running speed (HeroBodySample.RunSpeed) is Gothic's running jump (IsRunningJump), the /// platform makes it the leap in the direction of TakeOffVelocity - one measurement for both. /// - No fall without real falling: off the ground (beyond the platform's grounded grace) the hero falls only when /// moving down faster than FallSpeed and deeper below the top than the platform's ground snap - /// (HeroFallSample.GroundSnapHeight) - stairs, slopes and lifts stay walking. + /// (HeroBodySample.GroundSnapHeight) - stairs, slopes and lifts stay walking. /// public class HeroAirborneDomain { @@ -102,7 +102,7 @@ public class HeroAirborneDomain /// he falls flat (0 or less: LyingFallHeight). Returns what changed; landing is set for HeroAirEvent.Landed /// only. /// - public HeroAirEvent Tick(in HeroFallSample sample, float safeHeight, out HeroLanding landing) + public HeroAirEvent Tick(in HeroBodySample sample, float safeHeight, out HeroLanding landing) { landing = default; _jumpLyingDepth = safeHeight > 0f ? safeHeight : NpcFallDomain.LyingFallHeight; diff --git a/Assets/Gothic-Core/Scripts/Domain/Movement/SlopeSlideDomain.cs b/Assets/Gothic-Core/Scripts/Domain/Movement/SlopeSlideDomain.cs new file mode 100644 index 000000000..10b1875a1 --- /dev/null +++ b/Assets/Gothic-Core/Scripts/Domain/Movement/SlopeSlideDomain.cs @@ -0,0 +1,253 @@ +using Gothic.Core.Const; +using Gothic.Core.Models.Movement; +using UnityEngine; + +namespace Gothic.Core.Domain.Movement +{ + /// + /// Gothic's sliding down slopes (OpenGothic MoveAlgo::testSlide and the Slide state of MoveAlgo::tick), for the + /// hero and NPCs alike. Pure rules on a SlopeSlideState - the platform measures the ground under the feet (a ray + /// straight down, so stair risers and walls beside the body don't count) and moves the body. + /// - Ground slides when it's steeper than the guild's SLIDE_ANGLE and not steeper than 90 - SLIDE_ANGLE2 (a wall). + /// - The slide is gravity along the slope: g * sin(angle) downhill, capped at MaxSpeed (ours - Gothic has no cap). + /// - Ours, against single steep triangles (rocks, mesh seams): the ground must be steep for StartSeconds before a + /// slide begins, and walkable for StopSeconds before it ends. + /// - A slide that gets nowhere (a wall, a crevice) ends as Blocked - OpenGothic only slides when the body can move + /// downhill. No new slide then until the body moved BlockedReleaseDistance away or stood on walkable ground. + /// - No ground under the feet ends the slide as LostGround: the fall rules take over. + /// Sliding plays S_SLIDE when the body faces downhill, S_SLIDEB when it slides backwards (GetAnimation). + /// + public static class SlopeSlideDomain + { + /// + /// Seconds the ground must be steep in a row before the slide begins. + /// + public const float StartSeconds = 0.2f; + + /// + /// Seconds of walkable ground in a row that end a slide. + /// + public const float StopSeconds = 0.1f; + + /// + /// m/s - the slide gets no faster. + /// + public const float MaxSpeed = 6f; + + // A slide slower than this (m/s) for StuckSeconds gets nowhere: Blocked. + private const float _stuckSpeed = 0.3f; + private const float _stuckSeconds = 0.3f; + + /// + /// m (horizontal) a blocked body moves away before it can slide again. + /// + public const float BlockedReleaseDistance = 0.5f; + + // normal.y below this is a wall (about 89.4 deg), never slide ground. + private const float _wallNormalY = 0.01f; + + /// + /// OpenGothic MoveAlgo::testSlide: slideBegin = sin(90 - SLIDE_ANGLE), slideEnd = sin(SLIDE_ANGLE2), the ground + /// slides when slideEnd < normal.y < slideBegin. + /// + public static bool IsSlideGround(Vector3 normal, LedgeRules rules) + { + var slideBegin = Mathf.Min(Mathf.Cos(rules.SlideAngle * Mathf.Deg2Rad), 1f); + // SLIDE_ANGLE2 0 (Species.d never sets it): at least a wall, also for a float 90 deg normal (y ~ 1e-8). + var slideEnd = Mathf.Max(Mathf.Sin(rules.SlideAngle2 * Mathf.Deg2Rad), _wallNormalY); + return slideEnd < normal.y && normal.y < slideBegin; + } + + /// + /// m/s^2 along the slope, downhill: normal * normal.y - up, times gravity (OpenGothic: cross(n, cross(n, up))). + /// Its length is gravity * sin(angle). + /// + public static Vector3 GetAcceleration(Vector3 normal, float gravity) + { + return (normal * normal.y - Vector3.up) * gravity; + } + + /// + /// Horizontal downhill direction of the ground, zero on flat ground. + /// + public static Vector3 GetDownhill(Vector3 normal) + { + var downhill = new Vector3(normal.x, 0f, normal.z); + return downhill.sqrMagnitude < 0.000001f ? Vector3.zero : downhill.normalized; + } + + /// + /// moved (horizontal) goes up the slope - walking up a steep slope is no slide start for NPCs (ours: their + /// waypoint routes stay as they are, see NpcJumpFall). + /// + public static bool IsMovingUphill(Vector3 moved, Vector3 normal) + { + moved.y = 0f; + return Vector3.Dot(moved, GetDownhill(normal)) < 0f; + } + + /// + /// While the hero slides the stick can't walk him up the slope, sideways and downhill stay free (ours, Gothic + /// gives no control at all). moved: what the player's own movement moved the body this frame, slideVelocity: + /// the slide's. Returns the correction to add to the slide's move - zero when he didn't step uphill. + /// + public static Vector3 RemoveUphill(Vector3 moved, Vector3 slideVelocity) + { + var downhill = new Vector3(slideVelocity.x, 0f, slideVelocity.z); + if (downhill.sqrMagnitude < 0.000001f) + return Vector3.zero; + + downhill.Normalize(); + moved.y = 0f; + var uphill = -Vector3.Dot(moved, downhill); + return uphill > 0f ? downhill * uphill : Vector3.zero; + } + + /// + /// S_SLIDE when the body faces where it slides, S_SLIDEB when it slides backwards (OpenGothic + /// MoveAlgo::slideDir) - S_SLIDE if the model has no S_SLIDEB, null if it has neither (its normal animations + /// play). The caller says which of them its model has (the hero's animator, an NPC's MDS). + /// + public static string GetAnimation(Vector3 velocity, Vector3 facing, bool hasBackwards, bool hasForward) + { + velocity.y = 0f; + facing.y = 0f; + if (hasBackwards && Vector3.Dot(velocity, facing) < 0f) + return DaedalusConst.AniSlideBack; + return hasForward ? DaedalusConst.AniSlide : null; + } + + /// + /// One frame. feet: where the body stands now, hasGround/normal: the ground straight under it, gravity in m/s^2 + /// (0: no slide, e.g. swimming). + /// + public static SlopeSlideEvent Tick(SlopeSlideState state, Vector3 feet, bool hasGround, Vector3 normal, + LedgeRules rules, float gravity, float deltaTime) + { + var measured = state.HasPreviousFeet && deltaTime > 0f + ? (feet - state.PreviousFeet) / deltaTime + : Vector3.zero; + state.PreviousFeet = feet; + state.HasPreviousFeet = true; + state.GroundAngle = hasGround ? Vector3.Angle(normal, Vector3.up) : 0f; + state.IsSteepGround = hasGround && gravity > 0f && IsSlideGround(normal, rules); + + if (state.IsBlocked && (!state.IsSteepGround || GetFlatDistance(feet, state.BlockedFeet) > + BlockedReleaseDistance)) + state.IsBlocked = false; + + if (!state.IsSliding) + return TickStanding(state, feet, normal, gravity, deltaTime); + + if (!hasGround || gravity <= 0f) + { + Stop(state); + return SlopeSlideEvent.LostGround; + } + + if (!state.IsSteepGround) + { + state.WalkableSeconds += deltaTime; + if (state.WalkableSeconds < StopSeconds) + return SlopeSlideEvent.None; + Stop(state); + return SlopeSlideEvent.Stopped; + } + state.WalkableSeconds = 0f; + + Accelerate(state, measured, normal, gravity, deltaTime); + state.StuckSeconds = state.Velocity.magnitude < _stuckSpeed ? state.StuckSeconds + deltaTime : 0f; + if (state.StuckSeconds < _stuckSeconds) + return SlopeSlideEvent.None; + + Stop(state); + state.IsBlocked = true; + state.BlockedFeet = feet; + return SlopeSlideEvent.Blocked; + } + + /// + /// Not checked right now (climbing, swimming, lying, in the air, teleported...): any slide ends at once, the + /// steep time starts again. true if a slide was running. + /// + public static bool Hold(SlopeSlideState state, Vector3 feet) + { + var wasSliding = state.IsSliding; + Stop(state); + state.IsSteepGround = false; + state.IsBlocked = false; + state.PreviousFeet = feet; + state.HasPreviousFeet = true; + return wasSliding; + } + + /// + /// The body stands still and isn't sliding (NPCs: no slide starts from standing): the steep time starts again + /// and the next speed is measured from here. A block stays - only moving away or walkable ground ends it, else + /// standing still at a wall would let the slide into it start again and again. + /// + public static void Rest(SlopeSlideState state, Vector3 feet) + { + state.SteepSeconds = 0f; + state.PreviousFeet = feet; + state.HasPreviousFeet = true; + } + + /// + /// Horizontal m between the feet and where the slide began. + /// + public static float GetSlidDistance(SlopeSlideState state, Vector3 feet) + { + return GetFlatDistance(feet, state.StartFeet); + } + + private static SlopeSlideEvent TickStanding(SlopeSlideState state, Vector3 feet, Vector3 normal, + float gravity, float deltaTime) + { + state.SteepSeconds = state.IsSteepGround && !state.IsBlocked ? state.SteepSeconds + deltaTime : 0f; + if (state.SteepSeconds < StartSeconds) + return SlopeSlideEvent.None; + + state.IsSliding = true; + state.WalkableSeconds = 0f; + state.StuckSeconds = 0f; + state.StartFeet = feet; + state.Velocity = Vector3.ClampMagnitude(GetAcceleration(normal, gravity) * deltaTime, MaxSpeed); + return SlopeSlideEvent.Started; + } + + /// + /// The speed kept along the ground under the feet, never more than the body really moved along it (a wall or + /// a rock holds it back - like a physics body, without adding the player's own walking), plus this frame's + /// gravity along the slope. + /// + private static void Accelerate(SlopeSlideState state, Vector3 measured, Vector3 normal, float gravity, + float deltaTime) + { + var velocity = Vector3.ProjectOnPlane(state.Velocity, normal); + var speed = velocity.magnitude; + if (speed > 0.0001f) + { + var direction = velocity / speed; + speed = Mathf.Clamp(Vector3.Dot(measured, direction), 0f, speed); + velocity = direction * speed; + } + + state.Velocity = Vector3.ClampMagnitude(velocity + GetAcceleration(normal, gravity) * deltaTime, MaxSpeed); + } + + private static void Stop(SlopeSlideState state) + { + state.IsSliding = false; + state.Velocity = Vector3.zero; + state.SteepSeconds = 0f; + state.WalkableSeconds = 0f; + state.StuckSeconds = 0f; + } + + private static float GetFlatDistance(Vector3 a, Vector3 b) + { + return new Vector2(a.x - b.x, a.z - b.z).magnitude; + } + } +} diff --git a/Assets/Gothic-Core/Scripts/Domain/Movement/SlopeSlideDomain.cs.meta b/Assets/Gothic-Core/Scripts/Domain/Movement/SlopeSlideDomain.cs.meta new file mode 100644 index 000000000..16687b0da --- /dev/null +++ b/Assets/Gothic-Core/Scripts/Domain/Movement/SlopeSlideDomain.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: e5003fdee9c451248a4db0b13e147a21 \ No newline at end of file diff --git a/Assets/Gothic-Core/Scripts/Models/Movement/HeroBodyResult.cs b/Assets/Gothic-Core/Scripts/Models/Movement/HeroBodyResult.cs new file mode 100644 index 000000000..f24ebd558 --- /dev/null +++ b/Assets/Gothic-Core/Scripts/Models/Movement/HeroBodyResult.cs @@ -0,0 +1,33 @@ +using UnityEngine; + +namespace Gothic.Core.Models.Movement +{ + /// + /// What the platform applies to the hero's body after a frame of HeroBodyService.Tick (VR: the rig port IVrRig). + /// + public readonly struct HeroBodyResult + { + /// + /// What the fall changed this frame, handled already by HeroFallService (None while not tracked) - the + /// platform acts on it (VR: JumpStarted starts the running jump's leap). + /// + public readonly HeroAirEvent AirEvent; + + /// + /// World m/s down the slope the body slides with, zero = no slide (HeroSlideService). + /// + public readonly Vector3 SlideVelocity; + + /// + /// The ground is too steep to jump from: the platform refuses the take-off (HeroSlideService). + /// + public readonly bool IsTakeOffBlocked; + + public HeroBodyResult(HeroAirEvent airEvent, Vector3 slideVelocity, bool isTakeOffBlocked) + { + AirEvent = airEvent; + SlideVelocity = slideVelocity; + IsTakeOffBlocked = isTakeOffBlocked; + } + } +} diff --git a/Assets/Gothic-Core/Scripts/Models/Movement/HeroBodyResult.cs.meta b/Assets/Gothic-Core/Scripts/Models/Movement/HeroBodyResult.cs.meta new file mode 100644 index 000000000..5b9dd7bca --- /dev/null +++ b/Assets/Gothic-Core/Scripts/Models/Movement/HeroBodyResult.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: e1fedd2eda3b1c146a0ff488575df9ff \ No newline at end of file diff --git a/Assets/Gothic-Core/Scripts/Models/Movement/HeroFallSample.cs b/Assets/Gothic-Core/Scripts/Models/Movement/HeroBodySample.cs similarity index 73% rename from Assets/Gothic-Core/Scripts/Models/Movement/HeroFallSample.cs rename to Assets/Gothic-Core/Scripts/Models/Movement/HeroBodySample.cs index 61fb71266..ec750baa6 100644 --- a/Assets/Gothic-Core/Scripts/Models/Movement/HeroFallSample.cs +++ b/Assets/Gothic-Core/Scripts/Models/Movement/HeroBodySample.cs @@ -3,10 +3,11 @@ namespace Gothic.Core.Models.Movement { /// - /// One frame's measurement of the player's body for HeroFallService.Tick, given by the platform (VR: the rig port - /// IVrRig, with its grounded grace time). Platform-neutral: the rules don't know where it comes from. + /// One frame's measurement of the player's body for HeroBodyService.Tick (his falls and his slides), given by the + /// platform (VR: the rig port IVrRig, with its grounded grace time). Platform-neutral: the rules don't know where + /// it comes from. /// - public readonly struct HeroFallSample + public readonly struct HeroBodySample { /// /// Position of the feet (world, m). @@ -62,11 +63,20 @@ public readonly struct HeroFallSample public readonly float DeltaTime; + /// + /// Ground straight under the feet (a ray down, not the body's side contacts) - its normal decides a slide + /// (HeroSlideService). false: nothing within the platform's reach below. Required: a platform that left it out + /// would silently never slide and never block a jump from steep ground. + /// + public readonly bool HasGround; + + public readonly Vector3 GroundNormal; + public float FeetY => FeetPosition.y; - public HeroFallSample(Vector3 feetPosition, Vector3 forward, bool isGrounded, bool isJumping, bool isClimbing, + public HeroBodySample(Vector3 feetPosition, Vector3 forward, bool isGrounded, bool isJumping, bool isClimbing, bool isTransformed, float gravity, float maxFallSpeed, float groundSnapHeight, float runSpeed, - float deltaTime) + float deltaTime, bool hasGround, Vector3 groundNormal) { FeetPosition = feetPosition; Forward = forward; @@ -79,6 +89,8 @@ public HeroFallSample(Vector3 feetPosition, Vector3 forward, bool isGrounded, bo GroundSnapHeight = groundSnapHeight; RunSpeed = runSpeed; DeltaTime = deltaTime; + HasGround = hasGround; + GroundNormal = groundNormal; } } } diff --git a/Assets/Gothic-Core/Scripts/Models/Movement/HeroFallSample.cs.meta b/Assets/Gothic-Core/Scripts/Models/Movement/HeroBodySample.cs.meta similarity index 100% rename from Assets/Gothic-Core/Scripts/Models/Movement/HeroFallSample.cs.meta rename to Assets/Gothic-Core/Scripts/Models/Movement/HeroBodySample.cs.meta diff --git a/Assets/Gothic-Core/Scripts/Models/Movement/HeroSlideHold.cs b/Assets/Gothic-Core/Scripts/Models/Movement/HeroSlideHold.cs new file mode 100644 index 000000000..34d00de6c --- /dev/null +++ b/Assets/Gothic-Core/Scripts/Models/Movement/HeroSlideHold.cs @@ -0,0 +1,64 @@ +namespace Gothic.Core.Models.Movement +{ + /// + /// Why HeroSlideService doesn't check the hero for a slide right now (no slide, the jump allowed). An enum, not a + /// string: it's decided every frame. + /// + public enum HeroSlideHold + { + /// + /// Checked. + /// + None, + + /// + /// A hand holds a ladder or a ledge. + /// + Climbing, + + /// + /// Transformed into a monster: the puppet stands on any slope. + /// + Transformed, + + /// + /// Swimming or diving. + /// + NoGravity, + + /// + /// His own jump runs. + /// + Jumping, + + /// + /// In the air without his own jump (HeroFallService's phase isn't Grounded): the fall lands first. + /// + Airborne, + + /// + /// Lying after a fall flat until he stood up. + /// + LyingAfterFall, + + /// + /// Wading or deeper in water. + /// + InWater, + + /// + /// A body state other than stand, walk, run or sneak (fighting, sitting, a mob, casting...). + /// + Busy, + + /// + /// Teleported this frame. + /// + Teleported, + + /// + /// No hero (or his properties) right now - a slide running ends. + /// + NoHero + } +} diff --git a/Assets/Gothic-Core/Scripts/Models/Movement/HeroSlideHold.cs.meta b/Assets/Gothic-Core/Scripts/Models/Movement/HeroSlideHold.cs.meta new file mode 100644 index 000000000..8449705a3 --- /dev/null +++ b/Assets/Gothic-Core/Scripts/Models/Movement/HeroSlideHold.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: d7cd18f8c7c5aca43b70e31ae8428f5e \ No newline at end of file diff --git a/Assets/Gothic-Core/Scripts/Models/Movement/LedgeRules.cs b/Assets/Gothic-Core/Scripts/Models/Movement/LedgeRules.cs index 54d690c17..dc1d9d4e3 100644 --- a/Assets/Gothic-Core/Scripts/Models/Movement/LedgeRules.cs +++ b/Assets/Gothic-Core/Scripts/Models/Movement/LedgeRules.cs @@ -1,9 +1,10 @@ +using UnityEngine; using ZenKit.Daedalus; namespace Gothic.Core.Models.Movement { /// - /// Gothic's climbing values of a guild (C_GILVALUES), converted to metres. Angles in degrees. + /// Gothic's climbing and sliding values of a guild (C_GILVALUES), converted to metres. Angles in degrees. /// public struct LedgeRules { @@ -17,6 +18,7 @@ public struct LedgeRules JumpMidHeight = 2.05f, JumpUpHeight = 2f, SlideAngle = 45f, + SlideAngle2 = 0f, ClimbHeadingAngle = 45f }; @@ -29,7 +31,18 @@ public struct LedgeRules public float JumpLowHeight; public float JumpMidHeight; public float JumpUpHeight; + + /// + /// SLIDE_ANGLE: ground steeper than this slides (SlopeSlideDomain) and is no ledge top. + /// public float SlideAngle; + + /// + /// SLIDE_ANGLE2: ground this close to vertical (degrees from it) is a wall, no slide (OpenGothic + /// MoveAlgo::testSlide). 0 in Gothic's Species.d - only vertical ground stops a slide. + /// + public float SlideAngle2; + public float ClimbHeadingAngle; /// @@ -54,6 +67,8 @@ public static LedgeRules FromGuildValues(GuildValuesInstance values, int guild) JumpMidHeight = Metres(values.GetJumpMidHeight(guild), defaults.JumpMidHeight), JumpUpHeight = Metres(values.GetJumpUpHeight(guild), defaults.JumpUpHeight), SlideAngle = Degrees(values.GetSlideAngle(guild), defaults.SlideAngle), + // Not Degrees(): 0 is Gothic's own value here (only vertical ground is a wall), not "unset". + SlideAngle2 = Mathf.Clamp(values.GetSlideAngle2(guild), 0, 90), ClimbHeadingAngle = Degrees(values.GetClimbHeadingAngle(guild), defaults.ClimbHeadingAngle) }; } diff --git a/Assets/Gothic-Core/Scripts/Models/Movement/SlopeSlideEvent.cs b/Assets/Gothic-Core/Scripts/Models/Movement/SlopeSlideEvent.cs new file mode 100644 index 000000000..24f41698a --- /dev/null +++ b/Assets/Gothic-Core/Scripts/Models/Movement/SlopeSlideEvent.cs @@ -0,0 +1,30 @@ +namespace Gothic.Core.Models.Movement +{ + /// + /// What changed in a body's slide this frame (SlopeSlideDomain.Tick). + /// + public enum SlopeSlideEvent + { + None, + + /// + /// Steeper than SLIDE_ANGLE long enough: the slide begins (S_SLIDE / S_SLIDEB). + /// + Started, + + /// + /// Walkable ground again: he stands (OpenGothic: back to Run, the speed is dropped). + /// + Stopped, + + /// + /// No ground under the feet anymore (off an edge): a normal fall takes over. + /// + LostGround, + + /// + /// Held at the slope (a wall, a rock, a crevice): he stands where he is, no new slide until he moved away. + /// + Blocked + } +} diff --git a/Assets/Gothic-Core/Scripts/Models/Movement/SlopeSlideEvent.cs.meta b/Assets/Gothic-Core/Scripts/Models/Movement/SlopeSlideEvent.cs.meta new file mode 100644 index 000000000..a8b32459f --- /dev/null +++ b/Assets/Gothic-Core/Scripts/Models/Movement/SlopeSlideEvent.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: fc9052bee6bc9124398f570b910b9f31 \ No newline at end of file diff --git a/Assets/Gothic-Core/Scripts/Models/Movement/SlopeSlideState.cs b/Assets/Gothic-Core/Scripts/Models/Movement/SlopeSlideState.cs new file mode 100644 index 000000000..044ca7365 --- /dev/null +++ b/Assets/Gothic-Core/Scripts/Models/Movement/SlopeSlideState.cs @@ -0,0 +1,50 @@ +using UnityEngine; + +namespace Gothic.Core.Models.Movement +{ + /// + /// One body's slide down a slope (the hero, an NPC), advanced by SlopeSlideDomain.Tick every frame. Not saved: a + /// loaded game starts standing. + /// + public class SlopeSlideState + { + public bool IsSliding { get; set; } + + /// + /// World m/s along the slope, downhill. Zero while not sliding. + /// + public Vector3 Velocity { get; set; } + + /// + /// The ground under the feet is steeper than SLIDE_ANGLE this frame - no take-off from it (no debounce). + /// + public bool IsSteepGround { get; set; } + + /// + /// Angle of the ground under the feet in degrees this frame, 0 without ground (logs). + /// + public float GroundAngle { get; set; } + + /// + /// Seconds of steep ground in a row (before a slide), of walkable ground in a row (while sliding), and of + /// sliding without getting anywhere. + /// + public float SteepSeconds { get; set; } + public float WalkableSeconds { get; set; } + public float StuckSeconds { get; set; } + + /// + /// Stopped by a block at BlockedFeet: no new slide until he moved away or stands on walkable ground. + /// + public bool IsBlocked { get; set; } + public Vector3 BlockedFeet { get; set; } + + /// + /// Where the slide began (logs: how far he slid). + /// + public Vector3 StartFeet { get; set; } + + public Vector3 PreviousFeet { get; set; } + public bool HasPreviousFeet { get; set; } + } +} diff --git a/Assets/Gothic-Core/Scripts/Models/Movement/SlopeSlideState.cs.meta b/Assets/Gothic-Core/Scripts/Models/Movement/SlopeSlideState.cs.meta new file mode 100644 index 000000000..e464d1a3d --- /dev/null +++ b/Assets/Gothic-Core/Scripts/Models/Movement/SlopeSlideState.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: c683d48cf801d5a4abd0368187d4c3b7 \ No newline at end of file diff --git a/Assets/Gothic-Core/Scripts/ReflexProjectInstaller.cs b/Assets/Gothic-Core/Scripts/ReflexProjectInstaller.cs index 28af77ce4..91afb7b74 100644 --- a/Assets/Gothic-Core/Scripts/ReflexProjectInstaller.cs +++ b/Assets/Gothic-Core/Scripts/ReflexProjectInstaller.cs @@ -147,6 +147,8 @@ public void InstallBindings(ContainerBuilder containerBuilder) containerBuilder.AddSingleton(typeof(RoomService)); containerBuilder.AddSingleton(typeof(LedgeService)); containerBuilder.AddSingleton(typeof(HeroFallService)); + containerBuilder.AddSingleton(typeof(HeroSlideService)); + containerBuilder.AddSingleton(typeof(HeroBodyService)); // Misc containerBuilder.AddSingleton(typeof(AudioService)); diff --git a/Assets/Gothic-Core/Scripts/Services/Movement/HeroBodyService.cs b/Assets/Gothic-Core/Scripts/Services/Movement/HeroBodyService.cs new file mode 100644 index 000000000..ab5f709e8 --- /dev/null +++ b/Assets/Gothic-Core/Scripts/Services/Movement/HeroBodyService.cs @@ -0,0 +1,43 @@ +using Gothic.Core.Models.Movement; +using Reflex.Attributes; +using UnityEngine; + +namespace Gothic.Core.Services.Movement +{ + /// + /// The one entry point for the hero's body each frame: the platform measures it (HeroBodySample - VR: + /// VrHeroJumpFall from the rig port), calls Tick and applies the result. The order of the rules is decided here, + /// not per platform: + /// 1. HeroFallService - jumps, falls, fall damage, the lying landing. + /// 2. HeroSlideService - slides down steep slopes, no take-off from them. After the fall: a landing on a steep + /// slope is a landing, the slide begins after it (it reads the fall's phase and the landing's lying lock). + /// The result carries the fall's event of the frame (HeroAirEvent: JumpStarted starts the VR leap). The platform + /// still reads the two services' state for its body (HeroFallService.Phase / IsRunningJump / TakeOffVelocity, + /// HeroSlideService.IsSliding, the body state while sliding: HeroSlideService.TryGetLocomotionBodyState) - it + /// only never ticks them itself. + /// + public class HeroBodyService + { + [Inject] private readonly HeroFallService _heroFallService; + [Inject] private readonly HeroSlideService _heroSlideService; + + /// + /// One frame's measurement of the player's body. Called every frame by the platform, also on the ground. + /// + public HeroBodyResult Tick(in HeroBodySample sample) + { + var airEvent = _heroFallService.Tick(sample); + _heroSlideService.Tick(sample); + return new HeroBodyResult(airEvent, _heroSlideService.Velocity, _heroSlideService.IsTakeOffBlocked); + } + + /// + /// The player was teleported: a fall or slide measured so far ends there. + /// + public void OnTeleported(Vector3 feetPosition) + { + _heroFallService.OnTeleported(feetPosition); + _heroSlideService.OnTeleported(feetPosition); + } + } +} diff --git a/Assets/Gothic-Core/Scripts/Services/Movement/HeroBodyService.cs.meta b/Assets/Gothic-Core/Scripts/Services/Movement/HeroBodyService.cs.meta new file mode 100644 index 000000000..4cb1a37bc --- /dev/null +++ b/Assets/Gothic-Core/Scripts/Services/Movement/HeroBodyService.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 0a8301b387e36e54589ab0d78d90e013 \ No newline at end of file diff --git a/Assets/Gothic-Core/Scripts/Services/Movement/HeroFallService.cs b/Assets/Gothic-Core/Scripts/Services/Movement/HeroFallService.cs index f5ddcb702..a6e9816c0 100644 --- a/Assets/Gothic-Core/Scripts/Services/Movement/HeroFallService.cs +++ b/Assets/Gothic-Core/Scripts/Services/Movement/HeroFallService.cs @@ -18,7 +18,8 @@ namespace Gothic.Core.Services.Movement /// /// The hero's jumps and falls like the engine's: BS_JUMP / BS_FALL while in the air, fall damage at the landing /// (always, also without the combat system), lying and getting up after a fall flat. The platform measures (VR: - /// the rig port, VrHeroJumpFall) and calls Tick every frame; the phases come from HeroAirborneDomain. + /// the rig port, VrHeroJumpFall) and HeroBodyService ticks this every frame, before the slide; the phases come + /// from HeroAirborneDomain. /// Pose and damage are separate rules: /// - Pose: S_FALLDN as soon as he falls; a fall deeper than NpcFallDomain.LyingFallHeight (2 m, like NPCs), a jump /// deeper than FALLDOWN_HEIGHT below its take-off (like OpenGothic), falls flat (FallPose: on his face, on @@ -88,6 +89,11 @@ public class HeroFallService /// public bool IsRunningJump => _airborne.IsRunningJump; + /// + /// He lies after a fall flat and gets up (walking locked) - no slide meanwhile (HeroSlideService). + /// + public bool IsLyingAfterFall => _isLandingLocked; + /// /// The hero's horizontal movement (m/s) at the take-off of the jump running now - IsRunningJump is decided /// from it, the platform's leap goes in its direction. Zero on the ground. @@ -98,16 +104,17 @@ public HeroFallService() { GlobalEventDispatcher.LoadGameStart.AddListener(ResetAll); GlobalEventDispatcher.WorldSceneLoaded.AddListener(ResetAll); - // The landing's lock is timed by Tick, which only the platform calls - a dead hero doesn't get up. + // The landing's lock is timed by Tick, which only the platform's frames call - a dead hero doesn't get up. GlobalEventDispatcher.HeroDied.AddListener(_ => Unlock()); } /// - /// One frame's measurement of the player's body. Called every frame by the platform, also on the ground. - /// Returns what this frame changed, handled already (None while not tracked) - the platform acts on it (VR: - /// JumpStarted starts the running jump's leap). + /// One frame's measurement of the player's body - every frame, also on the ground. Only HeroBodyService + /// calls it (it decides the order with the slide). Returns what this frame changed, handled already (None + /// while not tracked) - HeroBodyService hands it on to the platform (VR: JumpStarted starts the running + /// jump's leap). /// - public HeroAirEvent Tick(in HeroFallSample sample) + internal HeroAirEvent Tick(in HeroBodySample sample) { UpdateLandingLock(); @@ -162,7 +169,7 @@ public HeroAirEvent Tick(in HeroFallSample sample) /// The player was teleported (thumbstick, Marvin, AI_Teleport, spawn, loading, ledge/ladder exits): whatever /// fall ran is dropped, a new one starts at the target. A lying landing's lock ends - he arrives standing. /// - public void OnTeleported(Vector3 feetPosition) + internal void OnTeleported(Vector3 feetPosition) { Unlock(); var hero = _npcService.GetHeroContainer(); @@ -176,7 +183,7 @@ public void OnTeleported(Vector3 feetPosition) /// Why the hero isn't tracked now, None if he is. A drawn weapon or a VR melee fight keeps him tracked: like /// Gothic the hero stays BS_STAND / BS_WALK / BS_RUN / BS_SNEAK then (no BS_FIGHT is set for him). /// - private static HeroFallHold GetHold(NpcContainer hero, in HeroFallSample sample) + private static HeroFallHold GetHold(NpcContainer hero, in HeroBodySample sample) { if (sample.IsClimbing) return HeroFallHold.Climbing; diff --git a/Assets/Gothic-Core/Scripts/Services/Movement/HeroSlideService.cs b/Assets/Gothic-Core/Scripts/Services/Movement/HeroSlideService.cs new file mode 100644 index 000000000..7022524ca --- /dev/null +++ b/Assets/Gothic-Core/Scripts/Services/Movement/HeroSlideService.cs @@ -0,0 +1,209 @@ +using Gothic.Core.Const; +using Gothic.Core.Domain.Movement; +using Gothic.Core.Logging; +using Gothic.Core.Models.Container; +using Gothic.Core.Models.Movement; +using Gothic.Core.Models.Vm; +using Gothic.Core.Services.Npc; +using Reflex.Attributes; +using UnityEngine; +using Logger = Gothic.Core.Logging.Logger; + +namespace Gothic.Core.Services.Movement +{ + /// + /// The hero slides down slopes steeper than his SLIDE_ANGLE like in Gothic (SlopeSlideDomain) - and can't jump off + /// such ground (IsTakeOffBlocked, OpenGothic Npc::tryJump: no jump while sliding). The platform measures the ground + /// straight under the feet (VR: VrHeroJumpFall, from the rig port) and HeroBodyService ticks this every frame, + /// after the fall; the platform moves the body with Velocity and takes back the player's own steps up the slope + /// meanwhile (SlopeSlideDomain.RemoveUphill). + /// - A slide is no fall: the body stays on the ground (the platform counts it as grounded), no fall damage. Off an + /// edge the slide ends and HeroFallService's normal fall begins from there. + /// - Body state: BS_STAND while sliding (OpenGothic: BS_NONE for S_SLIDE/S_SLIDEB), decided here - the platform + /// asks TryGetLocomotionBodyState before it sets walk/run/sneak (VR: VRHeroMovement). + /// Not checked (no slide, the jump allowed): climbing, transformed (the puppet stands on any slope - its own guild + /// isn't applied), no gravity or water, in the air (HeroFallService's phase not Grounded), lying after a fall + /// flat, down or busy (sitting, mobs), no hero. + /// Not saved: a loaded game starts standing. + /// + public class HeroSlideService + { + [Inject] private readonly NpcService _npcService; + [Inject] private readonly LedgeService _ledgeService; + [Inject] private readonly HeroFallService _heroFallService; + + private readonly SlopeSlideState _state = new(); + // Why the hero isn't checked right now (logged when it changes). + private HeroSlideHold _hold; + + public bool IsSliding => _state.IsSliding; + + /// + /// World m/s along the slope - zero while not sliding. + /// + public Vector3 Velocity => _state.IsSliding ? _state.Velocity : Vector3.zero; + + /// + /// The ground under the feet is too steep to jump from (no debounce: also before a slide begins). Without it + /// the hero climbed any slope by jumping again and again. + /// + public bool IsTakeOffBlocked => _hold == HeroSlideHold.None && _state.IsSteepGround; + + public HeroSlideService() + { + GlobalEventDispatcher.LoadGameStart.AddListener(ResetAll); + GlobalEventDispatcher.WorldSceneLoaded.AddListener(ResetAll); + } + + /// + /// The body state the scripts see for the hero's walking while Core decides it - false: the platform's own + /// walk/run/sneak counts. BS_STAND while he slides: no footsteps, no running for the NPCs' perceptions. A + /// platform asks this before it sets BS_WALK / BS_RUN / BS_SNEAK. + /// + public bool TryGetLocomotionBodyState(out VmGothicEnums.BodyState bodyState) + { + bodyState = VmGothicEnums.BodyState.BsStand; + return _state.IsSliding; + } + + /// + /// S_SLIDE when the body faces where it slides, S_SLIDEB when it slides backwards - null if the body's model + /// has neither (SlopeSlideDomain.GetAnimation). + /// + public string GetAnimation(Vector3 facing, bool hasBackwards, bool hasForward) + { + return SlopeSlideDomain.GetAnimation(_state.Velocity, facing, hasBackwards, hasForward); + } + + /// + /// One frame's measurement of the player's body (the same sample HeroFallService gets, after it). Only + /// HeroBodyService calls it. + /// + internal void Tick(in HeroBodySample sample) + { + var hero = _npcService.GetHeroContainer(); + if (hero?.Props == null) + { + // No slide velocity left behind for the platform to keep applying. + Hold(sample.FeetPosition, HeroSlideHold.NoHero, null); + return; + } + + var hold = GetHold(hero, sample); + if (hold != HeroSlideHold.None) + { + Hold(sample.FeetPosition, hold, hero); + return; + } + _hold = HeroSlideHold.None; + + var rules = _ledgeService.HeroRules; + var feet = sample.FeetPosition; + var speed = _state.Velocity.magnitude; + switch (SlopeSlideDomain.Tick(_state, feet, sample.HasGround, sample.GroundNormal, rules, sample.Gravity, + sample.DeltaTime)) + { + case SlopeSlideEvent.Started: + Logger.Log($"[HeroSlide] Slides down a {_state.GroundAngle:F0} deg slope at {feet.y:F2} " + + $"(SLIDE_ANGLE {rules.SlideAngle:F0}, SLIDE_ANGLE2 {rules.SlideAngle2:F0})", LogCat.Npc); + break; + case SlopeSlideEvent.Stopped: + LogEnd("walkable ground", feet, speed); + break; + case SlopeSlideEvent.LostGround: + LogEnd("no ground below - falls", feet, speed); + break; + case SlopeSlideEvent.Blocked: + LogEnd($"held at the {_state.GroundAngle:F0} deg slope", feet, speed); + break; + } + } + + /// + /// The player was teleported: a slide ends there. + /// + internal void OnTeleported(Vector3 feetPosition) + { + Hold(feetPosition, HeroSlideHold.Teleported, _npcService.GetHeroContainer()); + } + + /// + /// Why the hero isn't checked now, None if he is. Every frame: no strings. + /// + private HeroSlideHold GetHold(NpcContainer hero, in HeroBodySample sample) + { + if (sample.IsClimbing) + return HeroSlideHold.Climbing; + if (sample.IsTransformed) + return HeroSlideHold.Transformed; + if (sample.Gravity <= 0f) + return HeroSlideHold.NoGravity; + if (sample.IsJumping) + return HeroSlideHold.Jumping; + // Off a low ledge above a steep slope: the fall lands first (its damage counted), the slide after it. + if (_heroFallService.Phase != HeroAirPhase.Grounded) + return HeroSlideHold.Airborne; + if (_heroFallService.IsLyingAfterFall) + return HeroSlideHold.LyingAfterFall; + + var ai = hero.Vob?.AiHuman; + if (ai != null && ai.WaterLevel != (int)ZenGineConst.WaterLevel.Normal) + return HeroSlideHold.InWater; + + return hero.Props.BodyState is VmGothicEnums.BodyState.BsStand or VmGothicEnums.BodyState.BsWalk + or VmGothicEnums.BodyState.BsRun or VmGothicEnums.BodyState.BsSneak + ? HeroSlideHold.None + : HeroSlideHold.Busy; + } + + /// + /// Ends a running slide and logs why - the reason only when it changed, so the text is built once. + /// + private void Hold(Vector3 feet, HeroSlideHold hold, NpcContainer hero) + { + var speed = _state.Velocity.magnitude; + var wasSliding = SlopeSlideDomain.Hold(_state, feet); + if (wasSliding || hold != _hold) + { + var reason = GetText(hold, hero); + if (wasSliding) + LogEnd(reason, feet, speed); + else + Logger.LogEditor($"[HeroSlide] Not checked: {reason}", LogCat.Npc); + } + _hold = hold; + } + + private string GetText(HeroSlideHold hold, NpcContainer hero) + { + return hold switch + { + HeroSlideHold.Climbing => "climbing", + HeroSlideHold.Transformed => "transformed", + HeroSlideHold.NoGravity => "no gravity (swimming, diving)", + HeroSlideHold.Jumping => "jumping", + HeroSlideHold.Airborne => $"in the air ({_heroFallService.Phase})", + HeroSlideHold.LyingAfterFall => "lying after a fall", + HeroSlideHold.InWater => "in water", + HeroSlideHold.Busy => $"body state {hero?.Props?.BodyState}", + HeroSlideHold.Teleported => "teleported", + HeroSlideHold.NoHero => "no hero", + _ => hold.ToString() + }; + } + + private void LogEnd(string reason, Vector3 feet, float speed) + { + var distance = SlopeSlideDomain.GetSlidDistance(_state, feet); + Logger.Log($"[HeroSlide] Slide ended ({reason}) after {distance:F1} m at {speed:F1} m/s, at {feet.y:F2}", + LogCat.Npc); + } + + private void ResetAll() + { + SlopeSlideDomain.Hold(_state, Vector3.zero); + _state.HasPreviousFeet = false; + _hold = HeroSlideHold.None; + } + } +} diff --git a/Assets/Gothic-Core/Scripts/Services/Movement/HeroSlideService.cs.meta b/Assets/Gothic-Core/Scripts/Services/Movement/HeroSlideService.cs.meta new file mode 100644 index 000000000..ae142d1a9 --- /dev/null +++ b/Assets/Gothic-Core/Scripts/Services/Movement/HeroSlideService.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: dfbfd1aade0e66e48bc9f58d96fdeca5 \ No newline at end of file diff --git a/Assets/Gothic-Tests/EditMode/Movement/HeroAirborneDomainTest.cs b/Assets/Gothic-Tests/EditMode/Movement/HeroAirborneDomainTest.cs index 1389e465a..5760f7623 100644 --- a/Assets/Gothic-Tests/EditMode/Movement/HeroAirborneDomainTest.cs +++ b/Assets/Gothic-Tests/EditMode/Movement/HeroAirborneDomainTest.cs @@ -51,8 +51,8 @@ public void SetUp() private void Tick(float feetY, bool isGrounded, bool isJumping = false, float dt = _dt) { _feet = new Vector3(_feet.x, feetY, _feet.z) + _moveVelocity * dt; - var sample = new HeroFallSample(_feet, _forward, isGrounded, isJumping, false, false, _gravity, - _maxFallSpeed, _groundSnapHeight, _runSpeed, dt); + var sample = new HeroBodySample(_feet, _forward, isGrounded, isJumping, false, false, _gravity, + _maxFallSpeed, _groundSnapHeight, _runSpeed, dt, isGrounded, Vector3.up); switch (_domain.Tick(sample, _safeHeight, out var landing)) { case HeroAirEvent.Landed: @@ -356,6 +356,42 @@ public void JumpPastFalldownHeightInOneStepLandsLying() Assert.AreEqual(6f, _landing.Height, 0.01f); } + /// + /// A slide is no fall (HeroSlideService - the platform counts the sliding hero as grounded): 2 m down a steep + /// slope and off its edge, the drop counts from the edge, not from where the slide began. The platform's + /// grounded grace after the edge (XRI: 0.12 s) only lowers that start by the few cm fallen in it. + /// + [Test] + public void SlideOffAnEdgeFallsFromTheEdge() + { + Stand(10f); + // Down a 60 deg slope at 6 m/s, on the ground: 3 m/s across, 5.2 m/s down. + _moveVelocity = Vector3.forward * 3f; + var y = 10f; + while (y > 8f) + { + y = Mathf.Max(y - 5.2f * _dt, 8f); + Tick(y, true); + } + Assert.AreEqual(HeroAirPhase.Grounded, _domain.Phase); + + // Off the edge: the slide has ended, the grace still reports ground, then the fall 4 m down. + var velocityY = 0f; + for (var time = 0f; time < 0.12f; time += _dt) + { + velocityY -= _gravity * _dt; + y += velocityY * _dt; + Tick(y, true); + } + FallTo(y, 4f, velocityY); + + Assert.AreEqual(0, _teleports); + Assert.AreEqual(1, _falls); + Assert.AreEqual(1, _landings); + Assert.IsTrue(_landing.IsLying); + Assert.AreEqual(4f, _landing.Height, 0.1f); + } + [Test] public void SteppingOffASmallEdgeIsNoLanding() { diff --git a/Assets/Gothic-Tests/EditMode/Movement/SlopeSlideDomainTest.cs b/Assets/Gothic-Tests/EditMode/Movement/SlopeSlideDomainTest.cs new file mode 100644 index 000000000..8e89f4e8a --- /dev/null +++ b/Assets/Gothic-Tests/EditMode/Movement/SlopeSlideDomainTest.cs @@ -0,0 +1,261 @@ +using Gothic.Core.Const; +using Gothic.Core.Domain.Movement; +using Gothic.Core.Models.Movement; +using NUnit.Framework; +using UnityEngine; + +namespace Gothic.Tests.EditMode.Movement +{ + /// + /// Sliding down slopes (SlopeSlideDomain): which ground slides (SLIDE_ANGLE, SLIDE_ANGLE2), gravity along the + /// slope, the start/stop debounce against single steep triangles, blocked slides and the end at an edge. + /// + public class SlopeSlideDomainTest + { + private const float _dt = 1f / 72f; + private const float _gravity = 9.81f; + + private static readonly LedgeRules _human = LedgeRules.GothicHumanDefaults; + + private SlopeSlideState _state; + private Vector3 _feet; + + [SetUp] + public void SetUp() + { + _state = new SlopeSlideState(); + _feet = Vector3.zero; + } + + /// + /// The normal of ground sloping down towards +z by angle degrees. + /// + private static Vector3 Slope(float angle) + { + return Quaternion.Euler(angle, 0f, 0f) * Vector3.up; + } + + /// + /// One frame; the body moved by its slide velocity (moves = false: held in place). + /// + private SlopeSlideEvent Tick(Vector3 normal, bool hasGround = true, bool moves = true) + { + if (moves) + _feet += _state.Velocity * _dt; + return SlopeSlideDomain.Tick(_state, _feet, hasGround, normal, _human, _gravity, _dt); + } + + private SlopeSlideEvent TickFor(float seconds, Vector3 normal, bool hasGround = true, bool moves = true) + { + var result = SlopeSlideEvent.None; + for (var time = 0f; time < seconds; time += _dt) + { + var tick = Tick(normal, hasGround, moves); + if (tick != SlopeSlideEvent.None) + result = tick; + } + return result; + } + + [Test] + public void SlidesOnlySteeperThanSlideAngle() + { + Assert.IsFalse(SlopeSlideDomain.IsSlideGround(Vector3.up, _human)); + Assert.IsFalse(SlopeSlideDomain.IsSlideGround(Slope(40f), _human)); + Assert.IsTrue(SlopeSlideDomain.IsSlideGround(Slope(50f), _human)); + Assert.IsTrue(SlopeSlideDomain.IsSlideGround(Slope(85f), _human)); + Assert.IsFalse(SlopeSlideDomain.IsSlideGround(Slope(90f), _human), "a vertical wall isn't ground"); + } + + [Test] + public void SlideAngle2MakesNearVerticalGroundAWall() + { + var rules = _human; + rules.SlideAngle2 = 10f; + Assert.IsTrue(SlopeSlideDomain.IsSlideGround(Slope(75f), rules)); + Assert.IsFalse(SlopeSlideDomain.IsSlideGround(Slope(85f), rules)); + } + + [Test] + public void MonsterGuildsSlideFromTheirOwnAngle() + { + var bloodfly = _human; + bloodfly.SlideAngle = 75f; + Assert.IsFalse(SlopeSlideDomain.IsSlideGround(Slope(60f), bloodfly)); + Assert.IsTrue(SlopeSlideDomain.IsSlideGround(Slope(80f), bloodfly)); + } + + [Test] + public void GravityPullsDownTheSlope() + { + var acceleration = SlopeSlideDomain.GetAcceleration(Slope(60f), _gravity); + Assert.AreEqual(_gravity * Mathf.Sin(60f * Mathf.Deg2Rad), acceleration.magnitude, 0.001f); + Assert.Less(acceleration.y, 0f); + Assert.Greater(acceleration.z, 0f, "downhill is +z"); + Assert.AreEqual(0f, Vector3.Dot(acceleration, Slope(60f)), 0.001f, "along the ground"); + } + + [Test] + public void ShortSteepGroundDoesNotSlide() + { + Assert.AreEqual(SlopeSlideEvent.None, TickFor(SlopeSlideDomain.StartSeconds * 0.5f, Slope(60f))); + Assert.IsTrue(_state.IsSteepGround, "steep at once - no take-off from it"); + Tick(Vector3.up); + Assert.AreEqual(SlopeSlideEvent.None, TickFor(SlopeSlideDomain.StartSeconds * 0.5f, Slope(60f))); + Assert.IsFalse(_state.IsSliding); + } + + [Test] + public void SteepGroundStartsASlideThatGetsFaster() + { + Assert.AreEqual(SlopeSlideEvent.Started, TickFor(SlopeSlideDomain.StartSeconds + _dt, Slope(60f))); + var speed = _state.Velocity.magnitude; + TickFor(0.5f, Slope(60f)); + Assert.Greater(_state.Velocity.magnitude, speed + 2f); + Assert.Greater(_state.Velocity.z, 0f); + Assert.Less(_feet.y, 0f, "slid downhill"); + } + + [Test] + public void SlideSpeedIsCapped() + { + TickFor(10f, Slope(80f)); + Assert.IsTrue(_state.IsSliding); + Assert.AreEqual(SlopeSlideDomain.MaxSpeed, _state.Velocity.magnitude, 0.01f); + } + + [Test] + public void WalkableGroundEndsTheSlide() + { + TickFor(1f, Slope(60f)); + Assert.AreEqual(SlopeSlideEvent.None, Tick(Vector3.up), "one flat triangle doesn't end it"); + Assert.AreEqual(SlopeSlideEvent.Stopped, TickFor(SlopeSlideDomain.StopSeconds + _dt, Vector3.up)); + Assert.IsFalse(_state.IsSliding); + Assert.AreEqual(Vector3.zero, _state.Velocity); + } + + [Test] + public void NoGroundEndsTheSlideForAFall() + { + TickFor(1f, Slope(60f)); + Assert.AreEqual(SlopeSlideEvent.LostGround, Tick(Vector3.up, false)); + Assert.IsFalse(_state.IsSliding); + } + + [Test] + public void HeldBackSlideIsBlockedUntilMovedAway() + { + TickFor(SlopeSlideDomain.StartSeconds + _dt, Slope(60f)); + Assert.AreEqual(SlopeSlideEvent.Blocked, TickFor(1f, Slope(60f), moves: false)); + Assert.IsTrue(_state.IsBlocked); + + Assert.AreEqual(SlopeSlideEvent.None, TickFor(1f, Slope(60f), moves: false), "no new slide in place"); + + _feet += Vector3.right * (SlopeSlideDomain.BlockedReleaseDistance + 0.1f); + Assert.AreEqual(SlopeSlideEvent.Started, TickFor(SlopeSlideDomain.StartSeconds + 2f * _dt, Slope(60f))); + } + + [Test] + public void NoSlideWithoutGravity() + { + Assert.AreEqual(SlopeSlideEvent.None, TickWithGravity(1f, 0f)); + Assert.IsFalse(_state.IsSteepGround); + } + + private SlopeSlideEvent TickWithGravity(float seconds, float gravity) + { + var result = SlopeSlideEvent.None; + for (var time = 0f; time < seconds; time += _dt) + { + var tick = SlopeSlideDomain.Tick(_state, _feet, true, Slope(60f), _human, gravity, _dt); + if (tick != SlopeSlideEvent.None) + result = tick; + } + return result; + } + + [Test] + public void HoldEndsTheSlide() + { + TickFor(1f, Slope(60f)); + Assert.IsTrue(SlopeSlideDomain.Hold(_state, _feet)); + Assert.IsFalse(_state.IsSliding); + Assert.AreEqual(SlopeSlideEvent.None, TickFor(SlopeSlideDomain.StartSeconds * 0.5f, Slope(60f)), + "the steep time starts again"); + } + + [Test] + public void RestStartsTheSteepTimeAgain() + { + TickFor(SlopeSlideDomain.StartSeconds * 0.6f, Slope(60f)); + SlopeSlideDomain.Rest(_state, _feet); + Assert.AreEqual(SlopeSlideEvent.None, TickFor(SlopeSlideDomain.StartSeconds * 0.6f, Slope(60f)), + "two short bursts over steep ground don't add up"); + Assert.IsFalse(_state.IsSliding); + } + + [Test] + public void RestKeepsABlock() + { + TickFor(SlopeSlideDomain.StartSeconds + _dt, Slope(60f)); + Assert.AreEqual(SlopeSlideEvent.Blocked, TickFor(1f, Slope(60f), moves: false)); + SlopeSlideDomain.Rest(_state, _feet); + Assert.IsTrue(_state.IsBlocked, "standing still at the wall doesn't start the slide into it again"); + } + + [Test] + public void FacingDownhillSlidesForwardsElseBackwards() + { + var downhill = new Vector3(0f, -1f, 1f); + Assert.AreEqual(DaedalusConst.AniSlide, + SlopeSlideDomain.GetAnimation(downhill, Vector3.forward, true, true)); + Assert.AreEqual(DaedalusConst.AniSlideBack, + SlopeSlideDomain.GetAnimation(downhill, Vector3.back, true, true)); + } + + [Test] + public void ModelWithoutSlideBackwardsSlidesForwardsAlsoBackwards() + { + var downhill = new Vector3(0f, -1f, 1f); + Assert.AreEqual(DaedalusConst.AniSlide, + SlopeSlideDomain.GetAnimation(downhill, Vector3.back, false, true)); + } + + [Test] + public void ModelWithoutSlideAnimationsGetsNone() + { + var downhill = new Vector3(0f, -1f, 1f); + Assert.IsNull(SlopeSlideDomain.GetAnimation(downhill, Vector3.forward, true, false), + "S_SLIDEB alone isn't used facing downhill"); + Assert.IsNull(SlopeSlideDomain.GetAnimation(downhill, Vector3.back, false, false)); + } + + [Test] + public void StepsUpTheSlopeAreTakenBack() + { + var slide = new Vector3(0f, -2f, 2f); + var correction = SlopeSlideDomain.RemoveUphill(new Vector3(0.3f, 0.1f, -0.05f), slide); + Assert.AreEqual(0.05f, correction.z, 0.0001f, "the uphill part back downhill"); + Assert.AreEqual(0f, correction.x, 0.0001f, "the sideways step stays"); + Assert.AreEqual(0f, correction.y, 0.0001f, "no height"); + } + + [Test] + public void StepsSidewaysAndDownhillStayFree() + { + var slide = new Vector3(0f, -2f, 2f); + Assert.AreEqual(Vector3.zero, SlopeSlideDomain.RemoveUphill(Vector3.right * 0.1f, slide), "sideways"); + Assert.AreEqual(Vector3.zero, SlopeSlideDomain.RemoveUphill(Vector3.forward * 0.1f, slide), "downhill"); + Assert.AreEqual(Vector3.zero, SlopeSlideDomain.RemoveUphill(Vector3.back * 0.1f, Vector3.down), + "a slide straight down has no uphill"); + } + + [Test] + public void UphillIsAgainstTheDownhillDirection() + { + Assert.IsTrue(SlopeSlideDomain.IsMovingUphill(Vector3.back, Slope(60f))); + Assert.IsFalse(SlopeSlideDomain.IsMovingUphill(Vector3.forward, Slope(60f))); + Assert.IsFalse(SlopeSlideDomain.IsMovingUphill(Vector3.right, Slope(60f)), "sideways"); + } + } +} diff --git a/Assets/Gothic-Tests/EditMode/Movement/SlopeSlideDomainTest.cs.meta b/Assets/Gothic-Tests/EditMode/Movement/SlopeSlideDomainTest.cs.meta new file mode 100644 index 000000000..4674530f8 --- /dev/null +++ b/Assets/Gothic-Tests/EditMode/Movement/SlopeSlideDomainTest.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 6b6801f233aa21744a753fc45821ac0d \ No newline at end of file diff --git a/Assets/Gothic-VR/Scripts/Adapters/Player/VRHeroMovement.cs b/Assets/Gothic-VR/Scripts/Adapters/Player/VRHeroMovement.cs index a536a5d5f..cde365b98 100644 --- a/Assets/Gothic-VR/Scripts/Adapters/Player/VRHeroMovement.cs +++ b/Assets/Gothic-VR/Scripts/Adapters/Player/VRHeroMovement.cs @@ -5,6 +5,7 @@ using Gothic.Core.Models.Vm; using Gothic.Core.Services; using Gothic.Core.Services.Audio; +using Gothic.Core.Services.Movement; using Gothic.VR.Interaction.Ports; using Gothic.VR.Models; using Gothic.VR.Services; @@ -28,6 +29,7 @@ public class VRHeroMovement : MonoBehaviour [Inject] private readonly GroundSoundService _groundSoundService; [Inject] private readonly VRPlayerService _vrPlayerService; [Inject] private readonly VRHeroSpeedService _heroSpeedService; + [Inject] private readonly HeroSlideService _heroSlideService; // Gothic.ini footstepSounds: the hero's own steps - Gothic's RUN_ every stride of the way // walked (the VR body plays no step events; a timer stepped on while the run state lingered after a tap). @@ -200,6 +202,14 @@ private void UpdateHeroBodyState() if (props == null || !props.BodyState.IsLocomotion()) return; + // Core decides while it overrides the walking (BS_STAND while sliding down a slope) - no steps, no + // running for the scripts. + if (_heroSlideService.TryGetLocomotionBodyState(out var coreBodyState)) + { + props.BodyState = coreBodyState; + return; + } + // Crouched = sneaking. // Lying or standing up (the VR hero body's fall camera lowers the head) isn't sneaking - an NPC asked "why // are you sneaking around" while the hero got up. diff --git a/Assets/Gothic-VR/Scripts/Adapters/Player/VrHeroJumpFall.cs b/Assets/Gothic-VR/Scripts/Adapters/Player/VrHeroJumpFall.cs index fadc01e3b..10c11b3f8 100644 --- a/Assets/Gothic-VR/Scripts/Adapters/Player/VrHeroJumpFall.cs +++ b/Assets/Gothic-VR/Scripts/Adapters/Player/VrHeroJumpFall.cs @@ -11,18 +11,21 @@ namespace Gothic.VR.Adapters.Player { /// - /// Feeds the hero's jumps and falls (HeroFallService: body state, fall damage, lying landing) from the VR rig port: - /// feet height, grounded (with the rig's grace time), jumping, climbing, gravity, ground snap, the speed he runs - /// from (VrHeroSpeeds.RunThreshold), teleports. Measures only - the rules are in Core. - /// Sits next to VRPlayer (added by VRContextInteractionService). + /// Feeds the hero's body (HeroBodyService: his jumps and falls - body state, fall damage, lying landing - and his + /// slides down slopes) from the VR rig port: feet height, grounded (with the rig's grace time), the ground under + /// the feet, jumping, climbing, gravity, ground snap, the speed he runs from (VrHeroSpeeds.RunThreshold), + /// teleports - and hands the result back to the rig (the slide's velocity, no take-off from steep ground). + /// Measures only - the rules and their order are in Core. Sits next to VRPlayer (added by + /// VRContextInteractionService). /// A running jump (HeroFallService.IsRunningJump, the sprint) is a long leap at T_RUNL_2_JUMP's forward speed /// (VrHeroSpeeds.RunJump) in the direction of the run (HeroFallService.TakeOffVelocity - Core's measurement, the - /// same that decided the running jump), started on Tick's JumpStarted, until he lands, grabs or is teleported + /// same that decided the running jump), started on the result's JumpStarted, until he lands, grabs or is teleported /// (IVrRig.SetLeapVelocity). The standing and walking jump stays straight up. /// public class VrHeroJumpFall : MonoBehaviour { [Inject] private readonly HeroFallService _heroFallService; + [Inject] private readonly HeroBodyService _heroBodyService; [Inject] private readonly VRSpellTransformService _vrSpellTransformService; [Inject] private readonly VRHeroSpeedService _heroSpeedService; @@ -45,6 +48,14 @@ private void Awake() _rig.Teleported += OnTeleported; } + private void OnDisable() + { + if (_rig is not Object rigObject || rigObject == null) + return; + _rig.SlideVelocity = Vector3.zero; + _rig.IsTakeOffBlocked = false; + } + private void OnDestroy() { if (_rig is Object rigObject && rigObject != null) @@ -53,11 +64,15 @@ private void OnDestroy() private void Update() { - var sample = new HeroFallSample(_rig.Root.position, GetFacing(), _rig.IsGrounded, _rig.IsJumping, + var hasGround = _rig.TryGetGround(out _, out var groundNormal); + var sample = new HeroBodySample(_rig.Root.position, GetFacing(), _rig.IsGrounded, _rig.IsJumping, _rig.IsClimbing, _vrSpellTransformService != null && _vrSpellTransformService.IsTransformed, _rig.Gravity, _rig.MaxFallSpeed, _rig.GroundSnapHeight, _heroSpeedService.HeroSpeeds.RunThreshold, - Time.deltaTime); - UpdateLeap(_heroFallService.Tick(sample)); + Time.deltaTime, hasGround, groundNormal); + var result = _heroBodyService.Tick(sample); + _rig.SlideVelocity = result.SlideVelocity; + _rig.IsTakeOffBlocked = result.IsTakeOffBlocked; + UpdateLeap(result.AirEvent); } /// @@ -119,7 +134,8 @@ private Vector3 GetFacing() private void OnTeleported(Vector3 feetPosition) { EndLeap("teleported"); - _heroFallService.OnTeleported(feetPosition); + _heroBodyService.OnTeleported(feetPosition); + _rig.SlideVelocity = Vector3.zero; } } } diff --git a/Assets/Gothic-VR/Scripts/Adapters/Player/VrHeroLocomotion.cs b/Assets/Gothic-VR/Scripts/Adapters/Player/VrHeroLocomotion.cs index 98555eca3..ecb0c8bac 100644 --- a/Assets/Gothic-VR/Scripts/Adapters/Player/VrHeroLocomotion.cs +++ b/Assets/Gothic-VR/Scripts/Adapters/Player/VrHeroLocomotion.cs @@ -1,5 +1,6 @@ using System.Collections.Generic; using Gothic.Core; +using Gothic.Core.Const; using Gothic.Core.Logging; using Gothic.Core.Models.Container; using Gothic.Core.Models.Movement; @@ -18,7 +19,8 @@ namespace Gothic.VR.Adapters.Player /// Legs and torso of the VR hero body like the hero in Gothic: picks the animation and its playback speed from the /// player's velocity, the body state, the body's turn speed, crouching and swimming (VrHeroSwimPose) - idle, /// walk/run (played at the real speed - no sliding feet), walking backwards, strafing, turning on the spot, - /// jumping and falling (HeroFallService's phase), sneaking, swimming and diving. Worker of VRHeroBody + /// jumping and falling (HeroFallService's phase), sliding down slopes (HeroSlideService: S_SLIDE facing downhill, + /// S_SLIDEB backwards), sneaking, swimming and diving. Worker of VRHeroBody /// (new().Inject(), Bind per built body). A deep landing (lying, getting up) is VrHeroDownPose's. /// Publishes the body's walk/run/sneak speeds (its animations at its scale, VRHeroSpeedService.HeroBodySpeeds) - /// the rig moves at them (VRHeroMovement), so the feet match the ground. @@ -27,6 +29,7 @@ public class VrHeroLocomotion { [Inject] private readonly AnimationService _animationService; [Inject] private readonly HeroFallService _heroFallService; + [Inject] private readonly HeroSlideService _heroSlideService; [Inject] private readonly VRHeroSpeedService _heroSpeedService; private const float _idleSpeed = 0.15f; @@ -145,7 +148,7 @@ public void Update(NpcContainer hero, Transform body, IVrRig rig, float scale, b var isBackwards = local.z < -_backwardsShare * speed; var isTurning = Mathf.Abs(_bodyYawSpeed) >= _turnAnimationSpeed; - if (TryPlayAirAnimation(speed, isMoving)) + if (TryPlayAirAnimation(speed, isMoving) || TryPlaySlideAnimation(body.forward)) { _animator.Update(Time.deltaTime); return; @@ -293,6 +296,24 @@ private void StartTakeOff() _jumpLoop = isJumpUp && _animator.HasAnimation(_jumpUpAnimation) ? _jumpUpAnimation : _jumpAnimation; } + /// + /// S_SLIDE facing where he slides, S_SLIDEB backwards (S_SLIDE without it) - false: not sliding or the model + /// has no slide animation, the normal animations play. A landing's one-shot ends. + /// + private bool TryPlaySlideAnimation(Vector3 facing) + { + if (!_heroSlideService.IsSliding) + return false; + + var animation = _heroSlideService.GetAnimation(facing, _animator.HasAnimation(DaedalusConst.AniSlideBack), + _animator.HasAnimation(DaedalusConst.AniSlide)); + if (animation == null) + return false; + + _airOneShot = null; + return _animator.Play(animation); + } + /// /// S_FALLDN, deeper than NpcFallDomain.LyingFallHeight flat: HeroFallService's pose, S_FALL on his face or /// S_FALLB on his back. diff --git a/Assets/Gothic-VR/Scripts/Interaction/Backends/Xri/GothicJumpProvider.cs b/Assets/Gothic-VR/Scripts/Interaction/Backends/Xri/GothicJumpProvider.cs index cf9feac94..6d7e34ff0 100644 --- a/Assets/Gothic-VR/Scripts/Interaction/Backends/Xri/GothicJumpProvider.cs +++ b/Assets/Gothic-VR/Scripts/Interaction/Backends/Xri/GothicJumpProvider.cs @@ -1,6 +1,8 @@ +using Gothic.Core.Logging; using Gothic.VR.Interaction.Ports; using UnityEngine; using UnityEngine.XR.Interaction.Toolkit.Locomotion.Jump; +using Logger = Gothic.Core.Logging.Logger; namespace Gothic.VR.Interaction.Backends.Xri { @@ -13,6 +15,8 @@ namespace Gothic.VR.Interaction.Backends.Xri /// curve for a wanted rise. /// - CancelJump(): a hand grabbing a ledge or ladder mid-air ends the jump. Disabled by XriRig while climbing, /// XRI would otherwise keep the jump running and replay its rest after climbing. + /// - IsTakeOffBlocked: no take-off from ground too steep for Gothic (SLIDE_ANGLE) - the press is used up until + /// released. Jumping again and again climbed any slope. /// public class GothicJumpProvider : JumpProvider { @@ -43,6 +47,11 @@ public float Gravity set => _gravity = value; } + /// + /// The ground under the feet is too steep to jump from. Set by XriRig every frame. + /// + public bool IsTakeOffBlocked { get; set; } + protected override void Awake() { base.Awake(); @@ -57,6 +66,12 @@ protected override void Update() _isPressHandled = false; _isPressConsumed = false; } + else if (!_isPressHandled && !isJumping && IsTakeOffBlocked) + { + _isPressHandled = true; + _isPressConsumed = true; + Logger.Log("[XRI] No jump - the ground is too steep (SLIDE_ANGLE).", LogCat.VR); + } else if (!_isPressHandled && !isJumping && CanJump()) { _isPressHandled = true; diff --git a/Assets/Gothic-VR/Scripts/Interaction/Backends/Xri/XriRig.cs b/Assets/Gothic-VR/Scripts/Interaction/Backends/Xri/XriRig.cs index 0f9cec68f..fb4945421 100644 --- a/Assets/Gothic-VR/Scripts/Interaction/Backends/Xri/XriRig.cs +++ b/Assets/Gothic-VR/Scripts/Interaction/Backends/Xri/XriRig.cs @@ -25,7 +25,7 @@ namespace Gothic.VR.Interaction.Backends.Xri { /// /// IVrRig on top of XRI's XR Origin and locomotion providers. Sits on the XR Origin GameObject next to VRPlayer. - /// Sprinting and crouching are ours, as XRI has no providers for them. + /// Sprinting and crouching are ours, as XRI has no providers for them; sliding down slopes too (XriSlopeSlide). /// Gothic logic (menu, control modes, ini settings) lives in VRPlayer and VRContextInteractionService, not here. /// public class XriRig : MonoBehaviour, IVrRig @@ -165,6 +165,7 @@ public class XriRig : MonoBehaviour, IVrRig private IVrLedgeHandler _ledgeHandler; // SetLeapVelocity: a running jump's horizontal velocity, zero = none. private Vector3 _leapVelocity; + private XriSlopeSlide _slopeSlide; public event Action Teleported; @@ -182,7 +183,8 @@ public bool IsGrounded { get { - if (_gravityProvider.isGrounded || _characterController.isGrounded) + // A slide keeps the feet on the slope, also where XRI's head-down cast misses it (steep and thin). + if (_gravityProvider.isGrounded || _characterController.isGrounded || SlopeSlide.IsSliding) _lastGroundedTime = Time.time; return Time.time - _lastGroundedTime <= _groundedGraceTime; @@ -333,6 +335,26 @@ public float StepOffset public float FadeAlpha => _screenFade != null ? _screenFade.FadeAlpha : 0f; + /// + /// HeroSlideService's slide, set every frame. Ignored while a teleport is on its way. + /// + public Vector3 SlideVelocity + { + get => SlopeSlide.Velocity; + set => SlopeSlide.Velocity = _isTeleportQueued ? Vector3.zero : value; + } + + public bool IsTakeOffBlocked + { + get => _jumpProvider.IsTakeOffBlocked; + set => _jumpProvider.IsTakeOffBlocked = value; + } + + /// + /// Created on first use: adapters on this GameObject may ask before Start. + /// + private XriSlopeSlide SlopeSlide => _slopeSlide ??= new XriSlopeSlide(_characterController); + /// /// One Near-Far interactor per hand. Resolved lazily, as adapters on this GameObject ask in their Awake. /// @@ -388,6 +410,7 @@ private void Start() _bodyManipulator = ScriptableObject.CreateInstance(); _bodyTransformer.beforeApplyTransformations += OnBeforeApplyTransformations; _bodyTransformer.afterApplyTransformations += OnAfterApplyTransformations; + SlopeSlide.SetBodyTransformer(_bodyTransformer); } else { @@ -470,6 +493,10 @@ private void Update() UpdateClimbLock(); UpdateSprint(); UpdateCrouch(); + + // The slide moves the body down the slope: gravity's own fall speed would pile up on top of it. + if (SlopeSlide.IsSliding) + _gravityProvider.ResetFallForce(); } public void SetLeapVelocity(Vector3 velocity) @@ -533,6 +560,7 @@ private void OnBeforeApplyTransformations(XRBodyTransformer bodyTransformer) { if (!ReferenceEquals(bodyTransformer.constrainedBodyManipulator, _bodyManipulator)) bodyTransformer.constrainedBodyManipulator = _bodyManipulator; + SlopeSlide.OnBeforeMoves(Root.position); } private void OnAfterApplyTransformations(ApplyBodyTransformationsEventArgs args) @@ -686,6 +714,11 @@ private void UpdateCrouch() CameraOffset.localPosition = position; } + public bool TryGetGround(out Vector3 point, out Vector3 normal) + { + return SlopeSlide.TryGetGround(out point, out normal); + } + public void SetEyeHeightOverride(float? meters) { _eyeHeightOverride = meters; diff --git a/Assets/Gothic-VR/Scripts/Interaction/Backends/Xri/XriSlopeSlide.cs b/Assets/Gothic-VR/Scripts/Interaction/Backends/Xri/XriSlopeSlide.cs new file mode 100644 index 000000000..c0b2c5553 --- /dev/null +++ b/Assets/Gothic-VR/Scripts/Interaction/Backends/Xri/XriSlopeSlide.cs @@ -0,0 +1,137 @@ +using Gothic.Core.Const; +using Gothic.Core.Domain.Movement; +using UnityEngine; +using UnityEngine.XR.Interaction.Toolkit.Locomotion; + +namespace Gothic.VR.Interaction.Backends.Xri +{ + /// + /// The XRI side of sliding down a slope (IVrRig.TryGetGround, IVrRig.SlideVelocity) - HeroSlideService decides, + /// this only executes. Worker of XriRig. + /// - The ground probe: one ray straight down from the CharacterController's bottom center, once per frame. A sphere + /// cast would also touch stair edges and walls beside the feet and report their steep normals. It sees only the + /// Default layer (the world mesh and solid VOBs, like the NPCs' ground ray): an NPC, an item or a movable under + /// the feet is no slope - no slide and no blocked jump from a monster's back. + /// - The slide is a body transformation queued after XRI's own moves (the stick, gravity): it moves the + /// CharacterController along the slope (CharacterController.Move, so walls still stop it) and takes back what the + /// stick moved up the slope in the same frame (SlopeSlideDomain.RemoveUphill decides how much). + /// The CharacterController's slopeLimit (prefab) doesn't decide anything here: Gothic's SLIDE_ANGLE does. + /// + public class XriSlopeSlide + { + // The ray starts this far above the feet (a foot sunk into the slope) and reaches this far below them: on a + // 70 deg slope the thin capsule's center hangs ~0.2 m above the ground. + private const float _probeRise = 0.3f; + private const float _probeDepth = 0.5f; + // After XRI's moves (the move provider and gravity queue at priority 0). + private const int _priority = 10; + // A larger move in one frame is a teleport, not the stick: nothing is taken back. + private const float _maxStickMove = 1f; + + private readonly CharacterController _characterController; + private readonly DelegateXRBodyTransformation _transformation; + private readonly int _groundMask = 1 << Constants.DefaultLayer; + private XRBodyTransformer _bodyTransformer; + private Vector3 _velocity; + private int _queuedFrame = -1; + private Vector3 _originBeforeMoves; + + private int _probeFrame = -1; + private bool _hasGround; + private Vector3 _groundPoint; + private Vector3 _groundNormal = Vector3.up; + + public XriSlopeSlide(CharacterController characterController) + { + _characterController = characterController; + _transformation = new DelegateXRBodyTransformation(Apply); + } + + /// + /// A slide is queued for the body - never without a body transformer (nothing would move it, but the rig would + /// count the hero as grounded and hold his gravity). + /// + public bool IsSliding => _velocity != Vector3.zero && _bodyTransformer != null; + + /// + /// Set every frame while sliding: queues the slide for the body transformer's next update. + /// + public Vector3 Velocity + { + get => _velocity; + set + { + _velocity = value; + if (value != Vector3.zero && _bodyTransformer != null && _queuedFrame != Time.frameCount) + { + _queuedFrame = Time.frameCount; + _bodyTransformer.QueueTransformation(_transformation, _priority); + } + } + } + + public void SetBodyTransformer(XRBodyTransformer bodyTransformer) + { + _bodyTransformer = bodyTransformer; + } + + /// + /// The origin before this update's transformations (XRBodyTransformer.beforeApplyTransformations) - what the + /// stick moved is measured from it. + /// + public void OnBeforeMoves(Vector3 origin) + { + _originBeforeMoves = origin; + } + + public bool TryGetGround(out Vector3 point, out Vector3 normal) + { + if (_probeFrame != Time.frameCount) + { + _probeFrame = Time.frameCount; + Probe(); + } + + point = _groundPoint; + normal = _groundNormal; + return _hasGround; + } + + private void Probe() + { + _hasGround = false; + _groundNormal = Vector3.up; + if (_characterController == null || !_characterController.enabled) + return; + + var controllerTransform = _characterController.transform; + var feet = controllerTransform.TransformPoint(_characterController.center) + - Vector3.up * (_characterController.height * 0.5f * controllerTransform.lossyScale.y); + if (!Physics.Raycast(feet + Vector3.up * _probeRise, Vector3.down, out var hit, _probeRise + _probeDepth, + _groundMask, QueryTriggerInteraction.Ignore)) + return; + + _hasGround = true; + _groundPoint = hit.point; + _groundNormal = hit.normal; + } + + private void Apply(XRMovableBody body) + { + var velocity = _velocity; + if (velocity == Vector3.zero) + return; + + var motion = velocity * Time.deltaTime; + var moved = body.originTransform.position - _originBeforeMoves; + moved.y = 0f; + if (moved.sqrMagnitude < _maxStickMove * _maxStickMove) + motion += SlopeSlideDomain.RemoveUphill(moved, velocity); + + if (body.constrainedManipulator != null) + body.constrainedManipulator.MoveBody(motion); + else + body.originTransform.position += motion; + } + } +} diff --git a/Assets/Gothic-VR/Scripts/Interaction/Backends/Xri/XriSlopeSlide.cs.meta b/Assets/Gothic-VR/Scripts/Interaction/Backends/Xri/XriSlopeSlide.cs.meta new file mode 100644 index 000000000..85e2c3ff9 --- /dev/null +++ b/Assets/Gothic-VR/Scripts/Interaction/Backends/Xri/XriSlopeSlide.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 0495b2ba36390594595b200ff71e33fe \ No newline at end of file diff --git a/Assets/Gothic-VR/Scripts/Interaction/Ports/IVrRig.cs b/Assets/Gothic-VR/Scripts/Interaction/Ports/IVrRig.cs index b8423ddb2..80b55570b 100644 --- a/Assets/Gothic-VR/Scripts/Interaction/Ports/IVrRig.cs +++ b/Assets/Gothic-VR/Scripts/Interaction/Ports/IVrRig.cs @@ -48,7 +48,7 @@ public interface IVrRig /// /// How far in m the backend pulls the player down to the ground per frame (slopes, stairs) - a smaller drop is - /// no fall for the hero (HeroFallSample). Default: 0, for backends without snapping. + /// no fall for the hero (HeroBodySample). Default: 0, for backends without snapping. /// float GroundSnapHeight => 0f; @@ -221,5 +221,40 @@ void SetLedgeHandler(IVrLedgeHandler handler) void SetEyeHeightOverride(float? meters) { } + + /// + /// The ground straight under the feet (a ray down from the body's center, so stair risers and walls beside it + /// don't count), within a step below the feet - the world mesh only (Default layer: world and solid VOBs), not + /// NPCs, items or movables. Asked per frame: backends probe once per frame. + /// Default: no ground known (no slides). + /// + bool TryGetGround(out Vector3 point, out Vector3 normal) + { + point = default; + normal = Vector3.up; + return false; + } + + /// + /// The hero slides down a slope with this world velocity (m/s), zero = no slide (HeroSlideService decides). Set + /// every frame. Meanwhile the backend moves the body with it, removes the player's own movement up the slope, + /// holds gravity's fall speed and counts the body as grounded (a slide is no fall). + /// Default: not supported, the body stands on any slope. + /// + Vector3 SlideVelocity + { + get => Vector3.zero; + set { } + } + + /// + /// The ground is too steep to jump from (SLIDE_ANGLE): a press of the jump button does nothing until released. + /// Set every frame. Default: not supported. + /// + bool IsTakeOffBlocked + { + get => false; + set { } + } } } diff --git a/CLAUDE.md b/CLAUDE.md index e4f3c782d..81119a20e 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -52,7 +52,7 @@ Gothic.Core with engine, services, domain logic Within Core, responsibility is further split into layers: **Model** (data) ← **Domain** (business logic) ⇄ **Service** (orchestration) ← **Adapter** (Unity integration). Arrows point to what a layer may use: - Models only use Models. -- Domain and Services are one rank and may use each other. Domain classes are workers owned by a Service, created via `new XDomain().Inject()` (not registered in Reflex), and may `[Inject]` Services. +- Domain and Services are one rank and may use each other. Domain classes are workers owned by a Service, created via `new XDomain().Inject()` (not registered in Reflex), and may `[Inject]` Services - or, for a stateless rule set, a static class with its state passed in (see `Docs/architecture.md`). - Nothing below Adapters uses Adapters. Principles, dependency rules and "where does my code go": `Docs/architecture.md`. diff --git a/Docs/adr/2026-11-29-slope-slide.md b/Docs/adr/2026-11-29-slope-slide.md new file mode 100644 index 000000000..a95a00933 --- /dev/null +++ b/Docs/adr/2026-11-29-slope-slide.md @@ -0,0 +1,31 @@ +# ADR: Sliding down steep slopes + +- Date: 2026-11-29 +- Technical details: the class docs of SlopeSlideDomain, HeroSlideService and HeroBodyService (Core), NpcJumpFall and NpcSlopeSlide (Core), XriSlopeSlide and VrHeroJumpFall (VR); the map of the movement code: Docs/hero-movement.md + +## Context + +In Gothic nobody stands on ground that is too steep: the hero and NPCs slide down it, playing the slide animation (facing downhill, or backwards), until the ground is walkable again or they slide off an edge and fall. Each guild has its own limit: humans and most monsters 45 degrees, bloodflies and demons 75, minecrawlers and swampsharks 60. A second value marks ground so close to vertical that it counts as a wall; Gothic leaves it at zero. While sliding the hero can't jump. + +In the VR game the hero stood on any slope. Worse, jumping again and again carried him up any slope, even a cliff (play test in Mroczne Tajemnice, a Gothic 1 mod). NPCs never slid either. + +## Decisions + +1. **The hero and NPCs slide on ground steeper than their guild's slide angle, with Gothic's two values.** One rule for both, the angles come from the scripts, so mods and monsters bring their own. Flying monsters never slide, like they never fall. +2. **The slide is gravity along the slope, like OpenGothic, but never faster than 6 m/s.** Gothic has no limit; in VR a long slide would get uncomfortably fast. Not chosen: a fixed slide speed (the slide would feel the same on 46 and 80 degrees). +3. **No jump from ground steeper than the slide angle, at once, also before a slide has begun.** This is the fix for climbing a slope by jumping. Only the world and solid objects count as ground here: standing on an NPC, a monster or an item never blocks the jump. Not chosen: blocking the jump only while sliding (a quick jump right after landing would still work). +4. **The slope must be steep for a fifth of a second before the slide begins, and walkable for a tenth before it ends.** A single steep triangle of a rock or a mesh seam doesn't make anybody slide. Stairs don't either: only the ground straight under the feet counts, not the step edges beside them. For NPCs the time counts only while they walk over the steep ground: when they stop, it starts again. +5. **While the hero slides, the stick can't walk him up the slope; sideways and downhill stay free.** In Gothic the player has no control at all while sliding. In VR steering sideways helps to stay on the slope and keeps the player in charge of his view. Not chosen: no stick at all (a sudden loss of control in VR), or the stick fighting the slide (he could walk up again). +6. **A slide is no fall.** Sliding down a 50 m hillside costs no hit points; only when he slides off an edge does a normal fall begin there, with its damage counted from the edge. The scripts see a standing hero while he slides (like OpenGothic), so no footsteps and no "running" for the NPCs. +7. **A slide that gets nowhere (a wall, a crevice, a rock) ends, and he stands there.** No new slide until he moved half a meter away or stood on walkable ground. Otherwise he would be stuck in the slide pose. +8. **NPCs slide when they go down or across steep ground; walking up it stays walking.** In Gothic a slope too steep to walk up stops an NPC like a wall. Our NPCs move by their animations and their routes were never built around this; a slide back down would loop with the walk up again. Not chosen: Gothic's wall for NPCs (left for later, needs the route walking to know about it). +9. **NPCs slide only near the hero (40 m), like they fall only there.** Far away the world isn't loaded under them. + +## Consequences + +- Nothing new is saved: a loaded game starts standing. +- An NPC that dies, is knocked out or starts swimming mid-slide stops sliding at once. A dead or unconscious body stays as its death or knockout left it; any other gets its physics back. A fall or a climb still ends on the ground first, without the landing or idle animations. +- Not checked while climbing, swimming or wading, lying after a fall, after a teleport, while sitting or using something, or while transformed into a monster: the transformed hero still stands on any slope (his monster's own angle isn't applied yet). +- The hero with no slide animation in his model (a mod) still slides, with his normal animations. +- The fall is checked before the slide each frame, in Core (HeroBodyService): a landing on a steep slope is a landing, the slide begins after it, and no slide begins while he is in the air. A platform only measures the body and applies the result; the standing body state while sliding is Core's too, the platform asks for it before it sets walking or running. +- Flat mode can feed the same rules from its own controller once it runs again, through the same entry point. diff --git a/Docs/architecture.md b/Docs/architecture.md index a2e44992d..73a0ff2aa 100644 --- a/Docs/architecture.md +++ b/Docs/architecture.md @@ -140,7 +140,8 @@ working. | Adapters | `Adapters/` | MonoBehaviours bridging Unity and services | no rules, the only layer with Unity lifecycle | Dependency rules. Domain and Services share a rank and may use each other: a Domain class is a worker owned by a -Service (`new XDomain().Inject()`). +Service (`new XDomain().Inject()`). A stateless rule set in Domain may be a static class instead, its state passed in +(`SlopeSlideDomain`: shared by a service and an adapter, nothing to inject, tested directly). 1. Nothing outside `Adapters/` uses the `Adapters` namespace. Plain data classes there (`NpcProperties`, `InteractiveProperties`) belong in `Models/`. When a service must create an adapter, it injects a factory @@ -164,6 +165,7 @@ removed from the baseline. Rule 5 is enforced by the asmdef references. | change NPC AI or fights | see the map in `Docs/npc-ai.md` | | 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 how the hero or NPCs jump, fall, slide, climb or how fast the hero moves | see the map in `Docs/hero-movement.md` | | change world lights, lightmaps, fires, indoor sky | see the map in `Docs/world-lighting.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` | diff --git a/Docs/hero-movement.md b/Docs/hero-movement.md new file mode 100644 index 000000000..be25fc45d --- /dev/null +++ b/Docs/hero-movement.md @@ -0,0 +1,88 @@ +# Hero and NPC movement + +A map of the code that moves the hero's and the NPCs' bodies beyond walking: speeds, jumps and falls, fall damage, the +lying landing, slides down steep slopes, ledges and ladders. Gothic's values come from the scripts (`GIL_VALUES` of +the guild: `STEP_HEIGHT`, `SLIDE_ANGLE`, `FALLDOWN_HEIGHT`, ...), so mods and monsters bring their own. Core paths are +under `Assets/Gothic-Core/Scripts/`, VR paths under `Assets/Gothic-VR/Scripts/`. + +Decisions: `Docs/adr/2026-11-29-hero-speed-from-animations.md`, `Docs/adr/2026-11-29-hero-jump-fall.md`, +`Docs/adr/2026-11-29-slope-slide.md`, for ledges `Docs/adr/2026-10-28-vr-ledge-climbing.md`. + +## The hero, each frame + +1. `VrHeroJumpFall` (VR adapter, next to VRPlayer) measures the body from the rig port `IVrRig`: feet, grounded, + jumping, climbing, gravity, ground snap, the ground straight under the feet (`IVrRig.TryGetGround`), the run speed + (`VrHeroSpeeds.RunThreshold`). That is one `HeroBodySample` (`Models/Movement/`). +2. It calls `Services/Movement/HeroBodyService.Tick` - the only entry point. It decides the order: + - `HeroFallService` first: the phases from `Domain/Movement/HeroAirborneDomain` (jump, fall, fall flat, + landing, running jump and its `TakeOffVelocity`), BS_JUMP / BS_FALL, fall damage at the landing + (`NpcFallDomain.GetFallDamage`, raised as `GlobalEventDispatcher.FallDamage`, applied by `FightService`), the + lying landing's timeline (`HeroLanding.StandUpStart / StandUpEnd`), `GlobalEventDispatcher.HeroLanded`. + - `HeroSlideService` second: `Domain/Movement/SlopeSlideDomain` on a `SlopeSlideState` - slide or not, its speed, + no take-off from steep ground. +3. It applies the returned `HeroBodyResult` to the rig: `IVrRig.SlideVelocity`, `IVrRig.IsTakeOffBlocked`. Its + `AirEvent` is what the fall handled this frame: on `JumpStarted` a running jump (`HeroFallService.IsRunningJump`) + becomes `IVrRig.SetLeapVelocity` in the direction of `HeroFallService.TakeOffVelocity` - Core's one measurement. + +Teleports go to `HeroBodyService.OnTeleported`. The services' own `Tick` and `OnTeleported` are internal: a platform +never ticks them itself (Flat would feed the same `HeroBodySample`). + +## The hero's VR body and rig + +| Class | Owns | +|---|---| +| `Adapters/Player/VRHeroMovement` | the only writer of the rig's speeds (land speeds, water's and a transformation's wishes via `VRHeroSpeedService.SetHeroSpeedOverride`), BS_STAND / BS_WALK / BS_RUN / BS_SNEAK - while sliding the one Core decides (`HeroSlideService.TryGetLocomotionBodyState`: BS_STAND) | +| `Services/VRHeroSpeedService` (PlayerScope) | the land speeds (`HeroSpeeds`): the body's animation speeds (`HeroBodySpeeds`), else the rig's own (`IVrRig.DefaultMoveSpeed` / `DefaultRunSpeed`), the speed potion (`IsHeroSpeedBoosted`); the overrides (`HeroSpeedOverride`, water first, `GetOverrideSpeeds`) | +| `Adapters/Player/VrHeroLocomotion` (worker of VRHeroBody) | the body's walk/run/sneak, jump and fall animations, S_SLIDE / S_SLIDEB; measures the loops' speeds | +| `Adapters/Player/VrHeroDownPose` (worker of VRHeroBody) | lying and getting up, following HeroFallService's times (`DownReason`, `VrHeroDownAnimations`); a teleport (`IVrRig.Teleported`) ends the lying | +| `Adapters/Player/VRSwimDive` | BS_SWIM / BS_DIVE, the water's speed wish (half the land walk without the potion, cleared on WorldSceneLoaded) | +| `Interaction/Backends/Xri/XriRig` | `IVrRig` on XRI: grounded grace, ground snap, gravity, leap | +| `Interaction/Backends/Xri/XriSlopeSlide` (worker of XriRig) | the ground ray (Default layer only), the slide as a body transformation, `SlopeSlideDomain.RemoveUphill` on the stick | +| `Interaction/Backends/Xri/GothicJumpProvider` | the jump's rise, refuses the take-off when blocked, ledge jumps | + +## NPCs + +`Adapters/Npc/NpcJumpFall` (added to the NPC on demand, asleep while nothing happens, only within 40 m of the hero) +keeps the state switch, the fall and the landing. AI code reaches it through `Domain/Npc/INpcJumpFallFactory`: +`NpcChaseMovement` (climb, ladder, safe drop ahead), `AbstractWalkAnimationAction2` (ladders on a route), +`SpellHitDomain` (Windfist's throw). Its plain workers in `Adapters/Npc/`, internal to Core - nothing else uses them: + +| Class | Owns | +|---|---| +| `NpcMoveBody` | what all of them ask of the body: rest height, guild rules, can it move, ground below, the wall ahead of a fall or slide (near-vertical hits only), physics on/off, tracks | +| `NpcSlopeSlide` | the slide: start (not uphill), wall look-ahead, held on the ground, off an edge into NpcJumpFall's fall; logs `[NpcSlide]` | +| `NpcLedgeClimb` | ledge climbs (`LedgeService.ProbeNpcClimb`) and ladders (NavMesh links, root lift per animation) | +| `NpcAnimationSequence` | animations one after another for a landing or a climb | + +The rules: `Domain/Npc/NpcFallDomain` (can it move, fall damage, safe height, lying depth), `SlopeSlideDomain` +(shared with the hero), `LedgeService` / `LedgeProbeDomain`, `FallPose` (HUMANS.MDS fall sets). + +## Ledges and ladders (the hero) + +The hero's ledge climbing in VR has its own map: `Docs/ledge-climbing.md`. Its Gothic values (`LedgeRules`, also +`SLIDE_ANGLE` / `SLIDE_ANGLE2` for slides) come from `LedgeService.HeroRules` / `GetRules(guild)`. + +## Where does my change go? + +| You want to change ... | Put it into | +|---|---| +| when a jump or fall starts, falls flat, lands | `HeroAirborneDomain` (with `HeroAirborneDomainTest`) | +| fall damage | `NpcFallDomain.GetFallDamage` (hero and NPCs) | +| when the hero isn't tracked / doesn't slide | `HeroFallService.GetHold` / `HeroSlideService.GetHold` (`HeroSlideHold`) | +| the body state the scripts see while he slides | `HeroSlideService.TryGetLocomotionBodyState` | +| which ground slides, how fast, debounce, blocks | `SlopeSlideDomain` (with `SlopeSlideDomainTest`) | +| the order of the hero's rules per frame | `HeroBodyService` | +| what the VR rig does with a slide or jump | `XriSlopeSlide`, `GothicJumpProvider`, `XriRig` - executing only | +| the hero's speeds | `VRHeroMovement` / `VRHeroSpeedService` (`VrHeroSpeeds`, `VRConstants.Movement`) | +| an NPC's fall, landing, climb or slide | `NpcJumpFall` and its worker for that move | + +## Pitfalls + +- Nothing here is saved: a loaded game starts standing on the ground. +- Ground for slides and the jump block is the Default layer only (world and solid VOBs) - an NPC or item under the + feet is no slope. NPCs' ground rays use the same layer. +- A slide off an edge falls from the edge: the platform counts the sliding hero as grounded, so the fall starts at + the last grounded frame - a few cm lower by the rig's grounded grace + (`HeroAirborneDomainTest.SlideOffAnEdgeFallsFromTheEdge`). No slide starts while the fall's phase isn't Grounded + (`HeroSlideHold.Airborne`). +- `SlopeSlideDomain` is a static class: a stateless rule set shared by a service and an adapter, its state passed in. diff --git a/Docs/ledge-climbing.md b/Docs/ledge-climbing.md index 3cd8fe987..43765028a 100644 --- a/Docs/ledge-climbing.md +++ b/Docs/ledge-climbing.md @@ -3,6 +3,7 @@ The VR player climbs exactly the ledges Gothic's hero can climb: by gripping the lip and pulling up, by a comfort fade, or by teleporting onto the top. XRI backend only. Why it's built this way: Docs/adr/2026-10-28-vr-ledge-climbing.md. +Jumps, falls, slides down slopes, NPC climbs and the hero's speeds around it: Docs/hero-movement.md. ## Gothic's rules (Core)