NoJobEngine 2.0.7
Loading...
Searching...
No Matches
EditorLayer.cpp
Go to the documentation of this file.
13
19#include "Engine/Scene/Scene.h"
28
29#ifdef _WIN32
30#define NOMINMAX
31#include <Windows.h>
32#include <commdlg.h>
33#endif
34
35#include <imgui.h>
36#include <imgui_internal.h>
37#include <backends/imgui_impl_glfw.h>
38#include <backends/imgui_impl_opengl3.h>
39
40#include <GLFW/glfw3.h>
41#include <ImGuizmo.h>
42#include <glm/gtc/type_ptr.hpp>
43#include <glm/gtc/constants.hpp>
44
45#include <algorithm>
46#include <cmath>
47#include <cstdint>
48#include <cstring>
49#include <string>
50#include <filesystem>
51#include <fstream>
52#include <iterator>
53#include <vector>
54#include <cstdio>
55#include <cstdlib>
56#include <sstream>
57#include <unordered_map>
58#include <functional>
59#include <iomanip>
60#include <atomic>
61#include <mutex>
62#include <thread>
63
64#ifdef _WIN32
65#include <cctype>
66#endif
67
68namespace NoJob
69{
70 // Set during Init when there is no valid saved docking tree.
71 // DockSpaceOverViewport itself creates a root node, so checking for a node
72 // after that call cannot tell us whether a saved layout existed.
73 static bool s_BuildDefaultDockLayout = false;
74 static bool s_ShowBTAssetEditor = false;
75 static void DrawBTAssetEditorWindow(bool* opened);
76 namespace
77 {
78#ifdef _WIN32
79 std::vector<std::string> s_ScriptConsole;
80 std::mutex s_ScriptConsoleMutex;
81 bool s_ScriptsCompiled = false;
82 std::thread s_StandaloneBuildThread;
83 std::atomic_bool s_StandaloneBuildRunning{ false };
84 std::atomic_bool s_StandaloneBuildSucceeded{ false };
85 std::filesystem::path s_LastStandaloneBuildDirectory;
86 BuildSettings s_BuildSettings;
87 bool s_ShowBuildSettings = false;
88 char s_BuildNameBuffer[128]{};
89
90 void ScriptLog(std::string message)
91 {
92 std::lock_guard<std::mutex> lock(s_ScriptConsoleMutex);
93 s_ScriptConsole.push_back(std::move(message));
94 }
95
96 void ClearScriptLog()
97 {
98 std::lock_guard<std::mutex> lock(s_ScriptConsoleMutex);
99 s_ScriptConsole.clear();
100 }
101
102 std::filesystem::path FindCMakeExecutable()
103 {
104#ifdef _WIN32
105 wchar_t pathBuffer[32768]{};
106 const DWORD found = SearchPathW(nullptr, L"cmake.exe", nullptr,
107 static_cast<DWORD>(std::size(pathBuffer)), pathBuffer, nullptr);
108 if (found > 0 && found < std::size(pathBuffer))
109 return std::filesystem::path(pathBuffer);
110
111 wchar_t* programFilesX86 = nullptr;
112 std::size_t envLength = 0;
113 if (_wdupenv_s(&programFilesX86, &envLength, L"ProgramFiles(x86)") == 0 &&
114 programFilesX86)
115 {
116 const std::filesystem::path vswhere =
117 std::filesystem::path(programFilesX86) /
118 "Microsoft Visual Studio" / "Installer" / "vswhere.exe";
119 free(programFilesX86);
120
121 if (std::filesystem::exists(vswhere))
122 {
123 const std::wstring command =
124 L"\"" + vswhere.wstring() +
125 L"\" -latest -products * -property installationPath";
126 FILE* pipe = _wpopen(command.c_str(), L"rt");
127 if (pipe)
128 {
129 wchar_t buffer[4096]{};
130 std::wstring installPath;
131 if (fgetws(buffer, static_cast<int>(std::size(buffer)), pipe))
132 installPath = buffer;
133 _pclose(pipe);
134 while (!installPath.empty() &&
135 (installPath.back() == L'\r' || installPath.back() == L'\n' ||
136 installPath.back() == L' ' || installPath.back() == L'\t'))
137 installPath.pop_back();
138
139 if (!installPath.empty())
140 {
141 const auto bundled = std::filesystem::path(installPath) /
142 "Common7" / "IDE" / "CommonExtensions" /
143 "Microsoft" / "CMake" / "CMake" / "bin" / "cmake.exe";
144 if (std::filesystem::exists(bundled)) return bundled;
145 }
146 }
147 }
148 }
149
150 wchar_t* programFiles = nullptr;
151 envLength = 0;
152 if (_wdupenv_s(&programFiles, &envLength, L"ProgramFiles") == 0 &&
153 programFiles)
154 {
155 const auto standalone = std::filesystem::path(programFiles) /
156 "CMake" / "bin" / "cmake.exe";
157 free(programFiles);
158 if (std::filesystem::exists(standalone)) return standalone;
159 }
160#endif
161 return {};
162 }
163
164 int RunProcessToScriptConsole(
165 const std::filesystem::path& executable,
166 const std::vector<std::wstring>& arguments,
167 const std::string& prefix)
168 {
169#ifdef _WIN32
170 SECURITY_ATTRIBUTES security{};
171 security.nLength = sizeof(SECURITY_ATTRIBUTES);
172 security.bInheritHandle = TRUE;
173
174 HANDLE readPipe = nullptr;
175 HANDLE writePipe = nullptr;
176 if (!CreatePipe(&readPipe, &writePipe, &security, 0))
177 {
178 ScriptLog("[Scripts] CreatePipe failed.");
179 return -1;
180 }
181
182 SetHandleInformation(readPipe, HANDLE_FLAG_INHERIT, 0);
183
184 std::wstring commandLine = L"\"" + executable.wstring() + L"\"";
185 for (const auto& arg : arguments)
186 {
187 commandLine += L" \"";
188 for (wchar_t c : arg)
189 {
190 if (c == L'"')
191 commandLine += L'\\';
192 commandLine += c;
193 }
194 commandLine += L"\"";
195 }
196
197 STARTUPINFOW startup{};
198 startup.cb = sizeof(STARTUPINFOW);
199 startup.dwFlags = STARTF_USESTDHANDLES;
200 startup.hStdOutput = writePipe;
201 startup.hStdError = writePipe;
202 startup.hStdInput = GetStdHandle(STD_INPUT_HANDLE);
203
204 PROCESS_INFORMATION process{};
205 std::vector<wchar_t> mutableCommand(
206 commandLine.begin(), commandLine.end());
207 mutableCommand.push_back(L'\0');
208
209 const std::wstring workingDirectory =
211
212 const BOOL created = CreateProcessW(
213 executable.wstring().c_str(),
214 mutableCommand.data(),
215 nullptr,
216 nullptr,
217 TRUE,
218 CREATE_NO_WINDOW,
219 nullptr,
220 workingDirectory.c_str(),
221 &startup,
222 &process);
223
224 CloseHandle(writePipe);
225
226 if (!created)
227 {
228 const DWORD error = GetLastError();
229 CloseHandle(readPipe);
230 ScriptLog(
231 "[Scripts] CreateProcess failed (Win32 error " +
232 std::to_string(error) + ").");
233 return -1;
234 }
235
236 std::string pending;
237 char buffer[2048];
238 DWORD bytesRead = 0;
239 while (ReadFile(
240 readPipe,
241 buffer,
242 static_cast<DWORD>(sizeof(buffer)),
243 &bytesRead,
244 nullptr) &&
245 bytesRead > 0)
246 {
247 pending.append(buffer, buffer + bytesRead);
248
249 std::size_t newline = 0;
250 while ((newline = pending.find('\n')) != std::string::npos)
251 {
252 std::string line = pending.substr(0, newline);
253 pending.erase(0, newline + 1);
254 if (!line.empty() && line.back() == '\r')
255 line.pop_back();
256 if (!line.empty())
257 ScriptLog(prefix + line);
258 }
259 }
260
261 if (!pending.empty())
262 {
263 if (!pending.empty() && pending.back() == '\r')
264 pending.pop_back();
265 if (!pending.empty())
266 ScriptLog(prefix + pending);
267 }
268
269 WaitForSingleObject(process.hProcess, INFINITE);
270
271 DWORD exitCode = 1;
272 GetExitCodeProcess(process.hProcess, &exitCode);
273
274 CloseHandle(process.hThread);
275 CloseHandle(process.hProcess);
276 CloseHandle(readPipe);
277
278 return static_cast<int>(exitCode);
279#else
280 (void)executable;
281 (void)arguments;
282 (void)prefix;
283 return -1;
284#endif
285 }
286
287 bool BuildStandalone()
288 {
289 if (s_StandaloneBuildRunning.exchange(true))
290 {
291 ScriptLog("[Build] Standalone build is already running.");
292 return false;
293 }
294
295 const auto root = AssetManager::GetProjectRoot();
296 const auto cmake = FindCMakeExecutable();
297 if (cmake.empty())
298 {
299 ScriptLog("[Build] CMake was not found.");
300 s_StandaloneBuildRunning = false;
301 return false;
302 }
303
304 s_StandaloneBuildSucceeded = false;
305 if (s_StandaloneBuildThread.joinable())
306 s_StandaloneBuildThread.join();
307
308 const BuildSettings settings = s_BuildSettings;
309 s_StandaloneBuildThread = std::thread([root, cmake, settings]()
310 {
311 const auto result = StandaloneBuilder::Build(
312 root,
313 cmake,
314 settings,
315 [](std::string message) { ScriptLog(std::move(message)); },
316 [](const std::filesystem::path& executable,
317 const std::vector<std::wstring>& arguments,
318 const std::string& prefix)
319 {
320 return RunProcessToScriptConsole(executable, arguments, prefix);
321 });
322
323 s_StandaloneBuildSucceeded = result.Succeeded;
324 if (result.Succeeded)
325 s_LastStandaloneBuildDirectory = result.OutputDirectory;
326 s_StandaloneBuildRunning = false;
327 });
328 return true;
329 }
330
331 bool CompileProjectScripts()
332 {
334 {
335 ScriptLog("[Scripts] Compilation is already running.");
336 return false;
337 }
338
339 // ScriptRegistry/DLL lifecycle remains on the editor thread.
341 ClearScriptLog();
342 ScriptLog("[Scripts] Starting asynchronous script compilation...");
344 }
345#endif
346
347 std::filesystem::path FindNoJobProjectRoot()
348 {
349 auto containsProject = [](const std::filesystem::path& directory)
350 {
351 std::error_code ec;
352 if (!std::filesystem::exists(directory, ec))
353 return false;
354
355 bool hasProjectFile = false;
356 for (const auto& entry :
357 std::filesystem::directory_iterator(
358 directory,
359 std::filesystem::directory_options::skip_permission_denied,
360 ec))
361 {
362 if (ec) break;
363 if (entry.is_regular_file() &&
364 entry.path().extension() == ".nojobproject")
365 {
366 hasProjectFile = true;
367 break;
368 }
369 }
370
371 return hasProjectFile &&
372 std::filesystem::exists(directory / "CMakeLists.txt", ec);
373 };
374
375 auto walkUp = [&](std::filesystem::path start)
376 -> std::filesystem::path
377 {
378 std::error_code ec;
379 start = std::filesystem::absolute(start, ec).lexically_normal();
380
381 while (!start.empty())
382 {
383 if (containsProject(start))
384 return start;
385
386 const auto parent = start.parent_path();
387 if (parent == start)
388 break;
389 start = parent;
390 }
391 return {};
392 };
393
394 // First try the process working directory.
395 if (auto root = walkUp(std::filesystem::current_path()); !root.empty())
396 return root;
397
398#ifdef _WIN32
399 // Then try the executable location. This makes the editor portable
400 // when launched from out/build/... instead of the repository root.
401 std::wstring executable(MAX_PATH, L'\0');
402 const DWORD length = GetModuleFileNameW(
403 nullptr, executable.data(), static_cast<DWORD>(executable.size()));
404 if (length > 0)
405 {
406 executable.resize(length);
407 if (auto root =
408 walkUp(std::filesystem::path(executable).parent_path());
409 !root.empty())
410 return root;
411 }
412#endif
413
414 return std::filesystem::current_path();
415 }
416
417 ImVec2 ProjectColliderPoint(
418 const glm::vec3& point,
419 const glm::mat4& viewProjection,
420 const ImVec2& viewportMin,
421 const ImVec2& viewportSize,
422 bool& visible)
423 {
424 const glm::vec4 clip = viewProjection * glm::vec4(point, 1.0f);
425 if (clip.w <= 0.0001f)
426 {
427 visible = false;
428 return {};
429 }
430
431 const glm::vec3 ndc = glm::vec3(clip) / clip.w;
432 visible = ndc.z >= -1.0f && ndc.z <= 1.0f;
433
434 return {
435 viewportMin.x + (ndc.x * 0.5f + 0.5f) * viewportSize.x,
436 viewportMin.y + (1.0f - (ndc.y * 0.5f + 0.5f)) * viewportSize.y
437 };
438 }
439
440 void DrawColliderLine(
441 ImDrawList* drawList,
442 const glm::vec3& a,
443 const glm::vec3& b,
444 const glm::mat4& viewProjection,
445 const ImVec2& viewportMin,
446 const ImVec2& viewportSize,
447 ImU32 color,
448 float thickness)
449 {
450 bool visibleA = false;
451 bool visibleB = false;
452 const ImVec2 screenA = ProjectColliderPoint(
453 a, viewProjection, viewportMin, viewportSize, visibleA);
454 const ImVec2 screenB = ProjectColliderPoint(
455 b, viewProjection, viewportMin, viewportSize, visibleB);
456
457 if (!visibleA && !visibleB)
458 return;
459
460 drawList->AddLine(screenA, screenB, color, thickness);
461 }
462
463 glm::vec3 ColliderTransformPoint(
464 const glm::mat4& transform,
465 const glm::vec3& point)
466 {
467 return glm::vec3(transform * glm::vec4(point, 1.0f));
468 }
469
470 void DrawBoxColliderWire(
471 ImDrawList* drawList,
472 const glm::mat4& world,
473 const glm::vec3& size,
474 const glm::mat4& viewProjection,
475 const ImVec2& viewportMin,
476 const ImVec2& viewportSize,
477 ImU32 color,
478 float thickness)
479 {
480 const glm::vec3 h = glm::max(size * 0.5f, glm::vec3(0.005f));
481 const glm::vec3 local[8] = {
482 {-h.x,-h.y,-h.z}, { h.x,-h.y,-h.z},
483 { h.x, h.y,-h.z}, {-h.x, h.y,-h.z},
484 {-h.x,-h.y, h.z}, { h.x,-h.y, h.z},
485 { h.x, h.y, h.z}, {-h.x, h.y, h.z}
486 };
487
488 glm::vec3 points[8];
489 for (int i = 0; i < 8; ++i)
490 points[i] = ColliderTransformPoint(world, local[i]);
491
492 constexpr int edges[12][2] = {
493 {0,1},{1,2},{2,3},{3,0},
494 {4,5},{5,6},{6,7},{7,4},
495 {0,4},{1,5},{2,6},{3,7}
496 };
497
498 for (const auto& edge : edges)
499 DrawColliderLine(
500 drawList, points[edge[0]], points[edge[1]],
501 viewProjection, viewportMin, viewportSize,
502 color, thickness);
503 }
504
505 void DrawColliderEllipse(
506 ImDrawList* drawList,
507 const glm::mat4& world,
508 float radiusA,
509 float radiusB,
510 int plane,
511 const glm::vec3& offset,
512 const glm::mat4& viewProjection,
513 const ImVec2& viewportMin,
514 const ImVec2& viewportSize,
515 ImU32 color,
516 float thickness)
517 {
518 constexpr int segments = 48;
519 glm::vec3 previous{};
520 bool hasPrevious = false;
521
522 for (int i = 0; i <= segments; ++i)
523 {
524 const float angle =
525 glm::two_pi<float>() * static_cast<float>(i) /
526 static_cast<float>(segments);
527 const float c = std::cos(angle);
528 const float s = std::sin(angle);
529
530 glm::vec3 local = offset;
531 if (plane == 0) {
532 local.y += c * radiusA;
533 local.z += s * radiusB;
534 }
535 else if (plane == 1) {
536 local.x += c * radiusA;
537 local.z += s * radiusB;
538 }
539 else {
540 local.x += c * radiusA;
541 local.y += s * radiusB;
542 }
543
544 const glm::vec3 current =
545 ColliderTransformPoint(world, local);
546
547 if (hasPrevious)
548 DrawColliderLine(
549 drawList, previous, current,
550 viewProjection, viewportMin, viewportSize,
551 color, thickness);
552
553 previous = current;
554 hasPrevious = true;
555 }
556 }
557
558 void DrawSphereColliderWire(
559 ImDrawList* drawList,
560 const glm::mat4& world,
561 float radius,
562 const glm::mat4& viewProjection,
563 const ImVec2& viewportMin,
564 const ImVec2& viewportSize,
565 ImU32 color,
566 float thickness)
567 {
568 radius = std::max(radius, 0.005f);
569 DrawColliderEllipse(drawList, world, radius, radius, 0, {},
570 viewProjection, viewportMin, viewportSize, color, thickness);
571 DrawColliderEllipse(drawList, world, radius, radius, 1, {},
572 viewProjection, viewportMin, viewportSize, color, thickness);
573 DrawColliderEllipse(drawList, world, radius, radius, 2, {},
574 viewProjection, viewportMin, viewportSize, color, thickness);
575 }
576
577 void DrawCapsuleColliderWire(
578 ImDrawList* drawList,
579 const glm::mat4& world,
580 float radius,
581 float height,
582 const glm::mat4& viewProjection,
583 const ImVec2& viewportMin,
584 const ImVec2& viewportSize,
585 ImU32 color,
586 float thickness)
587 {
588 radius = std::max(radius, 0.005f);
589 height = std::max(height, radius * 2.0f);
590 const float halfCylinder = height * 0.5f - radius;
591
592 DrawColliderEllipse(drawList, world, radius, radius, 1,
593 { 0.0f, halfCylinder, 0.0f },
594 viewProjection, viewportMin, viewportSize, color, thickness);
595 DrawColliderEllipse(drawList, world, radius, radius, 1,
596 { 0.0f,-halfCylinder, 0.0f },
597 viewProjection, viewportMin, viewportSize, color, thickness);
598
599 const glm::vec3 top[4] = {
600 { radius, halfCylinder, 0.0f},
601 {-radius, halfCylinder, 0.0f},
602 {0.0f, halfCylinder, radius},
603 {0.0f, halfCylinder,-radius}
604 };
605 const glm::vec3 bottom[4] = {
606 { radius,-halfCylinder, 0.0f},
607 {-radius,-halfCylinder, 0.0f},
608 {0.0f,-halfCylinder, radius},
609 {0.0f,-halfCylinder,-radius}
610 };
611
612 for (int i = 0; i < 4; ++i)
613 DrawColliderLine(
614 drawList,
615 ColliderTransformPoint(world, top[i]),
616 ColliderTransformPoint(world, bottom[i]),
617 viewProjection, viewportMin, viewportSize,
618 color, thickness);
619
620 // Two full meridians create the rounded top/bottom silhouette.
621 DrawColliderEllipse(drawList, world, radius,
622 halfCylinder + radius, 2, {},
623 viewProjection, viewportMin, viewportSize, color, thickness);
624 DrawColliderEllipse(drawList, world, radius,
625 halfCylinder + radius, 0, {},
626 viewProjection, viewportMin, viewportSize, color, thickness);
627 }
628
629 // Editor-only AI perception overlay. Geometry is expressed in world units,
630 // so DetectionRadius is not accidentally multiplied by entity scale.
631 void DrawPerceptionWire(
632 ImDrawList* drawList,
633 const glm::mat4& world,
634 const PerceptionComponent& perception,
635 const glm::mat4& viewProjection,
636 const ImVec2& viewportMin,
637 const ImVec2& viewportSize,
638 ImU32 radiusColor,
639 ImU32 fovColor,
640 float thickness)
641 {
642 if (!perception.Enabled || !perception.DebugDraw)
643 return;
644
645 const float radius = std::max(0.0f, perception.DetectionRadius);
646 if (radius <= 0.0001f)
647 return;
648
649 const glm::vec3 origin = glm::vec3(world[3]) +
650 glm::vec3(0.0f, std::max(0.0f, perception.EyeHeight), 0.0f);
651 glm::vec3 forward = glm::vec3(world * glm::vec4(0, 0, -1, 0));
652 forward.y = 0.0f;
653 if (glm::length(forward) < 0.0001f)
654 forward = { 0, 0, -1 };
655 else
656 forward = glm::normalize(forward);
657
658 // Horizontal right vector; independent of nonuniform object scale.
659 const glm::vec3 right = glm::normalize(
660 glm::cross(forward, glm::vec3(0, 1, 0)));
661
662 constexpr int circleSegments = 64;
663 for (int i = 0; i < circleSegments; ++i)
664 {
665 const float a = glm::two_pi<float>() * float(i) / float(circleSegments);
666 const float b = glm::two_pi<float>() * float(i + 1) / float(circleSegments);
667 const glm::vec3 pa = origin + radius *
668 (forward * std::cos(a) + right * std::sin(a));
669 const glm::vec3 pb = origin + radius *
670 (forward * std::cos(b) + right * std::sin(b));
671 DrawColliderLine(drawList, pa, pb, viewProjection,
672 viewportMin, viewportSize, radiusColor, thickness);
673 }
674
675 const float halfFov = glm::radians(
676 glm::clamp(perception.FieldOfView, 0.0f, 360.0f) * 0.5f);
677 constexpr int arcSegments = 32;
678 glm::vec3 previous{};
679 for (int i = 0; i <= arcSegments; ++i)
680 {
681 const float t = float(i) / float(arcSegments);
682 const float angle = -halfFov + (2.0f * halfFov) * t;
683 const glm::vec3 point = origin + radius *
684 (forward * std::cos(angle) + right * std::sin(angle));
685 if (i > 0)
686 DrawColliderLine(drawList, previous, point, viewProjection,
687 viewportMin, viewportSize, fovColor, thickness);
688 if (i == 0 || i == arcSegments)
689 DrawColliderLine(drawList, origin, point, viewProjection,
690 viewportMin, viewportSize, fovColor, thickness);
691 previous = point;
692 }
693 }
694
695 void DrawSceneColliderGizmos(
696 Scene& scene,
697 Entity selectedEntity,
698 const glm::mat4& view,
699 const glm::mat4& projection,
700 const ImVec2& viewportMin,
701 const ImVec2& viewportSize,
702 bool isPlaying,
703 bool showAIDebugger,
704 bool showLastSeenMarker,
705 std::uint32_t debugAgent)
706 {
707 if (viewportSize.x <= 1.0f || viewportSize.y <= 1.0f)
708 return;
709
710 ImDrawList* drawList = ImGui::GetWindowDrawList();
711 drawList->PushClipRect(
712 viewportMin,
713 { viewportMin.x + viewportSize.x,
714 viewportMin.y + viewportSize.y },
715 true);
716
717 const glm::mat4 viewProjection = projection * view;
718 std::uint64_t selectedID = 0;
719 if (selectedEntity && selectedEntity.HasComponent<IDComponent>())
720 selectedID = selectedEntity.GetComponent<IDComponent>().ID;
721
722 for (Entity entity : scene.GetEntities())
723 {
724
725 const std::uint64_t entityID =
726 entity.GetComponent<IDComponent>().ID;
727 const bool selected =
728 selectedID != 0 && entityID == selectedID;
729
730 const float thickness = selected ? 2.5f : 1.25f;
731 const ImU32 normalColor = selected
732 ? IM_COL32(110, 255, 135, 255)
733 : IM_COL32(80, 205, 110, 175);
734 const ImU32 triggerColor = selected
735 ? IM_COL32(255, 205, 80, 255)
736 : IM_COL32(230, 170, 65, 175);
737
738 const glm::mat4 world = scene.GetWorldTransform(entity);
739
740 if (!isPlaying && entity.HasComponent<BoxColliderComponent>())
741 {
742 const auto& c =
743 entity.GetComponent<BoxColliderComponent>();
744 DrawBoxColliderWire(
745 drawList, world, c.Size,
746 viewProjection, viewportMin, viewportSize,
747 c.IsTrigger ? triggerColor : normalColor,
748 thickness);
749 }
750
751 if (!isPlaying && entity.HasComponent<SphereColliderComponent>())
752 {
753 const auto& c =
754 entity.GetComponent<SphereColliderComponent>();
755 DrawSphereColliderWire(
756 drawList, world, c.Radius,
757 viewProjection, viewportMin, viewportSize,
758 c.IsTrigger ? triggerColor : normalColor,
759 thickness);
760 }
761
762 if (!isPlaying && entity.HasComponent<CapsuleColliderComponent>())
763 {
764 const auto& c =
765 entity.GetComponent<CapsuleColliderComponent>();
766 DrawCapsuleColliderWire(
767 drawList, world, c.Radius, c.Height,
768 viewProjection, viewportMin, viewportSize,
769 c.IsTrigger ? triggerColor : normalColor,
770 thickness);
771 }
772
773 const glm::vec3 origin =
774 ColliderTransformPoint(world, { 0.0f, 0.0f, 0.0f });
775 glm::vec3 forward =
776 ColliderTransformPoint(world, { 0.0f, 0.0f, -1.0f }) -
777 origin;
778 if (glm::length(forward) > 0.0001f)
779 forward = glm::normalize(forward);
780 else
781 forward = { 0.0f, 0.0f, -1.0f };
782 if (entity.HasComponent<PerceptionComponent>())
783 {
784 const auto& perception =
785 entity.GetComponent<PerceptionComponent>();
786
787 // Dibujamos el radio y el FOV como hasta ahora.
788 DrawPerceptionWire(
789 drawList, world, perception,
790 viewProjection, viewportMin, viewportSize,
791 selected ? IM_COL32(75, 205, 255, 255)
792 : IM_COL32(65, 155, 205, 115),
793 selected ? IM_COL32(255, 165, 65, 255)
794 : IM_COL32(235, 140, 60, 170),
795 thickness);
796
797 // Draw runtime perception results for every agent while
798 // the AI Debugger is open, not just the selected entity.
799 // Each agent queries its own perception state by handle.
800 if (isPlaying && showAIDebugger &&
801 perception.Enabled && perception.DebugDraw)
802 {
803 const auto targets =
804 scene.GetPerceivedTargets(entity.GetHandle());
805
806 for (const auto& target : targets)
807 {
808 // Los objetivos visibles se dibujan en su
809 // posición actual; los recordados, en la última
810 // posición que conocía el agente.
811 glm::vec3 markerPosition =
812 target.LastKnownPosition;
813
814 if (target.IsVisible &&
815 scene.IsValid(target.EntityHandle))
816 {
817 markerPosition = glm::vec3(
818 scene.GetWorldTransform(
819 Entity(target.EntityHandle, &scene))[3]);
820 }
821
822 // Actual LOS endpoint, using the same eye offset as runtime.
823 const glm::vec3 eye = glm::vec3(world[3]) +
824 glm::vec3(0.0f, std::max(0.0f, perception.EyeHeight), 0.0f);
825 const glm::vec3 aim = markerPosition +
826 glm::vec3(0.0f, std::max(0.0f, perception.EyeHeight), 0.0f);
827 const ImU32 rayColor = target.IsVisible
828 ? IM_COL32(50, 230, 110, 255)
829 : IM_COL32(255, 205, 65, 210);
830 DrawColliderLine(drawList, eye, aim, viewProjection,
831 viewportMin, viewportSize, rayColor, 2.0f);
832
833 bool onScreen = false;
834
835 const ImVec2 screenPosition =
836 ProjectColliderPoint(
837 markerPosition,
838 viewProjection,
839 viewportMin,
840 viewportSize,
841 onScreen);
842
843 if (!onScreen)
844 continue;
845
846 const ImU32 markerColor = target.IsVisible
847 ? IM_COL32(50, 230, 110, 255)
848 : IM_COL32(255, 205, 65, 255);
849
850 drawList->AddCircleFilled(
851 screenPosition,
852 7.0f,
853 markerColor,
854 16);
855
856 drawList->AddCircle(
857 screenPosition,
858 10.0f,
859 markerColor,
860 16,
861 2.0f);
862 }
863 }
864 }
865
866 // Optional last-seen marker: driven exclusively by the AI Debugger.
867 if (isPlaying && showAIDebugger && showLastSeenMarker &&
868 entity.GetHandle() == debugAgent)
869 {
870 const auto lastSeen = scene.GetLastSeenTarget(entity.GetHandle());
871 if (lastSeen)
872 {
873 const glm::vec3 p = lastSeen->Position;
874 const ImU32 yellow = IM_COL32(255, 205, 65, 255);
875 constexpr float radius = 0.35f;
876 constexpr int segments = 24;
877 for (int i = 0; i < segments; ++i)
878 {
879 const float a = glm::two_pi<float>() * float(i) / float(segments);
880 const float b = glm::two_pi<float>() * float(i + 1) / float(segments);
881 DrawColliderLine(drawList,
882 p + glm::vec3(std::cos(a) * radius, 0.05f, std::sin(a) * radius),
883 p + glm::vec3(std::cos(b) * radius, 0.05f, std::sin(b) * radius),
884 viewProjection, viewportMin, viewportSize, yellow, 2.5f);
885 }
886 DrawColliderLine(drawList, p + glm::vec3(0, 0.05f, 0),
887 p + glm::vec3(0, 1.2f, 0), viewProjection,
888 viewportMin, viewportSize, yellow, 2.5f);
889 bool onScreen = false;
890 const ImVec2 projected = ProjectColliderPoint(p + glm::vec3(0, 1.35f, 0),
891 viewProjection, viewportMin, viewportSize, onScreen);
892 if (onScreen)
893 drawList->AddText(projected, yellow, "LAST SEEN");
894 }
895 }
896
897 // During Play only AI perception debug overlays are drawn.
898 if (isPlaying)
899 continue;
900
901 const ImU32 cameraColor =
902 selected ? IM_COL32(100, 220, 255, 255)
903 : IM_COL32(70, 170, 220, 180);
904 const ImU32 lightColor =
905 selected ? IM_COL32(255, 235, 90, 255)
906 : IM_COL32(235, 205, 70, 190);
907
908 if (entity.HasComponent<CameraComponent>())
909 {
910 const auto& camera =
911 entity.GetComponent<CameraComponent>();
912 const float distance = 1.5f;
913 float halfHeight = 0.7f;
914 float halfWidth = halfHeight *
915 (viewportSize.x / std::max(viewportSize.y, 1.0f));
916
917 if (camera.ProjectionType ==
918 CameraProjectionType::Perspective)
919 {
920 halfHeight =
921 std::tan(glm::radians(camera.PerspectiveFOV * 0.5f))
922 * distance;
923 halfWidth = halfHeight *
924 (viewportSize.x / std::max(viewportSize.y, 1.0f));
925 }
926 else
927 {
928 halfHeight = camera.OrthographicSize * 0.25f;
929 halfWidth = halfHeight *
930 (viewportSize.x / std::max(viewportSize.y, 1.0f));
931 }
932
933 const glm::vec3 localCorners[4] = {
934 {-halfWidth,-halfHeight,-distance},
935 { halfWidth,-halfHeight,-distance},
936 { halfWidth, halfHeight,-distance},
937 {-halfWidth, halfHeight,-distance}
938 };
939 glm::vec3 corners[4];
940 for (int i = 0; i < 4; ++i)
941 {
942 corners[i] =
943 ColliderTransformPoint(world, localCorners[i]);
944 DrawColliderLine(
945 drawList, origin, corners[i],
946 viewProjection, viewportMin, viewportSize,
947 cameraColor, thickness);
948 }
949 for (int i = 0; i < 4; ++i)
950 DrawColliderLine(
951 drawList, corners[i], corners[(i + 1) % 4],
952 viewProjection, viewportMin, viewportSize,
953 cameraColor, thickness);
954 }
955
956 if (entity.HasComponent<DirectionalLightComponent>())
957 {
958 DrawColliderLine(
959 drawList,
960 origin,
961 origin + forward * 1.0f,
962 viewProjection, viewportMin, viewportSize,
963 lightColor, thickness);
964 }
965
966 if (entity.HasComponent<PointLightComponent>())
967 {
968 const auto& light =
969 entity.GetComponent<PointLightComponent>();
970 const float radius =
971 std::min(std::max(light.Range * 0.04f, 0.12f), 0.55f);
972 DrawSphereColliderWire(
973 drawList,
974 glm::translate(glm::mat4(1.0f), origin),
975 radius,
976 viewProjection, viewportMin, viewportSize,
977 lightColor, thickness);
978 }
979
980 if (entity.HasComponent<ParticleSystemComponent>())
981 {
982 const auto& particles =
983 entity.GetComponent<ParticleSystemComponent>();
984 const ImU32 particleColor = selected
985 ? IM_COL32(255, 120, 210, 255)
986 : IM_COL32(220, 90, 185, 155);
987 if (particles.Shape == ParticleShape::Sphere)
988 {
989 DrawSphereColliderWire(
990 drawList,
991 glm::translate(glm::mat4(1.0f), origin),
992 std::max(particles.ShapeRadius, 0.01f),
993 viewProjection, viewportMin, viewportSize,
994 particleColor, thickness);
995 }
996 else if (particles.Shape == ParticleShape::Cone)
997 {
998 glm::vec3 dir = particles.Direction;
999 if (glm::length(dir) < 0.0001f) dir = { 0,1,0 };
1000 dir = glm::normalize(glm::mat3(world) * glm::normalize(dir));
1001 const float length = 1.25f;
1002 const float radius = std::tan(glm::radians(
1003 glm::clamp(particles.ConeAngle, 0.0f, 89.0f))) * length;
1004 glm::vec3 tangent = std::abs(dir.y) < 0.99f
1005 ? glm::normalize(glm::cross(dir, glm::vec3(0, 1, 0)))
1006 : glm::vec3(1, 0, 0);
1007 glm::vec3 bitangent = glm::normalize(glm::cross(dir, tangent));
1008 const glm::vec3 center = origin + dir * length;
1009 for (int i = 0;i < 4;++i)
1010 {
1011 const float a = glm::half_pi<float>() * float(i);
1012 const glm::vec3 edge = center +
1013 tangent * std::cos(a) * radius +
1014 bitangent * std::sin(a) * radius;
1015 DrawColliderLine(drawList, origin, edge,
1016 viewProjection, viewportMin, viewportSize,
1017 particleColor, thickness);
1018 }
1019 }
1020 }
1021
1022 if (entity.HasComponent<AudioSourceComponent>())
1023 {
1024 const auto& audio = entity.GetComponent<AudioSourceComponent>();
1025 if (audio.SpatialBlend > 0.001f)
1026 {
1027 const ImU32 minColor = selected
1028 ? IM_COL32(100, 220, 255, 255)
1029 : IM_COL32(80, 180, 235, 175);
1030 const ImU32 maxColor = selected
1031 ? IM_COL32(185, 120, 255, 255)
1032 : IM_COL32(150, 90, 220, 145);
1033 const glm::mat4 audioWorld =
1034 glm::translate(glm::mat4(1.0f), origin);
1035 DrawSphereColliderWire(
1036 drawList, audioWorld, std::max(audio.MinDistance, 0.01f),
1037 viewProjection, viewportMin, viewportSize,
1038 minColor, thickness);
1039 if (selected)
1040 DrawSphereColliderWire(
1041 drawList, audioWorld,
1042 std::max(audio.MaxDistance, audio.MinDistance + 0.01f),
1043 viewProjection, viewportMin, viewportSize,
1044 maxColor, 1.25f);
1045 }
1046 }
1047
1048 if (entity.HasComponent<AudioListenerComponent>() &&
1049 entity.GetComponent<AudioListenerComponent>().Enabled)
1050 {
1051 const ImU32 listenerColor = selected
1052 ? IM_COL32(255, 150, 90, 255)
1053 : IM_COL32(235, 125, 70, 180);
1054 DrawColliderLine(
1055 drawList, origin, origin + forward * 0.8f,
1056 viewProjection, viewportMin, viewportSize,
1057 listenerColor, thickness);
1058 }
1059
1060 if (entity.HasComponent<SpotLightComponent>())
1061 {
1062 const auto& light =
1063 entity.GetComponent<SpotLightComponent>();
1064 const float length =
1065 std::min(std::max(light.Range * 0.1f, 0.35f), 1.5f);
1066 const float radius =
1067 std::tan(glm::radians(light.OuterAngle)) * length;
1068 const glm::vec3 tipLocal{ 0.0f, 0.0f, 0.0f };
1069 const glm::vec3 ringLocal[4] = {
1070 { radius, 0.0f,-length},
1071 {-radius, 0.0f,-length},
1072 {0.0f, radius,-length},
1073 {0.0f,-radius,-length}
1074 };
1075 for (const auto& local : ringLocal)
1076 DrawColliderLine(
1077 drawList,
1078 ColliderTransformPoint(world, tipLocal),
1079 ColliderTransformPoint(world, local),
1080 viewProjection, viewportMin, viewportSize,
1081 lightColor, thickness);
1082 DrawColliderEllipse(
1083 drawList, world, radius, radius, 2,
1084 { 0.0f, 0.0f,-length },
1085 viewProjection, viewportMin, viewportSize,
1086 lightColor, thickness);
1087 }
1088 }
1089
1090 drawList->PopClipRect();
1091 }
1092
1093 std::string OpenModelFileDialog() {
1094#ifdef _WIN32
1095 char f[MAX_PATH]{};OPENFILENAMEA d{};d.lStructSize = sizeof(d);d.lpstrFile = f;d.nMaxFile = MAX_PATH;d.lpstrFilter =
1096 "3D Models\0*.obj;*.fbx;*.gltf;*.glb;*.dae;*.stl;*.ply;*.3ds;*.blend\0"
1097 "glTF / GLB\0*.gltf;*.glb\0"
1098 "FBX\0*.fbx\0"
1099 "Wavefront OBJ\0*.obj\0"
1100 "All Files\0*.*\0";d.Flags = OFN_PATHMUSTEXIST | OFN_FILEMUSTEXIST | OFN_NOCHANGEDIR;if (GetOpenFileNameA(&d) == TRUE)return f;
1101#endif
1102 return{};
1103 }
1104 std::string OpenHDRIFileDialog()
1105 {
1106#ifdef _WIN32
1107 char fileName[MAX_PATH]{};
1108 OPENFILENAMEA dialog{};
1109 dialog.lStructSize = sizeof(dialog);
1110 dialog.lpstrFile = fileName;
1111 dialog.nMaxFile = MAX_PATH;
1112 dialog.lpstrFilter =
1113 "HDR Environment (*.hdr)\0*.hdr\0"
1114 "All Files\0*.*\0";
1115 dialog.nFilterIndex = 1;
1116 dialog.Flags =
1117 OFN_PATHMUSTEXIST |
1118 OFN_FILEMUSTEXIST |
1119 OFN_NOCHANGEDIR;
1120 if (GetOpenFileNameA(&dialog) == TRUE)
1121 return fileName;
1122#endif
1123 return {};
1124 }
1125
1126 std::string OpenAudioFileDialog()
1127 {
1128#ifdef _WIN32
1129 char fileName[MAX_PATH]{};
1130 OPENFILENAMEA dialog{};
1131 dialog.lStructSize = sizeof(dialog);
1132 dialog.lpstrFile = fileName;
1133 dialog.nMaxFile = MAX_PATH;
1134 dialog.lpstrFilter =
1135 "Audio Files (*.wav;*.mp3;*.flac)\0*.wav;*.mp3;*.flac\0"
1136 "WAV (*.wav)\0*.wav\0"
1137 "MP3 (*.mp3)\0*.mp3\0"
1138 "FLAC (*.flac)\0*.flac\0"
1139 "All Files\0*.*\0";
1140 dialog.nFilterIndex = 1;
1141 dialog.Flags = OFN_PATHMUSTEXIST | OFN_FILEMUSTEXIST | OFN_NOCHANGEDIR;
1142 if (GetOpenFileNameA(&dialog) == TRUE) return fileName;
1143#endif
1144 return {};
1145 }
1146
1147 std::string OpenTextureFileDialog()
1148 {
1149#ifdef _WIN32
1150 char fileName[MAX_PATH]{};
1151
1152 OPENFILENAMEA dialog{};
1153 dialog.lStructSize = sizeof(dialog);
1154 dialog.lpstrFile = fileName;
1155 dialog.nMaxFile = MAX_PATH;
1156 dialog.lpstrFilter =
1157 "Image Files\0*.png;*.jpg;*.jpeg;*.bmp;*.tga\0"
1158 "PNG Files\0*.png\0"
1159 "JPEG Files\0*.jpg;*.jpeg\0"
1160 "All Files\0*.*\0";
1161 dialog.nFilterIndex = 1;
1162 dialog.Flags =
1163 OFN_PATHMUSTEXIST |
1164 OFN_FILEMUSTEXIST |
1165 OFN_NOCHANGEDIR;
1166
1167 if (GetOpenFileNameA(&dialog) == TRUE)
1168 return fileName;
1169#endif
1170 return {};
1171 }
1172 }
1173
1174 void EditorLayer::Init(GLFWwindow* window, Scene* scene)
1175 {
1177 std::snprintf(s_BuildNameBuffer, sizeof(s_BuildNameBuffer), "%s", s_BuildSettings.BuildName.c_str());
1178#ifdef _WIN32
1181#endif
1182 m_Scene = scene;
1183
1184 const auto projectRoot = FindNoJobProjectRoot();
1185 AssetManager::Init(projectRoot);
1186 std::filesystem::create_directories(
1187 AssetManager::GetAssetsDirectory() / "Scripts");
1188 m_ProjectPanel.Initialize();
1189
1190 IMGUI_CHECKVERSION();
1191 ImGui::CreateContext();
1192
1193 ImGuiIO& io = ImGui::GetIO();
1194 io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard;
1195 io.ConfigFlags |= ImGuiConfigFlags_DockingEnable;
1196
1197 // Keep the editor layout in the repository root instead of out/build.
1198 // Deleting the CMake build directory will therefore not erase it.
1199 static std::string imguiIniPath =
1200 (AssetManager::GetProjectRoot() / "NoJobEngineLayout.ini").string();
1201 io.IniFilename = imguiIniPath.c_str();
1202
1203 // A window-position-only ini is not enough: we need an actual docking
1204 // tree. This also repairs ini files produced by the previous broken
1205 // default-layout implementation.
1207 if (std::filesystem::exists(imguiIniPath))
1208 {
1209 std::ifstream iniFile(imguiIniPath);
1210 const std::string iniContents(
1211 (std::istreambuf_iterator<char>(iniFile)),
1212 std::istreambuf_iterator<char>());
1214 iniContents.find("[Docking][Data]") == std::string::npos;
1215 }
1216
1217 ImGui::StyleColorsDark();
1218
1219 ImGui_ImplGlfw_InitForOpenGL(window, true);
1220 ImGui_ImplOpenGL3_Init("#version 460");
1221 }
1222
1224 {
1225#ifdef _WIN32
1227 if (s_StandaloneBuildThread.joinable())
1228 s_StandaloneBuildThread.join();
1230#endif
1231 ImGui_ImplOpenGL3_Shutdown();
1232 ImGui_ImplGlfw_Shutdown();
1233 ImGui::DestroyContext();
1234 }
1235
1237 {
1238 ImGui_ImplOpenGL3_NewFrame();
1239 ImGui_ImplGlfw_NewFrame();
1240 ImGui::NewFrame();
1241 ImGuizmo::BeginFrame();
1242
1243 const ImGuiViewport* viewport = ImGui::GetMainViewport();
1244 const ImGuiID dockspaceID = ImGui::GetID("NoJobEngineDockSpace");
1245
1246 ImGui::DockSpaceOverViewport(
1247 dockspaceID,
1248 viewport,
1249 ImGuiDockNodeFlags_PassthruCentralNode);
1250
1251 // Build only when Init found no valid saved docking data.
1252 // Do not test DockBuilderGetNode here: DockSpaceOverViewport has
1253 // already created that node by this point.
1255 {
1257 ImGui::DockBuilderRemoveNode(dockspaceID);
1258 ImGui::DockBuilderAddNode(
1259 dockspaceID,
1260 ImGuiDockNodeFlags_PassthruCentralNode);
1261 ImGui::DockBuilderSetNodeSize(
1262 dockspaceID,
1263 viewport->WorkSize);
1264
1265 ImGuiID mainID = dockspaceID;
1266
1267 // Left: narrow Hierarchy.
1268 ImGuiID leftID = ImGui::DockBuilderSplitNode(
1269 mainID, ImGuiDir_Left, 0.075f, nullptr, &mainID);
1270
1271 // Right: Inspector.
1272 ImGuiID rightID = ImGui::DockBuilderSplitNode(
1273 mainID, ImGuiDir_Right, 0.14f, nullptr, &mainID);
1274
1275 // Bottom: Console + Project, leaving most space to Viewport.
1276 ImGuiID bottomID = ImGui::DockBuilderSplitNode(
1277 mainID, ImGuiDir_Down, 0.16f, nullptr, &mainID);
1278
1279 ImGuiID consoleID = ImGui::DockBuilderSplitNode(
1280 bottomID, ImGuiDir_Left, 0.22f, nullptr, &bottomID);
1281
1282 ImGui::DockBuilderDockWindow("Hierarchy", leftID);
1283 ImGui::DockBuilderDockWindow("Inspector", rightID);
1284 ImGui::DockBuilderDockWindow("Console", consoleID);
1285 ImGui::DockBuilderDockWindow("Project", bottomID);
1286 ImGui::DockBuilderDockWindow("Viewport", mainID);
1287
1288 ImGui::DockBuilderFinish(dockspaceID);
1289 }
1290 }
1291
1293
1295 {
1296#ifdef _WIN32
1298 {
1300 {
1301 s_ScriptsCompiled = true;
1302 ScriptLog("[Scripts] Hot reload completed successfully.");
1303 }
1304 else
1305 {
1306 s_ScriptsCompiled = false;
1307 ScriptLog("[Scripts] Build succeeded, but DLL reload failed.");
1308 }
1309 }
1310#endif
1311 DrawPlayToolbar();
1312#ifdef _WIN32
1313 if (ImGui::GetIO().KeyCtrl && ImGui::GetIO().KeyShift &&
1314 ImGui::IsKeyPressed(ImGuiKey_B, false))
1315 CompileProjectScripts();
1316#endif
1317 DrawMainMenu();
1318 DrawHierarchy();
1319 DrawViewport();
1320 DrawInspector();
1321 DrawConsole();
1322 DrawProjectPanel();
1323 if (m_ShowGraphicsSettings)
1324 DrawGraphicsSettings();
1325 DrawRendererProfiler();
1326 DrawAIDebugger();
1329
1330 if (m_SelectedEntity && ImGui::IsKeyPressed(ImGuiKey_Delete))
1331 DeleteSelectedEntity();
1332
1333 const ImGuiIO& io = ImGui::GetIO();
1334
1335 if (!io.WantTextInput && io.KeyCtrl && ImGui::IsKeyPressed(ImGuiKey_Z))
1336 {
1337 if (io.KeyShift)
1338 Redo();
1339 else
1340 Undo();
1341 }
1342
1343 if (!io.WantTextInput && io.KeyCtrl && ImGui::IsKeyPressed(ImGuiKey_Y))
1344 Redo();
1345
1346 if (m_SelectedEntity
1347 && io.KeyCtrl
1348 && ImGui::IsKeyPressed(ImGuiKey_D))
1349 {
1350 DuplicateSelectedEntity();
1351 }
1352
1353 if (!io.WantTextInput && m_SelectedEntity && ImGui::IsKeyPressed(ImGuiKey_F2))
1354 m_RenameSelectedRequested = true;
1355
1356 if (!io.WantTextInput && ImGui::IsKeyPressed(ImGuiKey_Escape))
1357 ClearMultiSelection();
1358 }
1359
1361 {
1362 ImGui::Render();
1363 ImGui_ImplOpenGL3_RenderDrawData(ImGui::GetDrawData());
1364 }
1365
1367 {
1368 m_SelectedEntity = entity;
1369 }
1370
1371 void EditorLayer::SetViewportTexture(std::uint32_t textureID)
1372 {
1373 m_ViewportTextureID = textureID;
1374 }
1375
1377 const glm::mat4& view,
1378 const glm::mat4& projection)
1379 {
1380 m_EditorView = view;
1381 m_EditorProjection = projection;
1382 }
1383
1385 std::shared_ptr<Mesh> mesh,
1386 std::shared_ptr<Material> material)
1387 {
1388 m_DefaultCubeMesh = std::move(mesh);
1389 m_DefaultCubeMaterial = std::move(material);
1390 }
1391
1392 std::uint32_t EditorLayer::GetViewportWidth() const
1393 {
1394 return static_cast<std::uint32_t>(
1395 std::max(1.0f, m_ViewportWidth));
1396 }
1397
1399 {
1400 return static_cast<std::uint32_t>(
1401 std::max(1.0f, m_ViewportHeight));
1402 }
1403
1404 Entity EditorLayer::CreateEmptyEntity()
1405 {
1406 if (!m_Scene)
1407 return {};
1408
1409 CaptureUndoSnapshot();
1410 Entity entity = m_Scene->CreateEntity("Empty Entity");
1411 m_SelectedEntity = entity;
1412 return entity;
1413 }
1414
1415 Entity EditorLayer::CreateCubeEntity()
1416 {
1417 if (!m_Scene)
1418 return {};
1419
1420 CaptureUndoSnapshot();
1421 Entity entity = m_Scene->CreateEntity("Cube");
1422
1423 if (m_DefaultCubeMesh)
1424 entity.AddComponent<MeshComponent>(m_DefaultCubeMesh);
1425
1426 if (m_DefaultCubeMaterial)
1427 {
1428 // Give every cube its own Material instance so editing one
1429 // entity's color does not recolor all cubes.
1430 auto material = std::make_shared<Material>(
1431 m_DefaultCubeMaterial->GetShader(),
1432 m_DefaultCubeMaterial->GetColor());
1433
1434 material->SetTexture(
1435 m_DefaultCubeMaterial->GetTexture());
1436 material->UseTexture() =
1437 m_DefaultCubeMaterial->UseTexture();
1438 material->Metallic() = m_DefaultCubeMaterial->Metallic();
1439 material->Roughness() = m_DefaultCubeMaterial->Roughness();
1440 material->AmbientOcclusion() = m_DefaultCubeMaterial->AmbientOcclusion();
1441 material->NormalStrength() = m_DefaultCubeMaterial->NormalStrength();
1442 material->EmissiveColor() = m_DefaultCubeMaterial->EmissiveColor();
1443 material->EmissiveStrength() = m_DefaultCubeMaterial->EmissiveStrength();
1444 material->SetNormalTexture(m_DefaultCubeMaterial->GetNormalTexture());
1445 material->SetMetallicTexture(m_DefaultCubeMaterial->GetMetallicTexture());
1446 material->SetRoughnessTexture(m_DefaultCubeMaterial->GetRoughnessTexture());
1447 material->SetAOTexture(m_DefaultCubeMaterial->GetAOTexture());
1448 material->SetEmissiveTexture(m_DefaultCubeMaterial->GetEmissiveTexture());
1449
1450 entity.AddComponent<MeshRendererComponent>(material);
1451 }
1452
1453 m_SelectedEntity = entity;
1454 return entity;
1455 }
1456
1457 Entity EditorLayer::CreateModelEntity(const std::filesystem::path& p)
1458 {
1459 if (!m_Scene || p.empty())
1460 return {};
1461
1462 try
1463 {
1464 CaptureUndoSnapshot();
1465
1466 auto mesh = AssetManager::LoadMesh(p);
1467 auto entity = m_Scene->CreateEntity(p.stem().string());
1468 entity.AddComponent<MeshComponent>(mesh);
1469
1470 std::shared_ptr<Material> material;
1471 if (m_DefaultCubeMaterial)
1472 {
1473 auto materials = AssetManager::ImportModelMaterials(
1474 p, m_DefaultCubeMaterial->GetShader());
1475 if (materials.empty())
1476 {
1477 material = std::make_shared<Material>(*m_DefaultCubeMaterial);
1478 material->UseTexture() = false;
1479 materials.push_back(material);
1480 }
1481 else material = materials.front();
1482
1483 entity.AddComponent<MeshRendererComponent>(material);
1484 entity.GetComponent<MeshRendererComponent>()
1485 .SetMaterials(std::move(materials));
1486 }
1487
1488 // Unity-style import: if the model contains an Assimp skeleton/animation,
1489 // automatically attach an Animator so the clips are immediately visible.
1490 try
1491 {
1492 const auto animationPath = AssetManager::ResolveProjectPath(p);
1493 auto animation = AnimationAsset::Load(animationPath);
1494 if (animation && animation->HasAnimations())
1495 {
1496 AnimatorComponent animator;
1497 animator.Animation = std::move(animation);
1498 animator.ClipIndex = 0;
1499 animator.TimeSeconds = 0.0f;
1500 animator.Speed = 1.0f;
1501 animator.Playing = true;
1502 animator.Loop = true;
1503 entity.AddComponent<AnimatorComponent>(std::move(animator));
1504 }
1505 }
1506 catch (...)
1507 {
1508 ScriptLog("[Import] Model animation discovery failed; model imported without Animator.");
1509 }
1510
1511 m_SelectedEntity = entity;
1512 return entity;
1513 }
1514 catch (...)
1515 {
1516 ScriptLog("[Import] Model entity creation failed.");
1517 return {};
1518 }
1519 }
1520
1521 void EditorLayer::ClearRedoHistory()
1522 {
1523 m_RedoHistory.clear();
1524 }
1525
1526 void EditorLayer::PushUndoSnapshot(std::unique_ptr<Scene> snapshot)
1527 {
1528 if (!snapshot)
1529 return;
1530
1531 m_UndoHistory.push_back(std::move(snapshot));
1532 if (m_UndoHistory.size() > MaxHistoryEntries)
1533 m_UndoHistory.erase(m_UndoHistory.begin());
1534
1535 ClearRedoHistory();
1536 }
1537
1538 void EditorLayer::CaptureUndoSnapshot()
1539 {
1540 if (m_Scene && !m_IsPlaying)
1541 PushUndoSnapshot(m_Scene->Copy());
1542 }
1543
1544 void EditorLayer::Undo()
1545 {
1546 if (!m_Scene || m_IsPlaying || m_UndoHistory.empty())
1547 return;
1548
1549 const std::uint32_t selected =
1550 m_SelectedEntity ? m_SelectedEntity.GetHandle() : 0;
1551
1552 m_RedoHistory.push_back(m_Scene->Copy());
1553 m_Scene->RestoreFrom(*m_UndoHistory.back());
1554 m_UndoHistory.pop_back();
1555
1556 m_SelectedEntity =
1557 selected != 0 && m_Scene->IsValid(selected)
1558 ? Entity(selected, m_Scene)
1559 : Entity{};
1560 }
1561
1562 void EditorLayer::Redo()
1563 {
1564 if (!m_Scene || m_IsPlaying || m_RedoHistory.empty())
1565 return;
1566
1567 const std::uint32_t selected =
1568 m_SelectedEntity ? m_SelectedEntity.GetHandle() : 0;
1569
1570 m_UndoHistory.push_back(m_Scene->Copy());
1571 m_Scene->RestoreFrom(*m_RedoHistory.back());
1572 m_RedoHistory.pop_back();
1573
1574 m_SelectedEntity =
1575 selected != 0 && m_Scene->IsValid(selected)
1576 ? Entity(selected, m_Scene)
1577 : Entity{};
1578 }
1579
1580 void EditorLayer::DeleteSelectedEntity()
1581 {
1582 if (!m_Scene || !m_SelectedEntity)
1583 return;
1584
1585 std::vector<Entity> selectedEntities;
1586 for (Entity entity : m_Scene->GetEntities())
1587 {
1588 if (IsMultiSelected(entity))
1589 selectedEntities.push_back(entity);
1590 }
1591
1592 if (selectedEntities.empty())
1593 selectedEntities.push_back(m_SelectedEntity);
1594
1595 // Keep only selected roots. If a child is also selected, its selected
1596 // ancestor owns the operation for that whole branch.
1597 std::vector<Entity> selectedRoots;
1598 for (Entity candidate : selectedEntities)
1599 {
1600 bool hasSelectedAncestor = false;
1601 Entity parent = m_Scene->GetParent(candidate);
1602 while (parent)
1603 {
1604 if (IsMultiSelected(parent))
1605 {
1606 hasSelectedAncestor = true;
1607 break;
1608 }
1609 parent = m_Scene->GetParent(parent);
1610 }
1611
1612 if (!hasSelectedAncestor)
1613 selectedRoots.push_back(candidate);
1614 }
1615
1616 CaptureUndoSnapshot();
1617
1618 // Destroy descendants first, then the root. This makes hierarchy
1619 // deletion independent from whether Scene::DestroyEntity itself is
1620 // recursive and prevents orphaned child entities.
1621 auto destroyHierarchy = [&](auto&& self, Entity entity) -> void
1622 {
1623 if (!entity || !m_Scene->IsValid(entity.GetHandle()))
1624 return;
1625
1626 const auto children = m_Scene->GetChildren(entity);
1627 for (Entity child : children)
1628 self(self, child);
1629
1630 if (m_Scene->IsValid(entity.GetHandle()))
1631 m_Scene->DestroyEntity(entity);
1632 };
1633
1634 for (Entity root : selectedRoots)
1635 destroyHierarchy(destroyHierarchy, root);
1636
1637 ClearMultiSelection();
1638 }
1639
1640 void EditorLayer::DuplicateSelectedEntity()
1641 {
1642 if (!m_Scene || !m_SelectedEntity)
1643 return;
1644
1645 std::vector<Entity> selectedEntities;
1646 for (Entity entity : m_Scene->GetEntities())
1647 {
1648 if (IsMultiSelected(entity))
1649 selectedEntities.push_back(entity);
1650 }
1651
1652 if (selectedEntities.empty())
1653 selectedEntities.push_back(m_SelectedEntity);
1654
1655 // Duplicate only selected roots. A selected descendant will already be
1656 // duplicated recursively with its selected ancestor.
1657 std::vector<Entity> selectedRoots;
1658 for (Entity candidate : selectedEntities)
1659 {
1660 bool hasSelectedAncestor = false;
1661 Entity parent = m_Scene->GetParent(candidate);
1662 while (parent)
1663 {
1664 if (IsMultiSelected(parent))
1665 {
1666 hasSelectedAncestor = true;
1667 break;
1668 }
1669 parent = m_Scene->GetParent(parent);
1670 }
1671
1672 if (!hasSelectedAncestor)
1673 selectedRoots.push_back(candidate);
1674 }
1675
1676 CaptureUndoSnapshot();
1677
1678 auto copyComponents = [&](Entity source, Entity copy)
1679 {
1680 copy.GetComponent<TransformComponent>() =
1681 source.GetComponent<TransformComponent>();
1682
1683 if (source.HasComponent<MeshComponent>())
1684 copy.AddComponent<MeshComponent>(
1685 source.GetComponent<MeshComponent>().MeshAsset);
1686
1687 if (source.HasComponent<MeshRendererComponent>())
1688 {
1689 const auto& src =
1690 source.GetComponent<MeshRendererComponent>();
1691 auto& dst =
1692 copy.AddComponent<MeshRendererComponent>(src.MaterialAsset);
1693 dst.MaterialAsset = src.MaterialAsset;
1694 dst.Materials = src.Materials;
1695 }
1696
1697 if (source.HasComponent<PerceptionComponent>())
1698 copy.AddComponent<PerceptionComponent>(
1699 source.GetComponent<PerceptionComponent>());
1700 if (source.HasComponent<NavAgentComponent>())
1701 copy.AddComponent<NavAgentComponent>(
1702 source.GetComponent<NavAgentComponent>());
1703 if (source.HasComponent<NativeScriptComponent>())
1704 copy.AddComponent<NativeScriptComponent>(
1705 source.GetComponent<NativeScriptComponent>());
1706 if (source.HasComponent<RigidbodyComponent>())
1707 copy.AddComponent<RigidbodyComponent>(
1708 source.GetComponent<RigidbodyComponent>());
1709 if (source.HasComponent<BoxColliderComponent>())
1710 copy.AddComponent<BoxColliderComponent>(
1711 source.GetComponent<BoxColliderComponent>());
1712 if (source.HasComponent<SphereColliderComponent>())
1713 copy.AddComponent<SphereColliderComponent>(
1714 source.GetComponent<SphereColliderComponent>());
1715 if (source.HasComponent<CapsuleColliderComponent>())
1716 copy.AddComponent<CapsuleColliderComponent>(
1717 source.GetComponent<CapsuleColliderComponent>());
1718 if (source.HasComponent<CameraComponent>())
1719 copy.AddComponent<CameraComponent>(
1720 source.GetComponent<CameraComponent>());
1721 if (source.HasComponent<DirectionalLightComponent>())
1722 copy.AddComponent<DirectionalLightComponent>(
1723 source.GetComponent<DirectionalLightComponent>());
1724 if (source.HasComponent<PointLightComponent>())
1725 copy.AddComponent<PointLightComponent>(
1726 source.GetComponent<PointLightComponent>());
1727 if (source.HasComponent<SpotLightComponent>())
1728 copy.AddComponent<SpotLightComponent>(
1729 source.GetComponent<SpotLightComponent>());
1730 if (source.HasComponent<AnimatorComponent>())
1731 copy.AddComponent<AnimatorComponent>(
1732 source.GetComponent<AnimatorComponent>());
1733 if (source.HasComponent<PrefabInstanceComponent>())
1734 copy.AddComponent<PrefabInstanceComponent>(
1735 source.GetComponent<PrefabInstanceComponent>());
1736 };
1737
1738 // Recursively clone a complete hierarchy. Parenting uses
1739 // keepWorldTransform=false because copied transforms are already local
1740 // transforms from the original hierarchy.
1741 auto duplicateHierarchy =
1742 [&](auto&& self, Entity source, Entity newParent) -> Entity
1743 {
1744 const auto sourceTag =
1745 source.GetComponent<TagComponent>().Tag;
1746
1747 Entity copy = m_Scene->CreateEntity(sourceTag + " Copy");
1748 copyComponents(source, copy);
1749
1750 if (newParent)
1751 m_Scene->SetParent(copy, newParent, false);
1752
1753 const auto children = m_Scene->GetChildren(source);
1754 for (Entity child : children)
1755 self(self, child, copy);
1756
1757 return copy;
1758 };
1759
1760 std::vector<std::uint32_t> newSelection;
1761 Entity lastCopy{};
1762
1763 for (Entity sourceRoot : selectedRoots)
1764 {
1765 if (!sourceRoot || !m_Scene->IsValid(sourceRoot.GetHandle()))
1766 continue;
1767
1768 // Preserve the original external parent for a duplicated root.
1769 Entity originalParent = m_Scene->GetParent(sourceRoot);
1770 Entity rootCopy =
1771 duplicateHierarchy(duplicateHierarchy, sourceRoot, Entity{});
1772
1773 if (originalParent)
1774 m_Scene->SetParent(rootCopy, originalParent, false);
1775
1776 newSelection.push_back(rootCopy.GetHandle());
1777 lastCopy = rootCopy;
1778 }
1779
1780 m_MultiSelection = std::move(newSelection);
1781 m_SelectedEntity = lastCopy;
1782 }
1783
1784 void EditorLayer::DrawMainMenu()
1785 {
1786 if (ImGui::BeginMainMenuBar())
1787 {
1788 if (ImGui::BeginMenu("File"))
1789 {
1790 if (ImGui::MenuItem("Save Scene", "Ctrl+S"))
1791 m_SaveSceneRequested = true;
1792 if (ImGui::MenuItem("Save Scene As..."))
1793 m_SaveSceneAsRequested = true;
1794 if (ImGui::MenuItem("Open Scene...", "Ctrl+O"))
1795 m_LoadSceneRequested = true;
1796 ImGui::Separator();
1797 if (ImGui::MenuItem("Load Graphics Test Scene"))
1798 m_GraphicsTestSceneRequested = true;
1799 ImGui::Separator();
1800 if (ImGui::MenuItem("Import 3D Model...")) { auto s = OpenModelFileDialog();if (!s.empty())try { CreateModelEntity(AssetManager::ImportModel(s)); } catch (...) { ScriptLog("[Import] 3D model import failed."); } }
1801 ImGui::Separator();
1802 ImGui::MenuItem("Exit");
1803 ImGui::EndMenu();
1804 }
1805
1806 if (ImGui::BeginMenu("Edit"))
1807 {
1808 if (ImGui::MenuItem(
1809 "Duplicate Entity",
1810 "Ctrl+D",
1811 false,
1812 static_cast<bool>(m_SelectedEntity)))
1813 {
1814 DuplicateSelectedEntity();
1815 }
1816
1817 if (ImGui::MenuItem(
1818 "Delete Entity",
1819 "Delete",
1820 false,
1821 static_cast<bool>(m_SelectedEntity)))
1822 {
1823 DeleteSelectedEntity();
1824 }
1825
1826 ImGui::Separator();
1827 ImGui::BeginDisabled(m_UndoHistory.empty() || m_IsPlaying);
1828 if (ImGui::MenuItem("Undo", "Ctrl+Z"))
1829 Undo();
1830 ImGui::EndDisabled();
1831
1832 ImGui::BeginDisabled(m_RedoHistory.empty() || m_IsPlaying);
1833 if (ImGui::MenuItem("Redo", "Ctrl+Y"))
1834 Redo();
1835 ImGui::EndDisabled();
1836 ImGui::EndMenu();
1837 }
1838
1839 if (s_ShowBuildSettings) ImGui::OpenPopup("Build Settings");
1840 if (ImGui::BeginPopupModal("Build Settings", &s_ShowBuildSettings, ImGuiWindowFlags_AlwaysAutoResize))
1841 {
1842 ImGui::InputText("Build Name", s_BuildNameBuffer, sizeof(s_BuildNameBuffer)); s_BuildSettings.BuildName = s_BuildNameBuffer;
1843 ImGui::SeparatorText("Scenes in Build"); int remove = -1;
1844 for (size_t i = 0;i < s_BuildSettings.Scenes.size();++i) { ImGui::PushID((int)i); bool startup = i == s_BuildSettings.StartupSceneIndex; if (ImGui::RadioButton("##startup", startup))s_BuildSettings.StartupSceneIndex = i; ImGui::SameLine(); ImGui::TextUnformatted(s_BuildSettings.Scenes[i].generic_string().c_str()); ImGui::SameLine(); if (ImGui::SmallButton("Remove"))remove = (int)i; ImGui::PopID(); }
1845 if (remove >= 0) { s_BuildSettings.Scenes.erase(s_BuildSettings.Scenes.begin() + remove); if (s_BuildSettings.Scenes.empty())s_BuildSettings.StartupSceneIndex = 0; else if (s_BuildSettings.StartupSceneIndex >= s_BuildSettings.Scenes.size())s_BuildSettings.StartupSceneIndex = s_BuildSettings.Scenes.size() - 1; }
1846 if (ImGui::Button("Add Scene...")) { auto selected = SceneFileDialog::Open(AssetManager::GetProjectRoot() / "Assets/Scenes"); if (!selected.empty()) { std::error_code ec;auto rel = std::filesystem::relative(selected, AssetManager::GetProjectRoot(), ec);if (!ec && std::find(s_BuildSettings.Scenes.begin(), s_BuildSettings.Scenes.end(), rel) == s_BuildSettings.Scenes.end())s_BuildSettings.Scenes.push_back(rel); } }
1847 ImGui::SeparatorText("Configuration"); bool debug = s_BuildSettings.Configuration == L"Debug"; if (ImGui::RadioButton("Debug", debug))s_BuildSettings.Configuration = L"Debug"; ImGui::SameLine(); if (ImGui::RadioButton("Release", !debug))s_BuildSettings.Configuration = L"Release";
1848 ImGui::Separator();
1849 if (ImGui::Button("Save Settings")) { s_BuildSettings.Save(AssetManager::GetProjectRoot());ScriptLog("[Build] Build Settings saved."); } ImGui::SameLine();
1850 if (ImGui::Button("Build")) { std::string error;if (!s_BuildSettings.IsValid(error))ScriptLog("[Build] " + error);else { s_BuildSettings.Save(AssetManager::GetProjectRoot());s_ShowBuildSettings = false;ImGui::CloseCurrentPopup();BuildStandalone(); } } ImGui::SameLine();
1851 if (ImGui::Button("Close")) { s_ShowBuildSettings = false;ImGui::CloseCurrentPopup(); }
1852 ImGui::EndPopup();
1853 }
1854
1855 if (ImGui::BeginMenu("Build"))
1856 {
1857#ifdef _WIN32
1858 ImGui::BeginDisabled(ProjectScriptBuildSystem::IsRunning());
1859 if (ImGui::MenuItem("Compile Scripts", "Ctrl+Shift+B"))
1860 CompileProjectScripts();
1861 ImGui::EndDisabled();
1862 ImGui::BeginDisabled(ProjectScriptBuildSystem::IsRunning());
1863 if (ImGui::MenuItem("Reload Scripts"))
1864 ProjectScriptManager::Load(AssetManager::GetProjectRoot());
1865 ImGui::EndDisabled();
1866 if (ProjectScriptBuildSystem::IsRunning())
1867 ImGui::TextDisabled("Compiling scripts...");
1868 ImGui::Separator();
1869 ImGui::BeginDisabled(
1870 ProjectScriptBuildSystem::IsRunning() || s_StandaloneBuildRunning.load());
1871 if (ImGui::MenuItem("Build Settings...")) s_ShowBuildSettings = true;
1872 if (ImGui::MenuItem("Build Project")) BuildStandalone();
1873 ImGui::EndDisabled();
1874 if (s_StandaloneBuildRunning.load())
1875 ImGui::TextDisabled("Building standalone...");
1876 if (s_StandaloneBuildSucceeded.load() &&
1877 !s_LastStandaloneBuildDirectory.empty())
1878 ImGui::TextDisabled("Last build: %s",
1879 s_LastStandaloneBuildDirectory.string().c_str());
1880 ImGui::Separator();
1881 ImGui::TextDisabled(ProjectScriptManager::IsLoaded()
1882 ? "ProjectScripts.dll loaded"
1883 : "ProjectScripts.dll not loaded");
1884#else
1885 ImGui::TextDisabled("Script compilation is currently implemented for Windows.");
1886#endif
1887 ImGui::EndMenu();
1888 }
1889
1890 if (ImGui::BeginMenu("GameObject"))
1891 {
1892 if (ImGui::MenuItem("Create Empty"))
1893 CreateEmptyEntity();
1894
1895 if (ImGui::BeginMenu("3D Object"))
1896 {
1897 if (ImGui::MenuItem("Cube"))
1898 CreateCubeEntity();
1899
1900 if (ImGui::MenuItem("Import 3D Model..."))
1901 {
1902 const std::string source = OpenModelFileDialog();
1903 if (!source.empty())
1904 {
1905 try
1906 {
1907 const auto imported = AssetManager::ImportModel(source);
1908 CreateModelEntity(imported);
1909 }
1910 catch (...)
1911 {
1912 ScriptLog("[Import] 3D model import failed.");
1913 }
1914 }
1915 }
1916
1917 ImGui::EndMenu();
1918 }
1919
1920 ImGui::Separator();
1921
1922 if (ImGui::MenuItem("Camera") && m_Scene)
1923 {
1924 CaptureUndoSnapshot();
1925 Entity camera = m_Scene->CreateEntity("Camera");
1926 camera.AddComponent<CameraComponent>();
1927 m_SelectedEntity = camera;
1928 }
1929
1930 if (m_SelectedEntity && ImGui::MenuItem("Create Prefab From Selected"))
1931 {
1932 ProjectAssetOperations::CreatePrefab(
1933 m_SelectedEntity,
1934 AssetManager::GetAssetsDirectory() / "Prefabs",
1935 [this](const std::string& message) { ScriptLog(message); });
1936 }
1937
1938 ImGui::Separator();
1939
1940 if (ImGui::BeginMenu("Light"))
1941 {
1942 if (ImGui::MenuItem("Directional Light") && m_Scene)
1943 {
1944 CaptureUndoSnapshot();
1945 Entity light = m_Scene->CreateEntity("Directional Light");
1946 light.AddComponent<DirectionalLightComponent>();
1947 m_SelectedEntity = light;
1948 }
1949 if (ImGui::MenuItem("Point Light") && m_Scene)
1950 {
1951 CaptureUndoSnapshot();
1952 Entity light = m_Scene->CreateEntity("Point Light");
1953 light.AddComponent<PointLightComponent>();
1954 m_SelectedEntity = light;
1955 }
1956 if (ImGui::MenuItem("Spot Light") && m_Scene)
1957 {
1958 CaptureUndoSnapshot();
1959 Entity light = m_Scene->CreateEntity("Spot Light");
1960 light.AddComponent<SpotLightComponent>();
1961 m_SelectedEntity = light;
1962 }
1963 ImGui::EndMenu();
1964 }
1965
1966 ImGui::EndMenu();
1967 }
1968 if (ImGui::BeginMenu("AI"))
1969 {
1970 ImGui::MenuItem("Behavior Tree Editor", nullptr, &s_ShowBTAssetEditor);
1971 if (ImGui::MenuItem("Neural Network Editor", nullptr, s_NeuralEditorPanel.IsOpen()))
1973 ImGui::MenuItem("AI Debugger", nullptr, &m_ShowAIDebugger);
1974 ImGui::Separator();
1975 if (ImGui::BeginMenu("Navigation"))
1976 {
1977 if (ImGui::MenuItem(
1978 "Bake NavMesh",
1979 nullptr,
1980 false,
1981 !m_IsPlaying))
1982 {
1983 m_BakeNavMeshRequested = true;
1984 }
1985
1986 if (ImGui::MenuItem(
1987 "Clear NavMesh",
1988 nullptr,
1989 false,
1990 !m_IsPlaying))
1991 {
1992 m_ClearNavMeshRequested = true;
1993 }
1994
1995 ImGui::Separator();
1996
1997 ImGui::MenuItem(
1998 "Show NavMesh",
1999 nullptr,
2000 &m_ShowNavMesh);
2001
2002 ImGui::EndMenu();
2003 }
2004
2005 ImGui::EndMenu();
2006 }
2007 if (ImGui::BeginMenu("View"))
2008 {
2009 ImGui::MenuItem("Hierarchy");
2010 ImGui::MenuItem("Inspector");
2011 ImGui::MenuItem("Console");
2012 ImGui::MenuItem("Graphics Settings", nullptr, &m_ShowGraphicsSettings);
2013 ImGui::MenuItem("Renderer Profiler", nullptr, &m_ShowRendererProfiler);
2014 ImGui::MenuItem("AI Debugger", nullptr, &m_ShowAIDebugger);
2015 ImGui::EndMenu();
2016 }
2017
2018 ImGui::EndMainMenuBar();
2019 }
2020 }
2021
2023 {
2024 m_Scene = scene;
2025 m_SelectedEntity = {};
2026 m_AIDebugAgent = 0;
2027 }
2028
2030 {
2031 const bool value = m_PlayRequested;
2032 m_PlayRequested = false;
2033 return value;
2034 }
2035
2037 {
2038 const bool value = m_PauseRequested;
2039 m_PauseRequested = false;
2040 return value;
2041 }
2042
2044 {
2045 const bool value = m_StopRequested;
2046 m_StopRequested = false;
2047 return value;
2048 }
2050 {
2051 const bool value = m_BakeNavMeshRequested;
2052 m_BakeNavMeshRequested = false;
2053 return value;
2054 }
2055
2057 {
2058 const bool value = m_ClearNavMeshRequested;
2059 m_ClearNavMeshRequested = false;
2060 return value;
2061 }
2062 void EditorLayer::SetRuntimeState(bool playing, bool paused)
2063 {
2064 m_IsPlaying = playing;
2065 m_IsPaused = paused;
2066 }
2067
2068 void EditorLayer::DrawPlayToolbar()
2069 {
2070 ImGui::Begin("Toolbar", nullptr,
2071 ImGuiWindowFlags_NoScrollbar
2072 | ImGuiWindowFlags_NoScrollWithMouse);
2073
2074 const float width = ImGui::GetContentRegionAvail().x;
2075 ImGui::SetCursorPosX(
2076 ImGui::GetCursorPosX() + (width - 170.0f) * 0.5f);
2077
2078 ImGui::BeginDisabled(m_IsPlaying);
2079 if (ImGui::Button("Play", ImVec2(50.0f, 0.0f)))
2080 m_PlayRequested = true;
2081 ImGui::EndDisabled();
2082
2083 ImGui::SameLine();
2084
2085 ImGui::BeginDisabled(!m_IsPlaying);
2086 if (ImGui::Button(
2087 m_IsPaused ? "Resume" : "Pause",
2088 ImVec2(60.0f, 0.0f)))
2089 {
2090 m_PauseRequested = true;
2091 }
2092 ImGui::EndDisabled();
2093
2094 ImGui::SameLine();
2095
2096 ImGui::BeginDisabled(!m_IsPlaying);
2097 if (ImGui::Button("Stop", ImVec2(50.0f, 0.0f)))
2098 m_StopRequested = true;
2099 ImGui::EndDisabled();
2100
2101 ImGui::End();
2102 }
2103
2104 bool EditorLayer::IsMultiSelected(Entity entity) const
2105 {
2106 return std::find(m_MultiSelection.begin(), m_MultiSelection.end(),
2107 entity.GetHandle()) != m_MultiSelection.end();
2108 }
2109
2110 void EditorLayer::ClearMultiSelection()
2111 {
2112 m_MultiSelection.clear();
2113 m_SelectedEntity = {};
2114 }
2115
2116 bool EditorLayer::HierarchyMatchesFilter(Entity entity) const
2117 {
2118 if (!entity) return false;
2119 std::string filter = m_HierarchySearch;
2120 if (filter.empty()) return true;
2121 std::transform(filter.begin(), filter.end(), filter.begin(),
2122 [](unsigned char c) { return (char)std::tolower(c); });
2123
2124 std::string name = entity.GetComponent<TagComponent>().Tag;
2125 std::transform(name.begin(), name.end(), name.begin(),
2126 [](unsigned char c) { return (char)std::tolower(c); });
2127 if (name.find(filter) != std::string::npos) return true;
2128
2129 for (Entity child : m_Scene->GetChildren(entity))
2130 if (HierarchyMatchesFilter(child)) return true;
2131 return false;
2132 }
2133
2134 void EditorLayer::DrawHierarchy()
2135 {
2136 ImGui::Begin("Hierarchy");
2137
2138 ImGui::SetNextItemWidth(-1.0f);
2139 ImGui::InputTextWithHint("##HierarchySearch", "Search Hierarchy...",
2140 m_HierarchySearch, sizeof(m_HierarchySearch));
2141
2142 if (m_MultiSelection.size() > 1)
2143 {
2144 ImGui::Text("%zu entities selected", m_MultiSelection.size());
2145 if (ImGui::SmallButton("Duplicate Selected"))
2146 DuplicateSelectedEntity();
2147 ImGui::SameLine();
2148 if (ImGui::SmallButton("Delete Selected"))
2149 DeleteSelectedEntity();
2150 }
2151
2152 ImGui::Separator();
2153
2154 if (ImGui::BeginPopupContextWindow(
2155 "HierarchyContext",
2156 ImGuiPopupFlags_MouseButtonRight
2157 | ImGuiPopupFlags_NoOpenOverItems))
2158 {
2159 if (ImGui::MenuItem("Create Empty"))
2160 CreateEmptyEntity();
2161
2162 if (ImGui::BeginMenu("3D Object"))
2163 {
2164 if (ImGui::MenuItem("Cube"))
2165 CreateCubeEntity();
2166 ImGui::EndMenu();
2167 }
2168
2169 ImGui::EndPopup();
2170 }
2171
2172 // Dropping an entity onto empty Hierarchy space makes it a root.
2173 if (ImGui::BeginDragDropTarget())
2174 {
2175 if (const ImGuiPayload* payload =
2176 ImGui::AcceptDragDropPayload("NOJOB_ENTITY"))
2177 {
2178 const auto handle =
2179 *static_cast<const std::uint32_t*>(payload->Data);
2180
2181 if (m_Scene->IsValid(handle))
2182 {
2183 CaptureUndoSnapshot();
2184 const bool dragIsMulti =
2185 std::find(m_MultiSelection.begin(), m_MultiSelection.end(), handle)
2186 != m_MultiSelection.end()
2187 && m_MultiSelection.size() > 1;
2188
2189 if (dragIsMulti)
2190 {
2191 for (std::uint32_t selectedHandle : m_MultiSelection)
2192 if (m_Scene->IsValid(selectedHandle))
2193 m_Scene->Unparent(Entity(selectedHandle, m_Scene), true);
2194 }
2195 else
2196 {
2197 m_Scene->Unparent(Entity(handle, m_Scene), true);
2198 }
2199 }
2200 }
2201 ImGui::EndDragDropTarget();
2202 }
2203
2204 if (m_Scene)
2205 {
2206 for (Entity entity : m_Scene->GetEntities())
2207 {
2208 if (entity.GetComponent<RelationshipComponent>().Parent == 0
2209 && HierarchyMatchesFilter(entity))
2210 DrawEntityNode(entity);
2211 }
2212 }
2213
2214 ImGui::End();
2215 }
2216
2217 void EditorLayer::DrawEntityNode(Entity entity)
2218 {
2219 if (!entity)
2220 return;
2221
2222 auto& tag = entity.GetComponent<TagComponent>().Tag;
2223 const auto& relationship =
2224 entity.GetComponent<RelationshipComponent>();
2225
2226 ImGuiTreeNodeFlags flags =
2227 ImGuiTreeNodeFlags_OpenOnArrow
2228 | ImGuiTreeNodeFlags_OpenOnDoubleClick
2229 | ImGuiTreeNodeFlags_SpanAvailWidth;
2230
2231 if (relationship.Children.empty())
2232 flags |= ImGuiTreeNodeFlags_Leaf;
2233
2234 if (entity == m_SelectedEntity || IsMultiSelected(entity))
2235 flags |= ImGuiTreeNodeFlags_Selected;
2236
2237 ImGui::PushID(static_cast<int>(entity.GetHandle()));
2238
2239 const bool open =
2240 ImGui::TreeNodeEx("EntityNode", flags, "%s", tag.c_str());
2241
2242 if (ImGui::IsItemClicked())
2243 {
2244 const bool ctrl = ImGui::GetIO().KeyCtrl;
2245 if (ctrl)
2246 {
2247 auto it = std::find(m_MultiSelection.begin(), m_MultiSelection.end(),
2248 entity.GetHandle());
2249 if (it == m_MultiSelection.end())
2250 m_MultiSelection.push_back(entity.GetHandle());
2251 else
2252 m_MultiSelection.erase(it);
2253 }
2254 else
2255 {
2256 m_MultiSelection.clear();
2257 m_MultiSelection.push_back(entity.GetHandle());
2258 }
2259 m_SelectedEntity = entity;
2260 }
2261
2262 if (ImGui::BeginDragDropSource())
2263 {
2264 const std::uint32_t handle = entity.GetHandle();
2265 ImGui::SetDragDropPayload(
2266 "NOJOB_ENTITY",
2267 &handle,
2268 sizeof(handle));
2269 ImGui::Text("%s", tag.c_str());
2270 ImGui::EndDragDropSource();
2271 }
2272
2273 if (ImGui::BeginDragDropTarget())
2274 {
2275 if (const ImGuiPayload* payload =
2276 ImGui::AcceptDragDropPayload("NOJOB_ENTITY"))
2277 {
2278 const auto childHandle =
2279 *static_cast<const std::uint32_t*>(payload->Data);
2280
2281 if (m_Scene->IsValid(childHandle))
2282 {
2283 CaptureUndoSnapshot();
2284
2285 const bool dragIsMulti =
2286 std::find(m_MultiSelection.begin(), m_MultiSelection.end(), childHandle)
2287 != m_MultiSelection.end()
2288 && m_MultiSelection.size() > 1;
2289
2290 if (dragIsMulti)
2291 {
2292 // Parent every selected entity that can legally become
2293 // a child of the drop target. Scene::SetParent keeps the
2294 // world transform and rejects invalid cycles.
2295 for (std::uint32_t selectedHandle : m_MultiSelection)
2296 {
2297 if (!m_Scene->IsValid(selectedHandle)
2298 || selectedHandle == entity.GetHandle())
2299 continue;
2300
2301 m_Scene->SetParent(
2302 Entity(selectedHandle, m_Scene),
2303 entity,
2304 true);
2305 }
2306 }
2307 else
2308 {
2309 m_Scene->SetParent(
2310 Entity(childHandle, m_Scene),
2311 entity,
2312 true);
2313 }
2314 }
2315 }
2316 ImGui::EndDragDropTarget();
2317 }
2318
2319 if (ImGui::BeginPopupContextItem("EntityContext"))
2320 {
2321 m_SelectedEntity = entity;
2322
2323 if (ImGui::MenuItem("Rename", "F2"))
2324 m_RenameSelectedRequested = true;
2325
2326 if (ImGui::MenuItem("Duplicate", "Ctrl+D"))
2327 DuplicateSelectedEntity();
2328
2329 if (ImGui::MenuItem("Create Prefab"))
2330 {
2331 ProjectAssetOperations::CreatePrefab(
2332 entity,
2333 AssetManager::GetAssetsDirectory() / "Prefabs",
2334 [this](const std::string& message) { ScriptLog(message); });
2335 }
2336
2337 if (relationship.Parent != 0
2338 && ImGui::MenuItem("Unparent"))
2339 {
2340 CaptureUndoSnapshot();
2341 m_Scene->Unparent(entity, true);
2342 }
2343
2344 if (ImGui::MenuItem("Delete", "Delete"))
2345 DeleteSelectedEntity();
2346
2347 ImGui::EndPopup();
2348 }
2349
2350 if (open)
2351 {
2352 const auto children = m_Scene->GetChildren(entity);
2353 for (Entity child : children)
2354 if (HierarchyMatchesFilter(child))
2355 DrawEntityNode(child);
2356
2357 ImGui::TreePop();
2358 }
2359
2360 ImGui::PopID();
2361 }
2362
2363
2364
2365 void EditorLayer::DrawViewport()
2366 {
2367 ImGui::PushStyleVar(
2368 ImGuiStyleVar_WindowPadding,
2369 ImVec2(0, 0));
2370
2371 ImGui::Begin("Viewport");
2372
2373 m_ViewportHovered = ImGui::IsWindowHovered();
2374 m_ViewportFocused = ImGui::IsWindowFocused();
2375
2376 const ImVec2 viewportMin =
2377 ImGui::GetCursorScreenPos();
2378
2379 const ImVec2 available =
2380 ImGui::GetContentRegionAvail();
2381
2382 m_ViewportWidth =
2383 std::max(1.0f, available.x);
2384
2385 m_ViewportHeight =
2386 std::max(1.0f, available.y);
2387
2388 if (m_ViewportTextureID != 0)
2389 {
2390 ImGui::Image(
2391 static_cast<ImTextureID>(
2392 static_cast<intptr_t>(
2393 m_ViewportTextureID)),
2394 ImVec2(
2395 m_ViewportWidth,
2396 m_ViewportHeight),
2397 ImVec2(0.0f, 1.0f),
2398 ImVec2(1.0f, 0.0f));
2399 }
2400
2401 // Gizmos are editor overlays, never part of the game framebuffer.
2402 // In Play, draw only AI perception debugging (when enabled).
2403 if (m_Scene && m_SelectedEntity)
2404 {
2405 DrawSceneColliderGizmos(
2406 *m_Scene,
2407 m_SelectedEntity,
2408 m_EditorView,
2409 m_EditorProjection,
2410 viewportMin,
2411 ImVec2(m_ViewportWidth, m_ViewportHeight),
2412 m_IsPlaying,
2413 m_ShowAIDebugger,
2414 m_AIDebugShowLastSeenMarker,
2415 m_AIDebugAgent);
2416 }
2417
2418 if (!m_IsPlaying &&
2419 m_CameraPreviewTextureID != 0 &&
2420 m_SelectedEntity &&
2421 m_SelectedEntity.HasComponent<CameraComponent>())
2422 {
2423 const ImVec2 previewSize(320.0f, 180.0f);
2424 const ImVec2 previewMin(
2425 viewportMin.x + m_ViewportWidth - previewSize.x - 16.0f,
2426 viewportMin.y + 16.0f);
2427 const ImVec2 previewMax(
2428 previewMin.x + previewSize.x,
2429 previewMin.y + previewSize.y);
2430
2431 ImDrawList* drawList = ImGui::GetWindowDrawList();
2432 drawList->AddRectFilled(
2433 { previewMin.x - 3.0f, previewMin.y - 3.0f },
2434 { previewMax.x + 3.0f, previewMax.y + 3.0f },
2435 IM_COL32(25, 25, 28, 240));
2436 drawList->AddImage(
2437 static_cast<ImTextureID>(
2438 static_cast<intptr_t>(m_CameraPreviewTextureID)),
2439 previewMin,
2440 previewMax,
2441 ImVec2(0.0f, 1.0f),
2442 ImVec2(1.0f, 0.0f));
2443 drawList->AddText(
2444 { previewMin.x + 8.0f, previewMin.y + 6.0f },
2445 IM_COL32(255, 255, 255, 220),
2446 "Camera Preview");
2447 }
2448
2449 // W = Translate, E = Rotate, R = Scale.
2450 // Only change tools while the viewport is active and the user
2451 // isn't currently dragging the gizmo.
2452 if (m_ViewportHovered && !ImGuizmo::IsUsing())
2453 {
2454 if (ImGui::IsKeyPressed(ImGuiKey_W))
2455 m_GizmoOperation = 0;
2456
2457 if (ImGui::IsKeyPressed(ImGuiKey_E))
2458 m_GizmoOperation = 1;
2459
2460 if (ImGui::IsKeyPressed(ImGuiKey_R))
2461 m_GizmoOperation = 2;
2462 }
2463
2464 if (m_SelectedEntity
2465 && m_ViewportWidth > 1.0f
2466 && m_ViewportHeight > 1.0f)
2467 {
2468
2469
2470 glm::mat4 transformMatrix =
2471 m_Scene->GetWorldTransform(m_SelectedEntity);
2472
2473 ImGuizmo::SetOrthographic(false);
2474 ImGuizmo::SetDrawlist();
2475 ImGuizmo::SetRect(
2476 viewportMin.x,
2477 viewportMin.y,
2478 m_ViewportWidth,
2479 m_ViewportHeight);
2480
2481 ImGuizmo::OPERATION operation =
2482 ImGuizmo::TRANSLATE;
2483
2484 if (m_GizmoOperation == 1)
2485 operation = ImGuizmo::ROTATE;
2486 else if (m_GizmoOperation == 2)
2487 operation = ImGuizmo::SCALE;
2488
2489 const ImGuizmo::MODE mode =
2490 operation == ImGuizmo::SCALE
2491 ? ImGuizmo::LOCAL
2492 : ImGuizmo::WORLD;
2493
2494 ImGuizmo::Manipulate(
2495 glm::value_ptr(m_EditorView),
2496 glm::value_ptr(m_EditorProjection),
2497 operation,
2498 mode,
2499 glm::value_ptr(transformMatrix));
2500
2501 const bool gizmoUsing = ImGuizmo::IsUsing();
2502 if (gizmoUsing && !m_GizmoWasUsing)
2503 m_TransformEditSnapshot = m_Scene->Copy();
2504
2505 if (gizmoUsing)
2506 {
2507 float translation[3]{};
2508 float rotationDegrees[3]{};
2509 float scale[3]{};
2510
2511 ImGuizmo::DecomposeMatrixToComponents(
2512 glm::value_ptr(transformMatrix),
2513 translation,
2514 rotationDegrees,
2515 scale);
2516
2517 // Gizmo operates in world space. Scene converts it back
2518 // into the selected entity's local transform if it has a parent.
2519 m_Scene->SetWorldTransform(
2520 m_SelectedEntity,
2521 transformMatrix);
2522 }
2523
2524 if (!gizmoUsing && m_GizmoWasUsing && m_TransformEditSnapshot)
2525 PushUndoSnapshot(std::move(m_TransformEditSnapshot));
2526
2527 m_GizmoWasUsing = gizmoUsing;
2528 }
2529
2530 // Small toolbar over the scene.
2531 ImGui::SetCursorScreenPos(
2532 ImVec2(viewportMin.x + 10.0f, viewportMin.y + 10.0f));
2533
2534 ImGui::BeginGroup();
2535
2536 if (ImGui::Button("W Move"))
2537 m_GizmoOperation = 0;
2538
2539 ImGui::SameLine();
2540
2541 if (ImGui::Button("E Rotate"))
2542 m_GizmoOperation = 1;
2543
2544 ImGui::SameLine();
2545
2546 if (ImGui::Button("R Scale"))
2547 m_GizmoOperation = 2;
2548
2549 ImGui::EndGroup();
2550
2551 ImGui::SetCursorScreenPos(
2552 ImVec2(viewportMin.x + 10.0f, viewportMin.y + 42.0f));
2553
2554 ImGui::TextDisabled(
2555 "RMB + mouse: camera | WASD: move | "
2556 "Q/E: down/up | Shift: faster");
2557
2558 ImGui::End();
2559 ImGui::PopStyleVar();
2560 }
2561
2562 void EditorLayer::DrawConsole()
2563 {
2564 ImGui::Begin("Console");
2565 ImGui::Text("[Info] NoJobEngine editor started.");
2566 ImGui::Text("[Info] Scene entity management active.");
2567 ImGui::Text(
2568 "[Info] Right click Hierarchy to create objects.");
2569#ifdef _WIN32
2570 std::vector<std::string> scriptConsoleSnapshot;
2571 {
2572 std::lock_guard<std::mutex> lock(s_ScriptConsoleMutex);
2573 scriptConsoleSnapshot = s_ScriptConsole;
2574 }
2575 if (!scriptConsoleSnapshot.empty())
2576 {
2577 ImGui::SeparatorText("Native Scripting");
2578 for (const auto& line : scriptConsoleSnapshot)
2579 ImGui::TextUnformatted(line.c_str());
2580 }
2581#endif
2582 ImGui::End();
2583 }
2584
2585
2586 std::string EditorLayer::OpenInspectorAudioFileDialog()
2587 {
2588 return OpenAudioFileDialog();
2589 }
2590
2591 std::string EditorLayer::OpenInspectorTextureFileDialog()
2592 {
2593 return OpenTextureFileDialog();
2594 }
2595
2596 void EditorLayer::LogInspectorMessage(const std::string& message)
2597 {
2598 ScriptLog(message);
2599 }
2600
2601 void EditorLayer::DrawProjectPanel()
2602 {
2603 m_ProjectPanel.Draw(
2604 m_Scene,
2605 m_SelectedEntity,
2606 m_DefaultCubeMesh,
2607 m_DefaultCubeMaterial,
2608 [this](const std::filesystem::path& path) { CreateModelEntity(path); },
2609 ScriptLog);
2610 }
2611
2612 void EditorLayer::DrawGraphicsSettings()
2613 {
2614 if (!ImGui::Begin("Graphics Settings", &m_ShowGraphicsSettings))
2615 {
2616 ImGui::End();
2617 return;
2618 }
2619
2620 ImGui::TextUnformatted("NoJobEngine Rendering Pipeline");
2621 ImGui::SeparatorText("HDR / Tone Mapping");
2622 ImGui::Checkbox("HDR", &m_GraphicsSettings.HDR);
2623 ImGui::SliderFloat("Exposure", &m_GraphicsSettings.Exposure, 0.1f, 3.0f);
2624
2625 ImGui::SeparatorText("Environment / IBL");
2626 ImGui::Checkbox(
2627 "Image Based Lighting", &m_GraphicsSettings.ImageBasedLighting);
2628 ImGui::SliderFloat(
2629 "Environment Intensity",
2630 &m_GraphicsSettings.EnvironmentIntensity, 0.0f, 4.0f);
2631 ImGui::SliderFloat(
2632 "Diffuse IBL",
2633 &m_GraphicsSettings.DiffuseIBLStrength, 0.0f, 1.0f);
2634 ImGui::SliderFloat(
2635 "Specular IBL",
2636 &m_GraphicsSettings.SpecularIBLStrength, 0.0f, 1.0f);
2637 ImGui::SliderFloat(
2638 "Environment Rotation",
2639 &m_GraphicsSettings.EnvironmentRotation, -180.0f, 180.0f,
2640 "%.0f deg");
2641
2642 if (ImGui::Button("Load HDRI..."))
2643 {
2644 const std::string path = OpenHDRIFileDialog();
2645 if (!path.empty())
2646 {
2647 std::filesystem::path selected(path);
2648 std::error_code ec;
2649 const auto relative = std::filesystem::relative(
2650 selected, m_ProjectPanel.GetCurrentDirectoryPath(), ec);
2651 if (!ec && !relative.empty() &&
2652 relative.generic_string().rfind("..", 0) != 0)
2653 {
2654 m_GraphicsSettings.EnvironmentHDRIPath =
2655 relative.generic_string();
2656 }
2657 else
2658 {
2659 m_GraphicsSettings.EnvironmentHDRIPath =
2660 selected.lexically_normal().string();
2661 }
2662 }
2663 }
2664 ImGui::SameLine();
2665 if (ImGui::Button("Clear HDRI"))
2666 m_GraphicsSettings.EnvironmentHDRIPath.clear();
2667
2668 if (m_GraphicsSettings.EnvironmentHDRIPath.empty())
2669 ImGui::TextDisabled("Environment: Procedural fallback");
2670 else
2671 {
2672 const std::filesystem::path hdriPath(
2673 m_GraphicsSettings.EnvironmentHDRIPath);
2674 ImGui::TextWrapped(
2675 "HDRI: %s", hdriPath.filename().string().c_str());
2676 }
2677
2678 const char* environmentSizes[] = { "128", "256", "512", "1024" };
2679 int environmentSizeIndex =
2680 m_GraphicsSettings.EnvironmentResolution <= 128 ? 0 :
2681 m_GraphicsSettings.EnvironmentResolution <= 256 ? 1 :
2682 m_GraphicsSettings.EnvironmentResolution <= 512 ? 2 : 3;
2683 if (ImGui::Combo(
2684 "Environment Resolution", &environmentSizeIndex,
2685 environmentSizes, 4))
2686 {
2687 const std::uint32_t sizes[] = { 128, 256, 512, 1024 };
2688 m_GraphicsSettings.EnvironmentResolution =
2689 sizes[environmentSizeIndex];
2690 }
2691
2692 ImGui::TextDisabled(
2693 "HDRI is converted to cubemaps and precomputed for real-time IBL.");
2694
2695 ImGui::SeparatorText("Bloom");
2696 ImGui::Checkbox("Bloom", &m_GraphicsSettings.Bloom);
2697 ImGui::SliderFloat("Bloom Threshold", &m_GraphicsSettings.BloomThreshold, 0.1f, 5.0f);
2698 ImGui::SliderFloat("Bloom Strength", &m_GraphicsSettings.BloomStrength, 0.0f, 1.0f);
2699
2700 ImGui::SeparatorText("Ambient Occlusion");
2701 ImGui::Checkbox("Screen Space AO", &m_GraphicsSettings.ScreenSpaceAO);
2702 ImGui::SliderFloat("AO Intensity", &m_GraphicsSettings.AOIntensity, 0.0f, 1.0f);
2703
2704 ImGui::SeparatorText("Anti-Aliasing");
2705 ImGui::Checkbox("FXAA", &m_GraphicsSettings.FXAA);
2706
2707 ImGui::Separator();
2708 ImGui::TextWrapped("ACES filmic tone mapping and final gamma conversion are applied once at the end of the HDR pipeline.");
2709 ImGui::End();
2710 }
2711
2712
2713 // V1.9 native Behavior Tree asset graph editor. Nodes are stored in stable
2714 // parent-first order; editor coordinates are derived from depth/order.
2715 static void DrawBTAssetEditorWindow(bool* opened)
2716 {
2717 static BTAsset asset = BTAsset::Default();
2718 static std::string currentName = "Default";
2719 static char assetName[128] = "Default";
2720 static int selected = 1;
2721 // Per-parent child creation drafts. A draft is not a property of the
2722 // currently selected node and must not leak between selections.
2723 struct ChildDraft { int Kind = 0; char Native[128] = "StopMoving"; };
2724 static std::unordered_map<BTNodeID, ChildDraft> childDrafts;
2725 static std::string childDraftAsset;
2726 static std::string message;
2727 static bool dirty = false;
2728 // Editor-only callback catalog. Never construct project-script instances here:
2729 // project DLLs may have a different C++ ABI / lifetime than the editor.
2730 // Names are metadata; execution callbacks belong exclusively to the runtime.
2731 const auto registeredCallbacks = []() {
2732 std::vector<std::string> actions{
2733 "ChaseTarget", "MoveForward", "Patrol", "StopMoving"
2734 };
2735 std::vector<std::string> conditions{
2736 "CanSeeTarget", "HasRememberedTarget"
2737 };
2738 // Metadata is copied out of ScriptRegistry; never instantiate scripts,
2739 // build a temporary BTNativeRegistry, or capture DLL callbacks here.
2740 for (const auto& entry : ProjectScriptManager::BehaviorTreeCallbackCatalog()) {
2741 if (entry.Name.empty()) continue;
2742 auto& destination = entry.IsCondition ? conditions : actions;
2743 destination.push_back(entry.Name);
2744 }
2745 auto normalize = [](std::vector<std::string>& names) {
2746 std::sort(names.begin(), names.end());
2747 names.erase(std::unique(names.begin(), names.end()), names.end());
2748 };
2749 normalize(actions);
2750 normalize(conditions);
2751 return std::make_pair(std::move(actions), std::move(conditions));
2752 }();
2753 const auto callbackPicker = [&](const char* label, const char* kind, std::string& value) {
2754 const bool condition = std::string_view(kind) == "Condition";
2755 const auto& names = condition ? registeredCallbacks.second : registeredCallbacks.first;
2756 if (ImGui::BeginCombo(label, value.c_str())) {
2757 for (const auto& name : names) {
2758 if (ImGui::Selectable(name.c_str(), value == name)) {
2759 if (value != name) { value = name; dirty = true; }
2760 }
2761 }
2762 ImGui::EndCombo();
2763 }
2764 if (std::find(names.begin(), names.end(), value) == names.end() && value != "-")
2765 ImGui::TextDisabled("Custom/unavailable callback: %s", value.c_str());
2766 };
2767 if (!ImGui::Begin("Behavior Tree Editor", opened)) { ImGui::End(); return; }
2768 const std::filesystem::path folder = BTAssetDirectory();
2769 const auto validName = [](const std::string& name) {
2770 if (name.empty() || name == "." || name == ".." || name.back() == '.' || name.back() == ' ') return false;
2771 return name.find_first_of("/\\:*?\"<>|") == std::string::npos;
2772 };
2773 const auto assetPath = [&](const std::string& name) { return BTAssetPath(name); };
2774 ImGui::TextUnformatted("Native Decision System - V1.9");
2775 ImGui::Text("Current asset: %s%s",currentName.c_str(),dirty ? " *" : "");
2776 const std::vector<std::string> available = ListBTAssetNames();
2777 // Restore the last opened asset on the first editor frame. Previously
2778 // BTAsset::Default() was displayed even when a saved .njbt existed.
2779 static bool initialAssetLoaded = false;
2780 const auto lastAssetPath = folder / ".last-opened-bt";
2781 const auto rememberAsset = [&](const std::string& name) {
2782 std::error_code ec;
2783 std::filesystem::create_directories(folder, ec);
2784 if (ec) return;
2785 std::ofstream out(lastAssetPath, std::ios::trunc);
2786 if (out) out << name << '\n';
2787 };
2788 if (!initialAssetLoaded) {
2789 initialAssetLoaded = true;
2790 std::string preferred;
2791 { std::ifstream in(lastAssetPath); std::getline(in, preferred); }
2792 const auto existsInList = [&](const std::string& name) {
2793 return std::find(available.begin(), available.end(), name) != available.end();
2794 };
2795 if (!existsInList(preferred))
2796 preferred = existsInList(currentName) ? currentName
2797 : (available.empty() ? std::string{} : available.front());
2798 if (!preferred.empty()) {
2799 try {
2800 BTAsset loaded = BTAsset::Load(assetPath(preferred));
2801 asset = std::move(loaded);
2802 currentName = preferred;
2803 std::snprintf(assetName, sizeof(assetName), "%s", preferred.c_str());
2804 selected = static_cast<int>(asset.Nodes.front().ID);
2805 dirty = false;
2806 message = "Restored " + assetPath(preferred).string();
2807 } catch (const std::exception& ex) {
2808 message = "Could not restore saved tree: " + std::string(ex.what());
2809 }
2810 }
2811 }
2812 if (ImGui::BeginCombo("Saved trees",currentName.c_str())) {
2813 for (const auto& name : available) {
2814 if (ImGui::Selectable(name.c_str(),name == currentName)) {
2815 try {
2816 auto loaded = BTAsset::Load(assetPath(name));
2817 asset = std::move(loaded); currentName = name;
2818 std::snprintf(assetName,sizeof(assetName),"%s",name.c_str());
2819 selected = static_cast<int>(asset.Nodes.front().ID);
2820 dirty = false; rememberAsset(name); message = "Loaded " + assetPath(name).string();
2821 } catch (const std::exception& ex) { message = ex.what(); }
2822 }
2823 }
2824 ImGui::EndCombo();
2825 }
2826 ImGui::InputText("Tree name",assetName,sizeof(assetName));
2827 if (ImGui::Button("Load")) {
2828 try {
2829 auto loaded = BTAsset::Load(assetPath(assetName));
2830 asset = std::move(loaded); currentName = assetName;
2831 selected = static_cast<int>(asset.Nodes.front().ID);
2832 dirty = false; rememberAsset(currentName); message = "Loaded " + assetPath(currentName).string();
2833 } catch (const std::exception& ex) { message = ex.what(); }
2834 }
2835 ImGui::SameLine();
2836 if (ImGui::Button("Save")) {
2837 try {
2838 if (!validName(currentName)) throw std::runtime_error("Invalid tree name");
2839 asset.Save(assetPath(currentName)); dirty = false; rememberAsset(currentName);
2840 message = "Saved " + std::filesystem::absolute(assetPath(currentName)).string();
2841 } catch (const std::exception& ex) { message = ex.what(); }
2842 }
2843 ImGui::SameLine();
2844 if (ImGui::Button("Save As")) {
2845 try {
2846 const std::string name(assetName);
2847 if (!validName(name)) throw std::runtime_error("Invalid tree name");
2848 if (name != currentName && std::filesystem::exists(assetPath(name)))
2849 throw std::runtime_error("A tree with that name already exists");
2850 asset.Save(assetPath(name)); currentName = name; dirty = false; rememberAsset(name);
2851 message = "Saved " + std::filesystem::absolute(assetPath(name)).string();
2852 } catch (const std::exception& ex) { message = ex.what(); }
2853 }
2854 ImGui::SameLine();
2855 if (ImGui::Button("New")) {
2856 asset = BTAsset::Default(); selected = 1; dirty = true;
2857 currentName = "Untitled";
2858 std::snprintf(assetName,sizeof(assetName),"%s",currentName.c_str());
2859 message = "New tree. Enter a name and click Save As.";
2860 }
2861 if (!message.empty()) ImGui::TextWrapped("%s",message.c_str());
2862 ImGui::Separator();
2863 // Layout lives in an editor-only sidecar. Runtime .njbt format stays unchanged.
2864 static std::unordered_map<BTNodeID, ImVec2> layout;
2865 static std::string layoutAsset;
2866 static bool layoutDirty = false;
2867 const auto layoutPath = [&](const std::string& name) { return folder / (name + ".njbt.layout"); };
2868 const auto loadLayout = [&](const std::string& name) {
2869 layout.clear();
2870 std::ifstream in(layoutPath(name));
2871 BTNodeID id; float x, y;
2872 while (in >> id >> x >> y) layout[id] = ImVec2(x,y);
2873 layoutDirty = false;
2874 };
2875 const auto saveLayout = [&](const std::string& name) {
2876 std::filesystem::create_directories(folder);
2877 std::ofstream out(layoutPath(name), std::ios::trunc);
2878 if (!out) throw std::runtime_error("Cannot save visual layout");
2879 for (const auto& [id, pos] : layout) out << id << ' ' << pos.x << ' ' << pos.y << '\n';
2880 if (!out) throw std::runtime_error("Cannot write visual layout");
2881 layoutDirty = false;
2882 };
2883 if (layoutAsset != currentName) { loadLayout(currentName); layoutAsset = currentName; }
2884 if (ImGui::Button("Save Layout")) {
2885 try { saveLayout(currentName); message = "Layout saved for " + currentName; }
2886 catch (const std::exception& e) { message = e.what(); }
2887 }
2888 ImGui::SameLine();
2889 if (ImGui::Button("Auto Arrange")) { layout.clear(); layoutDirty = true; }
2890 ImGui::SameLine();
2891 ImGui::TextDisabled("Drag nodes to arrange | Layout: %s", layoutDirty ? "unsaved" : "saved");
2892 ImGui::BeginChild("BTCanvas", ImVec2(0, -155), true, ImGuiWindowFlags_HorizontalScrollbar);
2893 const ImVec2 origin = ImGui::GetCursorScreenPos();
2894 constexpr float w = 188.f, h = 68.f, dx = 240.f, dy = 105.f;
2895 std::unordered_map<BTNodeID,ImVec2> positions;
2896 for (std::size_t i=0; i<asset.Nodes.size(); ++i) {
2897 const auto& n=asset.Nodes[i];
2898 int depth=0; BTNodeID ancestor=n.Parent;
2899 while (ancestor && depth<32) {
2900 ++depth; BTNodeID next=0;
2901 for (const auto& parent:asset.Nodes) if (parent.ID==ancestor) {next=parent.Parent;break;}
2902 ancestor=next;
2903 }
2904 if (!layout.contains(n.ID)) {
2905 layout[n.ID] = ImVec2(24.f + depth*dx, 22.f + static_cast<float>(i)*dy);
2906 layoutDirty = true;
2907 }
2908 positions[n.ID] = ImVec2(origin.x + layout.at(n.ID).x, origin.y + layout.at(n.ID).y);
2909 }
2910 auto* draw=ImGui::GetWindowDrawList();
2911 const ImU32 wireColor = IM_COL32(130,150,175,220);
2912 for (const auto& n:asset.Nodes) if (n.Parent && positions.contains(n.Parent)) {
2913 const auto a=positions.at(n.Parent), b=positions.at(n.ID);
2914 draw->AddBezierCubic(ImVec2(a.x+w,a.y+h/2), ImVec2(a.x+w+50,a.y+h/2),
2915 ImVec2(b.x-50,b.y+h/2),ImVec2(b.x,b.y+h/2),wireColor,2.5f);
2916 }
2917 float maxX=800.f, maxY=400.f;
2918 for (const auto& n:asset.Nodes) {
2919 const ImVec2 at=positions.at(n.ID);
2920 ImGui::SetCursorScreenPos(at);
2921 ImGui::PushID(static_cast<int>(n.ID));
2922 const bool active=selected==static_cast<int>(n.ID);
2923 const ImVec4 tint = n.Kind=="Decorator" ? ImVec4(.58f,.31f,.13f,1.f)
2924 : n.Kind=="Service" ? ImVec4(.16f,.43f,.55f,1.f)
2925 : n.Kind=="Parallel" ? ImVec4(.47f,.25f,.49f,1.f)
2926 : n.Kind=="Selector" ? ImVec4(.38f,.22f,.56f,1.f)
2927 : n.Kind=="Sequence" ? ImVec4(.20f,.38f,.66f,1.f)
2928 : n.Kind=="Condition" ? ImVec4(.65f,.43f,.14f,1.f)
2929 : ImVec4(.17f,.48f,.37f,1.f);
2930 ImGui::PushStyleColor(ImGuiCol_Button,tint);
2931 ImGui::PushStyleColor(ImGuiCol_ButtonHovered,ImVec4(std::min(tint.x+.12f,1.f),std::min(tint.y+.12f,1.f),std::min(tint.z+.12f,1.f),1.f));
2932 ImGui::PushStyleColor(ImGuiCol_ButtonActive,tint);
2933 std::string label = n.Kind + "##node";
2934 if (ImGui::Button(label.c_str(),ImVec2(w,h))) selected=static_cast<int>(n.ID);
2935 if (ImGui::IsItemActive() && ImGui::IsMouseDragging(ImGuiMouseButton_Left,2.f)) {
2936 const auto delta=ImGui::GetIO().MouseDelta;
2937 auto& pos=layout[n.ID];
2938 pos.x=std::max(0.f,pos.x+delta.x);
2939 pos.y=std::max(0.f,pos.y+delta.y);
2940 layoutDirty=true;
2941 selected=static_cast<int>(n.ID);
2942 }
2943 ImGui::PopStyleColor(3);
2944 if (active) draw->AddRect(ImVec2(at.x-3,at.y-3),ImVec2(at.x+w+3,at.y+h+3),IM_COL32(245,220,125,255),7.f,0,2.5f);
2945 const std::string subtitle = (n.Native=="-" ? "Composite" : n.Native);
2946 draw->AddText(ImVec2(at.x+12,at.y+38),IM_COL32(240,244,249,255),subtitle.c_str());
2947 draw->AddCircleFilled(ImVec2(at.x+w,at.y+h/2),5.f,IM_COL32(225,232,245,255));
2948 if (n.Parent) draw->AddCircleFilled(ImVec2(at.x,at.y+h/2),5.f,IM_COL32(225,232,245,255));
2949 ImGui::PopID();
2950 maxX=std::max(maxX,layout.at(n.ID).x+w+55.f);
2951 maxY=std::max(maxY,layout.at(n.ID).y+h+55.f);
2952 }
2953 ImGui::SetCursorScreenPos(origin);
2954 ImGui::Dummy(ImVec2(maxX,maxY));
2955 ImGui::EndChild();
2956 ImGui::SeparatorText("Selected node");
2957 BTAssetNode* current=nullptr;
2958 for (auto& n:asset.Nodes) if (n.ID==static_cast<BTNodeID>(selected)) current=&n;
2959 if (current) {
2960 if (childDraftAsset != currentName) {
2961 childDrafts.clear();
2962 childDraftAsset = currentName;
2963 }
2964 ChildDraft& childDraft = childDrafts[current->ID];
2965 ImGui::Text("#%llu %s",static_cast<unsigned long long>(current->ID),current->Kind.c_str());
2966 // This changes the SELECTED node; Child type below only affects new nodes.
2967 const char* nodeKinds[] = {"Sequence","Selector","Action","Condition","Decorator","Service","Parallel"};
2968 int selectedKind = 0;
2969 for (int k = 0; k < 7; ++k)
2970 if (current->Kind == nodeKinds[k]) { selectedKind = k; break; }
2971 if (ImGui::Combo("Node type##selected", &selectedKind, nodeKinds, 7)) {
2972 const bool hasChildren = std::any_of(asset.Nodes.begin(), asset.Nodes.end(),
2973 [&](const BTAssetNode& n) { return n.Parent == current->ID; });
2974 const bool leaf = selectedKind == 2 || selectedKind == 3;
2975 if (leaf && hasChildren) {
2976 message = "Remove child nodes before converting this node to Action/Condition.";
2977 } else {
2978 current->Kind = nodeKinds[selectedKind];
2979 if (selectedKind == 2 || selectedKind == 3) {
2980 if (current->Native == "-" || current->Native.empty())
2981 current->Native = selectedKind == 2 ? "StopMoving" : "CanSeeTarget";
2982 } else if (selectedKind == 0 || selectedKind == 1 || selectedKind == 6) {
2983 current->Native = "-";
2984 } else if (current->Native == "-" || current->Native.empty()) {
2985 current->Native = "StopMoving";
2986 }
2987 dirty = true;
2988 }
2989 }
2990 if (current->Kind=="Action" || current->Kind=="Condition" ||
2991 current->Kind=="Decorator" || current->Kind=="Service") {
2992 ImGui::Text("Native callback: %s",current->Native.c_str());
2993 }
2994 if (current->Kind=="Decorator" || current->Kind=="Service") {
2995 ImGui::TextDisabled("Decorator/Service must have exactly one child");
2996 }
2997 if (current->Kind=="Decorator" || current->Kind=="Service" ||
2998 current->Kind=="Action" || current->Kind=="Condition") {
2999 // The callback belongs to the selected BTAssetNode, never to a global field.
3000 // Reload the edit buffer on node/asset changes (including same ID in another tree).
3001 static BTNodeID editID = 0;
3002 static std::string editAsset;
3003 static std::string editKind;
3004 static char editNative[128] = {};
3005 static char editKey[128] = {};
3006 if (editID != current->ID || editAsset != currentName || editKind != current->Kind) {
3007 editID = current->ID;
3008 editAsset = currentName;
3009 editKind = current->Kind;
3010 std::snprintf(editNative, sizeof(editNative), "%s", current->Native.c_str());
3011 std::snprintf(editKey, sizeof(editKey), "%s", current->Parameter.c_str());
3012 }
3013 callbackPicker("Registered callback##selected", current->Kind.c_str(), current->Native);
3014 // Synchronize after selecting a registered name.
3015 if (current->Native != editNative)
3016 std::snprintf(editNative, sizeof(editNative), "%s", current->Native.c_str());
3017 if (ImGui::InputText("Native name##selected", editNative, sizeof(editNative))) {
3018 current->Native = editNative;
3019 dirty = true;
3020 }
3021 if (current->Kind=="Decorator" && ImGui::InputText("Observed Blackboard key",editKey,sizeof(editKey))) {
3022 current->Parameter=editKey[0] ? editKey : "-"; dirty=true;
3023 }
3024 if (current->Kind=="Service" && ImGui::DragFloat("Interval (seconds)",&current->Interval,.05f,.05f,60.f)) {
3025 current->Interval=std::max(.05f,current->Interval); dirty=true;
3026 }
3027 }
3028 const char* kinds[]={"Sequence","Selector","Action","Condition","Decorator","Service","Parallel"};
3029 ImGui::SeparatorText("Create child (not selected node properties)");
3030 ImGui::PushID(static_cast<int>(current->ID));
3031 ImGui::Combo("Child type", &childDraft.Kind, kinds, 7);
3032 if (childDraft.Kind >= 2 && childDraft.Kind != 6) {
3033 std::string proposed(childDraft.Native);
3034 callbackPicker("Registered callback##new", kinds[childDraft.Kind], proposed);
3035 if (proposed != childDraft.Native)
3036 std::snprintf(childDraft.Native, sizeof(childDraft.Native), "%s", proposed.c_str());
3037 ImGui::InputText("New child native name", childDraft.Native, sizeof(childDraft.Native));
3038 }
3039 ImGui::PopID();
3040 if (ImGui::Button("Add child")) {
3041 if (current->Kind=="Action" || current->Kind=="Condition") message="Cannot add children to a leaf";
3042 else {
3043 BTNodeID id=1; for (const auto& n:asset.Nodes) id=std::max(id,n.ID+1);
3044 asset.Nodes.push_back({id,static_cast<BTNodeID>(selected),kinds[childDraft.Kind],
3045 (childDraft.Kind>=2 && childDraft.Kind!=6)?childDraft.Native:"-"});
3046 selected=static_cast<int>(id); dirty=true;
3047 }
3048 }
3049 ImGui::SameLine();
3050 if (ImGui::Button("Delete branch") && current->Parent) {
3051 std::unordered_set<BTNodeID> removed{current->ID};
3052 bool changed=true;
3053 while (changed) {
3054 changed=false;
3055 for (const auto& n:asset.Nodes) if (removed.contains(n.Parent) && !removed.contains(n.ID)) {
3056 removed.insert(n.ID); changed=true;
3057 }
3058 }
3059 asset.Nodes.erase(std::remove_if(asset.Nodes.begin(),asset.Nodes.end(),
3060 [&](const BTAssetNode& n){return removed.contains(n.ID);}),asset.Nodes.end());
3061 selected=static_cast<int>(asset.Nodes.front().ID);
3062 for (BTNodeID id : removed) childDrafts.erase(id);
3063 dirty = true;
3064 }
3065 }
3066 ImGui::End();
3067 }
3068
3069 void EditorLayer::DrawAIDebugger()
3070 {
3071 if (!m_ShowAIDebugger) return;
3072 if (!ImGui::Begin("AI Debugger", &m_ShowAIDebugger)) { ImGui::End(); return; }
3073 if (!m_Scene) { ImGui::TextDisabled("No scene loaded."); ImGui::End(); return; }
3074
3075 ImGui::TextColored(m_IsPlaying ? ImVec4(0.3f, 0.9f, 0.5f, 1.0f) : ImVec4(0.8f, 0.8f, 0.8f, 1.0f),
3076 "%s", m_IsPlaying ? (m_IsPaused ? "PAUSED" : "LIVE - PLAY MODE") : "EDIT MODE - runtime data unavailable");
3077 ImGui::SameLine();
3078 ImGui::Checkbox("Active only", &m_AIDebugOnlyActive);
3079 ImGui::Separator();
3080 auto entities = m_Scene->GetEntities();
3081 std::vector<Entity> agents;
3082 int visibleTotal = 0, rememberedTotal = 0;
3083 for (auto entity : entities)
3084 {
3085 if (!entity.HasComponent<PerceptionComponent>() && !entity.HasComponent<NavAgentComponent>() &&
3086 (!entity.HasComponent<NativeScriptComponent>() || (entity.GetComponent<NativeScriptComponent>().ScriptName != "BTAssetAgent" && entity.GetComponent<NativeScriptComponent>().ScriptName != "NeuralTrainingAgent" && entity.GetComponent<NativeScriptComponent>().ScriptName != "GenericNeuralAgent" && entity.GetComponent<NativeScriptComponent>().ScriptName != "PongAgent"))) continue;
3087 if (m_AIDebugOnlyActive && entity.HasComponent<PerceptionComponent>() && !entity.GetComponent<PerceptionComponent>().Enabled) continue;
3088 agents.push_back(entity);
3089 if (entity.HasComponent<PerceptionComponent>() && m_IsPlaying)
3090 for (const auto& target : m_Scene->GetPerceivedTargets(entity.GetHandle()))
3091 target.IsVisible ? ++visibleTotal : ++rememberedTotal;
3092 }
3093 ImGui::Text("Agents: %d Visible: %d Remembered: %d", (int)agents.size(), visibleTotal, rememberedTotal);
3094 ImGui::Separator();
3095 if (ImGui::BeginChild("##AI_Agents", ImVec2(190, 0), true))
3096 {
3097 for (auto agent : agents)
3098 {
3099 const auto& name = agent.GetComponent<TagComponent>().Tag;
3100 const std::string label = name + "##AI" + std::to_string(agent.GetHandle());
3101 if (ImGui::Selectable(label.c_str(), m_AIDebugAgent == agent.GetHandle()))
3102 m_AIDebugAgent = agent.GetHandle();
3103 }
3104 }
3105 ImGui::EndChild();
3106 ImGui::SameLine();
3107 ImGui::BeginGroup();
3108 if (!m_Scene->IsValid(m_AIDebugAgent) ||
3109 std::none_of(agents.begin(), agents.end(), [&](Entity e) { return e.GetHandle() == m_AIDebugAgent; }))
3110 m_AIDebugAgent = agents.empty() ? 0 : agents.front().GetHandle();
3111 if (m_AIDebugAgent)
3112 {
3113 Entity agent(m_AIDebugAgent, m_Scene);
3114 if (ImGui::CollapsingHeader("Agent Information")) {
3115 ImGui::Text("Agent: %s", agent.GetComponent<TagComponent>().Tag.c_str());
3116 }
3117 if (ImGui::Button("Select in Hierarchy")) SetSelectedEntity(agent);
3118 if (ImGui::CollapsingHeader("Behavior Tree", ImGuiTreeNodeFlags_DefaultOpen)) {
3119 if (m_IsPlaying) {
3120 if (const auto bt=m_Scene->GetBehaviorTreeDebug(m_AIDebugAgent)) {
3121 ImGui::TextDisabled("Per-agent runtime snapshot (read-only)");
3122 const char* result=bt->LastResult==0?"Success":bt->LastResult==1?"Failure":"Running";
3123 ImGui::Text("Root: %s",result);
3124 // The graph and timeline observe the SAME per-agent runtime snapshot.
3125 // Never tick the BT from the editor; never mistake historical events
3126 // for complete historical snapshots of every node.
3127 static std::uint32_t timelineAgent = 0;
3128 static std::uint64_t timelineNode = 0;
3129 static std::uint64_t timelineTick = 0;
3130 static std::string timelineKind;
3131 static float graphZoom = 1.0f;
3132 if (timelineAgent != m_AIDebugAgent) {
3133 timelineAgent = m_AIDebugAgent;
3134 timelineNode = 0;
3135 timelineTick = 0;
3136 timelineKind.clear();
3137 }
3138 ImGui::SetNextItemWidth(145.0f);
3139 ImGui::SliderFloat("Graph zoom", &graphZoom, 0.65f, 1.65f, "%.2fx");
3140 ImGui::SameLine();
3141 if (ImGui::SmallButton("Clear event selection")) {
3142 timelineNode = 0;
3143 timelineTick = 0;
3144 timelineKind.clear();
3145 }
3146 if (bt->Nodes.empty()) {
3147 ImGui::TextDisabled("No compiled nodes to display.");
3148 } else {
3149 // Preorder + Depth are captured from the compiled BT runtime.
3150 // Compute subtree widths bottom-up so sibling branches do not overlap.
3151 const int count = static_cast<int>(bt->Nodes.size());
3152 std::vector<int> parents(count, -1);
3153 std::vector<std::vector<int>> children(count);
3154 std::vector<int> stack;
3155 for (int i = 0; i < count; ++i) {
3156 const int depth = std::max(0, bt->Nodes[i].Depth);
3157 while (static_cast<int>(stack.size()) > depth) stack.pop_back();
3158 if (!stack.empty()) {
3159 parents[i] = stack.back();
3160 children[stack.back()].push_back(i);
3161 }
3162 stack.push_back(i);
3163 }
3164 std::vector<float> widths(count, 1.0f), centers(count, 0.0f);
3165 for (int i = count - 1; i >= 0; --i) {
3166 if (!children[i].empty()) {
3167 float total = 0.0f;
3168 for (int child : children[i]) total += widths[child];
3169 widths[i] = std::max(1.0f, total);
3170 }
3171 }
3172 float cursor = 0.0f;
3173 std::function<void(int, float)> layout = [&](int index, float left) {
3174 centers[index] = left + widths[index] * 0.5f;
3175 float childLeft = left;
3176 for (int child : children[index]) {
3177 layout(child, childLeft);
3178 childLeft += widths[child];
3179 }
3180 if (!children[index].empty())
3181 centers[index] = (centers[children[index].front()] + centers[children[index].back()]) * 0.5f;
3182 };
3183 int maxDepth = 0;
3184 for (int i = 0; i < count; ++i) {
3185 maxDepth = std::max(maxDepth, std::max(0, bt->Nodes[i].Depth));
3186 if (parents[i] < 0) { layout(i, cursor); cursor += widths[i]; }
3187 }
3188 const float nodeW = 156.0f * graphZoom;
3189 const float nodeH = 49.0f * graphZoom;
3190 const float stepX = 180.0f * graphZoom;
3191 const float stepY = 90.0f * graphZoom;
3192 const float canvasW = std::max(330.0f, (cursor + 0.4f) * stepX);
3193 const float canvasH = (maxDepth + 1) * stepY + 36.0f * graphZoom;
3194 ImGui::BeginChild("##BTLiveGraph", ImVec2(0, 320), true,
3195 ImGuiWindowFlags_HorizontalScrollbar);
3196 const ImVec2 origin = ImGui::GetCursorScreenPos();
3197 ImGui::InvisibleButton("##BTGraphCanvas", ImVec2(canvasW, canvasH));
3198 ImDrawList* draw = ImGui::GetWindowDrawList();
3199 auto pos = [&](int i) {
3200 return ImVec2(origin.x + centers[i] * stepX,
3201 origin.y + 12.0f * graphZoom + std::max(0, bt->Nodes[i].Depth) * stepY);
3202 };
3203 for (int i = 0; i < count; ++i) {
3204 if (parents[i] < 0) continue;
3205 const ImVec2 a = pos(parents[i]), b = pos(i);
3206 const ImVec2 start(a.x, a.y + nodeH);
3207 const ImVec2 end(b.x, b.y);
3208 const float middle = (start.y + end.y) * 0.5f;
3209 const ImU32 lineColor = IM_COL32(105, 116, 137, 210);
3210 draw->AddLine(start, ImVec2(start.x, middle), lineColor, 1.5f);
3211 draw->AddLine(ImVec2(start.x, middle), ImVec2(end.x, middle), lineColor, 1.5f);
3212 draw->AddLine(ImVec2(end.x, middle), end, lineColor, 1.5f);
3213 }
3214 for (int i = 0; i < count; ++i) {
3215 const auto& node = bt->Nodes[i];
3216 const ImVec2 center = pos(i);
3217 const ImVec2 lo(center.x - nodeW * 0.5f, center.y);
3218 const ImVec2 hi(center.x + nodeW * 0.5f, center.y + nodeH);
3219 const bool selected = timelineNode == node.ID && timelineTick != 0;
3220 const ImU32 tint = node.Status < 0 ? IM_COL32(120, 130, 144, 255)
3221 : node.Status == 0 ? IM_COL32(60, 195, 110, 255)
3222 : node.Status == 1 ? IM_COL32(225, 85, 78, 255)
3223 : IM_COL32(92, 162, 245, 255);
3224 draw->AddRectFilled(lo, hi, IM_COL32(38, 44, 57, 255), 7.0f);
3225 draw->AddRect(lo, hi, selected ? IM_COL32(255, 215, 100, 255) : tint,
3226 7.0f, 0, selected ? 3.0f : (node.Active ? 2.5f : 1.5f));
3227 const float fontScale = graphZoom < 0.85f ? 0.85f : 1.0f;
3228 (void)fontScale;
3229 std::string label = node.Label;
3230 if (label.size() > 24) label = label.substr(0, 21) + "...";
3231 const char* state = node.Status < 0 ? "IDLE" : node.Status == 0 ? "SUCCESS"
3232 : node.Status == 1 ? "FAILURE" : "RUNNING";
3233 draw->AddText(ImVec2(lo.x + 8.0f, lo.y + 7.0f), IM_COL32(240, 242, 247, 255), label.c_str());
3234 draw->AddText(ImVec2(lo.x + 8.0f, lo.y + 26.0f * graphZoom), tint, state);
3235 if (node.Active)
3236 draw->AddCircleFilled(ImVec2(hi.x - 11.0f, lo.y + 11.0f), 4.0f, tint);
3237 if (ImGui::IsMouseHoveringRect(lo, hi, true)) {
3238 ImGui::SetTooltip("%s\nNode ID: %llu\nTicks: %zu\nExecuted this tick: %s",
3239 node.Label.c_str(), static_cast<unsigned long long>(node.ID),
3240 node.Ticks, node.Active ? "Yes" : "No");
3241 if (ImGui::IsMouseClicked(ImGuiMouseButton_Left)) {
3242 timelineNode = node.ID;
3243 timelineTick = 0;
3244 timelineKind.clear();
3245 }
3246 }
3247 }
3248 ImGui::EndChild();
3249 ImGui::TextDisabled("Blue Running | Green Success | Red Failure | Gray Idle");
3250 ImGui::TextDisabled("Scroll to pan; Shift+wheel for horizontal scroll. Click a node for details.");
3251 if (timelineNode != 0) {
3252 for (const auto& node : bt->Nodes) if (node.ID == timelineNode) {
3253 ImGui::SeparatorText("Selected node");
3254 ImGui::Text("%s | ID %llu | Ticks %zu", node.Label.c_str(),
3255 static_cast<unsigned long long>(node.ID), node.Ticks);
3256 if (timelineTick != 0)
3257 ImGui::Text("Selected event: tick %llu (%s)",
3258 static_cast<unsigned long long>(timelineTick), timelineKind.c_str());
3259 ImGui::TextDisabled("Node color represents the LIVE snapshot, not the historical event.");
3260 break;
3261 }
3262 }
3263 }
3264 if (ImGui::CollapsingHeader("Execution Timeline", ImGuiTreeNodeFlags_DefaultOpen)) {
3265 ImGui::TextDisabled("Per-agent bounded event history (latest first; ticks, not wall-clock time)");
3266 // Presentation-only filters: the recorded event history remains unchanged.
3267 static bool showActions = true;
3268 static bool showConditions = true;
3269 static bool showPriority = true;
3270 static bool showBlackboard = true;
3271 static char blackboardKeyFilter[128] = {};
3272 ImGui::Checkbox("Actions", &showActions);
3273 ImGui::SameLine(); ImGui::Checkbox("Conditions", &showConditions);
3274 ImGui::SameLine(); ImGui::Checkbox("Priority / Other", &showPriority);
3275 ImGui::SameLine(); ImGui::Checkbox("Blackboard", &showBlackboard);
3276 ImGui::SetNextItemWidth(-1.0f);
3277 ImGui::InputTextWithHint("##BlackboardKeyFilter", "Blackboard key filter (e.g. TargetPosition)",
3278 blackboardKeyFilter, sizeof(blackboardKeyFilter));
3279 ImGui::BeginChild("##BTEventTimeline", ImVec2(0, 190), true);
3280 if (bt->Events.empty()) ImGui::TextDisabled("No events recorded yet.");
3281 int eventIndex = 0;
3282 for (auto it = bt->Events.rbegin(); it != bt->Events.rend(); ++it, ++eventIndex) {
3283 const auto& e = *it;
3284 const bool isBlackboard = e.Kind == "Blackboard";
3285 const bool isAction = !isBlackboard && e.Detail.find("Action:") != std::string::npos;
3286 const bool isCondition = !isBlackboard && e.Detail.find("Condition:") != std::string::npos;
3287 if (isBlackboard && !showBlackboard) continue;
3288 if (isAction && !showActions) continue;
3289 if (isCondition && !showConditions) continue;
3290 if (!isBlackboard && !isAction && !isCondition && !showPriority) continue;
3291 if (isBlackboard && blackboardKeyFilter[0] != '\0') {
3292 const std::string key = e.Detail.substr(0, e.Detail.find(':'));
3293 if (key.find(blackboardKeyFilter) == std::string::npos) continue;
3294 }
3295 const ImVec4 tint = e.Kind == "Blackboard" ? ImVec4(.55f,.82f,.98f,1.f)
3296 : e.Kind == "Aborted" || e.Kind == "Failed"
3297 ? ImVec4(.95f,.42f,.32f,1.f)
3298 : e.Kind == "Succeeded" ? ImVec4(.3f,.85f,.5f,1.f)
3299 : e.Kind == "Running" ? ImVec4(.4f,.68f,1.f,1.f)
3300 : ImVec4(.95f,.8f,.35f,1.f);
3301 std::string nodeLabel = "Blackboard / Tree";
3302 for (const auto& node : bt->Nodes)
3303 if (node.ID == e.Node) { nodeLabel = node.Label; break; }
3304 ImGui::PushID(eventIndex);
3305 const std::string caption = "Tick " + std::to_string(e.Tick) + " | " + e.Kind + " | " + nodeLabel;
3306 const bool chosen = timelineTick == e.Tick && timelineNode == e.Node && timelineKind == e.Kind;
3307 if (ImGui::Selectable(caption.c_str(), chosen)) {
3308 timelineNode = e.Node;
3309 timelineTick = e.Tick;
3310 timelineKind = e.Kind;
3311 }
3312 if (ImGui::IsItemHovered() && !e.Detail.empty()) ImGui::SetTooltip("%s", e.Detail.c_str());
3313 if (!e.Detail.empty()) {
3314 ImGui::Indent();
3315 ImGui::TextColored(tint, "%s", e.Detail.c_str());
3316 ImGui::Unindent();
3317 }
3318 ImGui::PopID();
3319 }
3320 ImGui::EndChild();
3321 }
3322 if (ImGui::CollapsingHeader("Blackboard")) {
3323 ImGui::TextDisabled("Agent memory | %zu keys | revision %llu", bt->BlackboardEntries.size(),
3324 static_cast<unsigned long long>(bt->BlackboardRevision));
3325 if (bt->BlackboardEntries.empty()) ImGui::TextDisabled("No Blackboard keys set");
3326 else if (ImGui::BeginTable("##BTBlackboard", 3,
3327 ImGuiTableFlags_BordersInnerV | ImGuiTableFlags_RowBg | ImGuiTableFlags_Resizable | ImGuiTableFlags_ScrollY,
3328 ImVec2(0, 180))) {
3329 ImGui::TableSetupColumn("Key");
3330 ImGui::TableSetupColumn("Type");
3331 ImGui::TableSetupColumn("Value");
3332 ImGui::TableHeadersRow();
3333 for (const auto& entry : bt->BlackboardEntries) {
3334 ImGui::TableNextRow();
3335 ImGui::TableSetColumnIndex(0); ImGui::TextUnformatted(entry.Key.c_str());
3336 ImGui::TableSetColumnIndex(1); ImGui::TextDisabled("%s", entry.Type.c_str());
3337 ImGui::TableSetColumnIndex(2); ImGui::TextUnformatted(entry.Value.c_str());
3338 }
3339 ImGui::EndTable();
3340 }
3341 }
3342 } else ImGui::TextDisabled("No Behavior Tree debug data for this agent.");
3343 } else ImGui::TextDisabled("Available during Play.");
3344 }
3345 if (ImGui::CollapsingHeader("Behavior State")) {
3346 if (!m_IsPlaying)
3347 ImGui::TextDisabled("Available during Play.");
3348 else if (const auto debug = m_Scene->GetAIDebugState(m_AIDebugAgent))
3349 {
3350 const ImVec4 stateColor =
3351 debug->Current == "FLEE" ? ImVec4(1.0f, 0.4f, 0.35f, 1.0f) :
3352 debug->Current == "CHASE" ? ImVec4(1.0f, 0.78f, 0.25f, 1.0f) :
3353 ImVec4(0.4f, 0.85f, 0.55f, 1.0f);
3354 ImGui::TextColored(stateColor, "CURRENT: %s", debug->Current.c_str());
3355 ImGui::Text("Previous: %s", debug->Previous.empty() ? "-" : debug->Previous.c_str());
3356 ImGui::Text("Time in state: %.2f s", debug->TimeInState);
3357 if (ImGui::TreeNode("State Transitions"))
3358 {
3359 if (debug->History.empty()) ImGui::TextDisabled("No transitions yet.");
3360 for (auto it = debug->History.rbegin(); it != debug->History.rend(); ++it)
3361 ImGui::Text("%.1f s %s -> %s", it->AtSeconds, it->From.c_str(), it->To.c_str());
3362 ImGui::TreePop();
3363 }
3364 }
3365 else
3366 ImGui::TextDisabled("No runtime AI state (script missing or inactive).");
3367 }
3368 if (agent.HasComponent<PerceptionComponent>())
3369 {
3370 const auto& perception = agent.GetComponent<PerceptionComponent>();
3371 if (ImGui::CollapsingHeader("Perception")) {
3372 ImGui::Text("Enabled: %s | Debug: %s", perception.Enabled ? "Yes" : "No", perception.DebugDraw ? "On" : "Off");
3373 ImGui::Text("Radius: %.2f m | FOV: %.1f deg", perception.DetectionRadius, perception.FieldOfView);
3374 ImGui::Text("Eye: %.2f m | Interval: %.2f s", perception.EyeHeight, perception.UpdateInterval);
3375 ImGui::Text("Memory: %.2f s | Layer mask: 0x%08X", perception.MemoryDuration, (unsigned)perception.DetectionMask);
3376 ImGui::SeparatorText("Last Seen Target");
3377 ImGui::Checkbox("Show Last Seen Position in Scene", &m_AIDebugShowLastSeenMarker);
3378 if (!m_IsPlaying)
3379 ImGui::TextDisabled("Available during Play.");
3380 else if (const auto lastSeen = m_Scene->GetLastSeenTarget(m_AIDebugAgent))
3381 {
3382 const std::string name = m_Scene->IsValid(lastSeen->EntityHandle)
3383 ? Entity(lastSeen->EntityHandle, m_Scene).GetComponent<TagComponent>().Tag
3384 : "Unknown";
3385 ImGui::Text("Last target: %s (%u)", name.c_str(), lastSeen->EntityHandle);
3386 ImGui::TextColored(lastSeen->IsVisible ? ImVec4(0.3f, 0.9f, 0.4f, 1) : ImVec4(1, 0.8f, 0.3f, 1),
3387 "%s", lastSeen->IsVisible ? "VISIBLE" : "LOST SIGHT");
3388 ImGui::Text("Last detected: %.2f s ago", lastSeen->TimeSinceLastSeen);
3389 ImGui::Text("Last known position: X %.2f Y %.2f Z %.2f",
3390 lastSeen->Position.x, lastSeen->Position.y, lastSeen->Position.z);
3391 }
3392 else
3393 ImGui::TextDisabled("No target seen yet.");
3394 ImGui::SeparatorText("Tracked targets");
3395 const auto targets = m_IsPlaying ? m_Scene->GetPerceivedTargets(m_AIDebugAgent) : std::vector<Scene::PerceptionTargetInfo>{};
3396 if (targets.empty()) ImGui::TextDisabled("No tracked targets.");
3397 for (const auto& target : targets)
3398 {
3399 const std::string name = m_Scene->IsValid(target.EntityHandle)
3400 ? Entity(target.EntityHandle, m_Scene).GetComponent<TagComponent>().Tag : "Unknown";
3401 ImGui::PushID((int)target.EntityHandle);
3402 if (ImGui::TreeNodeEx("Target", ImGuiTreeNodeFlags_None, "%s (%u)", name.c_str(), target.EntityHandle))
3403 {
3404 ImGui::TextColored(target.IsVisible ? ImVec4(0.3f, 0.9f, 0.4f, 1) : ImVec4(1, 0.8f, 0.3f, 1),
3405 "%s", target.IsVisible ? "VISIBLE" : "REMEMBERED");
3406 ImGui::Text("Visible for: %.2f s", target.VisibleDuration);
3407 ImGui::Text("Tracked for: %.2f s", target.TrackedDuration);
3408 ImGui::Text("Last seen: %.2f s ago", target.TimeSinceLastSeen);
3409 ImGui::Text("Last position: %.2f, %.2f, %.2f", target.LastKnownPosition.x, target.LastKnownPosition.y, target.LastKnownPosition.z);
3410 const float remaining = target.IsVisible ? 1.0f :
3411 (perception.MemoryDuration > 0 ? std::clamp(1.0f - target.TimeSinceLastSeen / perception.MemoryDuration, 0.0f, 1.0f) : 0.0f);
3412 ImGui::ProgressBar(remaining, ImVec2(-1, 0), "Memory remaining");
3413 ImGui::TreePop();
3414 }
3415 ImGui::PopID();
3416 }
3417 }
3418 }
3419 if (agent.HasComponent<NativeScriptComponent>() &&
3420 (agent.GetComponent<NativeScriptComponent>().ScriptName == "NeuralTrainingAgent" ||
3421 agent.GetComponent<NativeScriptComponent>().ScriptName == "BTAssetAgent" ||
3422 agent.GetComponent<NativeScriptComponent>().ScriptName == "GenericNeuralAgent" ||
3423 agent.GetComponent<NativeScriptComponent>().ScriptName == "PongAgent")) {
3424 NeuralAgent::Snapshot snap;
3425 bool hasNeuralSnapshot = m_IsPlaying && NeuralAgent::Read(m_AIDebugAgent, snap);
3426 // Project scripts live in a separate DLL: its header-inline diagnostic map
3427 // is not the Editor's map. Query the running script instance instead.
3428 if (m_IsPlaying && !hasNeuralSnapshot) {
3429 const auto& scriptName = agent.GetComponent<NativeScriptComponent>().ScriptName;
3430 if (auto* runtime = m_Scene->FindRuntimeScript(m_AIDebugAgent, scriptName))
3431 hasNeuralSnapshot = runtime->GetNeuralDebugSnapshot(snap);
3432 }
3433 if (hasNeuralSnapshot &&
3434 ImGui::CollapsingHeader("Neural Inspector - Live",ImGuiTreeNodeFlags_DefaultOpen)) {
3435 ImGui::Text("Model: %s",snap.model.c_str());
3436 ImGui::Text("Status: %s | Target distance: %.2f",snap.status.c_str(),snap.distance);
3437 auto drawValues=[](const char* title,const std::vector<float>& values) {
3438 ImGui::TextUnformatted(title);
3439 for(size_t i=0;i<values.size();++i) {
3440 ImGui::PushID(static_cast<int>(i));
3441 ImGui::ProgressBar(std::clamp((values[i]+1.f)*0.5f,0.f,1.f),ImVec2(120,0));
3442 ImGui::SameLine(); ImGui::Text("[%d] %.4f",static_cast<int>(i),values[i]);
3443 ImGui::PopID();
3444 }
3445 };
3446 drawValues("Inputs",snap.inputs);
3447 drawValues("Predictions",snap.outputs);
3448 // Animated feed-forward graph. Read-only: no editor-side
3449 // mutation of the model or live agent state.
3450 static bool showNeuralGraph = true;
3451 ImGui::Checkbox("Animated neural graph", &showNeuralGraph);
3452 if (showNeuralGraph && snap.activations.size() >= 2) {
3453 const float graphWidth = std::max(260.f, ImGui::GetContentRegionAvail().x);
3454 const float graphHeight = 230.f;
3455 const ImVec2 origin = ImGui::GetCursorScreenPos();
3456 ImGui::InvisibleButton("##NeuralFeedForwardGraph", ImVec2(graphWidth, graphHeight));
3457 ImDrawList* dl = ImGui::GetWindowDrawList();
3458 dl->AddRectFilled(origin, ImVec2(origin.x+graphWidth,origin.y+graphHeight),
3459 IM_COL32(17,23,34,255), 5.f);
3460 const size_t count = snap.activations.size();
3461 const float time = static_cast<float>(ImGui::GetTime());
3462 const float phase = std::fmod(time * 0.65f, 1.f);
3463 auto nodePos = [&](size_t layer, size_t neuron, size_t n) {
3464 return ImVec2(origin.x + 22.f + (graphWidth-44.f)*float(layer)/float(count-1),
3465 origin.y + 24.f + (graphHeight-48.f)*(float(neuron)+0.5f)/float(n));
3466 };
3467 for (size_t l=1; l<count; ++l) {
3468 const auto& previous = snap.activations[l-1];
3469 const auto& current = snap.activations[l];
3470 const size_t a = std::min(previous.size(),size_t(24));
3471 const size_t b = std::min(current.size(),size_t(24));
3472 for(size_t i=0;i<a;++i) for(size_t j=0;j<b;++j) {
3473 const ImVec2 from=nodePos(l-1,i,a), to=nodePos(l,j,b);
3474 const float strength=std::clamp(std::abs(previous[i]*current[j]),0.f,1.f);
3475 dl->AddLine(from,to,IM_COL32(75,128,172,int(28+90*strength)),1.f);
3476 // Moving particle indicates propagation direction,
3477 // not a measured propagation delay.
3478 const float t=std::fmod(phase*float(count-1)+float(count-1)-(float(l)-1.f),1.f);
3479 const float visiblePhase=phase*float(count-1)-(float(l)-1.f);
3480 if(visiblePhase>=0.f && visiblePhase<=1.f && strength>0.08f) {
3481 const ImVec2 dot(from.x+(to.x-from.x)*t,from.y+(to.y-from.y)*t);
3482 dl->AddCircleFilled(dot,1.3f+1.5f*strength,IM_COL32(255,205,90,205));
3483 }
3484 }
3485 }
3486 for(size_t l=0;l<count;++l) {
3487 const auto& layer=snap.activations[l];
3488 const size_t n=std::min(layer.size(),size_t(24));
3489 for(size_t j=0;j<n;++j) {
3490 const ImVec2 center=nodePos(l,j,n);
3491 const float value=std::clamp(layer[j],-1.f,1.f);
3492 const ImU32 color=value>=0.f
3493 ? IM_COL32(70, int(115+125*value), 225, 255)
3494 : IM_COL32(int(115+120*(-value)), 95, 165, 255);
3495 dl->AddCircleFilled(center,5.f,color);
3496 dl->AddCircle(center,5.f,IM_COL32(215,225,240,190),0,1.f);
3497 }
3498 }
3499 ImGui::TextDisabled("Live activations | animated signal flow (illustrative)");
3500 if (std::any_of(snap.activations.begin(),snap.activations.end(),
3501 [](const auto& layer){return layer.size()>24;}))
3502 ImGui::TextDisabled("Graph displays first 24 neurons per layer");
3503 }
3504 if(ImGui::TreeNode("Layer activations")) {
3505 for(size_t i=0;i<snap.activations.size();++i) {
3506 ImGui::PushID(static_cast<int>(i));
3507 if(ImGui::TreeNodeEx("##neural_layer", ImGuiTreeNodeFlags_None, "Layer %d (%d neurons)", static_cast<int>(i), static_cast<int>(snap.activations[i].size()))) {
3508 drawValues("Activations",snap.activations[i]);
3509 ImGui::TreePop();
3510 }
3511 ImGui::PopID();
3512 }
3513 ImGui::TreePop();
3514 }
3515 if(ImGui::TreeNode("Weights and biases (saved model)")) {
3516 try {
3517 // Disk snapshot. To inspect changes made by training, reopen this section after saving.
3518 const auto model=Neural::NeuralNetwork::Load(NeuralAssetPath(snap.model).string());
3519 for(size_t layer=0;layer<model.Layers().size();++layer) {
3520 ImGui::PushID(static_cast<int>(layer));
3521 const auto& dense=model.Layers()[layer];
3522 if(ImGui::TreeNodeEx("##neural_dense", ImGuiTreeNodeFlags_None, "Dense %d (%d x %d)", static_cast<int>(layer), static_cast<int>(dense.Outputs()), static_cast<int>(dense.Inputs()))) {
3523 for(size_t neuron=0;neuron<dense.Outputs();++neuron) {
3524 ImGui::Text("Neuron %d | bias %.5f",static_cast<int>(neuron),dense.Biases()[neuron]);
3525 for(size_t input=0;input<dense.Inputs();++input) {
3526 ImGui::SameLine();
3527 ImGui::TextDisabled("w%d:%.3f",static_cast<int>(input),dense.Weights()(neuron,input));
3528 }
3529 }
3530 ImGui::TreePop();
3531 }
3532 ImGui::PopID();
3533 }
3534 } catch(const std::exception& e) { ImGui::TextDisabled("Cannot load model: %s",e.what()); }
3535 ImGui::TreePop();
3536 }
3537 }
3538 }
3539 if (agent.HasComponent<NavAgentComponent>())
3540 {
3541 const auto& nav = agent.GetComponent<NavAgentComponent>();
3542 if (ImGui::CollapsingHeader("Navigation")) {
3543 ImGui::Text("Enabled: %s | Speed: %.2f", nav.Enabled ? "Yes" : "No", nav.Speed);
3544 ImGui::Text("Destination: %s", nav.HasDestination ? "Set" : "None");
3545 if (nav.HasDestination) ImGui::Text("(%.2f, %.2f, %.2f)", nav.Destination.x, nav.Destination.y, nav.Destination.z);
3546 ImGui::Text("Stopping distance: %.2f", nav.StoppingDistance);
3547 }
3548 }
3549 }
3550 else ImGui::TextDisabled("No AI agents in this scene.");
3551 ImGui::EndGroup();
3552 ImGui::End();
3553 }
3554
3555 void EditorLayer::DrawRendererProfiler()
3556 {
3557 if (!m_ShowRendererProfiler)
3558 return;
3559
3560 if (!ImGui::Begin("Renderer Profiler", &m_ShowRendererProfiler))
3561 {
3562 ImGui::End();
3563 return;
3564 }
3565
3566 const auto& rendererStats = SceneRenderer::GetStatistics();
3567 const ImGuiIO& io = ImGui::GetIO();
3568
3569 ImGui::TextUnformatted("NoJobEngine Renderer V3");
3570 ImGui::SeparatorText("Frame");
3571 ImGui::Text("FPS: %.1f", io.Framerate);
3572 ImGui::Text("Frame Time: %.2f ms",
3573 io.Framerate > 0.0f ? 1000.0f / io.Framerate : 0.0f);
3574
3575 ImGui::SeparatorText("Scene Renderer");
3576 ImGui::Text("CPU Time: %.3f ms", rendererStats.CPUTimeMs);
3577 if (rendererStats.GPUTimeValid)
3578 ImGui::Text("GPU Time: %.3f ms", rendererStats.GPUTimeMs);
3579 else
3580 ImGui::TextDisabled("GPU Time: warming up...");
3581
3582 ImGui::SeparatorText("Geometry");
3583 ImGui::Text("Draw Calls: %u", rendererStats.DrawCalls);
3584 ImGui::Text("Triangles: %llu",
3585 static_cast<unsigned long long>(rendererStats.Triangles));
3586
3587 ImGui::SeparatorText("Shadows");
3588 ImGui::Text("Shadow Passes: %u", rendererStats.ShadowPasses);
3589 ImGui::Text("Shadow Draw Calls: %u",
3590 rendererStats.ShadowDrawCalls);
3591 ImGui::Text("Shadow Triangles: %llu",
3592 static_cast<unsigned long long>(rendererStats.ShadowTriangles));
3593
3594 ImGui::Separator();
3595 ImGui::TextDisabled(
3596 "GPU timing uses non-blocking queries with a 3-frame ring.");
3597 ImGui::End();
3598 }
3599
3601 {
3602 const bool requested = m_SaveSceneRequested;
3603 m_SaveSceneRequested = false;
3604 return requested;
3605 }
3606
3608 {
3609 const bool requested = m_SaveSceneAsRequested;
3610 m_SaveSceneAsRequested = false;
3611 return requested;
3612 }
3613
3615 {
3616 const bool requested = m_LoadSceneRequested;
3617 m_LoadSceneRequested = false;
3618 return requested;
3619 }
3620
3622 {
3623 const bool requested = m_GraphicsTestSceneRequested;
3624 m_GraphicsTestSceneRequested = false;
3625 return requested;
3626 }
3627
3628}
Animation declarations for the Animation subsystem.
AssetManager declarations for the Asset subsystem.
AssetRegistry declarations for the Asset Management subsystem.
AudioEngine declarations for the Audio subsystem.
BTAsset declarations for the Behavior Trees subsystem.
BTAssetPaths declarations for the Behavior Trees subsystem.
BTGameplay declarations for the Behavior Trees subsystem.
BuildSettings declarations for the Build and Packaging subsystem.
Components declarations for the Scenes and Native Scripting subsystem.
Main editor interaction, rendering and debugging layer.
Material declarations for the Rendering subsystem.
MaterialSerializer declarations for the Asset Management subsystem.
Mesh declarations for the Rendering subsystem.
Built-in gameplay scripts and neural agent examples.
NeuralEditorPanel declarations for the Editor Panels subsystem.
PrefabSerializer declarations for the Asset Management subsystem.
ProjectAssetOperations declarations for the Asset Management subsystem.
ProjectPanel declarations for the Asset Management subsystem.
Project-native script build orchestration and reload notifications.
Project script discovery, compilation and runtime loading.
Scene declarations for the Scenes and Native Scripting subsystem.
SceneFileDialog declarations for the Scenes and Native Scripting subsystem.
SceneRenderer declarations for the Scenes and Native Scripting subsystem.
Registration and creation of native gameplay scripts.
StandaloneBuilder declarations for the Build and Packaging subsystem.
Texture declarations for the Rendering subsystem.
static const std::filesystem::path & GetProjectRoot()
static const std::filesystem::path & GetAssetsDirectory()
static void Init(const std::filesystem::path &projectRoot)
std::vector< BTAssetNode > Nodes
Definition BTAsset.h:34
static BTAsset Default()
Definition BTAsset.h:35
void Save(const std::filesystem::path &path) const
Definition BTAsset.h:83
static BTAsset Load(const std::filesystem::path &path)
Definition BTAsset.h:92
void SetScene(Scene *scene)
void SetSelectedEntity(Entity entity)
void SetEditorCameraMatrices(const glm::mat4 &view, const glm::mat4 &projection)
bool ConsumeGraphicsTestSceneRequest()
void SetRuntimeState(bool playing, bool paused)
void Init(GLFWwindow *window, Scene *scene)
bool ConsumeClearNavMeshRequest()
void SetDefaultCubeAssets(std::shared_ptr< Mesh > mesh, std::shared_ptr< Material > material)
void SetViewportTexture(std::uint32_t textureID)
std::uint32_t GetViewportWidth() const
std::uint32_t GetViewportHeight() const
static void SetLogger(LogFunction logger)
static bool Start(const std::filesystem::path &projectRoot)
Starts compilation for the specified project root.
static bool ConsumeReloadPending()
Consumes the pending reload notification after compilation.
static bool Load(const std::filesystem::path &projectRoot)
static void SetLogger(LogFunction logger)
static std::vector< BTCallbackMetadata > BehaviorTreeCallbackCatalog()
static Result Build(const std::filesystem::path &projectRoot, const std::filesystem::path &cmakeExecutable, const BuildSettings &settings, const LogFunction &log, const ProcessFunction &runProcess)
std::filesystem::path BTAssetPath(const std::string &name)
static NeuralEditorPanel s_NeuralEditorPanel
static void DrawBTAssetEditorWindow(bool *opened)
std::uint64_t BTNodeID
Definition BTContext.h:19
static bool s_ShowBTAssetEditor
static bool s_BuildDefaultDockLayout
std::filesystem::path NeuralAssetPath(const std::string &name)
std::filesystem::path BTAssetDirectory()
std::vector< std::string > ListBTAssetNames()
std::string Kind
Definition BTAsset.h:28
BTNodeID Parent
Definition BTAsset.h:27
std::string Parameter
Definition BTAsset.h:29
std::string Native
Definition BTAsset.h:28
static BuildSettings Load(const std::filesystem::path &projectRoot)