NoJobEngine 2.0.7
Loading...
Searching...
No Matches
BTGameplay.h
Go to the documentation of this file.
1
6#pragma once
7#include "BTAsset.h"
8#include "BTAssetPaths.h"
9#include "BTScriptBridge.h"
13#include <optional>
14#include <glm/glm.hpp>
15#include <cmath>
16#include <algorithm>
17#include <cstdint>
18
19namespace NoJob {
20inline std::shared_ptr<BTNativeRegistry> CreateBTGameplayRegistry() {
21 auto r = std::make_shared<BTNativeRegistry>();
22 r->RegisterCondition("CanSeeTarget", [](BTContext& ctx) {
23 auto* s=BTGetScript(ctx);
24 if (!s || !s->GetEntity().GetScene()) return false;
25 const auto targets=s->GetEntity().GetScene()->GetPerceivedTargets(s->GetEntity().GetHandle());
26 for (const auto& target : targets) if (target.IsVisible) {
27 ctx.Blackboard().Set("TargetHandle", target.EntityHandle);
28 ctx.Blackboard().Set("TargetPosition", target.LastKnownPosition);
29 return true;
30 }
31 return false;
32 });
33 r->RegisterCondition("HasRememberedTarget", [](BTContext& ctx) {
34 auto* s=BTGetScript(ctx);
35 if (!s || !s->GetEntity().GetScene()) return false;
36 auto last=s->GetEntity().GetScene()->GetLastSeenTarget(s->GetEntity().GetHandle());
37 if (!last) return false;
38 ctx.Blackboard().Set("TargetPosition",last->Position);
39 return true;
40 });
41 r->RegisterAction("ChaseTarget", [](BTContext& ctx, float) {
42 auto* script = BTGetScript(ctx);
43 if (!script || !script->HasComponent<NavAgentComponent>() ||
44 !script->HasComponent<TransformComponent>()) return BTStatus::Failure;
45 const auto entity = script->GetEntity();
46 auto* scene = entity.GetScene();
47 if (!scene) return BTStatus::Failure;
48 auto& nav = script->GetComponent<NavAgentComponent>();
49 if (!nav.Enabled) return BTStatus::Failure;
50
51 // A running Sequence does not re-evaluate CanSeeTarget. Refresh the
52 // moving target here, otherwise the Blackboard position goes stale.
53 glm::vec3 destination{};
54 bool hasDestination = false;
55 if (const auto* handle = ctx.Blackboard().TryGet<std::uint32_t>("TargetHandle")) {
56 if (scene->IsValid(*handle)) {
57 for (const auto& perceived : scene->GetPerceivedTargets(entity.GetHandle())) {
58 if (perceived.EntityHandle == *handle && perceived.IsVisible) {
59 destination = perceived.LastKnownPosition;
60 ctx.Blackboard().Set("TargetPosition", destination);
61 hasDestination = true;
62 break;
63 }
64 }
65 }
66 }
67 // Continue to the last known position when the target is not visible.
68 if (!hasDestination) {
69 if (const auto* last = ctx.Blackboard().TryGet<glm::vec3>("TargetPosition")) {
70 destination = *last;
71 hasDestination = true;
72 }
73 }
74 if (!hasDestination) return BTStatus::Failure;
75
76 const glm::vec3 current = glm::vec3(scene->GetWorldTransform(entity)[3]);
77 glm::vec3 delta = destination - current;
78 delta.y = 0.0f;
79 const float stoppingDistance = std::max(nav.StoppingDistance, 0.05f);
80 if (glm::dot(delta, delta) <= stoppingDistance * stoppingDistance) {
81 nav.HasDestination = false;
82 return BTStatus::Success;
83 }
84
85 // Scene's navigation update detects changed destinations and repaths.
86 // Re-arm navigation even if it finished the previous destination.
87 nav.Destination = destination;
88 nav.HasDestination = true;
89 ctx.SetCancellation(ctx.ActiveNode(), [](BTContext& c) {
90 if (auto* owner = BTGetScript(c); owner && owner->HasComponent<NavAgentComponent>())
91 owner->GetComponent<NavAgentComponent>().HasDestination = false;
92 });
93 return BTStatus::Running;
94 });
95 // Native patrol task: four waypoints around the agent's spawn point.
96 // Runtime progress is stored per agent in the Blackboard.
97 r->RegisterAction("Patrol", [](BTContext& ctx, float dt) {
98 auto* script = BTGetScript(ctx);
99 if (!script || !script->HasComponent<NavAgentComponent>() ||
100 !script->HasComponent<TransformComponent>()) return BTStatus::Failure;
101 auto* scene = script->GetEntity().GetScene();
102 if (!scene) return BTStatus::Failure;
103 auto& nav = script->GetComponent<NavAgentComponent>();
104 if (!nav.Enabled) return BTStatus::Failure;
105 const glm::vec3 position = glm::vec3(scene->GetWorldTransform(script->GetEntity())[3]);
106 auto& bb = ctx.Blackboard();
107 if (!bb.Contains("PatrolOrigin")) bb.Set("PatrolOrigin", position);
108 const glm::vec3 origin = bb.Get<glm::vec3>("PatrolOrigin");
109 const float radius = std::max(bb.GetOr<float>("PatrolRadius", 3.f), 0.25f);
110 const float pause = std::max(bb.GetOr<float>("PatrolWaitSeconds", 0.4f), 0.f);
111 int index = bb.GetOr<int>("PatrolIndex", 0) % 4;
112 if (index < 0) index += 4;
113 const glm::vec3 offsets[4] = {
114 {radius,0.f,0.f}, {radius,0.f,radius}, {0.f,0.f,radius}, {0.f,0.f,0.f}
115 };
116 const glm::vec3 destination = origin + offsets[index];
117 glm::vec3 difference = destination - position;
118 difference.y = 0.f;
119 const float stoppingDistance = std::max(nav.StoppingDistance, 0.15f);
120 if (glm::dot(difference,difference) <= stoppingDistance*stoppingDistance) {
121 nav.HasDestination = false;
122 const float elapsed = bb.GetOr<float>("PatrolWaitElapsed", 0.f) + std::max(dt,0.f);
123 if (elapsed >= pause) {
124 bb.Set("PatrolIndex", (index+1)%4);
125 bb.Set("PatrolWaitElapsed", 0.f);
126 } else bb.Set("PatrolWaitElapsed", elapsed);
127 } else {
128 bb.Set("PatrolWaitElapsed", 0.f);
129 nav.Destination = destination;
130 nav.HasDestination = true;
131 }
132 ctx.SetCancellation(ctx.ActiveNode(), [](BTContext& c) {
133 if (auto* owner = BTGetScript(c); owner && owner->HasComponent<NavAgentComponent>())
134 owner->GetComponent<NavAgentComponent>().HasDestination = false;
135 });
136 return BTStatus::Running;
137 });
138 r->RegisterAction("StopMoving", [](BTContext& ctx,float) {
139 auto* s=BTGetScript(ctx);
140 if (!s || !s->HasComponent<NavAgentComponent>()) return BTStatus::Failure;
141 s->GetComponent<NavAgentComponent>().HasDestination=false;
142 return BTStatus::Success;
143 });
144 r->RegisterAction("MoveForward", [](BTContext& ctx,float dt) {
145 auto* s=BTGetScript(ctx);
146 if (!s || !s->HasComponent<TransformComponent>()) return BTStatus::Failure;
147 s->GetComponent<TransformComponent>().Position.x += dt;
148 return BTStatus::Running;
149 });
150 return r;
151}
152// Shared immutable tree asset; each script instance owns its own BT runtime and Blackboard.
153class BTAssetAgent final : public BTScriptController {
154public:
155 std::string BehaviorTreeAsset = "Default";
156 float PatrolRadius = 3.0f;
157 float PatrolWaitSeconds = 0.4f;
158 std::string NeuralModelName = "";
159 std::string NeuralTargetTag = "NeuralTarget";
160protected:
161 std::shared_ptr<const BTTree> CreateTree() override {
162 auto registry = CreateBTGameplayRegistry();
163 // V2.0.6: The BT owns navigation. Do not attach NeuralTrainingAgent to
164 // the same entity: two scripts writing NavAgent would compete.
165 registry->RegisterCondition("Neural.HasTarget", [this](BTContext& ctx) {
166 auto* scene = GetEntity().GetScene();
167 if (!scene) return false;
168 for (Entity target : scene->GetEntities()) {
169 if (target == GetEntity() || !target.HasComponent<TagComponent>() ||
170 !target.HasComponent<TransformComponent>() ||
171 target.GetComponent<TagComponent>().Tag != NeuralTargetTag) continue;
172 ctx.Blackboard().Set("NeuralTargetPosition", target.GetComponent<TransformComponent>().Position);
173 return true;
174 }
175 return false;
176 });
177 registry->RegisterAction("Neural.FollowTarget", [this](BTContext& ctx, float) {
180 if (!nav.Enabled) return BTStatus::Failure;
181 if (!m_NeuralModel) {
182 if (NeuralModelName.empty()) return BTStatus::Failure;
183 try {
184 m_NeuralModel.emplace(Neural::NeuralNetwork::Load(NeuralAssetPath(NeuralModelName).string()));
185 if (m_NeuralModel->Layers().front().Inputs() != 2 ||
186 m_NeuralModel->Layers().back().Outputs() != 2)
187 throw std::runtime_error("Neural.FollowTarget requires a 2->2 model");
188 } catch (const std::exception& e) {
189 std::fprintf(stderr, "[Neural BT] %s\n", e.what());
190 m_NeuralModel.reset();
191 return BTStatus::Failure;
192 }
193 }
194 auto* scene = GetEntity().GetScene();
195 if (!scene) return BTStatus::Failure;
196 glm::vec3 destination{};
197 bool found = false;
198 for (Entity target : scene->GetEntities()) {
199 if (target == GetEntity() || !target.HasComponent<TagComponent>() ||
200 !target.HasComponent<TransformComponent>() ||
201 target.GetComponent<TagComponent>().Tag != NeuralTargetTag) continue;
202 destination = target.GetComponent<TransformComponent>().Position;
203 found = true;
204 break;
205 }
206 if (!found) { nav.HasDestination = false; NeuralAgent::Clear(GetEntity().GetHandle()); return BTStatus::Failure; }
207 const glm::vec3 pos = GetComponent<TransformComponent>().Position;
208 const glm::vec3 delta = destination - pos;
209 const float distance = std::sqrt(delta.x*delta.x + delta.z*delta.z);
210 ctx.Blackboard().Set("NeuralTargetPosition", destination);
211 ctx.Blackboard().Set("NeuralTargetDistance", distance);
212 if (distance <= std::max(0.1f, nav.StoppingDistance)) {
213 nav.HasDestination = false;
214 return BTStatus::Success;
215 }
216 const std::vector<float> inputs{std::clamp(delta.x / 10.f, -1.f, 1.f),
217 std::clamp(delta.z / 10.f, -1.f, 1.f)};
218 const auto outputs = m_NeuralModel->Predict(inputs);
219 if (outputs.size() != 2 || !std::isfinite(outputs[0]) || !std::isfinite(outputs[1]))
220 return BTStatus::Failure;
221 const glm::vec3 direction(outputs[0], 0.f, outputs[1]);
222 const float magnitude = std::sqrt(direction.x*direction.x + direction.z*direction.z);
223 if (magnitude < 0.05f) return BTStatus::Failure;
224 ctx.Blackboard().Set("NeuralInputX", inputs[0]);
225 ctx.Blackboard().Set("NeuralInputZ", inputs[1]);
226 ctx.Blackboard().Set("NeuralOutputX", outputs[0]);
227 ctx.Blackboard().Set("NeuralOutputZ", outputs[1]);
229 snap.model = NeuralModelName; snap.status = "BT Neural.FollowTarget";
230 snap.inputs = inputs; snap.outputs = outputs; snap.distance = distance;
231 snap.activations = NeuralAgent::Activations(*m_NeuralModel, inputs);
232 NeuralAgent::Publish(GetEntity().GetHandle(), std::move(snap));
233 nav.Destination = pos + direction / magnitude * std::min(distance, 3.f);
234 nav.HasDestination = true;
235 ctx.SetCancellation(ctx.ActiveNode(), [](BTContext& c) {
236 if (auto* owner = BTGetScript(c); owner && owner->HasComponent<NavAgentComponent>())
237 owner->GetComponent<NavAgentComponent>().HasDestination = false;
238 });
239 return BTStatus::Running;
240 });
241 // Bind callbacks from sibling Native Scripts before constructing the tree.
242 // Scene creates all script instances before calling OnCreate().
243 std::fprintf(stderr, "[BT TRACE] BTAssetAgent::CreateTree entity=%u before scene bindings\n", GetEntity().GetHandle());
244 std::fflush(stderr);
245 if (auto* scene = GetEntity().GetScene()) {
246 std::fprintf(stderr, "[BT TRACE] Scene pointer=%p; calling RegisterEntityBehaviorTreeBindings\n", static_cast<void*>(scene));
247 std::fflush(stderr);
248 scene->RegisterEntityBehaviorTreeBindings(GetEntity().GetHandle(), *registry);
249 } else {
250 std::fprintf(stderr, "[BT TRACE] ERROR: GetScene() returned nullptr\n");
251 }
252 std::fprintf(stderr, "[BT TRACE] BTAssetAgent::CreateTree after bindings: Guard.Attack=%d Guard.HasTarget=%d\n",
253 registry->HasAction("Guard.Attack") ? 1 : 0, registry->HasCondition("Guard.HasTarget") ? 1 : 0);
254 std::fflush(stderr);
255 std::fprintf(stderr, "[BT DIAG] BTAssetAgent entity %u tree '%s': Guard.Attack registered=%d\n",
256 GetEntity().GetHandle(), BehaviorTreeAsset.c_str(),
257 registry->HasAction("Guard.Attack") ? 1 : 0);
258 const auto btAsset = BTAsset::Load(BTAssetPath(BehaviorTreeAsset));
259 // Fail with actionable diagnostics rather than an opaque missing callback.
260 for (const auto& node : btAsset.Nodes) {
261 if (node.Kind == "Action" && !registry->HasAction(node.Native))
262 throw std::runtime_error("BT asset '" + BehaviorTreeAsset + "': action '" + node.Native +
263 "' is not registered for this entity. Check that its Native Script "
264 "(e.g. GuardCombatBT) is attached, enabled, and loaded in the project DLL.");
265 if (node.Kind == "Condition" && !registry->HasCondition(node.Native))
266 throw std::runtime_error("BT asset '" + BehaviorTreeAsset + "': condition '" + node.Native +
267 "' is not registered for this entity. Check Native Scripts and project DLL.");
268 }
269 return btAsset.Build(std::move(registry));
270 }
271 void OnTreeStarted(BTContext& ctx) override {
272 m_NeuralModel.reset();
273 NeuralAgent::Clear(GetEntity().GetHandle());
274 ctx.Blackboard().Set("PatrolRadius", PatrolRadius);
275 ctx.Blackboard().Set("PatrolWaitSeconds", PatrolWaitSeconds);
276 }
277 void OnTreeStopped(BTContext&) override { m_NeuralModel.reset(); NeuralAgent::Clear(GetEntity().GetHandle()); }
278private:
279 std::optional<Neural::NeuralNetwork> m_NeuralModel;
280};
281inline void RegisterBTAssetAgent() {
282 ScriptRegistry::Register({"BTAssetAgent", "AI",
287 MakeMemberFieldDefinition<BTAssetAgent, std::string>("NeuralTargetTag", &BTAssetAgent::NeuralTargetTag, std::string("NeuralTarget"))},
288 [] { return std::make_unique<BTAssetAgent>(); }});
289}
290} // namespace NoJob
BTAsset declarations for the Behavior Trees subsystem.
BTAssetPaths declarations for the Behavior Trees subsystem.
BTScriptBridge declarations for the Behavior Trees subsystem.
NavigationSystem declarations for the Navigation subsystem.
Supervised training presets and live neural diagnostics for gameplay agents.
Registration and creation of native gameplay scripts.
std::string NeuralTargetTag
Definition BTGameplay.h:159
std::shared_ptr< const BTTree > CreateTree() override
Definition BTGameplay.h:161
std::string BehaviorTreeAsset
Definition BTGameplay.h:155
void OnTreeStarted(BTContext &ctx) override
Definition BTGameplay.h:271
void OnTreeStopped(BTContext &) override
Definition BTGameplay.h:277
std::string NeuralModelName
Definition BTGameplay.h:158
static BTAsset Load(const std::filesystem::path &path)
Definition BTAsset.h:92
void Set(std::string key, T &&value)
const T * TryGet(std::string_view key) const
void SetCancellation(BTNodeID id, std::function< void(BTContext &)> fn)
Definition BTContext.h:59
BTBlackboard & Blackboard()
Definition BTContext.h:90
BTNodeID ActiveNode() const noexcept
Definition BTContext.h:57
bool HasComponent() const
Definition Scene.h:865
Scene * GetScene() const
Definition Entity.h:42
static NeuralNetwork Load(const std::string &path)
Loads a serialized network.
static void Register(ScriptDefinition definition)
std::vector< std::vector< float > > Activations(const Neural::NeuralNetwork &net, const std::vector< float > &input)
void Clear(unsigned int entity)
Removes diagnostics when an agent is destroyed or reset.
void Publish(unsigned int entity, Snapshot snapshot)
Publishes an entity snapshot for live AI debugging.
std::filesystem::path BTAssetPath(const std::string &name)
std::shared_ptr< BTNativeRegistry > CreateBTGameplayRegistry()
Definition BTGameplay.h:20
void RegisterBTAssetAgent()
Definition BTGameplay.h:281
ScriptFieldDefinition MakeMemberFieldDefinition(const char *name, T TScript::*member, T defaultValue)
ScriptableEntity * BTGetScript(BTContext &context) noexcept
std::filesystem::path NeuralAssetPath(const std::string &name)
A copy of neural agent inference state for editor diagnostics.
std::vector< std::vector< float > > activations
std::string Tag
Definition Components.h:30