Skip to content
Open
62 changes: 55 additions & 7 deletions Assets/Gothic-Core/Scripts/Adapters/Npc/AiHandler.cs
Original file line number Diff line number Diff line change
Expand Up @@ -222,8 +222,11 @@ private void Update()
if (Vob.CurrentStateIndex == 0)
return;

CallAiFunction(Vob.CurrentStateIndex);
Properties.CurrentLoopState = LoopState.Loop;
CallStateFunction(Vob.CurrentStateIndex);
// 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:
Expand All @@ -250,7 +253,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)
Expand Down Expand Up @@ -336,6 +339,23 @@ public void CallStateEnd(int endFunction, NpcInstance other, NpcInstance victim)
}
}

/// <summary>
/// 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).
/// </summary>
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;
Expand Down Expand Up @@ -482,16 +502,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
Expand Down Expand Up @@ -523,6 +551,26 @@ public void StartNextRoutine()
}
}

/// <summary>
/// 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).
/// </summary>
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.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,9 @@ public class NpcProperties
public List<RoutineData> 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;
Expand Down Expand Up @@ -166,6 +169,11 @@ public bool AreAllQueued(Func<AbstractAnimationAction, bool> 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). 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).
public float KnockedOutTime = float.MinValue;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -214,6 +214,15 @@ public void OnNpcRoutineChanged(NpcContainer npcData)
MoveToRoutineWayPoint(index, npcData);
}

/// <summary>
/// The NPC is in visible range (not culled), its AI runs.
/// </summary>
public bool IsAwake(NpcContainer npcData)
{
return _indexByInstance.TryGetValue(npcData.Instance, out var index) &&
_states[index] == ObjectState.Enabled;
}

/// <summary>
/// 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.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}
Expand All @@ -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;
}
Expand Down
Original file line number Diff line number Diff line change
@@ -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;
Expand All @@ -14,9 +15,14 @@ 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;
// 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()
Expand All @@ -33,9 +39,11 @@ 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;
Props.NextStateRoutine = _routineEntry;

ai.ClearState(_callEndFunction);

Props.IsStateTimeActive = true;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
14 changes: 13 additions & 1 deletion Assets/Gothic-Core/Scripts/Models/Npc/RoutineData.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
namespace Gothic.Core.Models.Npc
using System;

namespace Gothic.Core.Models.Npc
{
public class RoutineData
{
Expand All @@ -10,5 +12,15 @@ public class RoutineData
public int NormalizedEnd;
public int Action;
public string Waypoint;

/// <summary>
/// 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).
/// </summary>
public bool IsSameActivity(RoutineData other)
{
return other != null && Action == other.Action &&
string.Equals(Waypoint, other.Waypoint, StringComparison.OrdinalIgnoreCase);
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,14 @@ public void NotifyNpcRoutineChanged(NpcContainer npc)
_npcDomain.OnNpcRoutineChanged(npc);
}

/// <summary>
/// The NPC is in visible range (not culled), its AI runs.
/// </summary>
public bool IsAwake(NpcContainer npc)
{
return _npcDomain.IsAwake(npc);
}

/// <summary>
/// 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.
Expand Down
29 changes: 26 additions & 3 deletions Assets/Gothic-Core/Scripts/Services/Npc/NpcAiService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -204,6 +209,10 @@ private void LogAssessEnemy(NpcProperties properties, NpcInstance self, NpcInsta
$"{e.Message}", LogCat.Ai);
return null;
}
finally
{
properties.IsInRoutineStateFunction = wasInRoutineStateFunction;
}
}
}

Expand Down Expand Up @@ -589,9 +598,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));
}

Expand Down Expand Up @@ -1581,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)
Expand Down
Loading