#include "application.h" #include "rendering/render_api.h" // RendererAPI #include "settings_manager.h" #include "hdri_manager.h" #include "platform/opengl/opengl_device.h" #include "platform/vulkan/vulkan_device.h" #include #include #include #include #include #include namespace Donut { Application* Application::s_instance = nullptr; // Scroll is delivered through a GLFW callback; accumulate it here and drain it // once per frame in process_input (chaining ImGui's own scroll handler). static double g_scroll_accum = 0.0; static GLFWscrollfun g_prev_scroll = nullptr; static void donut_scroll_callback(GLFWwindow* w, double x, double y) { if (g_prev_scroll) g_prev_scroll(w, x, y); g_scroll_accum += y; } Application::Application(const std::string& name, int width, int height) : m_running(true), m_minimized(false) { s_instance = this; // Select the render API before the window is created: the window is built // differently for Vulkan (GLFW_NO_API) than for OpenGL. Logger::init(); SettingsManager::initialize(); { const auto& settings = SettingsManager::get_settings_const(); RendererAPI::set_api(settings.graphics.render_api == "Vulkan" ? RendererAPI::API::Vulkan : RendererAPI::API::OpenGL); } if (RendererAPI::get_api() == RendererAPI::API::Vulkan) RHI::vulkan_prepare_glfw(); // must precede glfwInit() inside the Window ctor m_window = create_scope(name, width, height); m_window->set_event_callback([this](Event& event) { on_event(event); }); on_init(); } Application::~Application() { on_shutdown(); s_instance = nullptr; } auto Application::on_init() -> void { int w = 0, h = 0; glfwGetFramebufferSize((GLFWwindow*)m_window->get_native_window(), &w, &h); if (RendererAPI::get_api() == RendererAPI::API::Vulkan) m_device = RHI::create_vulkan_device(); else m_device = RHI::create_opengl_device(); RHI::NativeWindow native{ m_window->get_native_window(), w, h }; if (!m_device->init(native)) { DONUT_ERROR("RHI device initialization failed"); return; } m_hdri_path = "assets/hdri/hdr_blue_nebulae_1.hdr"; m_cubemap = m_device->create_cubemap_from_hdri(m_hdri_path); m_scene_renderer = create_scope(); m_scene_renderer->init(*m_device); m_black_hole_renderer = create_scope(); m_black_hole_renderer->init(*m_device); // Black-hole camera: large-scale orbital viewer outside the disk. m_camera.set_camera_mode(CameraMode::Orbital); m_camera.set_orbital_target(glm::vec3(0.0f)); m_camera.set_orbital_radius(4e11); // ~31 r_s: outside the 12 r_s disk m_camera.set_orbital_limits(2.2e11, 1.5e12); m_camera.set_orbital_speed(0.01f); m_camera.set_zoom_speed(3e10); m_camera.set_azimuth(0.0f); m_camera.set_elevation(1.25f); // Scene camera: normal-scale orbital world-builder viewer. m_scene_camera.set_camera_mode(CameraMode::Orbital); m_scene_camera.set_orbital_target(glm::vec3(0.0f)); m_scene_camera.set_orbital_radius(15.0); m_scene_camera.set_orbital_limits(2.0, 200.0); m_scene_camera.set_orbital_speed(0.01f); m_scene_camera.set_zoom_speed(2.0); m_scene_camera.set_azimuth(0.0f); m_scene_camera.set_elevation((float)std::numbers::pi / 3.0f); m_scene_camera.update_orbital(); m_device->init_imgui(); // Load the UI font into the device-created ImGui context (backend-agnostic; // the backend rebuilds the atlas on the next frame). ImGuiIO& io = ImGui::GetIO(); if (!io.Fonts->AddFontFromFileTTF("assets/fonts/inter/static/Inter_18pt-Regular.ttf", 16.0f)) io.Fonts->AddFontDefault(); g_prev_scroll = glfwSetScrollCallback((GLFWwindow*)m_window->get_native_window(), donut_scroll_callback); m_start_time = glfwGetTime(); DONUT_INFO("Application ready on {} backend", m_device->device_name()); } auto Application::run() -> void { while (m_running) { glfwPollEvents(); if (!m_minimized && m_device) render_frame(); } } auto Application::render_frame() -> void { RHI::CommandList* cmd = m_device->begin_frame(glm::vec4(0.05f, 0.06f, 0.10f, 1.0f)); if (!cmd) return; // frame skipped (e.g. swapchain recreation) m_device->imgui_new_frame(); build_ui(); process_input(); const glm::vec4 clear(0.05f, 0.06f, 0.10f, 1.0f); int w = 0, h = 0; glfwGetFramebufferSize((GLFWwindow*)m_window->get_native_window(), &w, &h); if (m_scene_mode) { float aspect = (float)w / (float)std::max(h, 1); m_scene_camera.set_projection(45.0f, aspect, 0.1f, 1000.0f); CameraView cv; cv.view = m_scene_camera.get_view_matrix(); cv.projection = m_scene_camera.get_projection_matrix(); cv.position = m_scene_camera.get_orbital_position(); cv.fb_width = w; cv.fb_height = h; cmd->begin_render_pass(nullptr, clear); m_scene_renderer->render(*cmd, cv, m_scene_objects, m_selected_object, m_cubemap.get()); m_device->imgui_render(*cmd); cmd->end_render_pass(); } else { GeodesicView gv; glm::vec3 pos, fwd; if (m_camera.get_camera_mode() == CameraMode::FPS) { pos = m_camera.get_position(); fwd = m_camera.get_forward_direction(); } else { pos = m_camera.get_orbital_position(); fwd = glm::normalize(m_camera.get_orbital_target() - pos); } glm::vec3 right = glm::normalize(glm::cross(fwd, glm::vec3(0, 1, 0))); gv.position = pos; gv.right = right; gv.up = glm::cross(right, fwd); gv.forward = fwd; gv.tan_half_fov = (float)tan(glm::radians(m_bh_params.fov_degrees * 0.5f)); gv.aspect = (float)BlackHoleRenderer::GEO_HI_W / (float)BlackHoleRenderer::GEO_HI_H; gv.moving = m_user_moving; gv.time = (float)(glfwGetTime() - m_start_time); m_black_hole_renderer->render_geodesic(*cmd, gv, m_bh_params, m_cubemap.get()); cmd->begin_render_pass(nullptr, clear); m_black_hole_renderer->blit(*cmd, w, h); m_device->imgui_render(*cmd); cmd->end_render_pass(); } m_device->end_frame(); } auto Application::process_input() -> void { GLFWwindow* window = (GLFWwindow*)m_window->get_native_window(); bool over_ui = ImGui::GetCurrentContext() && ImGui::GetIO().WantCaptureMouse; double now = glfwGetTime(); float dt = m_last_frame_time > 0.0 ? (float)(now - m_last_frame_time) : 0.0f; m_last_frame_time = now; double mx = 0, my = 0; glfwGetCursorPos(window, &mx, &my); bool left_down = glfwGetMouseButton(window, GLFW_MOUSE_BUTTON_LEFT) == GLFW_PRESS; if (!m_scene_mode && m_camera.get_camera_mode() == CameraMode::FPS) { if (left_down && !m_left_was_down) { m_fps_last_x = mx; m_fps_last_y = my; } if (left_down && !over_ui) m_camera.on_mouse_move(float(mx - m_fps_last_x), float(m_fps_last_y - my)); m_fps_last_x = mx; m_fps_last_y = my; m_left_was_down = left_down; bool over_kb = ImGui::GetCurrentContext() && ImGui::GetIO().WantCaptureKeyboard; bool moved = false; if (!over_kb && dt > 0.0f) { float mdt = dt * (glfwGetKey(window, GLFW_KEY_LEFT_SHIFT) == GLFW_PRESS ? 4.0f : 1.0f); if (glfwGetKey(window, GLFW_KEY_W) == GLFW_PRESS) { m_camera.move_forward(mdt); moved = true; } if (glfwGetKey(window, GLFW_KEY_S) == GLFW_PRESS) { m_camera.move_backward(mdt); moved = true; } if (glfwGetKey(window, GLFW_KEY_A) == GLFW_PRESS) { m_camera.move_left(mdt); moved = true; } if (glfwGetKey(window, GLFW_KEY_D) == GLFW_PRESS) { m_camera.move_right(mdt); moved = true; } if (glfwGetKey(window, GLFW_KEY_E) == GLFW_PRESS) { m_camera.move_up(mdt); moved = true; } if (glfwGetKey(window, GLFW_KEY_Q) == GLFW_PRESS) { m_camera.move_down(mdt); moved = true; } } g_scroll_accum = 0.0; m_user_moving = moved || (left_down && !over_ui); } else { Camera& cam = m_scene_mode ? m_scene_camera : m_camera; if (left_down && !m_left_was_down && !over_ui) cam.process_orbital_mouse_button(GLFW_MOUSE_BUTTON_LEFT, GLFW_PRESS, 0); else if (!left_down && m_left_was_down) cam.process_orbital_mouse_button(GLFW_MOUSE_BUTTON_LEFT, GLFW_RELEASE, 0); m_left_was_down = left_down; cam.process_orbital_mouse_move(mx, my); double scroll = g_scroll_accum; g_scroll_accum = 0.0; if (scroll != 0.0 && !over_ui) cam.process_orbital_scroll(0.0, scroll); m_user_moving = cam.is_dragging() || cam.is_panning(); } } auto Application::set_free_fly(bool enabled) -> void { const bool is_fps = m_camera.get_camera_mode() == CameraMode::FPS; if (enabled == is_fps) return; if (enabled) { // Seed the fly pose from the current orbital framing so the view is continuous. glm::vec3 pos = m_camera.get_orbital_position(); glm::vec3 fwd = glm::normalize(m_camera.get_orbital_target() - pos); float pitch = glm::degrees(asin(glm::clamp(fwd.y, -1.0f, 1.0f))); float yaw = glm::degrees(atan2(fwd.z, fwd.x)); m_camera.set_camera_mode(CameraMode::FPS); m_camera.set_movement_speed(2.0e10f); m_camera.set_mouse_sensitivity(0.15f); m_camera.set_position(pos); m_camera.set_rotation(glm::vec3(pitch, yaw, 0.0f)); } else { m_camera.set_camera_mode(CameraMode::Orbital); // orbital state was left intact } } auto Application::reset_camera() -> void { m_camera.set_camera_mode(CameraMode::Orbital); m_camera.set_orbital_radius(4e11); m_camera.set_azimuth(0.0f); m_camera.set_elevation(1.25f); } auto Application::set_hdri(const std::string& path) -> void { if (m_hdri_path == path || !m_device) return; m_device->wait_idle(); m_cubemap = m_device->create_cubemap_from_hdri(path); // old cube freed after idle m_hdri_path = path; } // One-time ImGui theme: rounded, roomy, dark with a warm accretion-disk accent. static auto apply_donut_style() -> void { ImGuiStyle& s = ImGui::GetStyle(); s.WindowRounding = 7.0f; s.ChildRounding = 5.0f; s.FrameRounding = 4.0f; s.GrabRounding = 4.0f; s.PopupRounding = 4.0f; s.ScrollbarRounding = 5.0f; s.TabRounding = 4.0f; s.WindowPadding = ImVec2(12, 12); s.FramePadding = ImVec2(9, 5); s.ItemSpacing = ImVec2(9, 8); s.ItemInnerSpacing = ImVec2(7, 5); s.WindowBorderSize = 0.0f; s.FrameBorderSize = 0.0f; s.WindowTitleAlign = ImVec2(0.02f, 0.5f); const ImVec4 amber = ImVec4(0.98f, 0.62f, 0.20f, 1.00f); const ImVec4 amberHi = ImVec4(1.00f, 0.73f, 0.36f, 1.00f); ImVec4* c = s.Colors; c[ImGuiCol_WindowBg] = ImVec4(0.07f, 0.08f, 0.10f, 0.97f); c[ImGuiCol_ChildBg] = ImVec4(0.10f, 0.11f, 0.13f, 0.55f); c[ImGuiCol_PopupBg] = ImVec4(0.09f, 0.10f, 0.12f, 0.98f); c[ImGuiCol_TitleBg] = ImVec4(0.09f, 0.10f, 0.12f, 1.00f); c[ImGuiCol_TitleBgActive] = ImVec4(0.13f, 0.14f, 0.17f, 1.00f); c[ImGuiCol_Text] = ImVec4(0.90f, 0.91f, 0.93f, 1.00f); c[ImGuiCol_TextDisabled] = ImVec4(0.48f, 0.50f, 0.54f, 1.00f); c[ImGuiCol_FrameBg] = ImVec4(0.16f, 0.17f, 0.20f, 1.00f); c[ImGuiCol_FrameBgHovered] = ImVec4(0.22f, 0.24f, 0.28f, 1.00f); c[ImGuiCol_FrameBgActive] = ImVec4(0.26f, 0.28f, 0.33f, 1.00f); c[ImGuiCol_Header] = ImVec4(0.17f, 0.19f, 0.23f, 1.00f); c[ImGuiCol_HeaderHovered] = ImVec4(0.24f, 0.27f, 0.32f, 1.00f); c[ImGuiCol_HeaderActive] = ImVec4(0.28f, 0.31f, 0.37f, 1.00f); c[ImGuiCol_Button] = ImVec4(0.20f, 0.22f, 0.26f, 1.00f); c[ImGuiCol_ButtonHovered] = ImVec4(0.27f, 0.30f, 0.35f, 1.00f); c[ImGuiCol_ButtonActive] = amber; c[ImGuiCol_SliderGrab] = amber; c[ImGuiCol_SliderGrabActive]= amberHi; c[ImGuiCol_CheckMark] = amberHi; c[ImGuiCol_Separator] = ImVec4(0.20f, 0.22f, 0.26f, 1.00f); c[ImGuiCol_ScrollbarGrab] = ImVec4(0.24f, 0.26f, 0.30f, 1.00f); } auto Application::build_ui() -> void { static bool styled = false; if (!styled) { apply_donut_style(); styled = true; } if (!m_device) return; // Full-viewport dock space with a pass-through centre, so the panel can be // docked to any edge while the render shows through the middle. ImGui::DockSpaceOverViewport(0, ImGui::GetMainViewport(), ImGuiDockNodeFlags_PassthruCentralNode); ImGui::SetNextWindowSize(ImVec2(340, 580), ImGuiCond_FirstUseEver); ImGui::Begin("Donut \xc2\xb7 Black Hole"); ImGuiIO& io = ImGui::GetIO(); ImGui::TextDisabled("%s", m_device->device_name().empty() ? "GPU" : m_device->device_name().c_str()); ImGui::Text("%.0f FPS", io.Framerate); ImGui::SameLine(); ImGui::TextDisabled("%.1f ms/frame", io.Framerate > 0 ? 1000.0f / io.Framerate : 0.0f); ImGui::Spacing(); if (ImGui::CollapsingHeader("Renderer", ImGuiTreeNodeFlags_DefaultOpen)) { auto& s = SettingsManager::get_settings(); const char* apis[] = { "OpenGL", "Vulkan" }; int cur = (s.graphics.render_api == "Vulkan") ? 1 : 0; if (ImGui::Combo("Graphics API", &cur, apis, 2)) { s.graphics.render_api = apis[cur]; SettingsManager::save_settings(); } const char* running = (RendererAPI::get_api() == RendererAPI::API::Vulkan) ? "Vulkan" : "OpenGL"; if (s.graphics.render_api != running) ImGui::TextColored(ImVec4(0.98f, 0.62f, 0.20f, 1.0f), "Restart to apply (%s running)", running); else ImGui::TextDisabled("Active backend: %s", running); } ImGui::Spacing(); ImGui::TextDisabled("VIEW"); if (ImGui::RadioButton("Black hole", !m_scene_mode)) m_scene_mode = false; ImGui::SameLine(); if (ImGui::RadioButton("Scene", m_scene_mode)) m_scene_mode = true; ImGui::Separator(); if (m_scene_mode) { build_scene_ui(); } else { BlackHoleParams& bh = m_bh_params; if (ImGui::CollapsingHeader("Camera", ImGuiTreeNodeFlags_DefaultOpen)) { bool ff = m_camera.get_camera_mode() == CameraMode::FPS; if (ImGui::RadioButton("Orbital", !ff)) set_free_fly(false); ImGui::SameLine(); if (ImGui::RadioButton("Free-fly", ff)) set_free_fly(true); ImGui::SameLine(); if (ImGui::Button("Reset view")) reset_camera(); ImGui::SliderFloat("FOV", &bh.fov_degrees, 20.0f, 90.0f, "%.0f\xc2\xb0"); ImGui::TextDisabled(ff ? "WASD move | Q/E down-up | Shift boost | drag look" : "Drag to orbit | scroll to zoom"); } if (ImGui::CollapsingHeader("Accretion disk", ImGuiTreeNodeFlags_DefaultOpen)) { ImGui::SliderFloat("Temperature", &bh.temperature, 2000.0f, 15000.0f, "%.0f K"); ImGui::SliderFloat("Brightness", &bh.brightness, 0.0f, 3.0f, "%.2f"); ImGui::SliderFloat("Inner radius", &bh.disk_inner_rs, 3.0f, 12.0f, "%.1f r_s"); if (bh.disk_outer_rs < bh.disk_inner_rs + 0.5f) bh.disk_outer_rs = bh.disk_inner_rs + 0.5f; ImGui::SliderFloat("Outer radius", &bh.disk_outer_rs, bh.disk_inner_rs + 0.5f, 25.0f, "%.1f r_s"); ImGui::SliderFloat("Turbulence", &bh.turbulence, 0.0f, 2.0f, "%.2f"); ImGui::TextDisabled("Inner edge is the ISCO (3 r_s). Novikov-Thorne profile."); } if (ImGui::CollapsingHeader("Quality")) { ImGui::SliderInt("Integration steps", &bh.quality_steps, 2000, 15000); ImGui::TextDisabled("Deeper lensing at higher cost. Settled frame is 4x supersampled."); } if (ImGui::CollapsingHeader("Environment", ImGuiTreeNodeFlags_DefaultOpen)) { auto& hdri = HDRIManager::get(); std::string preview = hdri.get_hdri_name(m_hdri_path); if (ImGui::BeginCombo("Starfield", preview.c_str())) { for (const auto& path : hdri.get_available_hdri()) { bool selected = (path == m_hdri_path); if (ImGui::Selectable(hdri.get_hdri_name(path).c_str(), selected)) set_hdri(path); if (selected) ImGui::SetItemDefaultFocus(); } ImGui::EndCombo(); } ImGui::TextDisabled("Switching rebuilds the cubemap (brief pause)."); } } ImGui::End(); } auto Application::build_scene_ui() -> void { if (!ImGui::CollapsingHeader("Objects", ImGuiTreeNodeFlags_DefaultOpen)) return; ImGui::TextDisabled("Drag to orbit, scroll to zoom. HDRI skybox behind."); auto& objs = m_scene_objects; if (m_selected_object >= (int)objs.size()) m_selected_object = (int)objs.size() - 1; ImGui::Text("Spheres (%d)", (int)objs.size()); if (ImGui::Button("Add") && objs.size() < 64) { SceneObject o; o.position = glm::vec3(((int)objs.size() % 5) * 5.0f - 10.0f, 2.0f, ((int)objs.size() / 5) * 5.0f); o.radius = 1.5f; o.color = glm::vec3(0.35f + 0.12f * (objs.size() % 5), 0.55f, 0.9f - 0.12f * (objs.size() % 4)); objs.push_back(o); m_selected_object = (int)objs.size() - 1; } ImGui::SameLine(); if (ImGui::Button("Delete") && !objs.empty()) { objs.erase(objs.begin() + m_selected_object); if (m_selected_object >= (int)objs.size()) m_selected_object = (int)objs.size() - 1; } ImGui::BeginChild("obj_list", ImVec2(0, 90), true); for (int i = 0; i < (int)objs.size(); ++i) { std::string label = "Sphere " + std::to_string(i); if (ImGui::Selectable(label.c_str(), m_selected_object == i)) m_selected_object = i; } ImGui::EndChild(); if (m_selected_object >= 0 && m_selected_object < (int)objs.size()) { SceneObject& o = objs[m_selected_object]; ImGui::DragFloat3("Position", &o.position.x, 0.1f); ImGui::DragFloat("Radius", &o.radius, 0.05f, 0.1f, 20.0f); ImGui::ColorEdit3("Color", &o.color.x); } } auto Application::close() -> void { m_running = false; } auto Application::on_event(Event& event) -> void { EventDispatcher dispatcher(event); dispatcher.dispatch([this, &event](WindowCloseEvent& e) { m_running = false; event.handled = true; return true; }); dispatcher.dispatch([this, &event](WindowResizeEvent& e) { m_minimized = (e.get_width() == 0 || e.get_height() == 0); if (m_device) m_device->resize(e.get_width(), e.get_height()); event.handled = true; return true; }); } auto Application::on_shutdown() -> void { if (m_device) { m_device->wait_idle(); m_scene_renderer.reset(); m_black_hole_renderer.reset(); m_cubemap.reset(); // Free HDRIManager's cached GPU textures now, while the render context // is still alive. On OpenGL these are GL textures owned by a static // singleton; letting them destruct at program exit would call // glDeleteTextures after the GL context is gone and crash on close. HDRIManager::get().clear_cache(); m_device->shutdown(); m_device.reset(); } SettingsManager::shutdown(); Logger::shutdown(); } };