perf(ai): AiRuntime 热路径去装箱/弱表一次注册 + 补 OnExit/Entry OnEnter 测试

This commit is contained in:
2026-07-03 14:20:19 +08:00
parent cdd1053bec
commit 5ad26b16e8
2 changed files with 34 additions and 5 deletions
@@ -15,6 +15,7 @@ namespace BaseGames.Tests.EditMode.AI
.To("Chase").When(c => c.Sensor.SeesPlayer(), "SeesPlayer");
b.State("Chase")
.OnEnter(c => c.Mover.FacePlayer())
.OnExit(c => c.Mover.Stop())
.Tick(c => c.Mover.MoveTo(c.Sensor.LastKnown))
.To("Search").When(c => c.Sensor.LostFor(2f), "LostFor(2s)");
b.State("Search")
@@ -89,5 +90,26 @@ namespace BaseGames.Tests.EditMode.AI
rt.Tick(1.5f);
Assert.AreEqual("Patrol", rt.CurrentStateName); // 累计 >3s
}
[Test]
public void Switch_RunsPreviousStateOnExit()
{
var ctx = new FakeAiContext();
var rt = new AiRuntime(Graph(), ctx);
ctx.S.Sees = true; rt.Tick(0.1f); // Patrol -> Chase
ctx.S.Sees = false; ctx.S.LostForValue = 5f; rt.Tick(0.1f);// Chase -> Search (触发 Chase.OnExit)
CollectionAssert.Contains(ctx.M.Calls, "Stop");
}
[Test]
public void Construct_InvokesEntryOnEnter()
{
var b = new BrainBuilder();
b.Entry("Start");
b.State("Start").OnEnter(c => c.Mover.LookAround());
var ctx = new FakeAiContext();
var rt = new AiRuntime(b.Build(), ctx);
CollectionAssert.Contains(ctx.M.Calls, "LookAround");
}
}
}
+12 -5
View File
@@ -31,6 +31,8 @@ namespace BaseGames.AI
void EnterInitial()
{
_byContext.Remove(_ctx); // 幂等:避免同一 ctx 重复键异常
_byContext.Add(_ctx, this);
_current = _graph.GetState(_graph.EntryState);
_timeInState = 0f;
_current.OnEnter?.Invoke(_ctx);
@@ -44,9 +46,6 @@ namespace BaseGames.AI
public void Tick(float dt)
{
_byContext.Remove(_ctx);
_byContext.Add(_ctx, this);
// IsControllable 让位门:受击/硬直/击飞时挂起,不推进决策也不跑 Tick。
if (!_ctx.Vitals.IsControllable)
{
@@ -66,13 +65,21 @@ namespace BaseGames.AI
bool TryTransition()
{
// 全局/父层转换优先(本任务只评估条件型;事件型在 Task 6 处理)
foreach (var t in _graph.GlobalTransitions)
var globals = _graph.GlobalTransitions;
for (int i = 0; i < globals.Count; i++)
{
var t = globals[i];
if (!t.IsEvent && t.Condition(_ctx))
return Switch(t);
}
foreach (var t in _current.Transitions)
var locals = _current.Transitions;
for (int i = 0; i < locals.Count; i++)
{
var t = locals[i];
if (!t.IsEvent && t.Condition(_ctx))
return Switch(t);
}
return false;
}