NoJobEngine 2.0.7
Loading...
Searching...
No Matches
NativeScripts.h
Go to the documentation of this file.
1
6#pragma once
8#include <cmath>
9#include <optional>
10#include <cstdio>
12#include <optional>
13#include <algorithm>
14#include <cstdio>
17
18namespace NoJob
19{
20 class Rotator final : public Script
21 {
22 public:
23 void OnUpdate(float deltaTime) override
24 {
26 t.Rotation += GetVec3("Axis", {0.0f,1.0f,0.0f}) * GetFloat("Speed",1.0f) * deltaTime;
27 }
28 };
29
30 class Oscillator final : public Script
31 {
32 public:
33 void OnCreate() override { m_Origin=GetComponent<TransformComponent>().Position; m_Time=0.0f; }
34 void OnUpdate(float deltaTime) override
35 {
36 m_Time += deltaTime;
38 const auto axis=GetVec3("Axis",{0.0f,1.0f,0.0f});
39 t.Position=m_Origin + axis * (std::sin(m_Time*GetFloat("Frequency",1.0f))*GetFloat("Amplitude",1.0f));
40 }
41 private:
42 glm::vec3 m_Origin{0.0f}; float m_Time=0.0f;
43 };
44
45 // V2.0.6 supervised learning example. Uses the existing NavAgent and a named .njn asset.
46 // Training is deterministic and runs once when Play starts if TrainOnPlay is enabled.
47 class NeuralTrainingAgent final : public Script
48 {
49 public:
50 void OnCreate() override
51 {
52 SetAIDebugState("Neural: initializing");
53 try
54 {
55 const auto& fields = ScriptComponent().Fields;
56 const auto it = fields.find("ModelName");
57 const std::string name = it != fields.end() &&
58 it->second.Type == ScriptFieldType::String ? it->second.String : "NeuralFollowerDemo";
59 const auto path = NeuralAssetPath(name);
60 if (GetBool("TrainOnPlay", false))
61 {
62 const std::string output = GetStringField("TrainingOutputName", "NeuralFollowerNew");
63 const std::string source = GetStringField("ResumeSourceName", "");
64 const auto history=NeuralAgent::TrainPreset(output, source, NeuralAgent::TrainingPreset::FollowXZ, GetInt("Epochs",1500), GetFloat("LearningRate",0.01f), GetBool("ResumeTraining",false), GetBool("OverwriteModel",false));
65 std::printf("[NeuralTrainingAgent] trained %s, final MSE %.8f\n", output.c_str(), history.epochLoss.empty()?0.f:history.epochLoss.back());
66 m_Model.emplace(Neural::NeuralNetwork::Load(NeuralAssetPath(output).string()));
67 }
68 else m_Model.emplace(NoJob::Neural::NeuralNetwork::Load(path.string()));
69 if (m_Model->Layers().front().Inputs()!=2 || m_Model->Layers().back().Outputs()!=2)
70 throw std::runtime_error("NeuralTrainingAgent requires a 2-input / 2-output model");
71 SetAIDebugState("Neural: ready");
72 }
73 catch (const std::exception& e)
74 {
75 std::fprintf(stderr,"[NeuralTrainingAgent] %s\n",e.what());
76 m_Model.reset();
77 SetAIDebugState("Neural: model error");
78 }
79 }
80 void OnDestroy() override { NeuralAgent::Clear(GetEntity().GetHandle()); }
81 void OnUpdate(float dt) override
82 {
83 TickAIDebug(dt);
84 if (!m_Model || !HasComponent<NavAgentComponent>()) return;
85 Scene* scene=GetEntity().GetScene();
86 if (!scene) return;
87 const auto& fields=ScriptComponent().Fields;
88 const auto it=fields.find("TargetTag");
89 const std::string targetTag=it!=fields.end() && it->second.Type==ScriptFieldType::String
90 ? it->second.String : "NeuralTarget";
91 const glm::vec3 pos=GetComponent<TransformComponent>().Position;
92 for (Entity target:scene->GetEntities())
93 {
94 if (target==GetEntity() || !target.HasComponent<TagComponent>() ||
95 target.GetComponent<TagComponent>().Tag!=targetTag) continue;
96 const glm::vec3 delta=target.GetComponent<TransformComponent>().Position-pos;
97 const float distance=std::sqrt(delta.x*delta.x+delta.z*delta.z);
99 if (distance < std::max(0.1f,nav.StoppingDistance))
100 {
101 nav.HasDestination=false;
102 SetAIDebugState("Neural: target reached");
103 return;
104 }
105 const std::vector<float> input{std::clamp(delta.x/10.f,-1.f,1.f),
106 std::clamp(delta.z/10.f,-1.f,1.f)};
107 const auto prediction=m_Model->Predict(input);
108 NeuralAgent::Snapshot snapshot;
109 snapshot.model=GetModelName(); snapshot.status="Inference";
110 snapshot.inputs=input; snapshot.outputs=prediction; snapshot.distance=distance;
111 snapshot.activations=NeuralAgent::Activations(*m_Model,input);
112 NeuralAgent::Publish(GetEntity().GetHandle(),std::move(snapshot));
113 if (prediction.size()!=2 || !std::isfinite(prediction[0]) || !std::isfinite(prediction[1]))
114 {
115 SetAIDebugState("Neural: invalid prediction");
116 return;
117 }
118 glm::vec3 direction(prediction[0],0.f,prediction[1]);
119 const float length=std::sqrt(direction.x*direction.x+direction.z*direction.z);
120 if (length<0.05f) { SetAIDebugState("Neural: no direction"); return; }
121 direction/=length;
122 // NavMesh pathfinding remains the responsibility of NavAgent.
123 nav.Destination=pos+direction*std::min(distance,3.f);
124 nav.HasDestination=true;
125 SetAIDebugState("Neural: following target");
126 return;
127 }
128 SetAIDebugState("Neural: target not found");
129 }
130 private:
131 std::string GetStringField(const char* key, const char* fallback) {
132 const auto& f=ScriptComponent().Fields; auto it=f.find(key);
133 return it!=f.end() && it->second.Type==ScriptFieldType::String ? it->second.String : fallback;
134 }
135 std::string GetModelName() {
136 const auto& fields=ScriptComponent().Fields;
137 auto it=fields.find("ModelName");
138 return it!=fields.end() && it->second.Type==ScriptFieldType::String ? it->second.String : "NeuralFollowerDemo";
139 }
140 std::optional<NoJob::Neural::NeuralNetwork> m_Model;
141 };
142
143 // Configurable neural agent: observation/action bindings are editor properties,
144 // independent of Behavior Trees and of the navigation system.
145 // ObservationPreset: 0 = relative XZ, 1 = target Y/self Y/delta Y,
146 // 2 = Pong (target X/Y, target velocity X/Y, self Y, horizontal distance).
147 // ActionMode: 0 = NavAgent XZ, 1 = Transform Y, 2 = Transform XZ.
148 class GenericNeuralAgent final : public Script {
149 public:
150 void OnCreate() override {
151 m_Model.reset(); m_HasPrevious=false;
152 const std::string name=GetStringField("ActiveModel");
153 try {
154 if (name.empty()) throw std::runtime_error("Select an ActiveModel");
155 m_Model.emplace(Neural::NeuralNetwork::Load(NeuralAssetPath(name).string()));
156 const int preset=std::clamp(GetInt("ObservationPreset",0),0,2);
157 const size_t inputs=preset==0?2:(preset==1?3:6);
158 const size_t outputs=preset==0?2:1;
159 if(m_Model->Layers().empty() || m_Model->Layers().front().Inputs()!=inputs ||
160 m_Model->Layers().back().Outputs()!=outputs)
161 throw std::runtime_error("Model input/output dimensions do not match ObservationPreset");
162 SetAIDebugState("Neural: ready");
163 } catch(const std::exception& e) {
164 std::fprintf(stderr,"[GenericNeuralAgent] %s\n",e.what());
165 SetAIDebugState("Neural: model error"); m_Model.reset();
166 }
167 }
168 void OnDestroy() override { NeuralAgent::Clear(GetEntity().GetHandle()); }
169 void OnUpdate(float dt) override {
170 TickAIDebug(dt);
171 if(!m_Model || dt<=0.f || !HasComponent<TransformComponent>()) return;
172 auto* scene=GetEntity().GetScene(); if(!scene) return;
173 const auto tag=GetStringField("TargetTag");
174 Entity target{};
175 for(Entity e:scene->GetEntities()) {
176 if(e==GetEntity() || !e.HasComponent<TagComponent>() || !e.HasComponent<TransformComponent>()) continue;
177 if(e.GetComponent<TagComponent>().Tag==tag) { target=e; break; }
178 }
179 if(!target) { SetAIDebugState("Neural: target missing"); NeuralAgent::Clear(GetEntity().GetHandle()); return; }
181 const glm::vec3 pos=own.Position;
182 const glm::vec3 tp=target.GetComponent<TransformComponent>().Position;
183 const glm::vec3 delta=tp-pos;
184 const float scale=std::max(0.01f,GetFloat("ObservationScale",10.f));
185 const int preset=std::clamp(GetInt("ObservationPreset",0),0,2);
186 const int action=std::clamp(GetInt("ActionMode",0),0,2);
187 std::vector<float> inputs;
188 if(preset==0) {
189 inputs={std::clamp(delta.x/scale,-1.f,1.f),std::clamp(delta.z/scale,-1.f,1.f)};
190 } else if(preset==1) {
191 inputs={std::clamp(tp.y/scale,-1.f,1.f),std::clamp(pos.y/scale,-1.f,1.f),
192 std::clamp(delta.y/scale,-1.f,1.f)};
193 } else {
194 const glm::vec3 velocity=m_HasPrevious ? (tp-m_PreviousTarget)/dt : glm::vec3(0.f);
195 inputs={std::clamp(tp.x/scale,-1.f,1.f),std::clamp(tp.y/scale,-1.f,1.f),
196 std::clamp(velocity.x/scale,-1.f,1.f),std::clamp(velocity.y/scale,-1.f,1.f),
197 std::clamp(pos.y/scale,-1.f,1.f),std::clamp(std::abs(delta.x)/scale,0.f,1.f)};
198 }
199 m_PreviousTarget=tp; m_HasPrevious=true;
200 try {
201 const auto outputs=m_Model->Predict(inputs);
202 if(outputs.size()!=(preset==0?2u:1u)) return;
203 for(float x:outputs) if(!std::isfinite(x)) return;
205 snap.model=GetStringField("ActiveModel"); snap.status="Generic neural inference";
206 snap.inputs=inputs; snap.outputs=outputs; snap.distance=glm::length(delta);
207 snap.activations=NeuralAgent::Activations(*m_Model,inputs);
208 NeuralAgent::Publish(GetEntity().GetHandle(),std::move(snap));
209 const float speed=std::max(0.f,GetFloat("MovementSpeed",3.f));
210 if(action==0) {
211 if(outputs.size()!=2 || !HasComponent<NavAgentComponent>()) return;
213 if(!nav.Enabled) return;
214 const glm::vec3 direction(outputs[0],0.f,outputs[1]);
215 const float length=glm::length(direction);
216 if(length<0.05f) {nav.HasDestination=false;return;}
217 nav.Destination=pos+(direction/length)*std::min(glm::length(delta),3.f);
218 nav.HasDestination=true;
219 } else if(action==1) {
220 if(outputs.size()!=1) return;
221 own.Position.y+=std::clamp(outputs[0],-1.f,1.f)*speed*dt;
222 } else {
223 if(outputs.size()!=2) return;
224 own.Position.x+=std::clamp(outputs[0],-1.f,1.f)*speed*dt;
225 own.Position.z+=std::clamp(outputs[1],-1.f,1.f)*speed*dt;
226 }
227 SetAIDebugState("Neural: inference active");
228 } catch(const std::exception& e) {
229 std::fprintf(stderr,"[GenericNeuralAgent] Inference: %s\n",e.what());
230 SetAIDebugState("Neural: inference error");
231 }
232 }
233 private:
234 std::string GetStringField(const char* key) {
235 const auto& fields=ScriptComponent().Fields;
236 const auto it=fields.find(key);
237 return it!=fields.end() && it->second.Type==ScriptFieldType::String?it->second.String:std::string{};
238 }
239 std::optional<Neural::NeuralNetwork> m_Model;
240 glm::vec3 m_PreviousTarget{0.f}; bool m_HasPrevious=false;
241 };
242
243 // Simple editor demo ball. No NavMesh required; this is a tracking example,
244 // not a complete scored Pong game with paddle collision rules.
245 class PongBallDemo final : public Script {
246 public:
247 void OnUpdate(float dt) override {
249 t.Position.x+=m_Direction.x*GetFloat("Speed",4.f)*dt;
250 t.Position.y+=m_Direction.y*GetFloat("Speed",4.f)*dt;
251 const float boundX=std::max(1.f,GetFloat("BoundX",8.f));
252 const float boundY=std::max(1.f,GetFloat("BoundY",4.f));
253 if(t.Position.x>boundX) {t.Position.x=boundX;m_Direction.x=-std::abs(m_Direction.x);}
254 if(t.Position.x< -boundX) {t.Position.x=-boundX;m_Direction.x=std::abs(m_Direction.x);}
255 if(t.Position.y>boundY) {t.Position.y=boundY;m_Direction.y=-std::abs(m_Direction.y);}
256 if(t.Position.y< -boundY) {t.Position.y=-boundY;m_Direction.y=std::abs(m_Direction.y);}
257 }
258 private:
259 glm::vec3 m_Direction{.83f,.56f,0.f};
260 };
261
263 {
264 static bool registered=false; if(registered) return; registered=true;
265 ScriptRegistry::Register({"Rotator","Transform",{
266 {"Speed",ScriptFieldValue::MakeFloat(1.0f)},
267 {"Axis",ScriptFieldValue::MakeVec3({0.0f,1.0f,0.0f})}},
268 []{return std::make_unique<Rotator>();}});
269 ScriptRegistry::Register({"NeuralTrainingAgent","AI / Neural",{
270 {"ModelName",ScriptFieldValue::MakeString("NeuralFollowerDemo")},
271 {"TargetTag",ScriptFieldValue::MakeString("NeuralTarget")},
272 {"TrainingOutputName",ScriptFieldValue::MakeString("NeuralFollowerNew")},
273 {"ResumeSourceName",ScriptFieldValue::MakeString("")},
274 {"TrainingPreset",ScriptFieldValue::MakeInt(0)},
275 {"TrainOnPlay",ScriptFieldValue::MakeBool(false)},
276 {"ResumeTraining",ScriptFieldValue::MakeBool(false)},
277 {"OverwriteModel",ScriptFieldValue::MakeBool(false)},
278 {"Epochs",ScriptFieldValue::MakeInt(1500)},
279 {"LearningRate",ScriptFieldValue::MakeFloat(0.01f)}},
280 []{return std::make_unique<NeuralTrainingAgent>();}});
281 ScriptRegistry::Register({"GenericNeuralAgent","AI / Neural",{
282 {"ActiveModel",ScriptFieldValue::MakeString("")},
283 {"TargetTag",ScriptFieldValue::MakeString("NeuralTarget")},
284 {"ObservationPreset",ScriptFieldValue::MakeInt(0)},
285 {"ActionMode",ScriptFieldValue::MakeInt(0)},
286 {"ObservationScale",ScriptFieldValue::MakeFloat(10.f)},
287 {"MovementSpeed",ScriptFieldValue::MakeFloat(3.f)},
288 {"TrainingOutputName",ScriptFieldValue::MakeString("NewNeuralModel")},
289 {"ResumeSourceName",ScriptFieldValue::MakeString("")},
290 {"TrainingPreset",ScriptFieldValue::MakeInt(0)},
291 {"ResumeTraining",ScriptFieldValue::MakeBool(false)},
292 {"OverwriteModel",ScriptFieldValue::MakeBool(false)},
293 {"Epochs",ScriptFieldValue::MakeInt(1500)},
294 {"LearningRate",ScriptFieldValue::MakeFloat(0.01f)}},
295 []{return std::make_unique<GenericNeuralAgent>();}});
296 ScriptRegistry::Register({"PongBallDemo","AI / Neural",{
297 {"Speed",ScriptFieldValue::MakeFloat(4.f)},
298 {"BoundX",ScriptFieldValue::MakeFloat(8.f)},
299 {"BoundY",ScriptFieldValue::MakeFloat(4.f)}},
300 []{return std::make_unique<PongBallDemo>();}});
301 ScriptRegistry::Register({"Oscillator","Transform",{
302 {"Amplitude",ScriptFieldValue::MakeFloat(1.0f)},
303 {"Frequency",ScriptFieldValue::MakeFloat(1.0f)},
304 {"Axis",ScriptFieldValue::MakeVec3({0.0f,1.0f,0.0f})}},
305 []{return std::make_unique<Oscillator>();}});
306 }
307}
Supervised training presets and live neural diagnostics for gameplay agents.
Path resolution and validation for neural model assets.
Dense neural network inference, training and serialization.
Registration and creation of native gameplay scripts.
T & GetComponent()
Definition Scene.h:851
bool HasComponent() const
Definition Scene.h:865
Scene * GetScene() const
Definition Entity.h:42
void OnCreate() override
Called when the runtime script instance is created.
void OnUpdate(float dt) override
Called during scene updates.
void OnDestroy() override
Called before the runtime script instance is destroyed.
static NeuralNetwork Load(const std::string &path)
Loads a serialized network.
void OnCreate() override
Called when the runtime script instance is created.
void OnDestroy() override
Called before the runtime script instance is destroyed.
void OnUpdate(float dt) override
Called during scene updates.
void OnUpdate(float deltaTime) override
Called during scene updates.
void OnCreate() override
Called when the runtime script instance is created.
void OnUpdate(float dt) override
Called during scene updates.
void OnUpdate(float deltaTime) override
Called during scene updates.
std::vector< Entity > GetEntities()
Definition Scene.cpp:231
static void Register(ScriptDefinition definition)
NativeScriptComponent & ScriptComponent()
void SetAIDebugState(const char *state)
int GetInt(const std::string &name, int fallback=0) const
glm::vec3 GetVec3(const std::string &name, glm::vec3 fallback={}) const
float GetFloat(const std::string &name, float fallback=0.0f) const
bool GetBool(const std::string &name, bool fallback=false) const
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.
Neural::TrainingHistory TrainPreset(const std::string &outputName, const std::string &sourceName, TrainingPreset preset, int epochs, float learningRate, bool resume, bool overwrite)
Trains a preset model and saves it independently of the active model.
void RegisterBuiltinScripts()
ScriptableEntity Script
std::filesystem::path NeuralAssetPath(const std::string &name)
std::unordered_map< std::string, ScriptFieldValue > Fields
Definition Components.h:319
A copy of neural agent inference state for editor diagnostics.
std::vector< std::vector< float > > activations
static ScriptFieldValue MakeInt(int value)
Definition Components.h:309
static ScriptFieldValue MakeBool(bool value)
Definition Components.h:310
static ScriptFieldValue MakeFloat(float value)
Definition Components.h:308
static ScriptFieldValue MakeString(std::string value)
Definition Components.h:311
static ScriptFieldValue MakeVec3(glm::vec3 value)
Definition Components.h:312
std::string Tag
Definition Components.h:30