36#include <imgui_internal.h>
37#include <backends/imgui_impl_glfw.h>
38#include <backends/imgui_impl_opengl3.h>
40#include <GLFW/glfw3.h>
42#include <glm/gtc/type_ptr.hpp>
43#include <glm/gtc/constants.hpp>
57#include <unordered_map>
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;
87 bool s_ShowBuildSettings =
false;
88 char s_BuildNameBuffer[128]{};
90 void ScriptLog(std::string message)
92 std::lock_guard<std::mutex> lock(s_ScriptConsoleMutex);
93 s_ScriptConsole.push_back(std::move(message));
98 std::lock_guard<std::mutex> lock(s_ScriptConsoleMutex);
99 s_ScriptConsole.clear();
102 std::filesystem::path FindCMakeExecutable()
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);
111 wchar_t* programFilesX86 =
nullptr;
112 std::size_t envLength = 0;
113 if (_wdupenv_s(&programFilesX86, &envLength, L
"ProgramFiles(x86)") == 0 &&
116 const std::filesystem::path vswhere =
117 std::filesystem::path(programFilesX86) /
118 "Microsoft Visual Studio" /
"Installer" /
"vswhere.exe";
119 free(programFilesX86);
121 if (std::filesystem::exists(vswhere))
123 const std::wstring command =
124 L
"\"" + vswhere.wstring() +
125 L
"\" -latest -products * -property installationPath";
126 FILE* pipe = _wpopen(command.c_str(), L
"rt");
129 wchar_t buffer[4096]{};
130 std::wstring installPath;
131 if (fgetws(buffer,
static_cast<int>(std::size(buffer)), pipe))
132 installPath = buffer;
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();
139 if (!installPath.empty())
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;
150 wchar_t* programFiles =
nullptr;
152 if (_wdupenv_s(&programFiles, &envLength, L
"ProgramFiles") == 0 &&
155 const auto standalone = std::filesystem::path(programFiles) /
156 "CMake" /
"bin" /
"cmake.exe";
158 if (std::filesystem::exists(standalone))
return standalone;
164 int RunProcessToScriptConsole(
165 const std::filesystem::path& executable,
166 const std::vector<std::wstring>& arguments,
167 const std::string& prefix)
170 SECURITY_ATTRIBUTES security{};
171 security.nLength =
sizeof(SECURITY_ATTRIBUTES);
172 security.bInheritHandle = TRUE;
174 HANDLE readPipe =
nullptr;
175 HANDLE writePipe =
nullptr;
176 if (!CreatePipe(&readPipe, &writePipe, &security, 0))
178 ScriptLog(
"[Scripts] CreatePipe failed.");
182 SetHandleInformation(readPipe, HANDLE_FLAG_INHERIT, 0);
184 std::wstring commandLine = L
"\"" + executable.wstring() + L
"\"";
185 for (
const auto& arg : arguments)
187 commandLine += L
" \"";
188 for (
wchar_t c : arg)
191 commandLine += L
'\\';
194 commandLine += L
"\"";
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);
204 PROCESS_INFORMATION process{};
205 std::vector<wchar_t> mutableCommand(
206 commandLine.begin(), commandLine.end());
207 mutableCommand.push_back(L
'\0');
209 const std::wstring workingDirectory =
212 const BOOL created = CreateProcessW(
213 executable.wstring().c_str(),
214 mutableCommand.data(),
220 workingDirectory.c_str(),
224 CloseHandle(writePipe);
228 const DWORD error = GetLastError();
229 CloseHandle(readPipe);
231 "[Scripts] CreateProcess failed (Win32 error " +
232 std::to_string(error) +
").");
242 static_cast<DWORD
>(
sizeof(buffer)),
247 pending.append(buffer, buffer + bytesRead);
249 std::size_t newline = 0;
250 while ((newline = pending.find(
'\n')) != std::string::npos)
252 std::string line = pending.substr(0, newline);
253 pending.erase(0, newline + 1);
254 if (!line.empty() && line.back() ==
'\r')
257 ScriptLog(prefix + line);
261 if (!pending.empty())
263 if (!pending.empty() && pending.back() ==
'\r')
265 if (!pending.empty())
266 ScriptLog(prefix + pending);
269 WaitForSingleObject(process.hProcess, INFINITE);
272 GetExitCodeProcess(process.hProcess, &exitCode);
274 CloseHandle(process.hThread);
275 CloseHandle(process.hProcess);
276 CloseHandle(readPipe);
278 return static_cast<int>(exitCode);
287 bool BuildStandalone()
289 if (s_StandaloneBuildRunning.exchange(
true))
291 ScriptLog(
"[Build] Standalone build is already running.");
296 const auto cmake = FindCMakeExecutable();
299 ScriptLog(
"[Build] CMake was not found.");
300 s_StandaloneBuildRunning =
false;
304 s_StandaloneBuildSucceeded =
false;
305 if (s_StandaloneBuildThread.joinable())
306 s_StandaloneBuildThread.join();
309 s_StandaloneBuildThread = std::thread([root, cmake, 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)
320 return RunProcessToScriptConsole(executable, arguments, prefix);
323 s_StandaloneBuildSucceeded = result.
Succeeded;
324 if (result.Succeeded)
325 s_LastStandaloneBuildDirectory = result.OutputDirectory;
326 s_StandaloneBuildRunning =
false;
331 bool CompileProjectScripts()
335 ScriptLog(
"[Scripts] Compilation is already running.");
342 ScriptLog(
"[Scripts] Starting asynchronous script compilation...");
347 std::filesystem::path FindNoJobProjectRoot()
349 auto containsProject = [](
const std::filesystem::path& directory)
352 if (!std::filesystem::exists(directory, ec))
355 bool hasProjectFile =
false;
356 for (
const auto& entry :
357 std::filesystem::directory_iterator(
359 std::filesystem::directory_options::skip_permission_denied,
363 if (entry.is_regular_file() &&
364 entry.path().extension() ==
".nojobproject")
366 hasProjectFile =
true;
371 return hasProjectFile &&
372 std::filesystem::exists(directory /
"CMakeLists.txt", ec);
375 auto walkUp = [&](std::filesystem::path start)
376 -> std::filesystem::path
379 start = std::filesystem::absolute(start, ec).lexically_normal();
381 while (!start.empty())
383 if (containsProject(start))
386 const auto parent = start.parent_path();
395 if (
auto root = walkUp(std::filesystem::current_path()); !root.empty())
401 std::wstring executable(MAX_PATH, L
'\0');
402 const DWORD length = GetModuleFileNameW(
403 nullptr, executable.data(),
static_cast<DWORD
>(executable.size()));
406 executable.resize(length);
408 walkUp(std::filesystem::path(executable).parent_path());
414 return std::filesystem::current_path();
417 ImVec2 ProjectColliderPoint(
418 const glm::vec3& point,
419 const glm::mat4& viewProjection,
420 const ImVec2& viewportMin,
421 const ImVec2& viewportSize,
424 const glm::vec4 clip = viewProjection * glm::vec4(point, 1.0f);
425 if (clip.w <= 0.0001f)
431 const glm::vec3 ndc = glm::vec3(clip) / clip.w;
432 visible = ndc.z >= -1.0f && ndc.z <= 1.0f;
435 viewportMin.x + (ndc.x * 0.5f + 0.5f) * viewportSize.x,
436 viewportMin.y + (1.0f - (ndc.y * 0.5f + 0.5f)) * viewportSize.y
440 void DrawColliderLine(
441 ImDrawList* drawList,
444 const glm::mat4& viewProjection,
445 const ImVec2& viewportMin,
446 const ImVec2& viewportSize,
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);
457 if (!visibleA && !visibleB)
460 drawList->AddLine(screenA, screenB, color, thickness);
463 glm::vec3 ColliderTransformPoint(
464 const glm::mat4& transform,
465 const glm::vec3& point)
467 return glm::vec3(transform * glm::vec4(point, 1.0f));
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,
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}
489 for (
int i = 0; i < 8; ++i)
490 points[i] = ColliderTransformPoint(world, local[i]);
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}
498 for (
const auto& edge : edges)
500 drawList, points[edge[0]], points[edge[1]],
501 viewProjection, viewportMin, viewportSize,
505 void DrawColliderEllipse(
506 ImDrawList* drawList,
507 const glm::mat4& world,
511 const glm::vec3& offset,
512 const glm::mat4& viewProjection,
513 const ImVec2& viewportMin,
514 const ImVec2& viewportSize,
518 constexpr int segments = 48;
519 glm::vec3 previous{};
520 bool hasPrevious =
false;
522 for (
int i = 0; i <= segments; ++i)
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);
530 glm::vec3 local = offset;
532 local.y += c * radiusA;
533 local.z += s * radiusB;
535 else if (plane == 1) {
536 local.x += c * radiusA;
537 local.z += s * radiusB;
540 local.x += c * radiusA;
541 local.y += s * radiusB;
544 const glm::vec3 current =
545 ColliderTransformPoint(world, local);
549 drawList, previous, current,
550 viewProjection, viewportMin, viewportSize,
558 void DrawSphereColliderWire(
559 ImDrawList* drawList,
560 const glm::mat4& world,
562 const glm::mat4& viewProjection,
563 const ImVec2& viewportMin,
564 const ImVec2& viewportSize,
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);
577 void DrawCapsuleColliderWire(
578 ImDrawList* drawList,
579 const glm::mat4& world,
582 const glm::mat4& viewProjection,
583 const ImVec2& viewportMin,
584 const ImVec2& viewportSize,
588 radius = std::max(radius, 0.005f);
589 height = std::max(height, radius * 2.0f);
590 const float halfCylinder = height * 0.5f - radius;
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);
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}
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}
612 for (
int i = 0; i < 4; ++i)
615 ColliderTransformPoint(world, top[i]),
616 ColliderTransformPoint(world, bottom[i]),
617 viewProjection, viewportMin, viewportSize,
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);
631 void DrawPerceptionWire(
632 ImDrawList* drawList,
633 const glm::mat4& world,
635 const glm::mat4& viewProjection,
636 const ImVec2& viewportMin,
637 const ImVec2& viewportSize,
642 if (!perception.Enabled || !perception.DebugDraw)
645 const float radius = std::max(0.0f, perception.DetectionRadius);
646 if (radius <= 0.0001f)
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));
653 if (glm::length(forward) < 0.0001f)
654 forward = { 0, 0, -1 };
656 forward = glm::normalize(forward);
659 const glm::vec3 right = glm::normalize(
660 glm::cross(forward, glm::vec3(0, 1, 0)));
662 constexpr int circleSegments = 64;
663 for (
int i = 0; i < circleSegments; ++i)
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);
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)
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));
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);
695 void DrawSceneColliderGizmos(
698 const glm::mat4& view,
699 const glm::mat4& projection,
700 const ImVec2& viewportMin,
701 const ImVec2& viewportSize,
704 bool showLastSeenMarker,
705 std::uint32_t debugAgent)
707 if (viewportSize.x <= 1.0f || viewportSize.y <= 1.0f)
710 ImDrawList* drawList = ImGui::GetWindowDrawList();
711 drawList->PushClipRect(
713 { viewportMin.x + viewportSize.x,
714 viewportMin.y + viewportSize.y },
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;
722 for (
Entity entity : scene.GetEntities())
725 const std::uint64_t entityID =
727 const bool selected =
728 selectedID != 0 && entityID == selectedID;
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);
738 const glm::mat4 world = scene.GetWorldTransform(entity);
743 entity.GetComponent<BoxColliderComponent>();
745 drawList, world, c.Size,
746 viewProjection, viewportMin, viewportSize,
747 c.IsTrigger ? triggerColor : normalColor,
754 entity.GetComponent<SphereColliderComponent>();
755 DrawSphereColliderWire(
756 drawList, world, c.Radius,
757 viewProjection, viewportMin, viewportSize,
758 c.IsTrigger ? triggerColor : normalColor,
765 entity.GetComponent<CapsuleColliderComponent>();
766 DrawCapsuleColliderWire(
767 drawList, world, c.Radius, c.Height,
768 viewProjection, viewportMin, viewportSize,
769 c.IsTrigger ? triggerColor : normalColor,
773 const glm::vec3 origin =
774 ColliderTransformPoint(world, { 0.0f, 0.0f, 0.0f });
776 ColliderTransformPoint(world, { 0.0f, 0.0f, -1.0f }) -
778 if (glm::length(forward) > 0.0001f)
779 forward = glm::normalize(forward);
781 forward = { 0.0f, 0.0f, -1.0f };
784 const auto& perception =
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),
800 if (isPlaying && showAIDebugger &&
801 perception.Enabled && perception.DebugDraw)
804 scene.GetPerceivedTargets(entity.GetHandle());
806 for (
const auto& target : targets)
811 glm::vec3 markerPosition =
812 target.LastKnownPosition;
814 if (target.IsVisible &&
815 scene.IsValid(target.EntityHandle))
817 markerPosition = glm::vec3(
818 scene.GetWorldTransform(
819 Entity(target.EntityHandle, &scene))[3]);
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);
833 bool onScreen =
false;
835 const ImVec2 screenPosition =
836 ProjectColliderPoint(
846 const ImU32 markerColor = target.IsVisible
847 ? IM_COL32(50, 230, 110, 255)
848 : IM_COL32(255, 205, 65, 255);
850 drawList->AddCircleFilled(
867 if (isPlaying && showAIDebugger && showLastSeenMarker &&
868 entity.GetHandle() == debugAgent)
870 const auto lastSeen = scene.GetLastSeenTarget(entity.GetHandle());
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)
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);
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);
893 drawList->AddText(projected, yellow,
"LAST SEEN");
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);
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));
917 if (camera.ProjectionType ==
918 CameraProjectionType::Perspective)
921 std::tan(glm::radians(camera.PerspectiveFOV * 0.5f))
923 halfWidth = halfHeight *
924 (viewportSize.x / std::max(viewportSize.y, 1.0f));
928 halfHeight = camera.OrthographicSize * 0.25f;
929 halfWidth = halfHeight *
930 (viewportSize.x / std::max(viewportSize.y, 1.0f));
933 const glm::vec3 localCorners[4] = {
934 {-halfWidth,-halfHeight,-distance},
935 { halfWidth,-halfHeight,-distance},
936 { halfWidth, halfHeight,-distance},
937 {-halfWidth, halfHeight,-distance}
939 glm::vec3 corners[4];
940 for (
int i = 0; i < 4; ++i)
943 ColliderTransformPoint(world, localCorners[i]);
945 drawList, origin, corners[i],
946 viewProjection, viewportMin, viewportSize,
947 cameraColor, thickness);
949 for (
int i = 0; i < 4; ++i)
951 drawList, corners[i], corners[(i + 1) % 4],
952 viewProjection, viewportMin, viewportSize,
953 cameraColor, thickness);
961 origin + forward * 1.0f,
962 viewProjection, viewportMin, viewportSize,
963 lightColor, thickness);
971 std::min(std::max(light.Range * 0.04f, 0.12f), 0.55f);
972 DrawSphereColliderWire(
974 glm::translate(glm::mat4(1.0f), origin),
976 viewProjection, viewportMin, viewportSize,
977 lightColor, thickness);
982 const auto& particles =
984 const ImU32 particleColor = selected
985 ? IM_COL32(255, 120, 210, 255)
986 : IM_COL32(220, 90, 185, 155);
989 DrawSphereColliderWire(
991 glm::translate(glm::mat4(1.0f), origin),
992 std::max(particles.ShapeRadius, 0.01f),
993 viewProjection, viewportMin, viewportSize,
994 particleColor, thickness);
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)
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);
1025 if (audio.SpatialBlend > 0.001f)
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);
1040 DrawSphereColliderWire(
1041 drawList, audioWorld,
1042 std::max(audio.MaxDistance, audio.MinDistance + 0.01f),
1043 viewProjection, viewportMin, viewportSize,
1051 const ImU32 listenerColor = selected
1052 ? IM_COL32(255, 150, 90, 255)
1053 : IM_COL32(235, 125, 70, 180);
1055 drawList, origin, origin + forward * 0.8f,
1056 viewProjection, viewportMin, viewportSize,
1057 listenerColor, thickness);
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}
1075 for (
const auto& local : ringLocal)
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);
1090 drawList->PopClipRect();
1093 std::string OpenModelFileDialog() {
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"
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;
1104 std::string OpenHDRIFileDialog()
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"
1115 dialog.nFilterIndex = 1;
1120 if (GetOpenFileNameA(&dialog) == TRUE)
1126 std::string OpenAudioFileDialog()
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"
1140 dialog.nFilterIndex = 1;
1141 dialog.Flags = OFN_PATHMUSTEXIST | OFN_FILEMUSTEXIST | OFN_NOCHANGEDIR;
1142 if (GetOpenFileNameA(&dialog) == TRUE)
return fileName;
1147 std::string OpenTextureFileDialog()
1150 char fileName[MAX_PATH]{};
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"
1161 dialog.nFilterIndex = 1;
1167 if (GetOpenFileNameA(&dialog) == TRUE)
1177 std::snprintf(s_BuildNameBuffer,
sizeof(s_BuildNameBuffer),
"%s", s_BuildSettings.BuildName.c_str());
1184 const auto projectRoot = FindNoJobProjectRoot();
1186 std::filesystem::create_directories(
1188 m_ProjectPanel.Initialize();
1190 IMGUI_CHECKVERSION();
1191 ImGui::CreateContext();
1193 ImGuiIO& io = ImGui::GetIO();
1194 io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard;
1195 io.ConfigFlags |= ImGuiConfigFlags_DockingEnable;
1199 static std::string imguiIniPath =
1201 io.IniFilename = imguiIniPath.c_str();
1207 if (std::filesystem::exists(imguiIniPath))
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;
1217 ImGui::StyleColorsDark();
1219 ImGui_ImplGlfw_InitForOpenGL(window,
true);
1220 ImGui_ImplOpenGL3_Init(
"#version 460");
1227 if (s_StandaloneBuildThread.joinable())
1228 s_StandaloneBuildThread.join();
1231 ImGui_ImplOpenGL3_Shutdown();
1232 ImGui_ImplGlfw_Shutdown();
1233 ImGui::DestroyContext();
1238 ImGui_ImplOpenGL3_NewFrame();
1239 ImGui_ImplGlfw_NewFrame();
1241 ImGuizmo::BeginFrame();
1243 const ImGuiViewport* viewport = ImGui::GetMainViewport();
1244 const ImGuiID dockspaceID = ImGui::GetID(
"NoJobEngineDockSpace");
1246 ImGui::DockSpaceOverViewport(
1249 ImGuiDockNodeFlags_PassthruCentralNode);
1257 ImGui::DockBuilderRemoveNode(dockspaceID);
1258 ImGui::DockBuilderAddNode(
1260 ImGuiDockNodeFlags_PassthruCentralNode);
1261 ImGui::DockBuilderSetNodeSize(
1263 viewport->WorkSize);
1265 ImGuiID mainID = dockspaceID;
1268 ImGuiID leftID = ImGui::DockBuilderSplitNode(
1269 mainID, ImGuiDir_Left, 0.075f,
nullptr, &mainID);
1272 ImGuiID rightID = ImGui::DockBuilderSplitNode(
1273 mainID, ImGuiDir_Right, 0.14f,
nullptr, &mainID);
1276 ImGuiID bottomID = ImGui::DockBuilderSplitNode(
1277 mainID, ImGuiDir_Down, 0.16f,
nullptr, &mainID);
1279 ImGuiID consoleID = ImGui::DockBuilderSplitNode(
1280 bottomID, ImGuiDir_Left, 0.22f,
nullptr, &bottomID);
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);
1288 ImGui::DockBuilderFinish(dockspaceID);
1301 s_ScriptsCompiled =
true;
1302 ScriptLog(
"[Scripts] Hot reload completed successfully.");
1306 s_ScriptsCompiled =
false;
1307 ScriptLog(
"[Scripts] Build succeeded, but DLL reload failed.");
1313 if (ImGui::GetIO().KeyCtrl && ImGui::GetIO().KeyShift &&
1314 ImGui::IsKeyPressed(ImGuiKey_B,
false))
1315 CompileProjectScripts();
1323 if (m_ShowGraphicsSettings)
1324 DrawGraphicsSettings();
1325 DrawRendererProfiler();
1330 if (m_SelectedEntity && ImGui::IsKeyPressed(ImGuiKey_Delete))
1331 DeleteSelectedEntity();
1333 const ImGuiIO& io = ImGui::GetIO();
1335 if (!io.WantTextInput && io.KeyCtrl && ImGui::IsKeyPressed(ImGuiKey_Z))
1343 if (!io.WantTextInput && io.KeyCtrl && ImGui::IsKeyPressed(ImGuiKey_Y))
1346 if (m_SelectedEntity
1348 && ImGui::IsKeyPressed(ImGuiKey_D))
1350 DuplicateSelectedEntity();
1353 if (!io.WantTextInput && m_SelectedEntity && ImGui::IsKeyPressed(ImGuiKey_F2))
1354 m_RenameSelectedRequested =
true;
1356 if (!io.WantTextInput && ImGui::IsKeyPressed(ImGuiKey_Escape))
1357 ClearMultiSelection();
1363 ImGui_ImplOpenGL3_RenderDrawData(ImGui::GetDrawData());
1368 m_SelectedEntity = entity;
1373 m_ViewportTextureID = textureID;
1377 const glm::mat4& view,
1378 const glm::mat4& projection)
1380 m_EditorView = view;
1381 m_EditorProjection = projection;
1385 std::shared_ptr<Mesh> mesh,
1386 std::shared_ptr<Material> material)
1388 m_DefaultCubeMesh = std::move(mesh);
1389 m_DefaultCubeMaterial = std::move(material);
1394 return static_cast<std::uint32_t
>(
1395 std::max(1.0f, m_ViewportWidth));
1400 return static_cast<std::uint32_t
>(
1401 std::max(1.0f, m_ViewportHeight));
1404 Entity EditorLayer::CreateEmptyEntity()
1409 CaptureUndoSnapshot();
1410 Entity entity = m_Scene->CreateEntity(
"Empty Entity");
1411 m_SelectedEntity = entity;
1415 Entity EditorLayer::CreateCubeEntity()
1420 CaptureUndoSnapshot();
1421 Entity entity = m_Scene->CreateEntity(
"Cube");
1423 if (m_DefaultCubeMesh)
1424 entity.AddComponent<MeshComponent>(m_DefaultCubeMesh);
1426 if (m_DefaultCubeMaterial)
1430 auto material = std::make_shared<Material>(
1431 m_DefaultCubeMaterial->GetShader(),
1432 m_DefaultCubeMaterial->GetColor());
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());
1450 entity.AddComponent<MeshRendererComponent>(material);
1453 m_SelectedEntity = entity;
1457 Entity EditorLayer::CreateModelEntity(
const std::filesystem::path& p)
1459 if (!m_Scene || p.empty())
1464 CaptureUndoSnapshot();
1466 auto mesh = AssetManager::LoadMesh(p);
1467 auto entity = m_Scene->CreateEntity(p.stem().string());
1468 entity.AddComponent<MeshComponent>(mesh);
1470 std::shared_ptr<Material> material;
1471 if (m_DefaultCubeMaterial)
1473 auto materials = AssetManager::ImportModelMaterials(
1474 p, m_DefaultCubeMaterial->GetShader());
1475 if (materials.empty())
1477 material = std::make_shared<Material>(*m_DefaultCubeMaterial);
1478 material->UseTexture() =
false;
1479 materials.push_back(material);
1481 else material = materials.front();
1483 entity.AddComponent<MeshRendererComponent>(material);
1484 entity.GetComponent<MeshRendererComponent>()
1485 .SetMaterials(std::move(materials));
1492 const auto animationPath = AssetManager::ResolveProjectPath(p);
1493 auto animation = AnimationAsset::Load(animationPath);
1494 if (animation && animation->HasAnimations())
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));
1508 ScriptLog(
"[Import] Model animation discovery failed; model imported without Animator.");
1511 m_SelectedEntity = entity;
1516 ScriptLog(
"[Import] Model entity creation failed.");
1521 void EditorLayer::ClearRedoHistory()
1523 m_RedoHistory.clear();
1526 void EditorLayer::PushUndoSnapshot(std::unique_ptr<Scene> snapshot)
1531 m_UndoHistory.push_back(std::move(snapshot));
1532 if (m_UndoHistory.size() > MaxHistoryEntries)
1533 m_UndoHistory.erase(m_UndoHistory.begin());
1538 void EditorLayer::CaptureUndoSnapshot()
1540 if (m_Scene && !m_IsPlaying)
1541 PushUndoSnapshot(m_Scene->Copy());
1544 void EditorLayer::Undo()
1546 if (!m_Scene || m_IsPlaying || m_UndoHistory.empty())
1549 const std::uint32_t selected =
1550 m_SelectedEntity ? m_SelectedEntity.GetHandle() : 0;
1552 m_RedoHistory.push_back(m_Scene->Copy());
1553 m_Scene->RestoreFrom(*m_UndoHistory.back());
1554 m_UndoHistory.pop_back();
1557 selected != 0 && m_Scene->IsValid(selected)
1558 ? Entity(selected, m_Scene)
1562 void EditorLayer::Redo()
1564 if (!m_Scene || m_IsPlaying || m_RedoHistory.empty())
1567 const std::uint32_t selected =
1568 m_SelectedEntity ? m_SelectedEntity.GetHandle() : 0;
1570 m_UndoHistory.push_back(m_Scene->Copy());
1571 m_Scene->RestoreFrom(*m_RedoHistory.back());
1572 m_RedoHistory.pop_back();
1575 selected != 0 && m_Scene->IsValid(selected)
1576 ? Entity(selected, m_Scene)
1580 void EditorLayer::DeleteSelectedEntity()
1582 if (!m_Scene || !m_SelectedEntity)
1585 std::vector<Entity> selectedEntities;
1586 for (Entity entity : m_Scene->GetEntities())
1588 if (IsMultiSelected(entity))
1589 selectedEntities.push_back(entity);
1592 if (selectedEntities.empty())
1593 selectedEntities.push_back(m_SelectedEntity);
1597 std::vector<Entity> selectedRoots;
1598 for (Entity candidate : selectedEntities)
1600 bool hasSelectedAncestor =
false;
1601 Entity parent = m_Scene->GetParent(candidate);
1604 if (IsMultiSelected(parent))
1606 hasSelectedAncestor =
true;
1609 parent = m_Scene->GetParent(parent);
1612 if (!hasSelectedAncestor)
1613 selectedRoots.push_back(candidate);
1616 CaptureUndoSnapshot();
1621 auto destroyHierarchy = [&](
auto&& self, Entity entity) ->
void
1623 if (!entity || !m_Scene->IsValid(entity.GetHandle()))
1626 const auto children = m_Scene->GetChildren(entity);
1627 for (Entity child : children)
1630 if (m_Scene->IsValid(entity.GetHandle()))
1631 m_Scene->DestroyEntity(entity);
1634 for (Entity root : selectedRoots)
1635 destroyHierarchy(destroyHierarchy, root);
1637 ClearMultiSelection();
1640 void EditorLayer::DuplicateSelectedEntity()
1642 if (!m_Scene || !m_SelectedEntity)
1645 std::vector<Entity> selectedEntities;
1646 for (Entity entity : m_Scene->GetEntities())
1648 if (IsMultiSelected(entity))
1649 selectedEntities.push_back(entity);
1652 if (selectedEntities.empty())
1653 selectedEntities.push_back(m_SelectedEntity);
1657 std::vector<Entity> selectedRoots;
1658 for (Entity candidate : selectedEntities)
1660 bool hasSelectedAncestor =
false;
1661 Entity parent = m_Scene->GetParent(candidate);
1664 if (IsMultiSelected(parent))
1666 hasSelectedAncestor =
true;
1669 parent = m_Scene->GetParent(parent);
1672 if (!hasSelectedAncestor)
1673 selectedRoots.push_back(candidate);
1676 CaptureUndoSnapshot();
1678 auto copyComponents = [&](Entity source, Entity copy)
1680 copy.GetComponent<TransformComponent>() =
1681 source.GetComponent<TransformComponent>();
1683 if (source.HasComponent<MeshComponent>())
1684 copy.AddComponent<MeshComponent>(
1685 source.GetComponent<MeshComponent>().MeshAsset);
1687 if (source.HasComponent<MeshRendererComponent>())
1690 source.GetComponent<MeshRendererComponent>();
1692 copy.AddComponent<MeshRendererComponent>(src.MaterialAsset);
1693 dst.MaterialAsset = src.MaterialAsset;
1694 dst.Materials = src.Materials;
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>());
1741 auto duplicateHierarchy =
1742 [&](
auto&& self, Entity source, Entity newParent) -> Entity
1744 const auto sourceTag =
1745 source.GetComponent<TagComponent>().Tag;
1747 Entity copy = m_Scene->CreateEntity(sourceTag +
" Copy");
1748 copyComponents(source, copy);
1751 m_Scene->SetParent(copy, newParent,
false);
1753 const auto children = m_Scene->GetChildren(source);
1754 for (Entity child : children)
1755 self(self, child, copy);
1760 std::vector<std::uint32_t> newSelection;
1763 for (Entity sourceRoot : selectedRoots)
1765 if (!sourceRoot || !m_Scene->IsValid(sourceRoot.GetHandle()))
1769 Entity originalParent = m_Scene->GetParent(sourceRoot);
1771 duplicateHierarchy(duplicateHierarchy, sourceRoot, Entity{});
1774 m_Scene->SetParent(rootCopy, originalParent,
false);
1776 newSelection.push_back(rootCopy.GetHandle());
1777 lastCopy = rootCopy;
1780 m_MultiSelection = std::move(newSelection);
1781 m_SelectedEntity = lastCopy;
1784 void EditorLayer::DrawMainMenu()
1786 if (ImGui::BeginMainMenuBar())
1788 if (ImGui::BeginMenu(
"File"))
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;
1797 if (ImGui::MenuItem(
"Load Graphics Test Scene"))
1798 m_GraphicsTestSceneRequested =
true;
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."); } }
1802 ImGui::MenuItem(
"Exit");
1806 if (ImGui::BeginMenu(
"Edit"))
1808 if (ImGui::MenuItem(
1812 static_cast<bool>(m_SelectedEntity)))
1814 DuplicateSelectedEntity();
1817 if (ImGui::MenuItem(
1821 static_cast<bool>(m_SelectedEntity)))
1823 DeleteSelectedEntity();
1827 ImGui::BeginDisabled(m_UndoHistory.empty() || m_IsPlaying);
1828 if (ImGui::MenuItem(
"Undo",
"Ctrl+Z"))
1830 ImGui::EndDisabled();
1832 ImGui::BeginDisabled(m_RedoHistory.empty() || m_IsPlaying);
1833 if (ImGui::MenuItem(
"Redo",
"Ctrl+Y"))
1835 ImGui::EndDisabled();
1839 if (s_ShowBuildSettings) ImGui::OpenPopup(
"Build Settings");
1840 if (ImGui::BeginPopupModal(
"Build Settings", &s_ShowBuildSettings, ImGuiWindowFlags_AlwaysAutoResize))
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";
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(); }
1855 if (ImGui::BeginMenu(
"Build"))
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...");
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());
1881 ImGui::TextDisabled(ProjectScriptManager::IsLoaded()
1882 ?
"ProjectScripts.dll loaded"
1883 :
"ProjectScripts.dll not loaded");
1885 ImGui::TextDisabled(
"Script compilation is currently implemented for Windows.");
1890 if (ImGui::BeginMenu(
"GameObject"))
1892 if (ImGui::MenuItem(
"Create Empty"))
1893 CreateEmptyEntity();
1895 if (ImGui::BeginMenu(
"3D Object"))
1897 if (ImGui::MenuItem(
"Cube"))
1900 if (ImGui::MenuItem(
"Import 3D Model..."))
1902 const std::string source = OpenModelFileDialog();
1903 if (!source.empty())
1907 const auto imported = AssetManager::ImportModel(source);
1908 CreateModelEntity(imported);
1912 ScriptLog(
"[Import] 3D model import failed.");
1922 if (ImGui::MenuItem(
"Camera") && m_Scene)
1924 CaptureUndoSnapshot();
1925 Entity camera = m_Scene->CreateEntity(
"Camera");
1926 camera.AddComponent<CameraComponent>();
1927 m_SelectedEntity = camera;
1930 if (m_SelectedEntity && ImGui::MenuItem(
"Create Prefab From Selected"))
1932 ProjectAssetOperations::CreatePrefab(
1934 AssetManager::GetAssetsDirectory() /
"Prefabs",
1935 [
this](
const std::string& message) { ScriptLog(message); });
1940 if (ImGui::BeginMenu(
"Light"))
1942 if (ImGui::MenuItem(
"Directional Light") && m_Scene)
1944 CaptureUndoSnapshot();
1945 Entity light = m_Scene->CreateEntity(
"Directional Light");
1946 light.AddComponent<DirectionalLightComponent>();
1947 m_SelectedEntity = light;
1949 if (ImGui::MenuItem(
"Point Light") && m_Scene)
1951 CaptureUndoSnapshot();
1952 Entity light = m_Scene->CreateEntity(
"Point Light");
1953 light.AddComponent<PointLightComponent>();
1954 m_SelectedEntity = light;
1956 if (ImGui::MenuItem(
"Spot Light") && m_Scene)
1958 CaptureUndoSnapshot();
1959 Entity light = m_Scene->CreateEntity(
"Spot Light");
1960 light.AddComponent<SpotLightComponent>();
1961 m_SelectedEntity = light;
1968 if (ImGui::BeginMenu(
"AI"))
1970 ImGui::MenuItem(
"Behavior Tree Editor",
nullptr, &s_ShowBTAssetEditor);
1973 ImGui::MenuItem(
"AI Debugger",
nullptr, &m_ShowAIDebugger);
1975 if (ImGui::BeginMenu(
"Navigation"))
1977 if (ImGui::MenuItem(
1983 m_BakeNavMeshRequested =
true;
1986 if (ImGui::MenuItem(
1992 m_ClearNavMeshRequested =
true;
2007 if (ImGui::BeginMenu(
"View"))
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);
2018 ImGui::EndMainMenuBar();
2025 m_SelectedEntity = {};
2031 const bool value = m_PlayRequested;
2032 m_PlayRequested =
false;
2038 const bool value = m_PauseRequested;
2039 m_PauseRequested =
false;
2045 const bool value = m_StopRequested;
2046 m_StopRequested =
false;
2051 const bool value = m_BakeNavMeshRequested;
2052 m_BakeNavMeshRequested =
false;
2058 const bool value = m_ClearNavMeshRequested;
2059 m_ClearNavMeshRequested =
false;
2064 m_IsPlaying = playing;
2065 m_IsPaused = paused;
2068 void EditorLayer::DrawPlayToolbar()
2070 ImGui::Begin(
"Toolbar",
nullptr,
2071 ImGuiWindowFlags_NoScrollbar
2072 | ImGuiWindowFlags_NoScrollWithMouse);
2074 const float width = ImGui::GetContentRegionAvail().x;
2075 ImGui::SetCursorPosX(
2076 ImGui::GetCursorPosX() + (width - 170.0f) * 0.5f);
2078 ImGui::BeginDisabled(m_IsPlaying);
2079 if (ImGui::Button(
"Play", ImVec2(50.0f, 0.0f)))
2080 m_PlayRequested =
true;
2081 ImGui::EndDisabled();
2085 ImGui::BeginDisabled(!m_IsPlaying);
2087 m_IsPaused ?
"Resume" :
"Pause",
2088 ImVec2(60.0f, 0.0f)))
2090 m_PauseRequested =
true;
2092 ImGui::EndDisabled();
2096 ImGui::BeginDisabled(!m_IsPlaying);
2097 if (ImGui::Button(
"Stop", ImVec2(50.0f, 0.0f)))
2098 m_StopRequested =
true;
2099 ImGui::EndDisabled();
2104 bool EditorLayer::IsMultiSelected(Entity entity)
const
2106 return std::find(m_MultiSelection.begin(), m_MultiSelection.end(),
2107 entity.GetHandle()) != m_MultiSelection.end();
2110 void EditorLayer::ClearMultiSelection()
2112 m_MultiSelection.clear();
2113 m_SelectedEntity = {};
2116 bool EditorLayer::HierarchyMatchesFilter(Entity entity)
const
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); });
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;
2129 for (Entity child : m_Scene->GetChildren(entity))
2130 if (HierarchyMatchesFilter(child))
return true;
2134 void EditorLayer::DrawHierarchy()
2136 ImGui::Begin(
"Hierarchy");
2138 ImGui::SetNextItemWidth(-1.0f);
2139 ImGui::InputTextWithHint(
"##HierarchySearch",
"Search Hierarchy...",
2140 m_HierarchySearch,
sizeof(m_HierarchySearch));
2142 if (m_MultiSelection.size() > 1)
2144 ImGui::Text(
"%zu entities selected", m_MultiSelection.size());
2145 if (ImGui::SmallButton(
"Duplicate Selected"))
2146 DuplicateSelectedEntity();
2148 if (ImGui::SmallButton(
"Delete Selected"))
2149 DeleteSelectedEntity();
2154 if (ImGui::BeginPopupContextWindow(
2156 ImGuiPopupFlags_MouseButtonRight
2157 | ImGuiPopupFlags_NoOpenOverItems))
2159 if (ImGui::MenuItem(
"Create Empty"))
2160 CreateEmptyEntity();
2162 if (ImGui::BeginMenu(
"3D Object"))
2164 if (ImGui::MenuItem(
"Cube"))
2173 if (ImGui::BeginDragDropTarget())
2175 if (
const ImGuiPayload* payload =
2176 ImGui::AcceptDragDropPayload(
"NOJOB_ENTITY"))
2179 *
static_cast<const std::uint32_t*
>(payload->Data);
2181 if (m_Scene->IsValid(handle))
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;
2191 for (std::uint32_t selectedHandle : m_MultiSelection)
2192 if (m_Scene->IsValid(selectedHandle))
2193 m_Scene->Unparent(Entity(selectedHandle, m_Scene),
true);
2197 m_Scene->Unparent(Entity(handle, m_Scene),
true);
2201 ImGui::EndDragDropTarget();
2206 for (Entity entity : m_Scene->GetEntities())
2208 if (entity.GetComponent<RelationshipComponent>().Parent == 0
2209 && HierarchyMatchesFilter(entity))
2210 DrawEntityNode(entity);
2217 void EditorLayer::DrawEntityNode(Entity entity)
2222 auto& tag = entity.GetComponent<TagComponent>().Tag;
2223 const auto& relationship =
2224 entity.GetComponent<RelationshipComponent>();
2226 ImGuiTreeNodeFlags flags =
2227 ImGuiTreeNodeFlags_OpenOnArrow
2228 | ImGuiTreeNodeFlags_OpenOnDoubleClick
2229 | ImGuiTreeNodeFlags_SpanAvailWidth;
2231 if (relationship.Children.empty())
2232 flags |= ImGuiTreeNodeFlags_Leaf;
2234 if (entity == m_SelectedEntity || IsMultiSelected(entity))
2235 flags |= ImGuiTreeNodeFlags_Selected;
2237 ImGui::PushID(
static_cast<int>(entity.GetHandle()));
2240 ImGui::TreeNodeEx(
"EntityNode", flags,
"%s", tag.c_str());
2242 if (ImGui::IsItemClicked())
2244 const bool ctrl = ImGui::GetIO().KeyCtrl;
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());
2252 m_MultiSelection.erase(it);
2256 m_MultiSelection.clear();
2257 m_MultiSelection.push_back(entity.GetHandle());
2259 m_SelectedEntity = entity;
2262 if (ImGui::BeginDragDropSource())
2264 const std::uint32_t handle = entity.GetHandle();
2265 ImGui::SetDragDropPayload(
2269 ImGui::Text(
"%s", tag.c_str());
2270 ImGui::EndDragDropSource();
2273 if (ImGui::BeginDragDropTarget())
2275 if (
const ImGuiPayload* payload =
2276 ImGui::AcceptDragDropPayload(
"NOJOB_ENTITY"))
2278 const auto childHandle =
2279 *
static_cast<const std::uint32_t*
>(payload->Data);
2281 if (m_Scene->IsValid(childHandle))
2283 CaptureUndoSnapshot();
2285 const bool dragIsMulti =
2286 std::find(m_MultiSelection.begin(), m_MultiSelection.end(), childHandle)
2287 != m_MultiSelection.end()
2288 && m_MultiSelection.size() > 1;
2295 for (std::uint32_t selectedHandle : m_MultiSelection)
2297 if (!m_Scene->IsValid(selectedHandle)
2298 || selectedHandle == entity.GetHandle())
2302 Entity(selectedHandle, m_Scene),
2310 Entity(childHandle, m_Scene),
2316 ImGui::EndDragDropTarget();
2319 if (ImGui::BeginPopupContextItem(
"EntityContext"))
2321 m_SelectedEntity = entity;
2323 if (ImGui::MenuItem(
"Rename",
"F2"))
2324 m_RenameSelectedRequested =
true;
2326 if (ImGui::MenuItem(
"Duplicate",
"Ctrl+D"))
2327 DuplicateSelectedEntity();
2329 if (ImGui::MenuItem(
"Create Prefab"))
2331 ProjectAssetOperations::CreatePrefab(
2333 AssetManager::GetAssetsDirectory() /
"Prefabs",
2334 [
this](
const std::string& message) { ScriptLog(message); });
2337 if (relationship.Parent != 0
2338 && ImGui::MenuItem(
"Unparent"))
2340 CaptureUndoSnapshot();
2341 m_Scene->Unparent(entity,
true);
2344 if (ImGui::MenuItem(
"Delete",
"Delete"))
2345 DeleteSelectedEntity();
2352 const auto children = m_Scene->GetChildren(entity);
2353 for (Entity child : children)
2354 if (HierarchyMatchesFilter(child))
2355 DrawEntityNode(child);
2365 void EditorLayer::DrawViewport()
2367 ImGui::PushStyleVar(
2368 ImGuiStyleVar_WindowPadding,
2371 ImGui::Begin(
"Viewport");
2373 m_ViewportHovered = ImGui::IsWindowHovered();
2374 m_ViewportFocused = ImGui::IsWindowFocused();
2376 const ImVec2 viewportMin =
2377 ImGui::GetCursorScreenPos();
2379 const ImVec2 available =
2380 ImGui::GetContentRegionAvail();
2383 std::max(1.0f, available.x);
2386 std::max(1.0f, available.y);
2388 if (m_ViewportTextureID != 0)
2391 static_cast<ImTextureID
>(
2392 static_cast<intptr_t
>(
2393 m_ViewportTextureID)),
2398 ImVec2(1.0f, 0.0f));
2403 if (m_Scene && m_SelectedEntity)
2405 DrawSceneColliderGizmos(
2411 ImVec2(m_ViewportWidth, m_ViewportHeight),
2414 m_AIDebugShowLastSeenMarker,
2419 m_CameraPreviewTextureID != 0 &&
2421 m_SelectedEntity.HasComponent<CameraComponent>())
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);
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));
2437 static_cast<ImTextureID
>(
2438 static_cast<intptr_t
>(m_CameraPreviewTextureID)),
2442 ImVec2(1.0f, 0.0f));
2444 { previewMin.x + 8.0f, previewMin.y + 6.0f },
2445 IM_COL32(255, 255, 255, 220),
2452 if (m_ViewportHovered && !ImGuizmo::IsUsing())
2454 if (ImGui::IsKeyPressed(ImGuiKey_W))
2455 m_GizmoOperation = 0;
2457 if (ImGui::IsKeyPressed(ImGuiKey_E))
2458 m_GizmoOperation = 1;
2460 if (ImGui::IsKeyPressed(ImGuiKey_R))
2461 m_GizmoOperation = 2;
2464 if (m_SelectedEntity
2465 && m_ViewportWidth > 1.0f
2466 && m_ViewportHeight > 1.0f)
2470 glm::mat4 transformMatrix =
2471 m_Scene->GetWorldTransform(m_SelectedEntity);
2473 ImGuizmo::SetOrthographic(
false);
2474 ImGuizmo::SetDrawlist();
2481 ImGuizmo::OPERATION operation =
2482 ImGuizmo::TRANSLATE;
2484 if (m_GizmoOperation == 1)
2485 operation = ImGuizmo::ROTATE;
2486 else if (m_GizmoOperation == 2)
2487 operation = ImGuizmo::SCALE;
2489 const ImGuizmo::MODE mode =
2490 operation == ImGuizmo::SCALE
2494 ImGuizmo::Manipulate(
2495 glm::value_ptr(m_EditorView),
2496 glm::value_ptr(m_EditorProjection),
2499 glm::value_ptr(transformMatrix));
2501 const bool gizmoUsing = ImGuizmo::IsUsing();
2502 if (gizmoUsing && !m_GizmoWasUsing)
2503 m_TransformEditSnapshot = m_Scene->Copy();
2507 float translation[3]{};
2508 float rotationDegrees[3]{};
2511 ImGuizmo::DecomposeMatrixToComponents(
2512 glm::value_ptr(transformMatrix),
2519 m_Scene->SetWorldTransform(
2524 if (!gizmoUsing && m_GizmoWasUsing && m_TransformEditSnapshot)
2525 PushUndoSnapshot(std::move(m_TransformEditSnapshot));
2527 m_GizmoWasUsing = gizmoUsing;
2531 ImGui::SetCursorScreenPos(
2532 ImVec2(viewportMin.x + 10.0f, viewportMin.y + 10.0f));
2534 ImGui::BeginGroup();
2536 if (ImGui::Button(
"W Move"))
2537 m_GizmoOperation = 0;
2541 if (ImGui::Button(
"E Rotate"))
2542 m_GizmoOperation = 1;
2546 if (ImGui::Button(
"R Scale"))
2547 m_GizmoOperation = 2;
2551 ImGui::SetCursorScreenPos(
2552 ImVec2(viewportMin.x + 10.0f, viewportMin.y + 42.0f));
2554 ImGui::TextDisabled(
2555 "RMB + mouse: camera | WASD: move | "
2556 "Q/E: down/up | Shift: faster");
2559 ImGui::PopStyleVar();
2562 void EditorLayer::DrawConsole()
2564 ImGui::Begin(
"Console");
2565 ImGui::Text(
"[Info] NoJobEngine editor started.");
2566 ImGui::Text(
"[Info] Scene entity management active.");
2568 "[Info] Right click Hierarchy to create objects.");
2570 std::vector<std::string> scriptConsoleSnapshot;
2572 std::lock_guard<std::mutex> lock(s_ScriptConsoleMutex);
2573 scriptConsoleSnapshot = s_ScriptConsole;
2575 if (!scriptConsoleSnapshot.empty())
2577 ImGui::SeparatorText(
"Native Scripting");
2578 for (
const auto& line : scriptConsoleSnapshot)
2579 ImGui::TextUnformatted(line.c_str());
2586 std::string EditorLayer::OpenInspectorAudioFileDialog()
2588 return OpenAudioFileDialog();
2591 std::string EditorLayer::OpenInspectorTextureFileDialog()
2593 return OpenTextureFileDialog();
2596 void EditorLayer::LogInspectorMessage(
const std::string& message)
2601 void EditorLayer::DrawProjectPanel()
2603 m_ProjectPanel.Draw(
2607 m_DefaultCubeMaterial,
2608 [
this](
const std::filesystem::path& path) { CreateModelEntity(path); },
2612 void EditorLayer::DrawGraphicsSettings()
2614 if (!ImGui::Begin(
"Graphics Settings", &m_ShowGraphicsSettings))
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);
2625 ImGui::SeparatorText(
"Environment / IBL");
2627 "Image Based Lighting", &m_GraphicsSettings.ImageBasedLighting);
2629 "Environment Intensity",
2630 &m_GraphicsSettings.EnvironmentIntensity, 0.0f, 4.0f);
2633 &m_GraphicsSettings.DiffuseIBLStrength, 0.0f, 1.0f);
2636 &m_GraphicsSettings.SpecularIBLStrength, 0.0f, 1.0f);
2638 "Environment Rotation",
2639 &m_GraphicsSettings.EnvironmentRotation, -180.0f, 180.0f,
2642 if (ImGui::Button(
"Load HDRI..."))
2644 const std::string path = OpenHDRIFileDialog();
2647 std::filesystem::path selected(path);
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)
2654 m_GraphicsSettings.EnvironmentHDRIPath =
2655 relative.generic_string();
2659 m_GraphicsSettings.EnvironmentHDRIPath =
2660 selected.lexically_normal().string();
2665 if (ImGui::Button(
"Clear HDRI"))
2666 m_GraphicsSettings.EnvironmentHDRIPath.clear();
2668 if (m_GraphicsSettings.EnvironmentHDRIPath.empty())
2669 ImGui::TextDisabled(
"Environment: Procedural fallback");
2672 const std::filesystem::path hdriPath(
2673 m_GraphicsSettings.EnvironmentHDRIPath);
2675 "HDRI: %s", hdriPath.filename().string().c_str());
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;
2684 "Environment Resolution", &environmentSizeIndex,
2685 environmentSizes, 4))
2687 const std::uint32_t sizes[] = { 128, 256, 512, 1024 };
2688 m_GraphicsSettings.EnvironmentResolution =
2689 sizes[environmentSizeIndex];
2692 ImGui::TextDisabled(
2693 "HDRI is converted to cubemaps and precomputed for real-time IBL.");
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);
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);
2704 ImGui::SeparatorText(
"Anti-Aliasing");
2705 ImGui::Checkbox(
"FXAA", &m_GraphicsSettings.FXAA);
2708 ImGui::TextWrapped(
"ACES filmic tone mapping and final gamma conversion are applied once at the end of the HDR pipeline.");
2718 static std::string currentName =
"Default";
2719 static char assetName[128] =
"Default";
2720 static int selected = 1;
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;
2731 const auto registeredCallbacks = []() {
2732 std::vector<std::string> actions{
2733 "ChaseTarget",
"MoveForward",
"Patrol",
"StopMoving"
2735 std::vector<std::string> conditions{
2736 "CanSeeTarget",
"HasRememberedTarget"
2741 if (entry.Name.empty())
continue;
2742 auto& destination = entry.IsCondition ? conditions : actions;
2743 destination.push_back(entry.Name);
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());
2750 normalize(conditions);
2751 return std::make_pair(std::move(actions), std::move(conditions));
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; }
2764 if (std::find(names.begin(), names.end(), value) == names.end() && value !=
"-")
2765 ImGui::TextDisabled(
"Custom/unavailable callback: %s", value.c_str());
2767 if (!ImGui::Begin(
"Behavior Tree Editor", opened)) { ImGui::End();
return; }
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;
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 ?
" *" :
"");
2779 static bool initialAssetLoaded =
false;
2780 const auto lastAssetPath = folder /
".last-opened-bt";
2781 const auto rememberAsset = [&](
const std::string& name) {
2783 std::filesystem::create_directories(folder, ec);
2785 std::ofstream out(lastAssetPath, std::ios::trunc);
2786 if (out) out << name <<
'\n';
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();
2795 if (!existsInList(preferred))
2796 preferred = existsInList(currentName) ? currentName
2797 : (available.empty() ? std::string{} : available.front());
2798 if (!preferred.empty()) {
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);
2806 message =
"Restored " + assetPath(preferred).string();
2807 }
catch (
const std::exception& ex) {
2808 message =
"Could not restore saved tree: " + std::string(ex.what());
2812 if (ImGui::BeginCombo(
"Saved trees",currentName.c_str())) {
2813 for (
const auto& name : available) {
2814 if (ImGui::Selectable(name.c_str(),name == currentName)) {
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(); }
2826 ImGui::InputText(
"Tree name",assetName,
sizeof(assetName));
2827 if (ImGui::Button(
"Load")) {
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(); }
2836 if (ImGui::Button(
"Save")) {
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(); }
2844 if (ImGui::Button(
"Save As")) {
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(); }
2855 if (ImGui::Button(
"New")) {
2857 currentName =
"Untitled";
2858 std::snprintf(assetName,
sizeof(assetName),
"%s",currentName.c_str());
2859 message =
"New tree. Enter a name and click Save As.";
2861 if (!message.empty()) ImGui::TextWrapped(
"%s",message.c_str());
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) {
2870 std::ifstream in(layoutPath(name));
2872 while (in >>
id >> x >> y) layout[id] = ImVec2(x,y);
2873 layoutDirty =
false;
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;
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(); }
2889 if (ImGui::Button(
"Auto Arrange")) { layout.clear(); layoutDirty =
true; }
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) {
2901 for (
const auto& parent:asset.
Nodes)
if (parent.ID==ancestor) {next=parent.Parent;
break;}
2904 if (!layout.contains(n.ID)) {
2905 layout[n.ID] = ImVec2(24.f + depth*dx, 22.f +
static_cast<float>(i)*dy);
2908 positions[n.ID] = ImVec2(origin.x + layout.at(n.ID).x, origin.y + layout.at(n.ID).y);
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);
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);
2941 selected=
static_cast<int>(n.ID);
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));
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);
2953 ImGui::SetCursorScreenPos(origin);
2954 ImGui::Dummy(ImVec2(maxX,maxY));
2956 ImGui::SeparatorText(
"Selected node");
2958 for (
auto& n:asset.
Nodes)
if (n.ID==
static_cast<BTNodeID>(selected)) current=&n;
2960 if (childDraftAsset != currentName) {
2961 childDrafts.clear();
2962 childDraftAsset = currentName;
2964 ChildDraft& childDraft = childDrafts[current->
ID];
2965 ImGui::Text(
"#%llu %s",
static_cast<unsigned long long>(current->
ID),current->
Kind.c_str());
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.";
2978 current->
Kind = nodeKinds[selectedKind];
2979 if (selectedKind == 2 || selectedKind == 3) {
2981 current->
Native = selectedKind == 2 ?
"StopMoving" :
"CanSeeTarget";
2982 }
else if (selectedKind == 0 || selectedKind == 1 || selectedKind == 6) {
2984 }
else if (current->
Native ==
"-" || current->
Native.empty()) {
2985 current->
Native =
"StopMoving";
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());
2994 if (current->
Kind==
"Decorator" || current->
Kind==
"Service") {
2995 ImGui::TextDisabled(
"Decorator/Service must have exactly one child");
2997 if (current->
Kind==
"Decorator" || current->
Kind==
"Service" ||
2998 current->
Kind==
"Action" || current->
Kind==
"Condition") {
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());
3013 callbackPicker(
"Registered callback##selected", current->
Kind.c_str(), current->
Native);
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;
3021 if (current->
Kind==
"Decorator" && ImGui::InputText(
"Observed Blackboard key",editKey,
sizeof(editKey))) {
3022 current->
Parameter=editKey[0] ? editKey :
"-"; dirty=
true;
3024 if (current->
Kind==
"Service" && ImGui::DragFloat(
"Interval (seconds)",¤t->
Interval,.05f,.05f,60.f)) {
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));
3040 if (ImGui::Button(
"Add child")) {
3041 if (current->
Kind==
"Action" || current->
Kind==
"Condition") message=
"Cannot add children to a leaf";
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;
3050 if (ImGui::Button(
"Delete branch") && current->
Parent) {
3051 std::unordered_set<BTNodeID> removed{current->
ID};
3055 for (
const auto& n:asset.
Nodes)
if (removed.contains(n.Parent) && !removed.contains(n.ID)) {
3056 removed.insert(n.ID); changed=
true;
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);
3069 void EditorLayer::DrawAIDebugger()
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; }
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");
3078 ImGui::Checkbox(
"Active only", &m_AIDebugOnlyActive);
3080 auto entities = m_Scene->GetEntities();
3081 std::vector<Entity> agents;
3082 int visibleTotal = 0, rememberedTotal = 0;
3083 for (
auto entity : entities)
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;
3093 ImGui::Text(
"Agents: %d Visible: %d Remembered: %d", (
int)agents.size(), visibleTotal, rememberedTotal);
3095 if (ImGui::BeginChild(
"##AI_Agents", ImVec2(190, 0),
true))
3097 for (
auto agent : agents)
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();
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();
3113 Entity agent(m_AIDebugAgent, m_Scene);
3114 if (ImGui::CollapsingHeader(
"Agent Information")) {
3115 ImGui::Text(
"Agent: %s", agent.GetComponent<TagComponent>().Tag.c_str());
3117 if (ImGui::Button(
"Select in Hierarchy")) SetSelectedEntity(agent);
3118 if (ImGui::CollapsingHeader(
"Behavior Tree", ImGuiTreeNodeFlags_DefaultOpen)) {
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);
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;
3136 timelineKind.clear();
3138 ImGui::SetNextItemWidth(145.0f);
3139 ImGui::SliderFloat(
"Graph zoom", &graphZoom, 0.65f, 1.65f,
"%.2fx");
3141 if (ImGui::SmallButton(
"Clear event selection")) {
3144 timelineKind.clear();
3146 if (bt->Nodes.empty()) {
3147 ImGui::TextDisabled(
"No compiled nodes to display.");
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);
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()) {
3168 for (
int child : children[i]) total += widths[child];
3169 widths[i] = std::max(1.0f, total);
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];
3180 if (!children[index].empty())
3181 centers[index] = (centers[children[index].front()] + centers[children[index].back()]) * 0.5f;
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]; }
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);
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);
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;
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);
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;
3244 timelineKind.clear();
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.");
3264 if (ImGui::CollapsingHeader(
"Execution Timeline", ImGuiTreeNodeFlags_DefaultOpen)) {
3265 ImGui::TextDisabled(
"Per-agent bounded event history (latest first; ticks, not wall-clock time)");
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.");
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;
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;
3312 if (ImGui::IsItemHovered() && !e.Detail.empty()) ImGui::SetTooltip(
"%s", e.Detail.c_str());
3313 if (!e.Detail.empty()) {
3315 ImGui::TextColored(tint,
"%s", e.Detail.c_str());
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,
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());
3342 }
else ImGui::TextDisabled(
"No Behavior Tree debug data for this agent.");
3343 }
else ImGui::TextDisabled(
"Available during Play.");
3345 if (ImGui::CollapsingHeader(
"Behavior State")) {
3347 ImGui::TextDisabled(
"Available during Play.");
3348 else if (
const auto debug = m_Scene->GetAIDebugState(m_AIDebugAgent))
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"))
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());
3366 ImGui::TextDisabled(
"No runtime AI state (script missing or inactive).");
3368 if (agent.HasComponent<PerceptionComponent>())
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);
3379 ImGui::TextDisabled(
"Available during Play.");
3380 else if (
const auto lastSeen = m_Scene->GetLastSeenTarget(m_AIDebugAgent))
3382 const std::string name = m_Scene->IsValid(lastSeen->EntityHandle)
3383 ? Entity(lastSeen->EntityHandle, m_Scene).GetComponent<TagComponent>().Tag
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);
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)
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))
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");
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);
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);
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]);
3446 drawValues(
"Inputs",snap.inputs);
3447 drawValues(
"Predictions",snap.outputs);
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));
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);
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));
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);
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");
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]);
3515 if(ImGui::TreeNode(
"Weights and biases (saved model)")) {
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) {
3527 ImGui::TextDisabled(
"w%d:%.3f",
static_cast<int>(input),dense.Weights()(neuron,input));
3534 }
catch(
const std::exception& e) { ImGui::TextDisabled(
"Cannot load model: %s",e.what()); }
3539 if (agent.HasComponent<NavAgentComponent>())
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);
3550 else ImGui::TextDisabled(
"No AI agents in this scene.");
3555 void EditorLayer::DrawRendererProfiler()
3557 if (!m_ShowRendererProfiler)
3560 if (!ImGui::Begin(
"Renderer Profiler", &m_ShowRendererProfiler))
3566 const auto& rendererStats = SceneRenderer::GetStatistics();
3567 const ImGuiIO& io = ImGui::GetIO();
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);
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);
3580 ImGui::TextDisabled(
"GPU Time: warming up...");
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));
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));
3595 ImGui::TextDisabled(
3596 "GPU timing uses non-blocking queries with a 3-frame ring.");
3602 const bool requested = m_SaveSceneRequested;
3603 m_SaveSceneRequested =
false;
3609 const bool requested = m_SaveSceneAsRequested;
3610 m_SaveSceneAsRequested =
false;
3616 const bool requested = m_LoadSceneRequested;
3617 m_LoadSceneRequested =
false;
3623 const bool requested = m_GraphicsTestSceneRequested;
3624 m_GraphicsTestSceneRequested =
false;
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
void Save(const std::filesystem::path &path) const
static BTAsset Load(const std::filesystem::path &path)
void SetScene(Scene *scene)
void SetSelectedEntity(Entity entity)
bool ConsumeLoadSceneRequest()
void SetEditorCameraMatrices(const glm::mat4 &view, const glm::mat4 &projection)
bool ConsumeGraphicsTestSceneRequest()
bool ConsumePlayRequest()
bool ConsumeStopRequest()
void SetRuntimeState(bool playing, bool paused)
bool ConsumePauseRequest()
void Init(GLFWwindow *window, Scene *scene)
bool ConsumeClearNavMeshRequest()
void SetDefaultCubeAssets(std::shared_ptr< Mesh > mesh, std::shared_ptr< Material > material)
bool ConsumeSaveSceneAsRequest()
void SetViewportTexture(std::uint32_t textureID)
bool ConsumeBakeNavMeshRequest()
std::uint32_t GetViewportWidth() const
std::uint32_t GetViewportHeight() const
bool ConsumeSaveSceneRequest()
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)
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()
static BuildSettings Load(const std::filesystem::path &projectRoot)