NoJobEngine 2.0.7
Loading...
Searching...
No Matches
BTScriptBridge.h
Go to the documentation of this file.
1
6#pragma once
10#include <memory>
11#include <stdexcept>
12#include <utility>
13#include <vector>
14#include <string>
15#include <optional>
16#include <cstdint>
17#include <functional>
18#include <unordered_map>
19#include <algorithm>
20#include <glm/vec3.hpp>
21
22namespace NoJob {
23// Type-safe access to the owning script. The pointer is valid only during Play.
24inline ScriptableEntity* BTGetScript(BTContext& context) noexcept {
25 return context.GetScript();
26}
27
28// Bind by script NAME, never by instance pointer. The entity-local script is
29// resolved on each tick, so trees remain reusable and reloads do not retain
30// dangling script pointers. Missing/disabled scripts fail gracefully.
31template<class T>
32void BTRegisterScriptAction(BTNativeRegistry& registry, std::string actionName,
33 std::string scriptName, BTStatus (T::*method)(BTContext&, float)) {
34 registry.RegisterAction(std::move(actionName), [name = std::move(scriptName), method](BTContext& ctx, float dt) {
35 auto* owner = BTGetScript(ctx);
36 auto* scene = owner ? owner->GetEntity().GetScene() : nullptr;
37 auto* script = scene ? dynamic_cast<T*>(scene->FindRuntimeScript(owner->GetEntity().GetHandle(), name)) : nullptr;
38 return script ? (script->*method)(ctx, dt) : BTStatus::Failure;
39 });
40}
41template<class T>
42void BTRegisterScriptCondition(BTNativeRegistry& registry, std::string conditionName,
43 std::string scriptName, bool (T::*method)(BTContext&)) {
44 registry.RegisterCondition(std::move(conditionName), [name = std::move(scriptName), method](BTContext& ctx) {
45 auto* owner = BTGetScript(ctx);
46 auto* scene = owner ? owner->GetEntity().GetScene() : nullptr;
47 auto* script = scene ? dynamic_cast<T*>(scene->FindRuntimeScript(owner->GetEntity().GetHandle(), name)) : nullptr;
48 return script && (script->*method)(ctx);
49 });
50}
51
52// Value-only snapshot. The editor never iterates BTContext's live containers.
54 int LastResult = 1;
55 struct Node { std::uint64_t ID; int Status; std::size_t Ticks; std::string Label; int Depth; bool Active; };
56 struct Event { std::uint64_t Tick; std::uint64_t Node; std::string Kind; std::string Detail; };
57 std::vector<Node> Nodes;
58 std::vector<Event> Events;
59 std::vector<BTBlackboard::DebugEntry> BlackboardEntries;
60 std::uint64_t BlackboardRevision = 0;
61 std::optional<std::uint32_t> TargetHandle;
62 std::optional<glm::vec3> TargetPosition;
63};
64// Native script base class. Scene already invokes OnCreate/OnUpdate/OnDestroy.
65// Derived classes build or receive a shared immutable BTTree in CreateTree().
66class BTScriptController : public Script {
67public:
68 void OnCreate() final {
69 m_Instance.reset();
70 auto tree = CreateTree();
71 if (!tree) throw std::runtime_error("BTScriptController: CreateTree returned null");
72 m_Instance = std::make_unique<BTInstance>(std::move(tree));
73 auto& ctx = m_Instance->Context();
74 ctx.BindScript(this);
75 m_BlackboardPrevious.clear();
76 m_BlackboardChanges.clear();
77 m_DebugTick = 0;
78 OnTreeStarted(ctx);
79 CaptureDebugSnapshot();
80 }
81
82 void OnUpdate(float deltaTime) final {
83 if (m_Instance) {
84 m_LastStatus = m_Instance->Tick(deltaTime);
85 CaptureDebugSnapshot();
86 }
87 }
88
89 void OnDestroy() final {
90 if (!m_Instance) return;
91 // Reset nodes while the script/entity is still valid.
92 m_Instance->Reset();
93 OnTreeStopped(m_Instance->Context());
94 m_BlackboardPrevious.clear();
95 m_BlackboardChanges.clear();
96 m_Instance->Context().UnbindScript();
97 m_Instance.reset();
98 m_DebugSnapshot = {};
99 }
100
101 // A copy of the last completed tick, safe to read without touching BTContext.
102 const BTDebugSnapshot& GetDebugSnapshot() const noexcept { return m_DebugSnapshot; }
103
104 BTInstance* GetBehaviorTreeInstance() noexcept { return m_Instance.get(); }
105 const BTInstance* GetBehaviorTreeInstance() const noexcept { return m_Instance.get(); }
106 BTStatus GetLastBehaviorTreeStatus() const noexcept { return m_LastStatus; }
107
108protected:
109 virtual std::shared_ptr<const BTTree> CreateTree() = 0;
110 virtual void OnTreeStarted(BTContext&) {}
111 virtual void OnTreeStopped(BTContext&) {}
112
113private:
114 void CaptureDebugSnapshot() {
115 if (!m_Instance) return;
116 BTDebugSnapshot next;
117 next.LastResult = static_cast<int>(m_LastStatus);
118 const auto& ctx = m_Instance->Context();
119 std::function<void(const BTNode&, int)> visit = [&](const BTNode& node, int depth) {
120 const auto status = ctx.LastStatuses().find(node.GetID());
121 const auto ticks = ctx.TickCounters().find(node.GetID());
122 next.Nodes.push_back({node.GetID(),
123 status == ctx.LastStatuses().end() ? -1 : status->second,
124 ticks == ctx.TickCounters().end() ? 0 : ticks->second,
125 node.DebugLabel(), depth, ctx.CurrentStatuses().contains(node.GetID())});
126 std::vector<const BTNode*> children;
127 node.CollectChildren(children);
128 for (const auto* child : children) if (child) visit(*child, depth + 1);
129 };
130 visit(m_Instance->Tree().Root(), 0);
131 // Track the Blackboard by comparing value snapshots. This is independent
132 // of observer callbacks and survives frequent BT execution events.
133 const auto entries = ctx.Blackboard().DebugEntries();
134 std::unordered_map<std::string, std::string> now;
135 now.reserve(entries.size());
136 for (const auto& entry : entries)
137 now.emplace(entry.Key, entry.Value);
138 const auto& runtimeEvents = ctx.Events();
139 const std::uint64_t tick = runtimeEvents.empty() ? m_DebugTick : runtimeEvents.back().Tick;
140 auto record = [&](const std::string& key, const std::string& before, const std::string& after) {
141 m_BlackboardChanges.push_back({tick, 0, "Blackboard", key + ": " + before + " -> " + after});
142 constexpr std::size_t limit = 48;
143 if (m_BlackboardChanges.size() > limit)
144 m_BlackboardChanges.erase(m_BlackboardChanges.begin(),
145 m_BlackboardChanges.begin() + (m_BlackboardChanges.size() - limit));
146 };
147 for (const auto& [key, value] : now) {
148 const auto it = m_BlackboardPrevious.find(key);
149 if (it == m_BlackboardPrevious.end()) record(key, "<unset>", value);
150 else if (it->second != value) record(key, it->second, value);
151 }
152 for (const auto& [key, value] : m_BlackboardPrevious)
153 if (!now.contains(key)) record(key, value, "<removed>");
154 m_BlackboardPrevious = std::move(now);
155 ++m_DebugTick;
156 for (const auto& event : ctx.Events())
157 next.Events.push_back({event.Tick, event.Node, event.Kind, event.Detail});
158 // Merge the separate per-agent Blackboard history for the timeline.
159 // Keep BT execution events intact and order changes by tick.
160 next.Events.insert(next.Events.end(), m_BlackboardChanges.begin(), m_BlackboardChanges.end());
161 std::stable_sort(next.Events.begin(), next.Events.end(),
162 [](const BTDebugSnapshot::Event& a, const BTDebugSnapshot::Event& b) {
163 return a.Tick < b.Tick;
164 });
165 next.BlackboardEntries = entries;
166 next.BlackboardRevision = ctx.Blackboard().Revision();
167 if (const auto* target = ctx.Blackboard().TryGet<std::uint32_t>("TargetHandle"))
168 next.TargetHandle = *target;
169 if (const auto* position = ctx.Blackboard().TryGet<glm::vec3>("TargetPosition"))
170 next.TargetPosition = *position;
171 m_DebugSnapshot = std::move(next);
172 }
173 std::uint64_t m_DebugTick = 0;
174 std::unordered_map<std::string, std::string> m_BlackboardPrevious;
175 std::vector<BTDebugSnapshot::Event> m_BlackboardChanges;
176 BTDebugSnapshot m_DebugSnapshot;
177 std::unique_ptr<BTInstance> m_Instance;
178 BTStatus m_LastStatus = BTStatus::Failure;
179};
180} // namespace NoJob
BTInstance declarations for the Behavior Trees subsystem.
Registry for native behavior tree callbacks.
Native gameplay script lifecycle and diagnostic interfaces.
void RegisterCondition(std::string name, Condition callback)
void RegisterAction(std::string name, Action callback)
Base class for behavior tree nodes with stable node identifiers.
Definition BTNode.h:15
BTNodeID GetID() const
Definition BTNode.h:21
virtual std::string DebugLabel() const
Definition BTNode.h:22
virtual void CollectChildren(std::vector< const BTNode * > &) const
Definition BTNode.h:29
BTStatus GetLastBehaviorTreeStatus() const noexcept
void OnUpdate(float deltaTime) final
Called during scene updates.
const BTInstance * GetBehaviorTreeInstance() const noexcept
virtual std::shared_ptr< const BTTree > CreateTree()=0
const BTDebugSnapshot & GetDebugSnapshot() const noexcept
void OnCreate() final
Called when the runtime script instance is created.
void OnDestroy() final
Called before the runtime script instance is destroyed.
BTInstance * GetBehaviorTreeInstance() noexcept
virtual void OnTreeStopped(BTContext &)
virtual void OnTreeStarted(BTContext &)
Base class for native gameplay scripts instantiated while a scene runs.
void BTRegisterScriptCondition(BTNativeRegistry &registry, std::string conditionName, std::string scriptName, bool(T::*method)(BTContext &))
ScriptableEntity Script
BTStatus
Result of a behavior tree node tick.
Definition BTNode.h:13
ScriptableEntity * BTGetScript(BTContext &context) noexcept
void BTRegisterScriptAction(BTNativeRegistry &registry, std::string actionName, std::string scriptName, BTStatus(T::*method)(BTContext &, float))
std::uint64_t BlackboardRevision
std::optional< glm::vec3 > TargetPosition
std::vector< Event > Events
std::vector< Node > Nodes
std::vector< BTBlackboard::DebugEntry > BlackboardEntries
std::optional< std::uint32_t > TargetHandle