From 913b875c9fd08f1a2b29f2e025fccb15c3357187 Mon Sep 17 00:00:00 2001 From: BoroBongo Date: Wed, 25 Nov 2026 21:54:41 +0000 Subject: [PATCH 1/7] fix: NPCs move on with their daily routine - a routine change ends the routine's state (Harad leaves the anvil, sleepers get up) - NpcRoutineService: when a visible NPC's routine entry changes (time or Npc_ExchangeRoutine) and its state is a routine state, it ends like the engine: _End once the current actions are done, then the new entry's state; perception/AI_StartState states, the dialog partner, dead/knocked out NPCs and same state+waypoint entries are left alone; culled NPCs keep the culling behaviour; removes the FIXME and the double NotifyNpcRoutineChanged - AiHandler/NpcAiService/StartState: AI_StartState from a routine state's start/loop function stays a routine state (engine keeps the end time) - G2 TA_Sleep is ZS_GotoBed -> ZS_Sleep - UseMob: AI_UseMob(x, -1) without a mob in use does nothing (engine) instead of walking to the nearest mob - NpcMeshCullingService.IsAwake; ADR 2026-11-25-routine-change-ends-state, npc-ai.md Co-Authored-By: Claude Opus 5.5 --- .../Scripts/Adapters/Npc/AiHandler.cs | 21 ++++- .../Adapters/Properties/NpcProperties.cs | 4 + .../Domain/Culling/NpcMeshCullingDomain.cs | 9 ++ .../Domain/Npc/Actions/AnimationAction.cs | 4 +- .../Actions/AnimationActions/StartState.cs | 7 +- .../Npc/Actions/AnimationActions/UseMob.cs | 8 ++ .../Services/Culling/NpcMeshCullingService.cs | 8 ++ .../Scripts/Services/Npc/NpcAiService.cs | 6 +- .../Scripts/Services/Npc/NpcRoutineService.cs | 86 +++++++++++++++++-- .../2026-11-25-routine-change-ends-state.md | 25 ++++++ Docs/npc-ai.md | 5 ++ 11 files changed, 170 insertions(+), 13 deletions(-) create mode 100644 Docs/adr/2026-11-25-routine-change-ends-state.md diff --git a/Assets/Gothic-Core/Scripts/Adapters/Npc/AiHandler.cs b/Assets/Gothic-Core/Scripts/Adapters/Npc/AiHandler.cs index 3290640ef..699622249 100644 --- a/Assets/Gothic-Core/Scripts/Adapters/Npc/AiHandler.cs +++ b/Assets/Gothic-Core/Scripts/Adapters/Npc/AiHandler.cs @@ -222,7 +222,7 @@ private void Update() if (Vob.CurrentStateIndex == 0) return; - CallAiFunction(Vob.CurrentStateIndex); + CallStateFunction(Vob.CurrentStateIndex); Properties.CurrentLoopState = LoopState.Loop; _nextLoopTime = 0f; break; @@ -250,7 +250,7 @@ private void Update() break; _nextLoopTime = Time.time + Properties.PerceptionTime; - var loopResponse = CallAiFunction(Properties.StateLoop); + var loopResponse = CallStateFunction(Properties.StateLoop); // Some ZS_*_Loop return !=0 when they want to quit. if (loopResponse != _daedalusLoopContinue) @@ -336,6 +336,23 @@ public void CallStateEnd(int endFunction, NpcInstance other, NpcInstance victim) } } + /// + /// The current state's start or loop function. While a routine state's runs, a state it starts with + /// AI_StartState belongs to the routine as well (NpcAiService.ExtAiStartState). + /// + private int CallStateFunction(int symbolIndex) + { + Properties.IsInRoutineStateFunction = Vob.CurrentStateIsRoutine; + try + { + return CallAiFunction(symbolIndex); + } + finally + { + Properties.IsInRoutineStateFunction = false; + } + } + private int CallAiFunction(int symbolIndex) { var returnContinue = _daedalusLoopContinue; diff --git a/Assets/Gothic-Core/Scripts/Adapters/Properties/NpcProperties.cs b/Assets/Gothic-Core/Scripts/Adapters/Properties/NpcProperties.cs index 31d2f4a7c..f28cd70d8 100644 --- a/Assets/Gothic-Core/Scripts/Adapters/Properties/NpcProperties.cs +++ b/Assets/Gothic-Core/Scripts/Adapters/Properties/NpcProperties.cs @@ -166,6 +166,10 @@ public bool AreAllQueued(Func match) // The current state's _End function is running (AI_StartState from inside it must not run it again). public bool IsInStateEnd; + // The start or loop function of a routine state is running: a state it starts with AI_StartState belongs to the + // routine too (G2's ZS_GotoBed starts ZS_Sleep) and ends when the routine changes (NpcRoutineService). + public bool IsInRoutineStateFunction; + // Time.time of the last knockout - the swing that knocked him out doesn't finish him off (FightService). public float KnockedOutTime = float.MinValue; diff --git a/Assets/Gothic-Core/Scripts/Domain/Culling/NpcMeshCullingDomain.cs b/Assets/Gothic-Core/Scripts/Domain/Culling/NpcMeshCullingDomain.cs index 992c6529a..e064ef644 100644 --- a/Assets/Gothic-Core/Scripts/Domain/Culling/NpcMeshCullingDomain.cs +++ b/Assets/Gothic-Core/Scripts/Domain/Culling/NpcMeshCullingDomain.cs @@ -214,6 +214,15 @@ public void OnNpcRoutineChanged(NpcContainer npcData) MoveToRoutineWayPoint(index, npcData); } + /// + /// The NPC is in visible range (not culled), its AI runs. + /// + public bool IsAwake(NpcContainer npcData) + { + return _indexByInstance.TryGetValue(npcData.Instance, out var index) && + _states[index] == ObjectState.Enabled; + } + /// /// While culled, the next visibility check needs to happen at the position where the routine schedule /// expects the NPC - not where it was culled out. diff --git a/Assets/Gothic-Core/Scripts/Domain/Npc/Actions/AnimationAction.cs b/Assets/Gothic-Core/Scripts/Domain/Npc/Actions/AnimationAction.cs index 2b48b546f..7874cab5c 100644 --- a/Assets/Gothic-Core/Scripts/Domain/Npc/Actions/AnimationAction.cs +++ b/Assets/Gothic-Core/Scripts/Domain/Npc/Actions/AnimationAction.cs @@ -5,13 +5,14 @@ namespace Gothic.Core.Domain.Npc.Actions public class AnimationAction { public AnimationAction(string string0 = null, int int0 = 0, int int1 = 0, uint uint0 = 0, float float0 = 0f, - bool bool0 = false, NpcInstance instance0 = null, NpcInstance instance1 = null) + bool bool0 = false, NpcInstance instance0 = null, NpcInstance instance1 = null, bool bool1 = false) { String0 = string0; Int0 = int0; Int1 = int1; Float0 = float0; Bool0 = bool0; + Bool1 = bool1; Instance0 = instance0; Instance1 = instance1; } @@ -21,6 +22,7 @@ public AnimationAction(string string0 = null, int int0 = 0, int int1 = 0, uint u public readonly int Int1; public readonly float Float0; public readonly bool Bool0; + public readonly bool Bool1; public readonly NpcInstance Instance0; public readonly NpcInstance Instance1; } diff --git a/Assets/Gothic-Core/Scripts/Domain/Npc/Actions/AnimationActions/StartState.cs b/Assets/Gothic-Core/Scripts/Domain/Npc/Actions/AnimationActions/StartState.cs index f878910c3..a6dd9e93b 100644 --- a/Assets/Gothic-Core/Scripts/Domain/Npc/Actions/AnimationActions/StartState.cs +++ b/Assets/Gothic-Core/Scripts/Domain/Npc/Actions/AnimationActions/StartState.cs @@ -14,6 +14,8 @@ public class StartState : AbstractAnimationAction private string _wayPoint => Action.String0; private NpcInstance _other => Action.Instance0; private NpcInstance _victim => Action.Instance1; + // Queued by the start/loop function of a routine state (G2 ZS_GotoBed -> ZS_Sleep): part of the routine. + private bool _isRoutineState => Action.Bool1; public StartState(AnimationAction action, NpcContainer npcContainer) : base(action, npcContainer) { @@ -33,8 +35,9 @@ public override void Start() Vob.NextStateIndex = _action; Vob.NextStateName = GameStateService.GothicVm.GetSymbolByIndex(_action)!.Name; Vob.NextStateValid = true; - // Like Gothic's isRtnState: started by AI_StartState, not by the daily routine (a save game continues it). - Vob.NextStateIsRoutine = false; + // Like Gothic's isRtnState: started by AI_StartState, not by the daily routine (a save game continues it) - + // unless the routine state itself started it, then it ends with the routine entry like the engine's. + Vob.NextStateIsRoutine = _isRoutineState; ai.ClearState(_callEndFunction); diff --git a/Assets/Gothic-Core/Scripts/Domain/Npc/Actions/AnimationActions/UseMob.cs b/Assets/Gothic-Core/Scripts/Domain/Npc/Actions/AnimationActions/UseMob.cs index b3bad2097..1df406462 100644 --- a/Assets/Gothic-Core/Scripts/Domain/Npc/Actions/AnimationActions/UseMob.cs +++ b/Assets/Gothic-Core/Scripts/Domain/Npc/Actions/AnimationActions/UseMob.cs @@ -60,6 +60,14 @@ public override void Start() return; } + // Like the engine, a state below 0 only leaves the mob in use. The _End of a state whose routine changed + // before the NPC got onto its mob (ZS_Smith_Anvil_End: AI_UseMob(BSANVIL, -1)) walked to the nearest one. + if (IsStopUsingMob && !NpcContainer.IsUsingMob()) + { + IsFinishedFlag = true; + return; + } + // Else: We have a new animation where we seek the Mob before walking towards and executing action. var container = GetNearestMob(); _mobContainer = container; diff --git a/Assets/Gothic-Core/Scripts/Services/Culling/NpcMeshCullingService.cs b/Assets/Gothic-Core/Scripts/Services/Culling/NpcMeshCullingService.cs index 9ae5c0027..342ef2e7d 100644 --- a/Assets/Gothic-Core/Scripts/Services/Culling/NpcMeshCullingService.cs +++ b/Assets/Gothic-Core/Scripts/Services/Culling/NpcMeshCullingService.cs @@ -41,6 +41,14 @@ public void NotifyNpcRoutineChanged(NpcContainer npc) _npcDomain.OnNpcRoutineChanged(npc); } + /// + /// The NPC is in visible range (not culled), its AI runs. + /// + public bool IsAwake(NpcContainer npc) + { + return _npcDomain.IsAwake(npc); + } + /// /// The NPCs that are awake (in visible range), without the hero. One snapshot per frame shared by all callers /// (perception ticks, fight lookups) - no allocation, no scan of the whole world. Read only, don't keep it. diff --git a/Assets/Gothic-Core/Scripts/Services/Npc/NpcAiService.cs b/Assets/Gothic-Core/Scripts/Services/Npc/NpcAiService.cs index 5a5bf7215..75b0e8f60 100644 --- a/Assets/Gothic-Core/Scripts/Services/Npc/NpcAiService.cs +++ b/Assets/Gothic-Core/Scripts/Services/Npc/NpcAiService.cs @@ -589,9 +589,13 @@ public void ExtAiStartState(NpcInstance npc, int action, bool stopCurrentState, } } + // A routine state hands its end time on (engine: the new state keeps it): G2's sleepers lie in ZS_Sleep, + // started by the routine's ZS_GotoBed, and get up when the routine changes. Perceptions don't. + var isRoutineState = container.Props.IsInRoutineStateFunction; + container.Props.AnimationQueue.Enqueue(new StartState( new AnimationAction(int0: action, int1: endFunction, bool0: stopCurrentState, string0: wayPointName, - instance0: other, instance1: victim), + instance0: other, instance1: victim, bool1: isRoutineState), container)); } diff --git a/Assets/Gothic-Core/Scripts/Services/Npc/NpcRoutineService.cs b/Assets/Gothic-Core/Scripts/Services/Npc/NpcRoutineService.cs index ebed6fad4..26f967e00 100644 --- a/Assets/Gothic-Core/Scripts/Services/Npc/NpcRoutineService.cs +++ b/Assets/Gothic-Core/Scripts/Services/Npc/NpcRoutineService.cs @@ -1,8 +1,11 @@ using System; using System.Linq; +using Gothic.Core.Domain.Npc.Actions.AnimationActions; using Gothic.Core.Extensions; using Gothic.Core.Logging; +using Gothic.Core.Models.Container; using Gothic.Core.Models.Npc; +using Gothic.Core.Models.Vm; using Gothic.Core.Services.Caches; using Gothic.Core.Services.Culling; using Gothic.Core.Services.World; @@ -31,9 +34,8 @@ public void Init() /// /// Advance the time-based daily routine of all NPCs - including culled ones, so that the world progresses - /// while we're not looking. Visible NPCs pick the new routine up with their next StartNextRoutine(). - /// For culled NPCs, the culling sphere follows the schedule to the new waypoint. - /// FIXME - Original G1 interrupts the current ZS_* state of visible NPCs when their routine changes. + /// while we're not looking. CalculateCurrentRoutine() ends the routine state of visible NPCs and moves the + /// culling sphere of culled ones to the new waypoint. /// private void OnGameTimeMinuteChanged(DateTime now) { @@ -52,10 +54,7 @@ public void RecalculateAllNpcRoutines() if (npc.Props == null || npc.Props.Routines.Count == 0) continue; - if (!CalculateCurrentRoutine(npc.Instance)) - continue; - - _npcMeshCullingService.NotifyNpcRoutineChanged(npc); + CalculateCurrentRoutine(npc.Instance); } } @@ -152,6 +151,7 @@ public void ExchangeRoutine(NpcInstance npc, int routineIndex) public bool CalculateCurrentRoutine(NpcInstance npc) { var npcProps = npc.GetUserData().Props; + var previousRoutine = npcProps.RoutineCurrent; var currentTime = _gameTimeService.GetCurrentDateTime(); var normalizedNow = currentTime.Hour % 24 * 60 + currentTime.Minute; RoutineData newRoutine = null; @@ -193,9 +193,81 @@ public bool CalculateCurrentRoutine(NpcInstance npc) npcProps.RoutineCurrent = newRoutine; if (changed) + { _npcMeshCullingService.NotifyNpcRoutineChanged(npc.GetUserData()); + EndRoutineState(npc.GetUserData(), previousRoutine); + } return changed; } + + /// + /// Like the engine, a routine entry ends at its end time (or when Npc_ExchangeRoutine replaces it): the state + /// the routine started ends with its _End - Harad leaves the anvil, a sleeper gets up - and the new entry's + /// state follows. Before, a visible NPC only moved on when its state ended by itself, and mob states loop + /// forever. States of perceptions or other AI_StartState calls (talk, fight, watching the hero) and a dialog + /// aren't cut, the NPC takes the new entry when they end. Culled NPCs start it when they come back into view. + /// + private void EndRoutineState(NpcContainer npc, RoutineData previousRoutine) + { + var props = npc.Props; + var vob = npc.Vob; + var newRoutine = props.RoutineCurrent; + + // The same state at the same spot (Bilgot: TA_Sit_Campfire 08-23 and 23-08) goes on, no standing up. + if (previousRoutine != null && newRoutine != null && previousRoutine.Action == newRoutine.Action && + string.Equals(previousRoutine.Waypoint, newRoutine.Waypoint, StringComparison.OrdinalIgnoreCase)) + return; + + if (!IsRoutineStateRunning(npc)) + return; + + switch (props.CurrentLoopState) + { + // The state runs: its _End is queued once the current actions are done (AiHandler LoopState.End), then + // the new routine state starts (LoopState.AfterEnd -> StartNextRoutine). + case LoopState.Loop: + props.CurrentLoopState = LoopState.End; + break; + // Its start function hasn't run yet: start the new entry instead (LoopState.None -> StartNextRoutine). + case LoopState.Start: + props.CurrentLoopState = LoopState.None; + break; + // None, End, AfterEnd: the NPC takes the new entry with its next StartNextRoutine anyway. + default: + return; + } + + var newState = newRoutine == null ? "-" : _vm.GetSymbolByIndex(newRoutine.Action)?.Name; + Logger.Log($"[Routine] {npc.Instance.GetName(NpcNameSlot.Slot0)}: routine changed - " + + $"{vob.CurrentStateName} ends, next {newState} at {newRoutine?.Waypoint}", LogCat.Ai); + } + + /// + /// The visible NPC is in a state of its routine (Gothic's isRtnState) that nothing else is about to replace. + /// + private bool IsRoutineStateRunning(NpcContainer npc) + { + var props = npc.Props; + var vob = npc.Vob; + if (props == null || vob == null || vob.Player) + return false; + + if (props.IsDead || props.BodyState == VmGothicEnums.BodyState.BsUnconscious) + return false; + + if (!vob.CurrentStateValid || !vob.CurrentStateIsRoutine) + return false; + + // A state change is on its way already (AI_StartState queued or about to start). + if (vob.NextStateValid || props.HasQueued()) + return false; + + var dialogs = _gameStateService.Dialogs; + if (dialogs.IsInDialog && dialogs.CurrentDialogNpc == npc) + return false; + + return _npcMeshCullingService.IsAwake(npc); + } } } diff --git a/Docs/adr/2026-11-25-routine-change-ends-state.md b/Docs/adr/2026-11-25-routine-change-ends-state.md new file mode 100644 index 000000000..16ceee881 --- /dev/null +++ b/Docs/adr/2026-11-25-routine-change-ends-state.md @@ -0,0 +1,25 @@ +# ADR: A routine change ends the routine's state + +- Date: 2026-11-25 +- Technical details: Docs/npc-ai.md (The loop, point 4) + +## Context + +NPCs follow a daily routine: from 07:10 to 07:20 Harad works at the anvil, then at the fire, then at the anvil again. Our NPCs only took the next entry of their routine when their current activity ended by itself. Working at an anvil, sitting on a bench or sleeping never ends by itself, so once Harad stood at the anvil he stayed there for good, and sleepers never got up in the morning while the player watched. + +In the original game each routine entry has an end time. When the time passes it, the activity the routine started is ended properly (the smith steps back from the anvil, the sleeper gets up) and the next entry begins. Reactions the NPC is busy with, like talking to the player, fighting or watching him, are not cut off. The reference engine does the same. + +## Decisions + +1. **When a visible NPC's routine entry changes, the activity of its routine ends properly and the next one starts.** The NPC finishes what it is doing at that moment, plays the ending (standing up, stepping back) and then walks to its next spot. Not chosen: teleporting the NPC to its new spot, as we do for NPCs out of sight, because the player would see it. +2. **Only activities started by the routine end, never reactions.** Talking, fighting, fleeing, watching the player and the dialog partner are left alone; the NPC takes its new routine entry when they are over. An activity the routine started itself counts as part of the routine: in Gothic 2, going to bed leads to sleeping, and the sleeper gets up in the morning. Not chosen: the reference engine's rule that every reaction started during a routine activity also ends with it (unless the NPC talks or has a target), because it can cut off reactions like watching the player. +3. **A new routine set by the story (a quest changes where an NPC lives) ends the current routine activity right away.** Like a change by time. An NPC in a dialog changes after the dialog. Not chosen: waiting for the old entry's end time like the reference engine, because an NPC sitting on a bench would ignore its new task for hours. +4. **Two entries in a row with the same activity at the same spot don't interrupt.** Bilgot sits at the campfire from 08:00 to 23:00 and from 23:00 to 08:00; he doesn't stand up and sit down again at 23:00. Not chosen: restarting the activity like the reference engine, because it shows as a pointless stand up and sit down. +5. **Ending to use an object that the NPC isn't using does nothing.** If the routine changes while the smith is still walking to the anvil, he doesn't walk to an anvil just to step back from it. The reference engine does the same. + +## Consequences + +- Smiths, cooks, sleepers, bench sitters and guards with several entries follow their schedule while the player watches. +- NPCs out of sight behave as before: they appear at their new spot when they come into view. +- A routine change while the NPC is in the middle of switching to another activity is skipped; that activity then runs until it ends by itself or the next routine change. +- Saved games: an activity the routine started (now also sleeping) isn't continued after loading, the NPC starts its routine entry again. diff --git a/Docs/npc-ai.md b/Docs/npc-ai.md index 76c40042f..69cc9b06f 100644 --- a/Docs/npc-ai.md +++ b/Docs/npc-ai.md @@ -16,6 +16,11 @@ unless a module is named. Decisions: `Docs/adr/2026-10-31-npc-ai-port.md`. `VmExternalSupport`, `VmExternalGuard` (no exception crosses into the VM). 3. The external calls the service of its area, mostly `Services/Npc/NpcAiService`. `AI_*` externals queue an action from `Domain/Npc/Actions/AnimationActions/` into `NpcProperties.AnimationQueue`. +4. The daily routine (`Services/Npc/NpcRoutineService`, every game minute): when a visible NPC's routine entry changes + (time or `Npc_ExchangeRoutine`) and its state belongs to the routine (`Vob.CurrentStateIsRoutine`, also states the + routine state started itself, e.g. G2 `ZS_GotoBed` -> `ZS_Sleep`), the state ends with its `_End` (`LoopState.End`) + and the new entry's state starts. Perception/`AI_StartState` states and the dialog partner are left alone. + Decisions: `Docs/adr/2026-11-25-routine-change-ends-state.md`. ## Who owns what From e78962129297902f2f3ec3c1b082377114c71069 Mon Sep 17 00:00:00 2001 From: BoroBongo Date: Wed, 25 Nov 2026 22:51:08 +0000 Subject: [PATCH 2/7] fix: after a sleep NPCs near the hero don't start getting up only to be put on their spot - the time-skip reset alone starts them over, the routine change doesn't end their states then Co-Authored-By: Claude Opus 5.5 --- .../Scripts/Services/Npc/NpcRoutineService.cs | 14 +++++++++----- .../Gothic-Core/Scripts/Services/Npc/NpcService.cs | 4 +++- Docs/adr/2026-11-25-routine-change-ends-state.md | 1 + Docs/npc-ai.md | 2 ++ 4 files changed, 15 insertions(+), 6 deletions(-) diff --git a/Assets/Gothic-Core/Scripts/Services/Npc/NpcRoutineService.cs b/Assets/Gothic-Core/Scripts/Services/Npc/NpcRoutineService.cs index 26f967e00..909d27265 100644 --- a/Assets/Gothic-Core/Scripts/Services/Npc/NpcRoutineService.cs +++ b/Assets/Gothic-Core/Scripts/Services/Npc/NpcRoutineService.cs @@ -39,14 +39,16 @@ public void Init() /// private void OnGameTimeMinuteChanged(DateTime now) { - RecalculateAllNpcRoutines(); + RecalculateAllNpcRoutines(endRoutineStates: true); } /// /// Every NPC's routine for the time right now: at each game minute and right after a time jump /// (NpcService.ResetNpcsAfterTimeSkip). /// - public void RecalculateAllNpcRoutines() + /// False after a time jump: the time-skip reset starts the visible NPCs over + /// itself, an _End started here would be cut off by it half-way. + public void RecalculateAllNpcRoutines(bool endRoutineStates) { foreach (var npc in _multiTypeCacheService.NpcCache) { @@ -54,7 +56,7 @@ public void RecalculateAllNpcRoutines() if (npc.Props == null || npc.Props.Routines.Count == 0) continue; - CalculateCurrentRoutine(npc.Instance); + CalculateCurrentRoutine(npc.Instance, endRoutineStates); } } @@ -148,7 +150,8 @@ public void ExchangeRoutine(NpcInstance npc, int routineIndex) /// /// Based on time of the day, we need to calculate routine. /// - public bool CalculateCurrentRoutine(NpcInstance npc) + /// On a change, end the visible NPC's routine state (EndRoutineState). + public bool CalculateCurrentRoutine(NpcInstance npc, bool endRoutineState = true) { var npcProps = npc.GetUserData().Props; var previousRoutine = npcProps.RoutineCurrent; @@ -195,7 +198,8 @@ public bool CalculateCurrentRoutine(NpcInstance npc) if (changed) { _npcMeshCullingService.NotifyNpcRoutineChanged(npc.GetUserData()); - EndRoutineState(npc.GetUserData(), previousRoutine); + if (endRoutineState) + EndRoutineState(npc.GetUserData(), previousRoutine); } return changed; diff --git a/Assets/Gothic-Core/Scripts/Services/Npc/NpcService.cs b/Assets/Gothic-Core/Scripts/Services/Npc/NpcService.cs index b0b74c48a..3eb8804f5 100644 --- a/Assets/Gothic-Core/Scripts/Services/Npc/NpcService.cs +++ b/Assets/Gothic-Core/Scripts/Services/Npc/NpcService.cs @@ -735,7 +735,9 @@ public bool InitNpc(GameObject go, bool initImmediately = false) /// private void ResetNpcsAfterTimeSkip() { - _npcRoutineService.RecalculateAllNpcRoutines(); + // The reset below owns the visible NPCs: the routine change doesn't end their states as well (it would + // start an _End that the reset cuts off a few frames later). + _npcRoutineService.RecalculateAllNpcRoutines(endRoutineStates: false); var visibleCount = 0; var culledCount = 0; diff --git a/Docs/adr/2026-11-25-routine-change-ends-state.md b/Docs/adr/2026-11-25-routine-change-ends-state.md index 16ceee881..bb5899ade 100644 --- a/Docs/adr/2026-11-25-routine-change-ends-state.md +++ b/Docs/adr/2026-11-25-routine-change-ends-state.md @@ -16,6 +16,7 @@ In the original game each routine entry has an end time. When the time passes it 3. **A new routine set by the story (a quest changes where an NPC lives) ends the current routine activity right away.** Like a change by time. An NPC in a dialog changes after the dialog. Not chosen: waiting for the old entry's end time like the reference engine, because an NPC sitting on a bench would ignore its new task for hours. 4. **Two entries in a row with the same activity at the same spot don't interrupt.** Bilgot sits at the campfire from 08:00 to 23:00 and from 23:00 to 08:00; he doesn't stand up and sit down again at 23:00. Not chosen: restarting the activity like the reference engine, because it shows as a pointless stand up and sit down. 5. **Ending to use an object that the NPC isn't using does nothing.** If the routine changes while the smith is still walking to the anvil, he doesn't walk to an anvil just to step back from it. The reference engine does the same. +6. **After a time jump (sleeping, Marvin's "set time") this rule stays out of the way.** The routines are recalculated for the new time, but the NPCs near the hero start over at their new spots anyway ([After a time jump every NPC starts over](2026-11-25-time-skip-npc-reset.md)). Not chosen: both at once - an NPC would begin to get up or walk off, and a few frames later the start-over cuts that off and puts it on its spot. ## Consequences diff --git a/Docs/npc-ai.md b/Docs/npc-ai.md index 69cc9b06f..f1051bf1c 100644 --- a/Docs/npc-ai.md +++ b/Docs/npc-ai.md @@ -20,6 +20,8 @@ unless a module is named. Decisions: `Docs/adr/2026-10-31-npc-ai-port.md`. (time or `Npc_ExchangeRoutine`) and its state belongs to the routine (`Vob.CurrentStateIsRoutine`, also states the routine state started itself, e.g. G2 `ZS_GotoBed` -> `ZS_Sleep`), the state ends with its `_End` (`LoopState.End`) and the new entry's state starts. Perception/`AI_StartState` states and the dialog partner are left alone. + After a time jump (`GameTimeSkipped`) `NpcService.ResetNpcsAfterTimeSkip` recalculates the routines without + ending states (`RecalculateAllNpcRoutines(endRoutineStates: false)`): its reset starts the visible NPCs over. Decisions: `Docs/adr/2026-11-25-routine-change-ends-state.md`. ## Who owns what From 152cafa88c3ebe64eda167dc7f30ed231e34f5b2 Mon Sep 17 00:00:00 2001 From: BoroBongo Date: Wed, 25 Nov 2026 22:54:02 +0000 Subject: [PATCH 3/7] fix: a G2 sleeper whose routine changes on the way to bed doesn't lie down for hours - the sleep queued for the old routine entry gives way to the new one Co-Authored-By: Claude Opus 5.5 --- .../Scripts/Adapters/Npc/AiHandler.cs | 36 ++++++++++++++++--- .../Adapters/Properties/NpcProperties.cs | 3 ++ .../Actions/AnimationActions/StartState.cs | 9 +++-- .../Scripts/Models/Npc/RoutineData.cs | 14 +++++++- .../Scripts/Services/Npc/NpcRoutineService.cs | 7 ++-- .../2026-11-25-routine-change-ends-state.md | 2 +- 6 files changed, 60 insertions(+), 11 deletions(-) diff --git a/Assets/Gothic-Core/Scripts/Adapters/Npc/AiHandler.cs b/Assets/Gothic-Core/Scripts/Adapters/Npc/AiHandler.cs index 699622249..5eb98a6af 100644 --- a/Assets/Gothic-Core/Scripts/Adapters/Npc/AiHandler.cs +++ b/Assets/Gothic-Core/Scripts/Adapters/Npc/AiHandler.cs @@ -499,16 +499,24 @@ public void StartNextRoutine() // reset and the next AI_UseItemToState put a second mesh into the hand. _npcService.RemoveUsedItemFromHand(NpcData); + // The routine state queued it for itself under an entry that has ended meanwhile (G2: the routine changed + // while ZS_GotoBed walked to bed - he lay down in ZS_Sleep for hours): the new entry starts instead. + if (Vob.NextStateValid && IsNextStateOfEndedRoutine()) + { + var current = Properties.RoutineCurrent; + Logger.Log($"[Routine] {NpcInstance.GetName(NpcNameSlot.Slot0)}: {Vob.NextStateName} belongs to an " + + $"ended routine entry - next {Vm.GetSymbolByIndex(current.Action)?.Name} " + + $"at {current.Waypoint}", LogCat.Ai); + ClearNextState(); + } + // We have set some "next" state. Use it instead of going back to daily routine first. if (Vob.NextStateValid) { StartRoutine(Vob.NextStateIndex, Vob.NextStateIsRoutine); // As we use NextStateIndex as new "current" one, we clear it now safely. - Vob.NextStateIndex = -1; - Vob.NextStateValid = false; - Vob.NextStateIsRoutine = false; - Vob.NextStateName = string.Empty; + ClearNextState(); } // If we have nothing prepared, start daily Routine. else @@ -540,6 +548,26 @@ public void StartNextRoutine() } } + /// + /// A routine next state (queued by the routine state itself) whose routine entry has ended before it started. + /// The routine change left the NPC alone meanwhile (NpcRoutineService: a state change was on its way). + /// + private bool IsNextStateOfEndedRoutine() + { + var entry = Properties.NextStateRoutine; + var current = Properties.RoutineCurrent; + return Vob.NextStateIsRoutine && entry != null && current != null && !entry.IsSameActivity(current); + } + + private void ClearNextState() + { + Vob.NextStateIndex = -1; + Vob.NextStateValid = false; + Vob.NextStateIsRoutine = false; + Vob.NextStateName = string.Empty; + Properties.NextStateRoutine = null; + } + public void StartRoutine(int action, string wayPointName) { // We need to set WayPoint within Daedalus instance as it calls _self.wp_ during routine loops. diff --git a/Assets/Gothic-Core/Scripts/Adapters/Properties/NpcProperties.cs b/Assets/Gothic-Core/Scripts/Adapters/Properties/NpcProperties.cs index f28cd70d8..a5b3e8c3a 100644 --- a/Assets/Gothic-Core/Scripts/Adapters/Properties/NpcProperties.cs +++ b/Assets/Gothic-Core/Scripts/Adapters/Properties/NpcProperties.cs @@ -19,6 +19,9 @@ public class NpcProperties public List Routines = new(); public RoutineData RoutinePrevious; public RoutineData RoutineCurrent; + // The entry a routine next state (Vob.NextStateIsRoutine, G2 ZS_GotoBed -> ZS_Sleep) was queued under. Has it + // ended before the state starts, the new entry starts instead (AiHandler.StartNextRoutine). + public RoutineData NextStateRoutine; // WayNet public WayPoint CurrentWayPoint; diff --git a/Assets/Gothic-Core/Scripts/Domain/Npc/Actions/AnimationActions/StartState.cs b/Assets/Gothic-Core/Scripts/Domain/Npc/Actions/AnimationActions/StartState.cs index a6dd9e93b..1829578de 100644 --- a/Assets/Gothic-Core/Scripts/Domain/Npc/Actions/AnimationActions/StartState.cs +++ b/Assets/Gothic-Core/Scripts/Domain/Npc/Actions/AnimationActions/StartState.cs @@ -1,4 +1,5 @@ using Gothic.Core.Models.Container; +using Gothic.Core.Models.Npc; using Gothic.Core.Const; using Gothic.Core.Services; using ZenKit.Daedalus; @@ -16,9 +17,12 @@ public class StartState : AbstractAnimationAction private NpcInstance _victim => Action.Instance1; // Queued by the start/loop function of a routine state (G2 ZS_GotoBed -> ZS_Sleep): part of the routine. private bool _isRoutineState => Action.Bool1; - + // The routine entry it was queued under: walking to bed can outlast it (AiHandler.StartNextRoutine). + private readonly RoutineData _routineEntry; + public StartState(AnimationAction action, NpcContainer npcContainer) : base(action, npcContainer) { + _routineEntry = _isRoutineState ? Props?.RoutineCurrent : null; } public override void Start() @@ -38,7 +42,8 @@ public override void Start() // Like Gothic's isRtnState: started by AI_StartState, not by the daily routine (a save game continues it) - // unless the routine state itself started it, then it ends with the routine entry like the engine's. Vob.NextStateIsRoutine = _isRoutineState; - + Props.NextStateRoutine = _routineEntry; + ai.ClearState(_callEndFunction); Props.IsStateTimeActive = true; diff --git a/Assets/Gothic-Core/Scripts/Models/Npc/RoutineData.cs b/Assets/Gothic-Core/Scripts/Models/Npc/RoutineData.cs index 232d5ffbb..1736b9a92 100644 --- a/Assets/Gothic-Core/Scripts/Models/Npc/RoutineData.cs +++ b/Assets/Gothic-Core/Scripts/Models/Npc/RoutineData.cs @@ -1,4 +1,6 @@ -namespace Gothic.Core.Models.Npc +using System; + +namespace Gothic.Core.Models.Npc { public class RoutineData { @@ -10,5 +12,15 @@ public class RoutineData public int NormalizedEnd; public int Action; public string Waypoint; + + /// + /// The same state at the same waypoint: for the NPC nothing changes between the two entries (Bilgot sits at the + /// campfire with TA_Sit_Campfire 08-23 and 23-08). + /// + public bool IsSameActivity(RoutineData other) + { + return other != null && Action == other.Action && + string.Equals(Waypoint, other.Waypoint, StringComparison.OrdinalIgnoreCase); + } } } diff --git a/Assets/Gothic-Core/Scripts/Services/Npc/NpcRoutineService.cs b/Assets/Gothic-Core/Scripts/Services/Npc/NpcRoutineService.cs index 909d27265..4db704568 100644 --- a/Assets/Gothic-Core/Scripts/Services/Npc/NpcRoutineService.cs +++ b/Assets/Gothic-Core/Scripts/Services/Npc/NpcRoutineService.cs @@ -219,8 +219,7 @@ private void EndRoutineState(NpcContainer npc, RoutineData previousRoutine) var newRoutine = props.RoutineCurrent; // The same state at the same spot (Bilgot: TA_Sit_Campfire 08-23 and 23-08) goes on, no standing up. - if (previousRoutine != null && newRoutine != null && previousRoutine.Action == newRoutine.Action && - string.Equals(previousRoutine.Waypoint, newRoutine.Waypoint, StringComparison.OrdinalIgnoreCase)) + if (previousRoutine != null && previousRoutine.IsSameActivity(newRoutine)) return; if (!IsRoutineStateRunning(npc)) @@ -263,7 +262,9 @@ private bool IsRoutineStateRunning(NpcContainer npc) if (!vob.CurrentStateValid || !vob.CurrentStateIsRoutine) return false; - // A state change is on its way already (AI_StartState queued or about to start). + // A state change is on its way already (AI_StartState queued or about to start). If the routine state + // queued it for itself (G2 ZS_GotoBed -> ZS_Sleep), the new entry wins once it's due + // (AiHandler.StartNextRoutine drops a routine next state whose entry has ended). if (vob.NextStateValid || props.HasQueued()) return false; diff --git a/Docs/adr/2026-11-25-routine-change-ends-state.md b/Docs/adr/2026-11-25-routine-change-ends-state.md index bb5899ade..e3351f5cc 100644 --- a/Docs/adr/2026-11-25-routine-change-ends-state.md +++ b/Docs/adr/2026-11-25-routine-change-ends-state.md @@ -22,5 +22,5 @@ In the original game each routine entry has an end time. When the time passes it - Smiths, cooks, sleepers, bench sitters and guards with several entries follow their schedule while the player watches. - NPCs out of sight behave as before: they appear at their new spot when they come into view. -- A routine change while the NPC is in the middle of switching to another activity is skipped; that activity then runs until it ends by itself or the next routine change. +- A routine change while the NPC is in the middle of switching to a reaction (talking, fighting) waits: the NPC takes the new entry when the reaction is over. If the routine itself started the switch (on the way to bed before lying down), the new entry starts instead once the NPC gets there - he doesn't lie down for hours under the old entry. - Saved games: an activity the routine started (now also sleeping) isn't continued after loading, the NPC starts its routine entry again. From 60547d1fba0b19d18b55594b1816ff03b6dfc20d Mon Sep 17 00:00:00 2001 From: BoroBongo Date: Wed, 25 Nov 2026 22:54:20 +0000 Subject: [PATCH 4/7] fix: a routine change made by a state's own start function isn't lost - the AI loop no longer overwrites it with "looping" Co-Authored-By: Claude Opus 5.5 --- Assets/Gothic-Core/Scripts/Adapters/Npc/AiHandler.cs | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/Assets/Gothic-Core/Scripts/Adapters/Npc/AiHandler.cs b/Assets/Gothic-Core/Scripts/Adapters/Npc/AiHandler.cs index 5eb98a6af..6fd71078e 100644 --- a/Assets/Gothic-Core/Scripts/Adapters/Npc/AiHandler.cs +++ b/Assets/Gothic-Core/Scripts/Adapters/Npc/AiHandler.cs @@ -223,7 +223,10 @@ private void Update() return; CallStateFunction(Vob.CurrentStateIndex); - Properties.CurrentLoopState = LoopState.Loop; + // The start function can end its own state at once (Npc_ExchangeRoutine(self, ...) inside a + // ZS_*: NpcRoutineService sets None) - looping would drop that change. + if (Properties.CurrentLoopState == LoopState.Start) + Properties.CurrentLoopState = LoopState.Loop; _nextLoopTime = 0f; break; case LoopState.Loop: From 748bd5fb752274bf2302a4539e353a61f30ff76e Mon Sep 17 00:00:00 2001 From: BoroBongo Date: Wed, 25 Nov 2026 22:54:49 +0000 Subject: [PATCH 5/7] refactor: the routine change uses the shared "is down" rule - a magically frozen NPC counts like everywhere else Co-Authored-By: Claude Opus 5.5 --- Assets/Gothic-Core/Scripts/Services/Npc/NpcRoutineService.cs | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/Assets/Gothic-Core/Scripts/Services/Npc/NpcRoutineService.cs b/Assets/Gothic-Core/Scripts/Services/Npc/NpcRoutineService.cs index 4db704568..cd1ff58d2 100644 --- a/Assets/Gothic-Core/Scripts/Services/Npc/NpcRoutineService.cs +++ b/Assets/Gothic-Core/Scripts/Services/Npc/NpcRoutineService.cs @@ -5,7 +5,6 @@ using Gothic.Core.Logging; using Gothic.Core.Models.Container; using Gothic.Core.Models.Npc; -using Gothic.Core.Models.Vm; using Gothic.Core.Services.Caches; using Gothic.Core.Services.Culling; using Gothic.Core.Services.World; @@ -256,7 +255,7 @@ private bool IsRoutineStateRunning(NpcContainer npc) if (props == null || vob == null || vob.Player) return false; - if (props.IsDead || props.BodyState == VmGothicEnums.BodyState.BsUnconscious) + if (npc.IsDown()) return false; if (!vob.CurrentStateValid || !vob.CurrentStateIsRoutine) From 5b1b8c3aa5f28e23836e0088aeeb83652cf01bb2 Mon Sep 17 00:00:00 2001 From: BoroBongo Date: Wed, 25 Nov 2026 22:55:04 +0000 Subject: [PATCH 6/7] refactor: the routine change asks DialogModel.IsTalkingTo whether the hero talks to the NPC Co-Authored-By: Claude Opus 5.5 --- Assets/Gothic-Core/Scripts/Services/Npc/NpcRoutineService.cs | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/Assets/Gothic-Core/Scripts/Services/Npc/NpcRoutineService.cs b/Assets/Gothic-Core/Scripts/Services/Npc/NpcRoutineService.cs index cd1ff58d2..b094c174d 100644 --- a/Assets/Gothic-Core/Scripts/Services/Npc/NpcRoutineService.cs +++ b/Assets/Gothic-Core/Scripts/Services/Npc/NpcRoutineService.cs @@ -267,8 +267,7 @@ private bool IsRoutineStateRunning(NpcContainer npc) if (vob.NextStateValid || props.HasQueued()) return false; - var dialogs = _gameStateService.Dialogs; - if (dialogs.IsInDialog && dialogs.CurrentDialogNpc == npc) + if (_gameStateService.Dialogs.IsTalkingTo(npc)) return false; return _npcMeshCullingService.IsAwake(npc); From 7c3db588e9177e4522a4fa0fdf73aa80ab35ce66 Mon Sep 17 00:00:00 2001 From: BoroBongo Date: Wed, 25 Nov 2026 22:56:20 +0000 Subject: [PATCH 7/7] fix: a reaction started by a perception inside a routine state stays a reaction - the routine change doesn't cut it off Co-Authored-By: Claude Opus 5.5 --- .../Adapters/Properties/NpcProperties.cs | 3 ++- .../Scripts/Services/Npc/NpcAiService.cs | 23 +++++++++++++++++-- 2 files changed, 23 insertions(+), 3 deletions(-) diff --git a/Assets/Gothic-Core/Scripts/Adapters/Properties/NpcProperties.cs b/Assets/Gothic-Core/Scripts/Adapters/Properties/NpcProperties.cs index a5b3e8c3a..073956594 100644 --- a/Assets/Gothic-Core/Scripts/Adapters/Properties/NpcProperties.cs +++ b/Assets/Gothic-Core/Scripts/Adapters/Properties/NpcProperties.cs @@ -170,7 +170,8 @@ public bool AreAllQueued(Func match) public bool IsInStateEnd; // The start or loop function of a routine state is running: a state it starts with AI_StartState belongs to the - // routine too (G2's ZS_GotoBed starts ZS_Sleep) and ends when the routine changes (NpcRoutineService). + // routine too (G2's ZS_GotoBed starts ZS_Sleep) and ends when the routine changes (NpcRoutineService). False + // while a perception runs inside it (NpcAiService.ExecutePerception): a reaction never belongs to the routine. public bool IsInRoutineStateFunction; // Time.time of the last knockout - the swing that knocked him out doesn't finish him off (FightService). diff --git a/Assets/Gothic-Core/Scripts/Services/Npc/NpcAiService.cs b/Assets/Gothic-Core/Scripts/Services/Npc/NpcAiService.cs index 75b0e8f60..55355b238 100644 --- a/Assets/Gothic-Core/Scripts/Services/Npc/NpcAiService.cs +++ b/Assets/Gothic-Core/Scripts/Services/Npc/NpcAiService.cs @@ -182,6 +182,11 @@ private void LogAssessEnemy(NpcProperties properties, NpcInstance self, NpcInsta // won't undo damage already done to the VM by an external further down the call chain, // but it stops this specific call from cascading further and gives a clear, attributable // log instead of an anonymous NullReferenceException. + // + // A perception's AI_StartState is a reaction, also when it runs from inside the NPC's own routine state + // function (Npc_SendSinglePerc(self, self, ...)): it doesn't belong to the routine (ExtAiStartState). + var wasInRoutineStateFunction = properties.IsInRoutineStateFunction; + properties.IsInRoutineStateFunction = false; using (new VmGlobalsScope(_gameStateService.GothicVm, self, other, victim, item)) { try @@ -204,6 +209,10 @@ private void LogAssessEnemy(NpcProperties properties, NpcInstance self, NpcInsta $"{e.Message}", LogCat.Ai); return null; } + finally + { + properties.IsInRoutineStateFunction = wasInRoutineStateFunction; + } } } @@ -1585,8 +1594,18 @@ private void ExecutePassivePerception(VmGothicEnums.PerceptionType perception, i return; } - using (new VmGlobalsScope(vm, receiver.Instance, other, victim, item)) - ExtAiStartState(receiver.Instance, perceptionFunction, true, ""); + // A reaction, also when sent from inside the receiver's own routine state function (see ExecutePerception). + var wasInRoutineStateFunction = receiver.Props.IsInRoutineStateFunction; + receiver.Props.IsInRoutineStateFunction = false; + try + { + using (new VmGlobalsScope(vm, receiver.Instance, other, victim, item)) + ExtAiStartState(receiver.Instance, perceptionFunction, true, ""); + } + finally + { + receiver.Props.IsInRoutineStateFunction = wasInRoutineStateFunction; + } } public void ExtSetTrueGuild(NpcInstance npc, int guild)