diff --git a/.github/actions/setup-build/action.yml b/.github/actions/setup-build/action.yml index c1272fcd..c8174630 100644 --- a/.github/actions/setup-build/action.yml +++ b/.github/actions/setup-build/action.yml @@ -66,10 +66,12 @@ runs: max-size: 500M variant: sccache - - name: Configure sccache for clang-cl (Windows) + - name: Configure compiler for Windows if: inputs.platform == 'windows' shell: pwsh run: | - echo "CC=sccache clang-cl" >> $env:GITHUB_ENV - echo "CXX=sccache clang-cl" >> $env:GITHUB_ENV + echo "CC=clang-cl" >> $env:GITHUB_ENV + echo "CXX=clang-cl" >> $env:GITHUB_ENV + echo "CMAKE_CXX_COMPILER_LAUNCHER=sccache" >> $env:GITHUB_ENV + echo "CMAKE_C_COMPILER_LAUNCHER=sccache" >> $env:GITHUB_ENV diff --git a/CMakeLists.txt b/CMakeLists.txt index 895dd29e..5b1766d3 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -115,6 +115,9 @@ if(CLANG_FORMAT) "${CMAKE_SOURCE_DIR}/test/*.cc" "${CMAKE_SOURCE_DIR}/test/*.h") + # Exclude third-party library directories from formatting + list(FILTER ALL_SOURCE_FILES EXCLUDE REGEX "src/lib/.*") + add_custom_target(yaze-format COMMAND ${CLANG_FORMAT} -i --style=Google ${ALL_SOURCE_FILES} COMMENT "Running clang-format on source files" diff --git a/src/app/controller.cc b/src/app/controller.cc index f79cc208..1f1c79a7 100644 --- a/src/app/controller.cc +++ b/src/app/controller.cc @@ -49,9 +49,7 @@ void Controller::SetStartupEditor(const std::string& editor_name, } } -void Controller::OnInput() { - PRINT_IF_ERROR(HandleEvents(window_)); -} +void Controller::OnInput() { PRINT_IF_ERROR(HandleEvents(window_)); } absl::Status Controller::OnLoad() { if (editor_manager_.quit() || !window_.active_) { diff --git a/src/app/editor/agent/agent_chat_history_codec.cc b/src/app/editor/agent/agent_chat_history_codec.cc index 1a815017..a93ee584 100644 --- a/src/app/editor/agent/agent_chat_history_codec.cc +++ b/src/app/editor/agent/agent_chat_history_codec.cc @@ -311,8 +311,7 @@ absl::StatusOr AgentChatHistoryCodec::Load( if (config_json.contains("model_presets") && config_json["model_presets"].is_array()) { for (const auto& preset_json : config_json["model_presets"]) { - if (!preset_json.is_object()) - continue; + if (!preset_json.is_object()) continue; AgentConfigSnapshot::ModelPreset preset; preset.name = preset_json.value("name", ""); preset.model = preset_json.value("model", ""); diff --git a/src/app/editor/agent/agent_chat_history_popup.cc b/src/app/editor/agent/agent_chat_history_popup.cc index 7fd255bc..a90187bf 100644 --- a/src/app/editor/agent/agent_chat_history_popup.cc +++ b/src/app/editor/agent/agent_chat_history_popup.cc @@ -41,8 +41,7 @@ AgentChatHistoryPopup::AgentChatHistoryPopup() { } void AgentChatHistoryPopup::Draw() { - if (!visible_) - return; + if (!visible_) return; const auto& theme = AgentUI::GetTheme(); @@ -50,8 +49,7 @@ void AgentChatHistoryPopup::Draw() { ImGuiIO& io = ImGui::GetIO(); pulse_animation_ += io.DeltaTime * 2.0f; scanline_offset_ += io.DeltaTime * 0.3f; - if (scanline_offset_ > 1.0f) - scanline_offset_ -= 1.0f; + if (scanline_offset_ > 1.0f) scanline_offset_ -= 1.0f; glitch_animation_ += io.DeltaTime * 5.0f; blink_counter_ = static_cast(pulse_animation_ * 2.0f) % 2; @@ -151,8 +149,7 @@ void AgentChatHistoryPopup::DrawMessageList() { const auto& msg = messages_[i]; // Skip internal messages - if (msg.is_internal) - continue; + if (msg.is_internal) continue; if (!MessagePassesFilters(msg, i)) { continue; @@ -677,9 +674,7 @@ void AgentChatHistoryPopup::ExportHistory() { } } -void AgentChatHistoryPopup::ScrollToBottom() { - needs_scroll_ = true; -} +void AgentChatHistoryPopup::ScrollToBottom() { needs_scroll_ = true; } } // namespace editor } // namespace yaze diff --git a/src/app/editor/agent/agent_chat_history_popup.h b/src/app/editor/agent/agent_chat_history_popup.h index 817cd336..d0c46b2d 100644 --- a/src/app/editor/agent/agent_chat_history_popup.h +++ b/src/app/editor/agent/agent_chat_history_popup.h @@ -16,7 +16,7 @@ class ToastManager; /** * @class AgentChatHistoryPopup * @brief ImGui popup drawer for displaying chat history on the left side - * + * * Provides a quick-access sidebar for viewing recent chat messages, * complementing the ProposalDrawer on the right. Features: * - Recent message list with timestamps @@ -24,7 +24,7 @@ class ToastManager; * - Scroll to view older messages * - Quick actions (clear, export, open full chat) * - Syncs with AgentChatWidget and AgentEditor - * + * * Positioned on the LEFT side of the screen as a slide-out panel. */ class AgentChatHistoryPopup { diff --git a/src/app/editor/agent/agent_chat_widget.cc b/src/app/editor/agent/agent_chat_widget.cc index d734392f..c7d7d80d 100644 --- a/src/app/editor/agent/agent_chat_widget.cc +++ b/src/app/editor/agent/agent_chat_widget.cc @@ -2,10 +2,13 @@ #include "app/editor/agent/agent_chat_widget.h" +#include + #include #include #include #include +#include #include #include #include @@ -35,9 +38,6 @@ #include "util/file_util.h" #include "util/platform_paths.h" -#include -#include - #if defined(YAZE_WITH_GRPC) #include "app/test/test_manager.h" #endif @@ -212,8 +212,7 @@ void AgentChatWidget::SetProposalDrawer(ProposalDrawer* drawer) { void AgentChatWidget::SetChatHistoryPopup(AgentChatHistoryPopup* popup) { chat_history_popup_ = popup; - if (!chat_history_popup_) - return; + if (!chat_history_popup_) return; // Set up callback to open this chat window chat_history_popup_->SetOpenChatCallback( @@ -1295,8 +1294,7 @@ void AgentChatWidget::RenderCollaborationPanel() { session_name_buffer_, IM_ARRAYSIZE(session_name_buffer_)); ImGui::SameLine(); - if (!can_host) - ImGui::BeginDisabled(); + if (!can_host) ImGui::BeginDisabled(); ImGui::PushStyleColor(ImGuiCol_Button, ImVec4(0.6f, 0.5f, 0.0f, 0.8f)); ImGui::PushStyleColor(ImGuiCol_ButtonHovered, ImVec4(1.0f, 0.843f, 0.0f, 1.0f)); @@ -1347,8 +1345,7 @@ void AgentChatWidget::RenderCollaborationPanel() { join_code_buffer_, IM_ARRAYSIZE(join_code_buffer_)); ImGui::SameLine(); - if (!can_join) - ImGui::BeginDisabled(); + if (!can_join) ImGui::BeginDisabled(); ImGui::PushStyleColor(ImGuiCol_Button, ImVec4(0.1f, 0.4f, 0.1f, 0.8f)); ImGui::PushStyleColor(ImGuiCol_ButtonHovered, ImVec4(0.133f, 0.545f, 0.133f, 1.0f)); @@ -1392,8 +1389,7 @@ void AgentChatWidget::RenderCollaborationPanel() { // Leave/Refresh if (collaboration_state_.active) { - if (!can_leave) - ImGui::BeginDisabled(); + if (!can_leave) ImGui::BeginDisabled(); ImGui::PushStyleColor(ImGuiCol_Button, ImVec4(0.7f, 0.2f, 0.2f, 0.8f)); ImGui::PushStyleColor(ImGuiCol_ButtonHovered, ImVec4(0.863f, 0.078f, 0.235f, 1.0f)); @@ -1416,12 +1412,10 @@ void AgentChatWidget::RenderCollaborationPanel() { } } ImGui::PopStyleColor(2); - if (!can_leave) - ImGui::EndDisabled(); + if (!can_leave) ImGui::EndDisabled(); ImGui::SameLine(); - if (!can_refresh) - ImGui::BeginDisabled(); + if (!can_refresh) ImGui::BeginDisabled(); ImGui::PushStyleColor(ImGuiCol_Button, ImVec4(0.4f, 0.4f, 0.6f, 0.8f)); ImGui::PushStyleColor(ImGuiCol_ButtonHovered, ImVec4(0.416f, 0.353f, 0.804f, 1.0f)); @@ -1433,8 +1427,7 @@ void AgentChatWidget::RenderCollaborationPanel() { ImGui::IsItemHovered(ImGuiHoveredFlags_AllowWhenDisabled)) { ImGui::SetTooltip("Provide refresh_session callback to enable"); } - if (!can_refresh) - ImGui::EndDisabled(); + if (!can_refresh) ImGui::EndDisabled(); } else { ImGui::TextDisabled(ICON_MD_INFO " Start or join a session to collaborate."); @@ -1482,8 +1475,7 @@ void AgentChatWidget::RenderMultimodalPanel() { reinterpret_cast(&multimodal_state_.capture_mode), static_cast(CaptureMode::kRegionSelect)); - if (!can_capture) - ImGui::BeginDisabled(); + if (!can_capture) ImGui::BeginDisabled(); if (ImGui::SmallButton(ICON_MD_PHOTO_CAMERA " Capture##mm_cap")) { if (multimodal_state_.capture_mode == CaptureMode::kRegionSelect) { // Begin region selection mode @@ -1513,8 +1505,7 @@ void AgentChatWidget::RenderMultimodalPanel() { } } } - if (!can_capture) - ImGui::EndDisabled(); + if (!can_capture) ImGui::EndDisabled(); ImGui::SameLine(); if (multimodal_state_.last_capture_path.has_value()) { @@ -1528,8 +1519,7 @@ void AgentChatWidget::RenderMultimodalPanel() { "%s", multimodal_state_.last_capture_path->filename().string().c_str()); } - if (!can_send) - ImGui::BeginDisabled(); + if (!can_send) ImGui::BeginDisabled(); ImGui::SameLine(); if (ImGui::SmallButton(ICON_MD_SEND " Analyze##mm_send")) { if (!multimodal_state_.last_capture_path.has_value()) { @@ -1560,8 +1550,7 @@ void AgentChatWidget::RenderMultimodalPanel() { } } } - if (!can_send) - ImGui::EndDisabled(); + if (!can_send) ImGui::EndDisabled(); // Screenshot preview section if (multimodal_state_.preview.loaded && @@ -2229,8 +2218,7 @@ void AgentChatWidget::RenderModelConfigControls() { match = absl::AsciiStrToLower(info.parameter_size).find(filter) != std::string::npos; } - if (!match) - continue; + if (!match) continue; } bool is_selected = agent_config_.ai_model == info.name; @@ -2774,34 +2762,29 @@ void AgentChatWidget::RenderZ3EDCommandPanel() { } } } - if (ImGui::IsItemHovered()) - ImGui::SetTooltip("List"); + if (ImGui::IsItemHovered()) ImGui::SetTooltip("List"); ImGui::SameLine(); if (ImGui::SmallButton(ICON_MD_DIFFERENCE)) { if (z3ed_callbacks_.diff_proposal) { auto result = z3ed_callbacks_.diff_proposal(""); - if (result.ok()) - z3ed_command_state_.command_output = *result; + if (result.ok()) z3ed_command_state_.command_output = *result; } } - if (ImGui::IsItemHovered()) - ImGui::SetTooltip("Diff"); + if (ImGui::IsItemHovered()) ImGui::SetTooltip("Diff"); ImGui::SameLine(); if (ImGui::SmallButton(ICON_MD_CHECK)) { if (z3ed_callbacks_.accept_proposal) { z3ed_callbacks_.accept_proposal(""); } } - if (ImGui::IsItemHovered()) - ImGui::SetTooltip("Accept"); + if (ImGui::IsItemHovered()) ImGui::SetTooltip("Accept"); ImGui::SameLine(); if (ImGui::SmallButton(ICON_MD_CLOSE)) { if (z3ed_callbacks_.reject_proposal) { z3ed_callbacks_.reject_proposal(""); } } - if (ImGui::IsItemHovered()) - ImGui::SetTooltip("Reject"); + if (ImGui::IsItemHovered()) ImGui::SetTooltip("Reject"); if (!z3ed_command_state_.command_output.empty()) { ImGui::Separator(); @@ -2859,8 +2842,7 @@ void AgentChatWidget::RenderRomSyncPanel() { collaboration_state_.active && collaboration_state_.mode == CollaborationMode::kNetwork; - if (!can_sync) - ImGui::BeginDisabled(); + if (!can_sync) ImGui::BeginDisabled(); if (ImGui::Button(ICON_MD_CLOUD_UPLOAD " Send ROM Sync", ImVec2(-1, 0))) { if (rom_sync_callbacks_.generate_rom_diff) { @@ -2935,8 +2917,7 @@ void AgentChatWidget::RenderSnapshotPreviewPanel() { bool can_share = collaboration_state_.active && collaboration_state_.mode == CollaborationMode::kNetwork; - if (!can_share) - ImGui::BeginDisabled(); + if (!can_share) ImGui::BeginDisabled(); if (ImGui::Button(ICON_MD_SHARE " Share with Collaborators", ImVec2(-1, 0))) { diff --git a/src/app/editor/agent/agent_chat_widget.h b/src/app/editor/agent/agent_chat_widget.h index 278fe941..8b47d005 100644 --- a/src/app/editor/agent/agent_chat_widget.h +++ b/src/app/editor/agent/agent_chat_widget.h @@ -35,8 +35,9 @@ class AgentChatHistoryPopup; /** * @class AgentChatWidget - * @brief Modern AI chat widget with comprehensive z3ed and yaze-server integration - * + * @brief Modern AI chat widget with comprehensive z3ed and yaze-server + * integration + * * Features: * - AI Provider Configuration (Ollama, Gemini, Mock) * - Z3ED Command Palette (run, plan, diff, accept, test) @@ -452,8 +453,8 @@ class AgentChatWidget { size_t last_known_history_size_ = 0; // UI state - int active_tab_ = - 0; // 0=Chat, 1=Config, 2=Commands, 3=Collab, 4=ROM Sync, 5=Files, 6=Prompt + int active_tab_ = 0; // 0=Chat, 1=Config, 2=Commands, 3=Collab, 4=ROM Sync, + // 5=Files, 6=Prompt bool show_agent_config_ = false; cli::agent::PromptMode prompt_mode_ = cli::agent::PromptMode::kStandard; bool show_z3ed_commands_ = false; diff --git a/src/app/editor/agent/agent_collaboration_coordinator.cc b/src/app/editor/agent/agent_collaboration_coordinator.cc index 1e99d3b4..b2098f5a 100644 --- a/src/app/editor/agent/agent_collaboration_coordinator.cc +++ b/src/app/editor/agent/agent_collaboration_coordinator.cc @@ -20,8 +20,6 @@ #include "util/file_util.h" #include "util/macro.h" #include "util/platform_paths.h" - -#include namespace fs = std::filesystem; namespace yaze { diff --git a/src/app/editor/agent/agent_editor.cc b/src/app/editor/agent/agent_editor.cc index 4fbf6baf..1f21dab8 100644 --- a/src/app/editor/agent/agent_editor.cc +++ b/src/app/editor/agent/agent_editor.cc @@ -111,8 +111,7 @@ absl::Status AgentEditor::Save() { } absl::Status AgentEditor::Update() { - if (!active_) - return absl::OkStatus(); + if (!active_) return absl::OkStatus(); // Draw configuration dashboard DrawDashboard(); @@ -149,15 +148,13 @@ void AgentEditor::SetRomContext(Rom* rom) { } void AgentEditor::DrawDashboard() { - if (!active_) - return; + if (!active_) return; // Animate retro effects ImGuiIO& io = ImGui::GetIO(); pulse_animation_ += io.DeltaTime * 2.0f; scanline_offset_ += io.DeltaTime * 0.4f; - if (scanline_offset_ > 1.0f) - scanline_offset_ -= 1.0f; + if (scanline_offset_ > 1.0f) scanline_offset_ -= 1.0f; glitch_timer_ += io.DeltaTime * 5.0f; blink_counter_ = static_cast(pulse_animation_ * 2.0f) % 2; @@ -328,7 +325,6 @@ void AgentEditor::DrawDashboard() { } void AgentEditor::DrawConfigurationPanel() { - // AI Provider Configuration if (ImGui::CollapsingHeader(ICON_MD_SETTINGS " AI Provider", ImGuiTreeNodeFlags_DefaultOpen)) { @@ -348,8 +344,7 @@ void AgentEditor::DrawConfigurationPanel() { if (ImGui::Button(ICON_MD_SETTINGS " Mock", button_size)) { current_profile_.provider = "mock"; } - if (is_mock) - ImGui::PopStyleColor(); + if (is_mock) ImGui::PopStyleColor(); ImGui::SameLine(); if (is_ollama) @@ -357,8 +352,7 @@ void AgentEditor::DrawConfigurationPanel() { if (ImGui::Button(ICON_MD_CLOUD " Ollama", button_size)) { current_profile_.provider = "ollama"; } - if (is_ollama) - ImGui::PopStyleColor(); + if (is_ollama) ImGui::PopStyleColor(); ImGui::SameLine(); if (is_gemini) @@ -366,8 +360,7 @@ void AgentEditor::DrawConfigurationPanel() { if (ImGui::Button(ICON_MD_SMART_TOY " Gemini", button_size)) { current_profile_.provider = "gemini"; } - if (is_gemini) - ImGui::PopStyleColor(); + if (is_gemini) ImGui::PopStyleColor(); ImGui::Separator(); ImGui::Spacing(); @@ -488,8 +481,7 @@ void AgentEditor::DrawConfigurationPanel() { if (tags_buf[0] == '\0' && !current_profile_.tags.empty()) { std::string tags_str; for (size_t i = 0; i < current_profile_.tags.size(); ++i) { - if (i > 0) - tags_str += ", "; + if (i > 0) tags_str += ", "; tags_str += current_profile_.tags[i]; } strncpy(tags_buf, tags_str.c_str(), sizeof(tags_buf) - 1); @@ -1674,9 +1666,7 @@ void AgentEditor::SetChatActive(bool active) { } } -void AgentEditor::ToggleChat() { - SetChatActive(!IsChatActive()); -} +void AgentEditor::ToggleChat() { SetChatActive(!IsChatActive()); } void AgentEditor::OpenChatWindow() { if (chat_widget_) { @@ -1938,9 +1928,7 @@ bool AgentEditor::IsConnectedToServer() const { } #endif -bool AgentEditor::IsInSession() const { - return in_session_; -} +bool AgentEditor::IsInSession() const { return in_session_; } AgentEditor::CollaborationMode AgentEditor::GetCurrentMode() const { return current_mode_; @@ -1991,9 +1979,7 @@ void AgentEditor::SetupChatWidgetCallbacks() { return context; }; - collab_callbacks.leave_session = [this]() { - return this->LeaveSession(); - }; + collab_callbacks.leave_session = [this]() { return this->LeaveSession(); }; collab_callbacks.refresh_session = [this]() -> absl::StatusOr< diff --git a/src/app/editor/agent/agent_editor.h b/src/app/editor/agent/agent_editor.h index 17e59477..4de49205 100644 --- a/src/app/editor/agent/agent_editor.h +++ b/src/app/editor/agent/agent_editor.h @@ -31,10 +31,10 @@ class NetworkCollaborationCoordinator; /** * @class AgentEditor * @brief Comprehensive AI Agent Platform & Bot Creator - * + * * A full-featured bot creation and management platform: * - Agent provider configuration (Ollama, Gemini, Mock) - * - Model selection and parameters + * - Model selection and parameters * - System prompt editing with live syntax highlighting * - Bot profile management (create, save, load custom bots) * - Chat history viewer and management @@ -43,7 +43,7 @@ class NetworkCollaborationCoordinator; * - Z3ED command automation presets * - Multimodal/vision configuration * - Export/Import bot configurations - * + * * The chat widget is separate and managed by EditorManager, with * a dense/compact mode for focused conversations. */ diff --git a/src/app/editor/agent/agent_ui_theme.cc b/src/app/editor/agent/agent_ui_theme.cc index 129bc1ac..12658f21 100644 --- a/src/app/editor/agent/agent_ui_theme.cc +++ b/src/app/editor/agent/agent_ui_theme.cc @@ -171,9 +171,7 @@ void StatusBadge(const char* text, ButtonColor color) { ImGui::PopStyleColor(); } -void VerticalSpacing(float amount) { - ImGui::Dummy(ImVec2(0, amount)); -} +void VerticalSpacing(float amount) { ImGui::Dummy(ImVec2(0, amount)); } void HorizontalSpacing(float amount) { ImGui::Dummy(ImVec2(amount, 0)); diff --git a/src/app/editor/agent/agent_ui_theme.h b/src/app/editor/agent/agent_ui_theme.h index ca8cf854..baebdf38 100644 --- a/src/app/editor/agent/agent_ui_theme.h +++ b/src/app/editor/agent/agent_ui_theme.h @@ -11,9 +11,10 @@ namespace editor { /** * @struct AgentUITheme * @brief Centralized theme colors for Agent UI components - * - * All hardcoded colors from AgentChatWidget, AgentEditor, and AgentChatHistoryPopup - * are consolidated here and derived from the current theme. + * + * All hardcoded colors from AgentChatWidget, AgentEditor, and + * AgentChatHistoryPopup are consolidated here and derived from the current + * theme. */ struct AgentUITheme { // Message colors diff --git a/src/app/editor/agent/network_collaboration_coordinator.cc b/src/app/editor/agent/network_collaboration_coordinator.cc index 55a6afdc..ba452e13 100644 --- a/src/app/editor/agent/network_collaboration_coordinator.cc +++ b/src/app/editor/agent/network_collaboration_coordinator.cc @@ -55,8 +55,7 @@ class WebSocketClient { } bool Send(const std::string& message) { - if (!connected_ || !client_) - return false; + if (!connected_ || !client_) return false; // For HTTP fallback: POST message to server // A full WebSocket would send WebSocket frames @@ -65,8 +64,7 @@ class WebSocketClient { } std::string Receive() { - if (!connected_ || !client_) - return ""; + if (!connected_ || !client_) return ""; // For HTTP fallback: Poll for messages // A full WebSocket would read frames from the socket @@ -320,9 +318,7 @@ absl::Status NetworkCollaborationCoordinator::SendAIQuery( return absl::OkStatus(); } -bool NetworkCollaborationCoordinator::IsConnected() const { - return connected_; -} +bool NetworkCollaborationCoordinator::IsConnected() const { return connected_; } void NetworkCollaborationCoordinator::SetMessageCallback( MessageCallback callback) { @@ -527,8 +523,7 @@ void NetworkCollaborationCoordinator::HandleWebSocketMessage( void NetworkCollaborationCoordinator::WebSocketReceiveLoop() { while (!should_stop_ && connected_) { - if (!ws_client_) - break; + if (!ws_client_) break; std::string message = ws_client_->Receive(); if (!message.empty()) { @@ -608,9 +603,7 @@ absl::Status NetworkCollaborationCoordinator::SendAIQuery(const std::string&, "Network collaboration requires JSON support"); } -bool NetworkCollaborationCoordinator::IsConnected() const { - return false; -} +bool NetworkCollaborationCoordinator::IsConnected() const { return false; } void NetworkCollaborationCoordinator::SetMessageCallback(MessageCallback) {} void NetworkCollaborationCoordinator::SetParticipantCallback( diff --git a/src/app/editor/code/assembly_editor.cc b/src/app/editor/code/assembly_editor.cc index 5707522e..288b98d1 100644 --- a/src/app/editor/code/assembly_editor.cc +++ b/src/app/editor/code/assembly_editor.cc @@ -1,5 +1,4 @@ #include "assembly_editor.h" -#include "app/editor/system/editor_card_registry.h" #include #include @@ -7,6 +6,7 @@ #include "absl/strings/match.h" #include "absl/strings/str_cat.h" +#include "app/editor/system/editor_card_registry.h" #include "app/gui/core/icons.h" #include "app/gui/core/ui_helpers.h" #include "app/gui/widgets/text_editor.h" @@ -42,8 +42,7 @@ static const char* const kIdentifiers[] = { TextEditor::LanguageDefinition GetAssemblyLanguageDef() { TextEditor::LanguageDefinition language_65816; - for (auto& k : kKeywords) - language_65816.mKeywords.emplace(k); + for (auto& k : kKeywords) language_65816.mKeywords.emplace(k); for (auto& k : kIdentifiers) { TextEditor::Identifier id; @@ -178,8 +177,7 @@ void AssemblyEditor::Initialize() { text_editor_.SetLanguageDefinition(GetAssemblyLanguageDef()); // Register cards with EditorCardManager - if (!dependencies_.card_registry) - return; + if (!dependencies_.card_registry) return; auto* card_registry = dependencies_.card_registry; card_registry->RegisterCard({.card_id = "assembly.editor", .display_name = "Assembly Editor", @@ -194,14 +192,15 @@ void AssemblyEditor::Initialize() { .shortcut_hint = "", .priority = 20}); - // Don't show by default - only show when user explicitly opens Assembly Editor + // Don't show by default - only show when user explicitly opens Assembly + // Editor } absl::Status AssemblyEditor::Load() { // Register cards with EditorCardRegistry (dependency injection) - // Note: Assembly editor uses dynamic file tabs, so we register the main editor window - if (!dependencies_.card_registry) - return absl::OkStatus(); + // Note: Assembly editor uses dynamic file tabs, so we register the main + // editor window + if (!dependencies_.card_registry) return absl::OkStatus(); auto* card_registry = dependencies_.card_registry; return absl::OkStatus(); @@ -464,8 +463,6 @@ absl::Status AssemblyEditor::Redo() { return absl::OkStatus(); } -absl::Status AssemblyEditor::Update() { - return absl::OkStatus(); -} +absl::Status AssemblyEditor::Update() { return absl::OkStatus(); } } // namespace yaze::editor diff --git a/src/app/editor/code/project_file_editor.cc b/src/app/editor/code/project_file_editor.cc index 32ee4f00..4b0190af 100644 --- a/src/app/editor/code/project_file_editor.cc +++ b/src/app/editor/code/project_file_editor.cc @@ -22,8 +22,7 @@ ProjectFileEditor::ProjectFileEditor() { } void ProjectFileEditor::Draw() { - if (!active_) - return; + if (!active_) return; ImGui::SetNextWindowSize(ImVec2(900, 700), ImGuiCond_FirstUseEver); if (!ImGui::Begin(absl::StrFormat("%s Project Editor###ProjectFileEditor", @@ -57,8 +56,7 @@ void ProjectFileEditor::Draw() { ImGui::TableNextColumn(); bool can_save = !filepath_.empty() && IsModified(); - if (!can_save) - ImGui::BeginDisabled(); + if (!can_save) ImGui::BeginDisabled(); if (ImGui::Button(absl::StrFormat("%s Save", ICON_MD_SAVE).c_str())) { auto status = SaveFile(); if (status.ok() && toast_manager_) { @@ -67,8 +65,7 @@ void ProjectFileEditor::Draw() { toast_manager_->Show(std::string(status.message()), ToastType::kError); } } - if (!can_save) - ImGui::EndDisabled(); + if (!can_save) ImGui::EndDisabled(); ImGui::TableNextColumn(); if (ImGui::Button(absl::StrFormat("%s Save As", ICON_MD_SAVE_AS).c_str())) { @@ -251,8 +248,7 @@ void ProjectFileEditor::ValidateContent() { std::string trimmed = std::string(absl::StripAsciiWhitespace(line)); // Skip empty lines and comments - if (trimmed.empty() || trimmed[0] == '#') - continue; + if (trimmed.empty() || trimmed[0] == '#') continue; // Check for section headers if (trimmed[0] == '[' && trimmed[trimmed.size() - 1] == ']') { @@ -284,8 +280,7 @@ void ProjectFileEditor::ValidateContent() { } void ProjectFileEditor::ShowValidationErrors() { - if (validation_errors_.empty()) - return; + if (validation_errors_.empty()) return; ImGui::TextColored(ImVec4(1.0f, 0.3f, 0.3f, 1.0f), "Validation Errors:"); for (const auto& error : validation_errors_) { diff --git a/src/app/editor/code/project_file_editor.h b/src/app/editor/code/project_file_editor.h index d8462f06..85c3faf3 100644 --- a/src/app/editor/code/project_file_editor.h +++ b/src/app/editor/code/project_file_editor.h @@ -15,7 +15,7 @@ class ToastManager; /** * @class ProjectFileEditor * @brief Editor for .yaze project files with syntax highlighting and validation - * + * * Provides a rich text editing experience for yaze project files with: * - Syntax highlighting for INI-style format * - Real-time validation diff --git a/src/app/editor/dungeon/dungeon_canvas_viewer.cc b/src/app/editor/dungeon/dungeon_canvas_viewer.cc index 73976ff3..88e0ad4a 100644 --- a/src/app/editor/dungeon/dungeon_canvas_viewer.cc +++ b/src/app/editor/dungeon/dungeon_canvas_viewer.cc @@ -12,11 +12,10 @@ namespace yaze::editor { -// DrawDungeonTabView() removed - DungeonEditorV2 uses EditorCard system for flexible docking +// DrawDungeonTabView() removed - DungeonEditorV2 uses EditorCard system for +// flexible docking -void DungeonCanvasViewer::Draw(int room_id) { - DrawDungeonCanvas(room_id); -} +void DungeonCanvasViewer::Draw(int room_id) { DrawDungeonCanvas(room_id); } void DungeonCanvasViewer::DrawDungeonCanvas(int room_id) { // Validate room_id and ROM @@ -198,11 +197,11 @@ void DungeonCanvasViewer::DrawDungeonCanvas(int room_id) { // Check if critical properties changed and trigger reload if (prev_blockset != room.blockset || prev_palette != room.palette || prev_layout != room.layout || prev_spriteset != room.spriteset) { - // Only reload if ROM is properly loaded if (room.rom() && room.rom()->is_loaded()) { // Force reload of room graphics - // Room buffers are now self-contained - no need for separate palette operations + // Room buffers are now self-contained - no need for separate palette + // operations room.LoadRoomGraphics(room.blockset); room.RenderRoomGraphics(); // Applies palettes internally } @@ -314,9 +313,7 @@ void DungeonCanvasViewer::DrawDungeonCanvas(int room_id) { // Separator gui::CanvasMenuItem sep; sep.label = "---"; - sep.enabled_condition = []() { - return false; - }; + sep.enabled_condition = []() { return false; }; object_bounds_menu.subitems.push_back(sep); // Sub-menu for filtering by layer @@ -524,14 +521,16 @@ void DungeonCanvasViewer::DrawDungeonCanvas(int room_id) { room.LoadObjects(); } - // CRITICAL: Process texture queue BEFORE drawing to ensure textures are ready - // This must happen before DrawRoomBackgroundLayers() attempts to draw bitmaps + // CRITICAL: Process texture queue BEFORE drawing to ensure textures are + // ready This must happen before DrawRoomBackgroundLayers() attempts to draw + // bitmaps if (rom_ && rom_->is_loaded()) { gfx::Arena::Get().ProcessTextureQueue(nullptr); } // Draw the room's background layers to canvas - // This already includes objects rendered by ObjectDrawer in Room::RenderObjectsToBackground() + // This already includes objects rendered by ObjectDrawer in + // Room::RenderObjectsToBackground() DrawRoomBackgroundLayers(room_id); // Render sprites as simple 16x16 squares with labels @@ -642,8 +641,8 @@ std::pair DungeonCanvasViewer::RoomToCanvasCoordinates( int room_x, int room_y) const { // Convert room coordinates (tile units) to UNSCALED canvas pixel coordinates // Dungeon tiles are 8x8 pixels (not 16x16!) - // IMPORTANT: Return UNSCALED coordinates - Canvas drawing functions apply scale internally - // Do NOT multiply by scale here or we get double-scaling! + // IMPORTANT: Return UNSCALED coordinates - Canvas drawing functions apply + // scale internally Do NOT multiply by scale here or we get double-scaling! // Simple conversion: tile units → pixel units (no scale, no offset) return {room_x * 8, room_y * 8}; @@ -657,8 +656,7 @@ std::pair DungeonCanvasViewer::CanvasToRoomCoordinates( // IMPORTANT: Mouse coordinates are in screen space, must undo scale first float scale = canvas_.global_scale(); - if (scale <= 0.0f) - scale = 1.0f; // Prevent division by zero + if (scale <= 0.0f) scale = 1.0f; // Prevent division by zero // Step 1: Convert screen space → logical pixel space int logical_x = static_cast(canvas_x / scale); @@ -720,7 +718,8 @@ void DungeonCanvasViewer::CalculateWallDimensions( // Object visualization methods void DungeonCanvasViewer::DrawObjectPositionOutlines(const zelda3::Room& room) { // Draw colored rectangles showing object positions - // This helps visualize object placement even if graphics don't render correctly + // This helps visualize object placement even if graphics don't render + // correctly const auto& objects = room.GetTileObjects(); @@ -752,10 +751,12 @@ void DungeonCanvasViewer::DrawObjectPositionOutlines(const zelda3::Room& room) { continue; } - // Convert object position (tile coordinates) to canvas pixel coordinates (UNSCALED) + // Convert object position (tile coordinates) to canvas pixel coordinates + // (UNSCALED) auto [canvas_x, canvas_y] = RoomToCanvasCoordinates(obj.x(), obj.y()); - // Calculate object dimensions based on type and size (UNSCALED logical pixels) + // Calculate object dimensions based on type and size (UNSCALED logical + // pixels) int width = 8; // Default 8x8 pixels int height = 8; @@ -852,8 +853,7 @@ absl::Status DungeonCanvasViewer::LoadAndRenderRoomGraphics(int room_id) { } void DungeonCanvasViewer::DrawRoomBackgroundLayers(int room_id) { - if (room_id < 0 || room_id >= zelda3::NumberOfRooms || !rooms_) - return; + if (room_id < 0 || room_id >= zelda3::NumberOfRooms || !rooms_) return; auto& room = (*rooms_)[room_id]; auto& layer_settings = GetRoomLayerSettings(room_id); @@ -866,8 +866,9 @@ void DungeonCanvasViewer::DrawRoomBackgroundLayers(int room_id) { if (layer_settings.bg1_visible && bg1_bitmap.is_active() && bg1_bitmap.width() > 0 && bg1_bitmap.height() > 0) { if (!bg1_bitmap.texture()) { - // Queue texture creation for background layer 1 via Arena's deferred system - // BATCHING FIX: Don't process immediately - let the main loop handle batching + // Queue texture creation for background layer 1 via Arena's deferred + // system BATCHING FIX: Don't process immediately - let the main loop + // handle batching gfx::Arena::Get().QueueTextureCommand( gfx::Arena::TextureCommandType::CREATE, &bg1_bitmap); @@ -892,8 +893,9 @@ void DungeonCanvasViewer::DrawRoomBackgroundLayers(int room_id) { if (layer_settings.bg2_visible && bg2_bitmap.is_active() && bg2_bitmap.width() > 0 && bg2_bitmap.height() > 0) { if (!bg2_bitmap.texture()) { - // Queue texture creation for background layer 2 via Arena's deferred system - // BATCHING FIX: Don't process immediately - let the main loop handle batching + // Queue texture creation for background layer 2 via Arena's deferred + // system BATCHING FIX: Don't process immediately - let the main loop + // handle batching gfx::Arena::Get().QueueTextureCommand( gfx::Arena::TextureCommandType::CREATE, &bg2_bitmap); @@ -931,8 +933,7 @@ void DungeonCanvasViewer::DrawRoomBackgroundLayers(int room_id) { int non_zero_pixels = 0; for (size_t i = 0; i < bg1_data.size(); i += 100) { // Sample every 100th pixel - if (bg1_data[i] != 0) - non_zero_pixels++; + if (bg1_data[i] != 0) non_zero_pixels++; } LOG_DEBUG("DungeonCanvasViewer", "BG1 bitmap data: %zu pixels, ~%d non-zero samples", @@ -951,8 +952,7 @@ void DungeonCanvasViewer::DrawRoomBackgroundLayers(int room_id) { int non_zero_pixels = 0; for (size_t i = 0; i < bg2_data.size(); i += 100) { // Sample every 100th pixel - if (bg2_data[i] != 0) - non_zero_pixels++; + if (bg2_data[i] != 0) non_zero_pixels++; } LOG_DEBUG("DungeonCanvasViewer", "BG2 bitmap data: %zu pixels, ~%d non-zero samples", diff --git a/src/app/editor/dungeon/dungeon_canvas_viewer.h b/src/app/editor/dungeon/dungeon_canvas_viewer.h index a0cb6c34..5c1d44cd 100644 --- a/src/app/editor/dungeon/dungeon_canvas_viewer.h +++ b/src/app/editor/dungeon/dungeon_canvas_viewer.h @@ -15,7 +15,7 @@ namespace editor { /** * @brief Handles the main dungeon canvas rendering and interaction - * + * * In Link to the Past, dungeon "layers" are not separate visual layers * but a game concept where objects exist on different logical levels. * Players move between these levels using stair objects that act as diff --git a/src/app/editor/dungeon/dungeon_editor_v2.cc b/src/app/editor/dungeon/dungeon_editor_v2.cc index 4cc50c01..1c1c9463 100644 --- a/src/app/editor/dungeon/dungeon_editor_v2.cc +++ b/src/app/editor/dungeon/dungeon_editor_v2.cc @@ -1,10 +1,10 @@ #include "dungeon_editor_v2.h" -#include "app/editor/system/editor_card_registry.h" #include #include #include "absl/strings/str_format.h" +#include "app/editor/system/editor_card_registry.h" #include "app/gfx/resource/arena.h" #include "app/gfx/types/snes_palette.h" #include "app/gfx/util/palette_manager.h" @@ -24,15 +24,15 @@ void DungeonEditorV2::Initialize(gfx::IRenderer* renderer, Rom* rom) { // Don't initialize emulator preview yet - ROM might not be loaded // Will be initialized in Load() instead - // Setup docking class for room windows (ImGui::GetID will be called in Update when ImGui is ready) + // Setup docking class for room windows (ImGui::GetID will be called in Update + // when ImGui is ready) room_window_class_.DockingAllowUnclassed = true; // Room windows can dock with anything room_window_class_.DockingAlwaysTabBar = true; // Always show tabs when multiple rooms // Register all cards with EditorCardRegistry (dependency injection) - if (!dependencies_.card_registry) - return; + if (!dependencies_.card_registry) return; auto* card_registry = dependencies_.card_registry; card_registry->RegisterCard({.card_id = MakeCardId("dungeon.control_panel"), @@ -99,7 +99,8 @@ void DungeonEditorV2::Initialize(gfx::IRenderer* renderer, Rom* rom) { .visibility_flag = &show_debug_controls_, .priority = 80}); - // Show control panel and room selector by default when Dungeon Editor is activated + // Show control panel and room selector by default when Dungeon Editor is + // activated show_control_panel_ = true; show_room_selector_ = true; } @@ -187,7 +188,8 @@ absl::Status DungeonEditorV2::Update() { } // CARD-BASED EDITOR: All windows are independent top-level cards - // No parent wrapper - this allows closing control panel without affecting rooms + // No parent wrapper - this allows closing control panel without affecting + // rooms DrawLayout(); @@ -343,7 +345,8 @@ void DungeonEditorV2::DrawRoomTab(int room_id) { } // Initialize room graphics and objects in CORRECT ORDER - // Critical sequence: 1. Load data from ROM, 2. Load objects (sets floor graphics), 3. Render + // Critical sequence: 1. Load data from ROM, 2. Load objects (sets floor + // graphics), 3. Render if (room.IsLoaded()) { bool needs_render = false; @@ -355,7 +358,8 @@ void DungeonEditorV2::DrawRoomTab(int room_id) { room_id); } - // Step 2: Load objects from ROM (CRITICAL: sets floor1_graphics_, floor2_graphics_!) + // Step 2: Load objects from ROM (CRITICAL: sets floor1_graphics_, + // floor2_graphics_!) if (room.GetTileObjects().empty()) { room.LoadObjects(); needs_render = true; @@ -366,7 +370,8 @@ void DungeonEditorV2::DrawRoomTab(int room_id) { // Step 3: Render to bitmaps (now floor graphics are set correctly!) auto& bg1_bitmap = room.bg1_buffer().bitmap(); if (needs_render || !bg1_bitmap.is_active() || bg1_bitmap.width() == 0) { - room.RenderRoomGraphics(); // Includes RenderObjectsToBackground() internally + room.RenderRoomGraphics(); // Includes RenderObjectsToBackground() + // internally LOG_DEBUG("[DungeonEditorV2]", "Rendered room %d to bitmaps", room_id); } } @@ -417,9 +422,7 @@ void DungeonEditorV2::OnEntranceSelected(int entrance_id) { OnRoomSelected(room_id); } -void DungeonEditorV2::add_room(int room_id) { - OnRoomSelected(room_id); -} +void DungeonEditorV2::add_room(int room_id) { OnRoomSelected(room_id); } void DungeonEditorV2::FocusRoom(int room_id) { // Focus the room card if it exists @@ -782,8 +785,8 @@ void DungeonEditorV2::DrawRoomGraphicsCard() { ImGui::Text("Blockset: %02X", room.blockset); ImGui::Separator(); - // Create a canvas for displaying room graphics (16 blocks, 2 columns, 8 rows) - // Each block is 128x32, so 2 cols = 256 wide, 8 rows = 256 tall + // Create a canvas for displaying room graphics (16 blocks, 2 columns, 8 + // rows) Each block is 128x32, so 2 cols = 256 wide, 8 rows = 256 tall static gui::Canvas room_gfx_canvas("##RoomGfxCanvas", ImVec2(256 + 1, 256 + 1)); @@ -810,8 +813,7 @@ void DungeonEditorV2::DrawRoomGraphicsCard() { constexpr int block_height = 32; for (int block : blocks) { - if (current_block >= 16) - break; // Show first 16 blocks + if (current_block >= 16) break; // Show first 16 blocks // Ensure the graphics sheet is loaded if (block < static_cast(gfx::Arena::Get().gfx_sheets().size())) { diff --git a/src/app/editor/dungeon/dungeon_editor_v2.h b/src/app/editor/dungeon/dungeon_editor_v2.h index db98f7bb..7b2e1928 100644 --- a/src/app/editor/dungeon/dungeon_editor_v2.h +++ b/src/app/editor/dungeon/dungeon_editor_v2.h @@ -26,16 +26,16 @@ namespace editor { /** * @brief DungeonEditorV2 - Simplified dungeon editor using component delegation - * + * * This is a drop-in replacement for DungeonEditor that properly delegates * to the component system instead of implementing everything inline. - * + * * Architecture: * - DungeonRoomLoader handles ROM data loading * - DungeonRoomSelector handles room selection UI * - DungeonCanvasViewer handles canvas rendering and display * - DungeonObjectSelector handles object selection and preview - * + * * The editor acts as a coordinator, not an implementer. */ class DungeonEditorV2 : public Editor { @@ -81,10 +81,8 @@ class DungeonEditorV2 : public Editor { // ROM state bool IsRomLoaded() const override { return rom_ && rom_->is_loaded(); } std::string GetRomStatus() const override { - if (!rom_) - return "No ROM loaded"; - if (!rom_->is_loaded()) - return "ROM failed to load"; + if (!rom_) return "No ROM loaded"; + if (!rom_->is_loaded()) return "ROM failed to load"; return absl::StrFormat("ROM loaded: %s", rom_->title()); } diff --git a/src/app/editor/dungeon/dungeon_object_interaction.cc b/src/app/editor/dungeon/dungeon_object_interaction.cc index 9e0653e1..08e6440e 100644 --- a/src/app/editor/dungeon/dungeon_object_interaction.cc +++ b/src/app/editor/dungeon/dungeon_object_interaction.cc @@ -114,8 +114,7 @@ void DungeonObjectInteraction::CheckForObjectSelection() { } void DungeonObjectInteraction::DrawObjectSelectRect() { - if (!canvas_->IsMouseHovering()) - return; + if (!canvas_->IsMouseHovering()) return; const ImGuiIO& io = ImGui::GetIO(); const ImVec2 canvas_pos = canvas_->zero_point(); @@ -160,8 +159,7 @@ void DungeonObjectInteraction::DrawObjectSelectRect() { } void DungeonObjectInteraction::SelectObjectsInRect() { - if (!rooms_ || current_room_id_ < 0 || current_room_id_ >= 296) - return; + if (!rooms_ || current_room_id_ < 0 || current_room_id_ >= 296) return; auto& room = (*rooms_)[current_room_id_]; selected_object_indices_.clear(); @@ -186,8 +184,7 @@ void DungeonObjectInteraction::SelectObjectsInRect() { } void DungeonObjectInteraction::DrawSelectionHighlights() { - if (!rooms_ || current_room_id_ < 0 || current_room_id_ >= 296) - return; + if (!rooms_ || current_room_id_ < 0 || current_room_id_ >= 296) return; auto& room = (*rooms_)[current_room_id_]; const auto& objects = room.GetTileObjects(); @@ -243,11 +240,9 @@ void DungeonObjectInteraction::DrawSelectionHighlights() { } void DungeonObjectInteraction::PlaceObjectAtPosition(int room_x, int room_y) { - if (!object_loaded_ || preview_object_.id_ < 0 || !rooms_) - return; + if (!object_loaded_ || preview_object_.id_ < 0 || !rooms_) return; - if (current_room_id_ < 0 || current_room_id_ >= 296) - return; + if (current_room_id_ < 0 || current_room_id_ >= 296) return; // Create new object at the specified position auto new_object = preview_object_; @@ -270,8 +265,7 @@ void DungeonObjectInteraction::PlaceObjectAtPosition(int room_x, int room_y) { } void DungeonObjectInteraction::DrawSelectBox() { - if (!is_selecting_) - return; + if (!is_selecting_) return; ImDrawList* draw_list = ImGui::GetWindowDrawList(); ImVec2 canvas_pos = canvas_->zero_point(); @@ -290,10 +284,8 @@ void DungeonObjectInteraction::DrawSelectBox() { } void DungeonObjectInteraction::DrawDragPreview() { - if (!is_dragging_ || selected_object_indices_.empty() || !rooms_) - return; - if (current_room_id_ < 0 || current_room_id_ >= 296) - return; + if (!is_dragging_ || selected_object_indices_.empty() || !rooms_) return; + if (current_room_id_ < 0 || current_room_id_ >= 296) return; // Draw drag preview for selected objects ImDrawList* draw_list = ImGui::GetWindowDrawList(); @@ -332,13 +324,11 @@ void DungeonObjectInteraction::DrawDragPreview() { } void DungeonObjectInteraction::UpdateSelectedObjects() { - if (!is_selecting_ || !rooms_) - return; + if (!is_selecting_ || !rooms_) return; selected_objects_.clear(); - if (current_room_id_ < 0 || current_room_id_ >= 296) - return; + if (current_room_id_ < 0 || current_room_id_ >= 296) return; auto& room = (*rooms_)[current_room_id_]; @@ -352,8 +342,7 @@ void DungeonObjectInteraction::UpdateSelectedObjects() { bool DungeonObjectInteraction::IsObjectInSelectBox( const zelda3::RoomObject& object) const { - if (!is_selecting_) - return false; + if (!is_selecting_) return false; // Convert object position to canvas coordinates auto [canvas_x, canvas_y] = RoomToCanvasCoordinates(object.x_, object.y_); @@ -413,8 +402,7 @@ void DungeonObjectInteraction::ClearSelection() { } void DungeonObjectInteraction::ShowContextMenu() { - if (!canvas_->IsMouseHovering()) - return; + if (!canvas_->IsMouseHovering()) return; // Show context menu on right-click when not dragging if (ImGui::IsMouseClicked(ImGuiMouseButton_Right) && !is_dragging_) { @@ -455,10 +443,8 @@ void DungeonObjectInteraction::ShowContextMenu() { } void DungeonObjectInteraction::HandleDeleteSelected() { - if (selected_object_indices_.empty() || !rooms_) - return; - if (current_room_id_ < 0 || current_room_id_ >= 296) - return; + if (selected_object_indices_.empty() || !rooms_) return; + if (current_room_id_ < 0 || current_room_id_ >= 296) return; auto& room = (*rooms_)[current_room_id_]; @@ -481,10 +467,8 @@ void DungeonObjectInteraction::HandleDeleteSelected() { } void DungeonObjectInteraction::HandleCopySelected() { - if (selected_object_indices_.empty() || !rooms_) - return; - if (current_room_id_ < 0 || current_room_id_ >= 296) - return; + if (selected_object_indices_.empty() || !rooms_) return; + if (current_room_id_ < 0 || current_room_id_ >= 296) return; auto& room = (*rooms_)[current_room_id_]; const auto& objects = room.GetTileObjects(); @@ -501,10 +485,8 @@ void DungeonObjectInteraction::HandleCopySelected() { } void DungeonObjectInteraction::HandlePasteObjects() { - if (!has_clipboard_data_ || !rooms_) - return; - if (current_room_id_ < 0 || current_room_id_ >= 296) - return; + if (!has_clipboard_data_ || !rooms_) return; + if (current_room_id_ < 0 || current_room_id_ >= 296) return; auto& room = (*rooms_)[current_room_id_]; diff --git a/src/app/editor/dungeon/dungeon_object_interaction.h b/src/app/editor/dungeon/dungeon_object_interaction.h index 3fd00161..7cc02a8a 100644 --- a/src/app/editor/dungeon/dungeon_object_interaction.h +++ b/src/app/editor/dungeon/dungeon_object_interaction.h @@ -13,10 +13,12 @@ namespace yaze { namespace editor { /** - * @brief Handles object selection, placement, and interaction within the dungeon canvas - * - * This component manages mouse interactions for object selection (similar to OverworldEditor), - * object placement, drag operations, and multi-object selection. + * @brief Handles object selection, placement, and interaction within the + * dungeon canvas + * + * This component manages mouse interactions for object selection (similar to + * OverworldEditor), object placement, drag operations, and multi-object + * selection. */ class DungeonObjectInteraction { public: diff --git a/src/app/editor/dungeon/dungeon_object_selector.cc b/src/app/editor/dungeon/dungeon_object_selector.cc index 3a1ce9fc..5fdf2fa7 100644 --- a/src/app/editor/dungeon/dungeon_object_selector.cc +++ b/src/app/editor/dungeon/dungeon_object_selector.cc @@ -93,7 +93,8 @@ void DungeonObjectSelector::DrawObjectRenderer() { int preview_y = 128 - 16; // Center vertically // TODO: Implement preview using ObjectDrawer + small BackgroundBuffer - // For now, use primitive shape rendering (shows object ID and rough dimensions) + // For now, use primitive shape rendering (shows object ID and rough + // dimensions) RenderObjectPrimitive(preview_object_, preview_x, preview_y); } @@ -266,9 +267,8 @@ void DungeonObjectSelector::DrawObjectBrowser() { object_name = std::string(name_ptr); } } - } else if ( - obj_id < - 0x1C0) { // Type3RoomObjectNames has 128 elements (0x140-0x1BF) + } else if (obj_id < 0x1C0) { // Type3RoomObjectNames has 128 elements + // (0x140-0x1BF) int type3_index = obj_id - 0x140; if (type3_index >= 0 && type3_index < std::size(zelda3::Type3RoomObjectNames)) { @@ -362,14 +362,14 @@ void DungeonObjectSelector::DrawRoomGraphics() { const int block_height = 32; // Reduced height for (int block : blocks) { - if (current_block >= 16) - break; // Only show first 16 blocks + if (current_block >= 16) break; // Only show first 16 blocks // Ensure the graphics sheet is loaded and has a valid texture if (block < gfx::Arena::Get().gfx_sheets().size()) { auto& gfx_sheet = gfx::Arena::Get().gfx_sheets()[block]; - // Calculate position in a grid layout instead of horizontal concatenation + // Calculate position in a grid layout instead of horizontal + // concatenation int row = current_block / max_blocks_per_row; int col = current_block % max_blocks_per_row; @@ -381,7 +381,6 @@ void DungeonObjectSelector::DrawRoomGraphics() { room_gfx_canvas_.zero_point().x + room_gfx_canvas_.width() && y + block_height <= room_gfx_canvas_.zero_point().y + room_gfx_canvas_.height()) { - // Only draw if the texture is valid if (gfx_sheet.texture() != 0) { room_gfx_canvas_.draw_list()->AddImage( diff --git a/src/app/editor/dungeon/dungeon_object_selector.h b/src/app/editor/dungeon/dungeon_object_selector.h index 6781adfa..a43933bc 100644 --- a/src/app/editor/dungeon/dungeon_object_selector.h +++ b/src/app/editor/dungeon/dungeon_object_selector.h @@ -94,7 +94,8 @@ class DungeonObjectSelector { gui::Canvas room_gfx_canvas_{"##RoomGfxCanvas", ImVec2(0x100 + 1, 0x10 * 0x40 + 1)}; gui::Canvas object_canvas_; - // ObjectRenderer removed - using ObjectDrawer in Room::RenderObjectsToBackground() + // ObjectRenderer removed - using ObjectDrawer in + // Room::RenderObjectsToBackground() // Editor systems std::unique_ptr* dungeon_editor_system_ = diff --git a/src/app/editor/dungeon/dungeon_room_loader.h b/src/app/editor/dungeon/dungeon_room_loader.h index 5946f975..e28e052f 100644 --- a/src/app/editor/dungeon/dungeon_room_loader.h +++ b/src/app/editor/dungeon/dungeon_room_loader.h @@ -14,7 +14,7 @@ namespace editor { /** * @brief Manages loading and saving of dungeon room data - * + * * This component handles all ROM-related operations for loading room data, * calculating room sizes, and managing room graphics. */ diff --git a/src/app/editor/dungeon/dungeon_room_selector.h b/src/app/editor/dungeon/dungeon_room_selector.h index 53cd1fc8..4c9bc81c 100644 --- a/src/app/editor/dungeon/dungeon_room_selector.h +++ b/src/app/editor/dungeon/dungeon_room_selector.h @@ -2,6 +2,7 @@ #define YAZE_APP_EDITOR_DUNGEON_DUNGEON_ROOM_SELECTOR_H #include + #include "app/rom.h" #include "imgui/imgui.h" #include "zelda3/dungeon/room.h" diff --git a/src/app/editor/dungeon/dungeon_toolset.cc b/src/app/editor/dungeon/dungeon_toolset.cc index 26fff349..5f19ee25 100644 --- a/src/app/editor/dungeon/dungeon_toolset.cc +++ b/src/app/editor/dungeon/dungeon_toolset.cc @@ -29,15 +29,13 @@ void DungeonToolset::Draw() { // Undo button TableNextColumn(); if (Button(ICON_MD_UNDO)) { - if (undo_callback_) - undo_callback_(); + if (undo_callback_) undo_callback_(); } // Redo button TableNextColumn(); if (Button(ICON_MD_REDO)) { - if (redo_callback_) - redo_callback_(); + if (redo_callback_) redo_callback_(); } // Separator @@ -141,8 +139,7 @@ void DungeonToolset::Draw() { // Palette button TableNextColumn(); if (Button(ICON_MD_PALETTE)) { - if (palette_toggle_callback_) - palette_toggle_callback_(); + if (palette_toggle_callback_) palette_toggle_callback_(); } ImGui::EndTable(); diff --git a/src/app/editor/dungeon/dungeon_toolset.h b/src/app/editor/dungeon/dungeon_toolset.h index dad599eb..fd84a7e5 100644 --- a/src/app/editor/dungeon/dungeon_toolset.h +++ b/src/app/editor/dungeon/dungeon_toolset.h @@ -11,7 +11,7 @@ namespace editor { /** * @brief Handles the dungeon editor toolset UI - * + * * This component manages the toolbar with placement modes, background layer * selection, and other editing tools. */ diff --git a/src/app/editor/dungeon/dungeon_usage_tracker.h b/src/app/editor/dungeon/dungeon_usage_tracker.h index a5b85a81..8ef56f48 100644 --- a/src/app/editor/dungeon/dungeon_usage_tracker.h +++ b/src/app/editor/dungeon/dungeon_usage_tracker.h @@ -9,7 +9,7 @@ namespace editor { /** * @brief Tracks and analyzes usage statistics for dungeon resources - * + * * This component manages blockset, spriteset, and palette usage statistics * across all dungeon rooms, providing insights for optimization. */ diff --git a/src/app/editor/dungeon/object_editor_card.cc b/src/app/editor/dungeon/object_editor_card.cc index 1e4a17e1..3651555c 100644 --- a/src/app/editor/dungeon/object_editor_card.cc +++ b/src/app/editor/dungeon/object_editor_card.cc @@ -67,7 +67,6 @@ void ObjectEditorCard::Draw(bool* p_open) { // Tabbed interface for Browser and Preview if (ImGui::BeginTabBar("##ObjectEditorTabs", ImGuiTabBarFlags_None)) { - // Tab 1: Object Browser if (ImGui::BeginTabItem(ICON_MD_LIST " Browser")) { DrawObjectSelector(); diff --git a/src/app/editor/dungeon/object_editor_card.h b/src/app/editor/dungeon/object_editor_card.h index 0385b7c3..d668d064 100644 --- a/src/app/editor/dungeon/object_editor_card.h +++ b/src/app/editor/dungeon/object_editor_card.h @@ -17,13 +17,14 @@ namespace yaze { namespace editor { /** - * @brief Unified card combining object selection, emulator preview, and canvas interaction - * + * @brief Unified card combining object selection, emulator preview, and canvas + * interaction + * * This card replaces three separate components: * - Object Selector (choosing which object to place) * - Emulator Preview (seeing how objects look in-game) * - Object Interaction Controls (placing, selecting, deleting objects) - * + * * It provides a complete workflow for managing dungeon objects in one place. */ class ObjectEditorCard { diff --git a/src/app/editor/editor.h b/src/app/editor/editor.h index bd72d934..ddf41326 100644 --- a/src/app/editor/editor.h +++ b/src/app/editor/editor.h @@ -34,28 +34,28 @@ class UserSettings; /** * @struct EditorDependencies * @brief Unified dependency container for all editor types - * + * * This struct encapsulates all dependencies that editors might need, * providing a clean interface for dependency injection. It supports * both standard editors and specialized ones (emulator, dungeon) that * need additional dependencies like renderers. - * + * * Design Philosophy: * - Single point of dependency management * - Type-safe for common dependencies * - Extensible via custom_data for editor-specific needs * - Session-aware for multi-session support - * + * * Usage: * ```cpp * EditorDependencies deps; * deps.rom = current_rom; * deps.card_registry = &card_registry_; * deps.session_id = session_index; - * + * * // Standard editor * OverworldEditor editor(deps); - * + * * // Specialized editor with renderer * deps.renderer = renderer_; * DungeonEditor dungeon_editor(deps); diff --git a/src/app/editor/editor_manager.cc b/src/app/editor/editor_manager.cc index 92508087..5198ddb2 100644 --- a/src/app/editor/editor_manager.cc +++ b/src/app/editor/editor_manager.cc @@ -92,8 +92,9 @@ std::string GetEditorName(EditorType type) { } // namespace // Static registry of editors that use the card-based layout system -// These editors register their cards with EditorCardManager and manage their own windows -// They do NOT need the traditional ImGui::Begin/End wrapper - they create cards internally +// These editors register their cards with EditorCardManager and manage their +// own windows They do NOT need the traditional ImGui::Begin/End wrapper - they +// create cards internally bool EditorManager::IsCardBasedEditor(EditorType type) { return EditorRegistry::IsCardBasedEditor(type); } @@ -115,13 +116,9 @@ void EditorManager::ShowHexEditor() { } #ifdef YAZE_WITH_GRPC -void EditorManager::ShowAIAgent() { - agent_editor_.set_active(true); -} +void EditorManager::ShowAIAgent() { agent_editor_.set_active(true); } -void EditorManager::ShowChatHistory() { - agent_chat_history_popup_.Toggle(); -} +void EditorManager::ShowChatHistory() { agent_chat_history_popup_.Toggle(); } #endif EditorManager::EditorManager() @@ -154,7 +151,8 @@ EditorManager::EditorManager() // - Session ID tracking (current_session_id_) // // INITIALIZATION ORDER (CRITICAL): - // 1. PopupManager - MUST be first, MenuOrchestrator/UICoordinator take ref to it + // 1. PopupManager - MUST be first, MenuOrchestrator/UICoordinator take ref to + // it // 2. SessionCoordinator - Independent, can be early // 3. MenuOrchestrator - Depends on PopupManager, SessionCoordinator // 4. UICoordinator - Depends on PopupManager, SessionCoordinator @@ -173,14 +171,16 @@ EditorManager::EditorManager() static_cast(&sessions_), &card_registry_, &toast_manager_, &user_settings_); - // STEP 3: Initialize MenuOrchestrator (depends on popup_manager_, session_coordinator_) + // STEP 3: Initialize MenuOrchestrator (depends on popup_manager_, + // session_coordinator_) menu_orchestrator_ = std::make_unique( this, menu_builder_, rom_file_manager_, project_manager_, editor_registry_, *session_coordinator_, toast_manager_, *popup_manager_); session_coordinator_->SetEditorManager(this); - // STEP 4: Initialize UICoordinator (depends on popup_manager_, session_coordinator_, card_registry_) + // STEP 4: Initialize UICoordinator (depends on popup_manager_, + // session_coordinator_, card_registry_) ui_coordinator_ = std::make_unique( this, rom_file_manager_, project_manager_, editor_registry_, card_registry_, *session_coordinator_, window_delegate_, toast_manager_, @@ -253,8 +253,9 @@ void EditorManager::Initialize(gfx::IRenderer* renderer, PRINT_IF_ERROR(OpenRomOrProject(filename)); } - // Note: PopupManager is now initialized in constructor before MenuOrchestrator - // This ensures all menu callbacks can safely call popup_manager_.Show() + // Note: PopupManager is now initialized in constructor before + // MenuOrchestrator This ensures all menu callbacks can safely call + // popup_manager_.Show() // Register emulator cards early (emulator Initialize might not be called) // Using EditorCardRegistry directly @@ -506,7 +507,8 @@ void EditorManager::Initialize(gfx::IRenderer* renderer, // Initialize welcome screen callbacks welcome_screen_.SetOpenRomCallback([this]() { status_ = LoadRom(); - // LoadRom() already handles closing welcome screen and showing editor selection + // LoadRom() already handles closing welcome screen and showing editor + // selection }); welcome_screen_.SetNewProjectCallback([this]() { @@ -643,7 +645,7 @@ void EditorManager::OpenEditorAndCardsFromFlags(const std::string& editor_name, /** * @brief Main update loop for the editor application - * + * * DELEGATION FLOW: * 1. Update timing manager for accurate delta time * 2. Draw popups (PopupManager) - modal dialogs across all sessions @@ -652,12 +654,12 @@ void EditorManager::OpenEditorAndCardsFromFlags(const std::string& editor_name, * 5. Iterate all sessions and update active editors * 6. Draw session UI (SessionCoordinator) - session switcher, manager * 7. Draw sidebar (EditorCardRegistry) - card-based editor UI - * - * Note: EditorManager retains the main loop to coordinate multi-session updates, - * but delegates specific drawing/state operations to specialized components. + * + * Note: EditorManager retains the main loop to coordinate multi-session + * updates, but delegates specific drawing/state operations to specialized + * components. */ absl::Status EditorManager::Update() { - // Update timing manager for accurate delta time across the application // This fixes animation timing issues that occur when mouse isn't moving TimingManager::Get().Update(); @@ -729,7 +731,8 @@ absl::Status EditorManager::Update() { } // CRITICAL: Draw UICoordinator UI components FIRST (before ROM checks) - // This ensures Welcome Screen, Command Palette, etc. work even without ROM loaded + // This ensures Welcome Screen, Command Palette, etc. work even without ROM + // loaded if (ui_coordinator_) { ui_coordinator_->DrawAllUI(); } @@ -774,8 +777,7 @@ absl::Status EditorManager::Update() { // Iterate through ALL sessions to support multi-session docking for (size_t session_idx = 0; session_idx < sessions_.size(); ++session_idx) { auto& session = sessions_[session_idx]; - if (!session.rom.is_loaded()) - continue; // Skip sessions with invalid ROMs + if (!session.rom.is_loaded()) continue; // Skip sessions with invalid ROMs // Use RAII SessionScope for clean context switching SessionScope scope(this, session_idx); @@ -870,8 +872,7 @@ absl::Status EditorManager::Update() { for (size_t session_idx = 0; session_idx < sessions_.size(); ++session_idx) { auto& session = sessions_[session_idx]; - if (!session.rom.is_loaded()) - continue; + if (!session.rom.is_loaded()) continue; for (auto editor : session.editors.active_editors_) { if (*editor->active() && IsCardBasedEditor(editor->type())) { @@ -888,7 +889,8 @@ absl::Status EditorManager::Update() { // Determine which category to show in sidebar std::string sidebar_category; - // Priority 1: Use active_category from card manager (user's last interaction) + // Priority 1: Use active_category from card manager (user's last + // interaction) if (!card_registry_.GetActiveCategory().empty() && std::find(active_categories.begin(), active_categories.end(), card_registry_.GetActiveCategory()) != @@ -942,14 +944,17 @@ void EditorManager::DrawContextSensitiveCardControl() { /** * @brief Draw the main menu bar - * + * * DELEGATION: * - Menu items: MenuOrchestrator::BuildMainMenu() - * - ROM selector: EditorManager::DrawRomSelector() (inline, needs current_rom_ access) - * - Menu bar extras: UICoordinator::DrawMenuBarExtras() (session indicator, version) - * - * Note: ROM selector stays in EditorManager because it needs direct access to sessions_ - * and current_rom_ for the combo box. Could be extracted to SessionCoordinator in future. + * - ROM selector: EditorManager::DrawRomSelector() (inline, needs current_rom_ + * access) + * - Menu bar extras: UICoordinator::DrawMenuBarExtras() (session indicator, + * version) + * + * Note: ROM selector stays in EditorManager because it needs direct access to + * sessions_ and current_rom_ for the combo box. Could be extracted to + * SessionCoordinator in future. */ void EditorManager::DrawMenuBar() { static bool show_display_settings = false; @@ -965,7 +970,8 @@ void EditorManager::DrawMenuBar() { ui_coordinator_->DrawRomSelector(); } - // Delegate menu bar extras to UICoordinator (session indicator, version display) + // Delegate menu bar extras to UICoordinator (session indicator, version + // display) if (ui_coordinator_) { ui_coordinator_->DrawMenuBarExtras(); } @@ -1090,7 +1096,8 @@ void EditorManager::DrawMenuBar() { // Workspace preset dialogs are now in UICoordinator - // Layout presets UI (session dialogs are drawn by SessionCoordinator at lines 907-915) + // Layout presets UI (session dialogs are drawn by SessionCoordinator at lines + // 907-915) if (ui_coordinator_) { ui_coordinator_->DrawLayoutPresets(); } @@ -1098,15 +1105,16 @@ void EditorManager::DrawMenuBar() { /** * @brief Load a ROM file into a new or existing session - * + * * DELEGATION: * - File dialog: util::FileDialogWrapper * - ROM loading: RomFileManager::LoadRom() - * - Session management: EditorManager (searches for empty session or creates new) + * - Session management: EditorManager (searches for empty session or creates + * new) * - Dependency injection: ConfigureEditorDependencies() * - Asset loading: LoadAssets() (calls Initialize/Load on all editors) * - UI updates: UICoordinator (hides welcome, shows editor selection) - * + * * FLOW: * 1. Show file dialog and get filename * 2. Check for duplicate sessions (prevent opening same ROM twice) @@ -1212,16 +1220,16 @@ absl::Status EditorManager::LoadAssets() { /** * @brief Save the current ROM file - * + * * DELEGATION: * - Editor data saving: Each editor's Save() method (overworld, dungeon, etc.) * - ROM file writing: RomFileManager::SaveRom() - * + * * RESPONSIBILITIES STILL IN EDITORMANAGER: * - Coordinating editor saves (dungeon maps, overworld maps, graphics sheets) * - Checking feature flags to determine what to save * - Accessing current session's editors - * + * * This stays in EditorManager because it requires knowledge of all editors * and the order in which they must be saved to maintain ROM integrity. */ @@ -1305,7 +1313,8 @@ absl::Status EditorManager::OpenRomOrProject(const std::string& filename) { // Apply project feature flags to the session session->feature_flags = current_project_.feature_flags; - // Update test manager with current ROM for ROM-dependent tests (only when tests are enabled) + // Update test manager with current ROM for ROM-dependent tests (only when + // tests are enabled) #ifdef YAZE_ENABLE_TESTING LOG_DEBUG("EditorManager", "Setting ROM in TestManager - %p ('%s')", (void*)GetCurrentRom(), @@ -1380,7 +1389,8 @@ absl::Status EditorManager::OpenProject() { // Apply project feature flags to the session session->feature_flags = current_project_.feature_flags; - // Update test manager with current ROM for ROM-dependent tests (only when tests are enabled) + // Update test manager with current ROM for ROM-dependent tests (only when + // tests are enabled) #ifdef YAZE_ENABLE_TESTING LOG_DEBUG("EditorManager", "Setting ROM in TestManager - %p ('%s')", (void*)GetCurrentRom(), @@ -1672,8 +1682,7 @@ std::string EditorManager::GenerateUniqueEditorTitle( // ============================================================================ void EditorManager::JumpToDungeonRoom(int room_id) { - if (!GetCurrentEditorSet()) - return; + if (!GetCurrentEditorSet()) return; // Switch to dungeon editor SwitchToEditor(EditorType::kDungeon); @@ -1683,8 +1692,7 @@ void EditorManager::JumpToDungeonRoom(int room_id) { } void EditorManager::JumpToOverworldMap(int map_id) { - if (!GetCurrentEditorSet()) - return; + if (!GetCurrentEditorSet()) return; // Switch to overworld editor SwitchToEditor(EditorType::kOverworld); @@ -1695,8 +1703,7 @@ void EditorManager::JumpToOverworldMap(int map_id) { void EditorManager::SwitchToEditor(EditorType editor_type) { auto* editor_set = GetCurrentEditorSet(); - if (!editor_set) - return; + if (!editor_set) return; // Toggle the editor for (auto* editor : editor_set->active_editors_) { @@ -1756,7 +1763,6 @@ EditorManager::SessionScope::SessionScope(EditorManager* manager, prev_rom_(manager->GetCurrentRom()), prev_editor_set_(manager->GetCurrentEditorSet()), prev_session_id_(manager->GetCurrentSessionId()) { - // Set new session context manager_->session_coordinator_->SwitchToSession(session_id); } @@ -1777,16 +1783,16 @@ bool EditorManager::HasDuplicateSession(const std::string& filepath) { /** * @brief Injects dependencies into all editors within an EditorSet - * + * * This function is called whenever a new session is created or a ROM is loaded * into an existing session. It configures the EditorDependencies struct with * pointers to all the managers and services that editors need, then applies * them to the editor set. - * + * * @param editor_set The set of editors to configure * @param rom The ROM instance for this session * @param session_id The unique ID for this session - * + * * Dependencies injected: * - rom: The ROM data for this session * - session_id: For creating session-aware card IDs diff --git a/src/app/editor/editor_manager.h b/src/app/editor/editor_manager.h index a56ae1f1..635e5b71 100644 --- a/src/app/editor/editor_manager.h +++ b/src/app/editor/editor_manager.h @@ -3,13 +3,6 @@ #define IMGUI_DEFINE_MATH_OPERATORS -#include "app/editor/editor.h" -#include "app/editor/session_types.h" -#include "app/editor/system/user_settings.h" -#include "app/editor/ui/workspace_manager.h" - -#include "imgui/imgui.h" - #include #include #include @@ -18,6 +11,8 @@ #include "absl/status/status.h" #include "app/editor/agent/agent_chat_history_popup.h" #include "app/editor/code/project_file_editor.h" +#include "app/editor/editor.h" +#include "app/editor/session_types.h" #include "app/editor/system/editor_card_registry.h" #include "app/editor/system/editor_registry.h" #include "app/editor/system/menu_orchestrator.h" @@ -27,15 +22,18 @@ #include "app/editor/system/rom_file_manager.h" #include "app/editor/system/session_coordinator.h" #include "app/editor/system/toast_manager.h" +#include "app/editor/system/user_settings.h" #include "app/editor/system/window_delegate.h" #include "app/editor/ui/editor_selection_dialog.h" #include "app/editor/ui/layout_manager.h" #include "app/editor/ui/menu_builder.h" #include "app/editor/ui/ui_coordinator.h" #include "app/editor/ui/welcome_screen.h" +#include "app/editor/ui/workspace_manager.h" #include "app/emu/emulator.h" #include "app/rom.h" #include "core/project.h" +#include "imgui/imgui.h" #include "yaze_config.h" #include "zelda3/overworld/overworld.h" @@ -65,7 +63,8 @@ namespace editor { */ class EditorManager { public: - // Constructor and destructor must be defined in .cc file for std::unique_ptr with forward-declared types + // Constructor and destructor must be defined in .cc file for std::unique_ptr + // with forward-declared types EditorManager(); ~EditorManager(); @@ -170,12 +169,10 @@ class EditorManager { void LoadWorkspaceLayout() { window_delegate_.LoadWorkspaceLayout(); } void ResetWorkspaceLayout() { window_delegate_.ResetWorkspaceLayout(); } void ShowAllWindows() { - if (ui_coordinator_) - ui_coordinator_->ShowAllWindows(); + if (ui_coordinator_) ui_coordinator_->ShowAllWindows(); } void HideAllWindows() { - if (ui_coordinator_) - ui_coordinator_->HideAllWindows(); + if (ui_coordinator_) ui_coordinator_->HideAllWindows(); } // Layout presets (inline delegation) @@ -191,47 +188,38 @@ class EditorManager { void Quit() { quit_ = true; } // UI visibility controls (public for MenuOrchestrator) - // UI visibility controls - inline for performance (single-line wrappers delegating to UICoordinator) + // UI visibility controls - inline for performance (single-line wrappers + // delegating to UICoordinator) void ShowGlobalSearch() { - if (ui_coordinator_) - ui_coordinator_->ShowGlobalSearch(); + if (ui_coordinator_) ui_coordinator_->ShowGlobalSearch(); } void ShowCommandPalette() { - if (ui_coordinator_) - ui_coordinator_->ShowCommandPalette(); + if (ui_coordinator_) ui_coordinator_->ShowCommandPalette(); } void ShowPerformanceDashboard() { - if (ui_coordinator_) - ui_coordinator_->SetPerformanceDashboardVisible(true); + if (ui_coordinator_) ui_coordinator_->SetPerformanceDashboardVisible(true); } void ShowImGuiDemo() { - if (ui_coordinator_) - ui_coordinator_->SetImGuiDemoVisible(true); + if (ui_coordinator_) ui_coordinator_->SetImGuiDemoVisible(true); } void ShowImGuiMetrics() { - if (ui_coordinator_) - ui_coordinator_->SetImGuiMetricsVisible(true); + if (ui_coordinator_) ui_coordinator_->SetImGuiMetricsVisible(true); } void ShowHexEditor(); void ShowEmulator() { - if (ui_coordinator_) - ui_coordinator_->SetEmulatorVisible(true); + if (ui_coordinator_) ui_coordinator_->SetEmulatorVisible(true); } void ShowMemoryEditor() { - if (ui_coordinator_) - ui_coordinator_->SetMemoryEditorVisible(true); + if (ui_coordinator_) ui_coordinator_->SetMemoryEditorVisible(true); } void ShowResourceLabelManager() { - if (ui_coordinator_) - ui_coordinator_->SetResourceLabelManagerVisible(true); + if (ui_coordinator_) ui_coordinator_->SetResourceLabelManagerVisible(true); } void ShowCardBrowser() { - if (ui_coordinator_) - ui_coordinator_->ShowCardBrowser(); + if (ui_coordinator_) ui_coordinator_->ShowCardBrowser(); } void ShowWelcomeScreen() { - if (ui_coordinator_) - ui_coordinator_->SetWelcomeScreenVisible(true); + if (ui_coordinator_) ui_coordinator_->SetWelcomeScreenVisible(true); } #ifdef YAZE_ENABLE_TESTING @@ -294,8 +282,8 @@ class EditorManager { // Project file editor ProjectFileEditor project_file_editor_; - // Note: Editor selection dialog and welcome screen are now managed by UICoordinator - // Kept here for backward compatibility during transition + // Note: Editor selection dialog and welcome screen are now managed by + // UICoordinator Kept here for backward compatibility during transition EditorSelectionDialog editor_selection_dialog_; WelcomeScreen welcome_screen_; diff --git a/src/app/editor/editor_safeguards.h b/src/app/editor/editor_safeguards.h index b314fc7b..54f2c518 100644 --- a/src/app/editor/editor_safeguards.h +++ b/src/app/editor/editor_safeguards.h @@ -27,10 +27,8 @@ namespace editor { // Helper function for generating consistent ROM status messages inline std::string GetRomStatusMessage(const Rom* rom) { - if (!rom) - return "No ROM loaded"; - if (!rom->is_loaded()) - return "ROM failed to load"; + if (!rom) return "No ROM loaded"; + if (!rom->is_loaded()) return "ROM failed to load"; return absl::StrFormat("ROM loaded: %s", rom->title()); } diff --git a/src/app/editor/graphics/gfx_group_editor.cc b/src/app/editor/graphics/gfx_group_editor.cc index da1dcb60..a5a2cf6c 100644 --- a/src/app/editor/graphics/gfx_group_editor.cc +++ b/src/app/editor/graphics/gfx_group_editor.cc @@ -221,14 +221,14 @@ void DrawPaletteFromPaletteGroup(gfx::SnesPalette& palette) { } for (size_t n = 0; n < palette.size(); n++) { PushID(n); - if ((n % 8) != 0) - SameLine(0.0f, GetStyle().ItemSpacing.y); + if ((n % 8) != 0) SameLine(0.0f, GetStyle().ItemSpacing.y); // Small icon of the color in the palette if (gui::SnesColorButton(absl::StrCat("Palette", n), palette[n], ImGuiColorEditFlags_NoAlpha | ImGuiColorEditFlags_NoPicker | - ImGuiColorEditFlags_NoTooltip)) {} + ImGuiColorEditFlags_NoTooltip)) { + } PopID(); } diff --git a/src/app/editor/graphics/graphics_editor.cc b/src/app/editor/graphics/graphics_editor.cc index 8800581b..469954f3 100644 --- a/src/app/editor/graphics/graphics_editor.cc +++ b/src/app/editor/graphics/graphics_editor.cc @@ -1,11 +1,11 @@ #include "graphics_editor.h" -#include "app/editor/system/editor_card_registry.h" #include #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/str_cat.h" +#include "app/editor/system/editor_card_registry.h" #include "app/gfx/core/bitmap.h" #include "app/gfx/debug/performance/performance_profiler.h" #include "app/gfx/resource/arena.h" @@ -44,8 +44,7 @@ constexpr ImGuiTableFlags kGfxEditTableFlags = ImGuiTableFlags_SizingFixedFit; void GraphicsEditor::Initialize() { - if (!dependencies_.card_registry) - return; + if (!dependencies_.card_registry) return; auto* card_registry = dependencies_.card_registry; card_registry->RegisterCard({.card_id = "graphics.sheet_editor", @@ -116,8 +115,7 @@ absl::Status GraphicsEditor::Load() { } absl::Status GraphicsEditor::Update() { - if (!dependencies_.card_registry) - return absl::OkStatus(); + if (!dependencies_.card_registry) return absl::OkStatus(); auto* card_registry = dependencies_.card_registry; static gui::EditorCard sheet_editor_card("Sheet Editor", ICON_MD_EDIT); @@ -131,7 +129,8 @@ absl::Status GraphicsEditor::Update() { player_anims_card.SetDefaultSize(500, 600); prototype_card.SetDefaultSize(600, 500); - // Sheet Editor Card - Check visibility flag exists and is true before rendering + // Sheet Editor Card - Check visibility flag exists and is true before + // rendering bool* sheet_editor_visible = card_registry->GetVisibilityFlag("graphics.sheet_editor"); if (sheet_editor_visible && *sheet_editor_visible) { @@ -141,7 +140,8 @@ absl::Status GraphicsEditor::Update() { sheet_editor_card.End(); } - // Sheet Browser Card - Check visibility flag exists and is true before rendering + // Sheet Browser Card - Check visibility flag exists and is true before + // rendering bool* sheet_browser_visible = card_registry->GetVisibilityFlag("graphics.sheet_browser"); if (sheet_browser_visible && *sheet_browser_visible) { @@ -154,7 +154,8 @@ absl::Status GraphicsEditor::Update() { sheet_browser_card.End(); } - // Player Animations Card - Check visibility flag exists and is true before rendering + // Player Animations Card - Check visibility flag exists and is true before + // rendering bool* player_anims_visible = card_registry->GetVisibilityFlag("graphics.player_animations"); if (player_anims_visible && *player_anims_visible) { @@ -164,7 +165,8 @@ absl::Status GraphicsEditor::Update() { player_anims_card.End(); } - // Prototype Viewer Card - Check visibility flag exists and is true before rendering + // Prototype Viewer Card - Check visibility flag exists and is true before + // rendering bool* prototype_visible = card_registry->GetVisibilityFlag("graphics.prototype_viewer"); if (prototype_visible && *prototype_visible) { @@ -207,14 +209,14 @@ absl::Status GraphicsEditor::UpdateGfxEdit() { /** * @brief Draw the graphics editing toolset with enhanced ROM hacking features - * + * * Enhanced Features: * - Multi-tool selection for different editing modes * - Real-time zoom controls for precise pixel editing * - Sheet copy/paste operations for ROM graphics management * - Color picker integration with SNES palette system * - Tile size controls for 8x8 and 16x16 SNES tiles - * + * * Performance Notes: * - Toolset updates are batched to minimize ImGui overhead * - Color buttons use cached palette data for fast rendering @@ -434,7 +436,8 @@ absl::Status GraphicsEditor::UpdateGfxTabView() { auto draw_tile_event = [&]() { current_sheet_canvas_.DrawTileOnBitmap(tile_size_, ¤t_bitmap, current_color_); - // Notify Arena that this sheet has been modified for cross-editor synchronization + // Notify Arena that this sheet has been modified for cross-editor + // synchronization gfx::Arena::Get().NotifySheetModified(sheet_id); }; @@ -442,15 +445,15 @@ absl::Status GraphicsEditor::UpdateGfxTabView() { nullptr, gfx::Arena::Get().mutable_gfx_sheets()->at(sheet_id), current_color_, draw_tile_event, tile_size_, current_scale_); - // Notify Arena that this sheet has been modified for cross-editor synchronization + // Notify Arena that this sheet has been modified for cross-editor + // synchronization gfx::Arena::Get().NotifySheetModified(sheet_id); ImGui::EndChild(); ImGui::EndTabItem(); } - if (!open) - release_queue_.push(sheet_id); + if (!open) release_queue_.push(sheet_id); } ImGui::EndTabBar(); @@ -638,9 +641,7 @@ absl::Status GraphicsEditor::UpdateScadView() { status_ = DrawExperimentalFeatures(); } - NEXT_COLUMN() { - status_ = DrawPaletteControls(); - } + NEXT_COLUMN() { status_ = DrawPaletteControls(); } NEXT_COLUMN() gui::BitmapCanvasPipeline(scr_canvas_, scr_bitmap_, 0x200, 0x200, 0x20, diff --git a/src/app/editor/graphics/screen_editor.cc b/src/app/editor/graphics/screen_editor.cc index 83f7465b..81623a5a 100644 --- a/src/app/editor/graphics/screen_editor.cc +++ b/src/app/editor/graphics/screen_editor.cc @@ -1,11 +1,11 @@ #include "screen_editor.h" -#include "app/editor/system/editor_card_registry.h" #include #include #include #include "absl/strings/str_format.h" +#include "app/editor/system/editor_card_registry.h" #include "app/gfx/core/bitmap.h" #include "app/gfx/debug/performance/performance_profiler.h" #include "app/gfx/resource/arena.h" @@ -25,8 +25,7 @@ namespace editor { constexpr uint32_t kRedPen = 0xFF0000FF; void ScreenEditor::Initialize() { - if (!dependencies_.card_registry) - return; + if (!dependencies_.card_registry) return; auto* card_registry = dependencies_.card_registry; card_registry->RegisterCard({.card_id = "screen.dungeon_maps", @@ -122,8 +121,7 @@ absl::Status ScreenEditor::Load() { } absl::Status ScreenEditor::Update() { - if (!dependencies_.card_registry) - return absl::OkStatus(); + if (!dependencies_.card_registry) return absl::OkStatus(); auto* card_registry = dependencies_.card_registry; static gui::EditorCard dungeon_maps_card("Dungeon Maps", ICON_MD_MAP); @@ -140,7 +138,8 @@ absl::Status ScreenEditor::Update() { title_screen_card.SetDefaultSize(600, 500); naming_screen_card.SetDefaultSize(500, 400); - // Dungeon Maps Card - Check visibility flag exists and is true before rendering + // Dungeon Maps Card - Check visibility flag exists and is true before + // rendering bool* dungeon_maps_visible = card_registry->GetVisibilityFlag("screen.dungeon_maps"); if (dungeon_maps_visible && *dungeon_maps_visible) { @@ -150,7 +149,8 @@ absl::Status ScreenEditor::Update() { dungeon_maps_card.End(); } - // Inventory Menu Card - Check visibility flag exists and is true before rendering + // Inventory Menu Card - Check visibility flag exists and is true before + // rendering bool* inventory_menu_visible = card_registry->GetVisibilityFlag("screen.inventory_menu"); if (inventory_menu_visible && *inventory_menu_visible) { @@ -160,7 +160,8 @@ absl::Status ScreenEditor::Update() { inventory_menu_card.End(); } - // Overworld Map Card - Check visibility flag exists and is true before rendering + // Overworld Map Card - Check visibility flag exists and is true before + // rendering bool* overworld_map_visible = card_registry->GetVisibilityFlag("screen.overworld_map"); if (overworld_map_visible && *overworld_map_visible) { @@ -170,7 +171,8 @@ absl::Status ScreenEditor::Update() { overworld_map_card.End(); } - // Title Screen Card - Check visibility flag exists and is true before rendering + // Title Screen Card - Check visibility flag exists and is true before + // rendering bool* title_screen_visible = card_registry->GetVisibilityFlag("screen.title_screen"); if (title_screen_visible && *title_screen_visible) { @@ -180,7 +182,8 @@ absl::Status ScreenEditor::Update() { title_screen_card.End(); } - // Naming Screen Card - Check visibility flag exists and is true before rendering + // Naming Screen Card - Check visibility flag exists and is true before + // rendering bool* naming_screen_visible = card_registry->GetVisibilityFlag("screen.naming_screen"); if (naming_screen_visible && *naming_screen_visible) { @@ -513,14 +516,14 @@ void ScreenEditor::DrawDungeonMapsTabs() { /** * @brief Draw dungeon room graphics editor with enhanced tile16 editing - * + * * Enhanced Features: * - Interactive tile16 selector with visual feedback * - Real-time tile16 composition from 4x 8x8 tiles * - Tile metadata editing (mirroring, palette, etc.) * - Integration with ROM graphics buffer * - Undo/redo support for tile modifications - * + * * Performance Notes: * - Cached tile16 rendering to avoid repeated composition * - Efficient tile selector with grid-based snapping @@ -602,7 +605,8 @@ void ScreenEditor::DrawDungeonMapsRoomGfx() { } if (current_tile_canvas_.DrawTilePainter(*cached_tile8, 16)) { - // Modify the tile16 based on the selected tile and current_tile16_info + // Modify the tile16 based on the selected tile and + // current_tile16_info gfx::ModifyTile16(tile16_blockset_, rom()->graphics_buffer(), current_tile16_info[0], current_tile16_info[1], current_tile16_info[2], current_tile16_info[3], 212, @@ -645,14 +649,14 @@ void ScreenEditor::DrawDungeonMapsRoomGfx() { /** * @brief Draw dungeon maps editor with enhanced ROM hacking features - * + * * Enhanced Features: * - Multi-mode editing (DRAW, EDIT, SELECT) * - Real-time tile16 preview and editing * - Floor/basement management for complex dungeons * - Copy/paste operations for floor layouts * - Integration with ROM tile16 data - * + * * Performance Notes: * - Lazy loading of dungeon graphics * - Cached tile16 rendering for fast updates @@ -720,8 +724,7 @@ void ScreenEditor::DrawDungeonMapsEditor() { ImGui::Text("Selected tile8: %d", selected_tile8_); ImGui::Separator(); ImGui::Text("For use with custom inserted graphics assembly patches."); - if (ImGui::Button("Load GFX from BIN file")) - LoadBinaryGfx(); + if (ImGui::Button("Load GFX from BIN file")) LoadBinaryGfx(); ImGui::EndTable(); } @@ -857,10 +860,8 @@ void ScreenEditor::DrawTitleScreenCompositeCanvas() { // Create tile word: tile_id | (palette << 10) | h_flip | v_flip uint16_t tile_word = selected_title_tile16_ & 0x3FF; tile_word |= (title_palette_ & 0x07) << 10; - if (title_h_flip_) - tile_word |= 0x4000; - if (title_v_flip_) - tile_word |= 0x8000; + if (title_h_flip_) tile_word |= 0x4000; + if (title_v_flip_) tile_word |= 0x8000; // Update BG1 buffer and re-render both layers and composite title_screen_.mutable_bg1_buffer()[tilemap_index] = tile_word; @@ -912,10 +913,8 @@ void ScreenEditor::DrawTitleScreenBG1Canvas() { // Create tile word: tile_id | (palette << 10) | h_flip | v_flip uint16_t tile_word = selected_title_tile16_ & 0x3FF; tile_word |= (title_palette_ & 0x07) << 10; - if (title_h_flip_) - tile_word |= 0x4000; - if (title_v_flip_) - tile_word |= 0x8000; + if (title_h_flip_) tile_word |= 0x4000; + if (title_v_flip_) tile_word |= 0x8000; // Update buffer and re-render title_screen_.mutable_bg1_buffer()[tilemap_index] = tile_word; @@ -957,10 +956,8 @@ void ScreenEditor::DrawTitleScreenBG2Canvas() { // Create tile word: tile_id | (palette << 10) | h_flip | v_flip uint16_t tile_word = selected_title_tile16_ & 0x3FF; tile_word |= (title_palette_ & 0x07) << 10; - if (title_h_flip_) - tile_word |= 0x4000; - if (title_v_flip_) - tile_word |= 0x8000; + if (title_h_flip_) tile_word |= 0x4000; + if (title_v_flip_) tile_word |= 0x8000; // Update buffer and re-render title_screen_.mutable_bg2_buffer()[tilemap_index] = tile_word; diff --git a/src/app/editor/message/message_data.h b/src/app/editor/message/message_data.h index 892aca44..b05e0c36 100644 --- a/src/app/editor/message/message_data.h +++ b/src/app/editor/message/message_data.h @@ -31,9 +31,9 @@ // - Hieroglyphs // // 4. **Dictionary System** (`DictionaryEntry`): -// Compression system using byte values 0x88+ to reference common words/phrases -// stored separately in ROM. This saves space by replacing frequently-used -// text with single-byte references. +// Compression system using byte values 0x88+ to reference common +// words/phrases stored separately in ROM. This saves space by replacing +// frequently-used text with single-byte references. // // 5. **Message Data** (`MessageData`): // Represents a single in-game message with both raw binary data and parsed @@ -121,21 +121,22 @@ static const std::unordered_map CharEncoder = { {0x65, ' '}, {0x66, '_'}, }; -// Finds the ROM byte value for a given character (reverse lookup in CharEncoder) -// Returns 0xFF if character is not found +// Finds the ROM byte value for a given character (reverse lookup in +// CharEncoder) Returns 0xFF if character is not found uint8_t FindMatchingCharacter(char value); // Checks if a byte value represents a dictionary entry // Returns dictionary index (0-96) or -1 if not a dictionary entry int8_t FindDictionaryEntry(uint8_t value); -// Converts a human-readable message string (with [command] tokens) into ROM bytes -// This is the inverse operation of ParseMessageData +// Converts a human-readable message string (with [command] tokens) into ROM +// bytes This is the inverse operation of ParseMessageData std::vector ParseMessageToData(std::string str); -// Represents a single dictionary entry (common word/phrase) used for text compression -// Dictionary entries are stored separately in ROM and referenced by bytes 0x88-0xE8 -// Example: Dictionary entry 0x00 might contain "the" and be referenced as [D:00] +// Represents a single dictionary entry (common word/phrase) used for text +// compression Dictionary entries are stored separately in ROM and referenced by +// bytes 0x88-0xE8 Example: Dictionary entry 0x00 might contain "the" and be +// referenced as [D:00] struct DictionaryEntry { uint8_t ID = 0; // Dictionary index (0-96) std::string Contents = ""; // The actual text this entry represents @@ -152,7 +153,8 @@ struct DictionaryEntry { // Checks if this dictionary entry's text appears in the given string bool ContainedInString(std::string_view s) const { - // Convert to std::string to avoid Debian string_view bug with absl::StrContains + // Convert to std::string to avoid Debian string_view bug with + // absl::StrContains return absl::StrContains(std::string(s), Contents); } @@ -190,12 +192,13 @@ std::string ReplaceAllDictionaryWords( DictionaryEntry FindRealDictionaryEntry( uint8_t value, const std::vector& dictionary); -// Special marker inserted into commands to protect them from dictionary replacements -// during optimization. Removed after dictionary replacement is complete. +// Special marker inserted into commands to protect them from dictionary +// replacements during optimization. Removed after dictionary replacement is +// complete. const std::string CHEESE = "\uBEBE"; -// Represents a complete in-game message with both raw and parsed representations -// Messages can exist in two forms: +// Represents a complete in-game message with both raw and parsed +// representations Messages can exist in two forms: // 1. Raw: Direct ROM bytes with dictionary references as [D:XX] tokens // 2. Parsed: Fully expanded with dictionary words replaced by actual text struct MessageData { @@ -433,8 +436,8 @@ std::string ParseTextDataByte(uint8_t value); absl::StatusOr ParseSingleMessage( const std::vector& rom_data, int* current_pos); -// Converts MessageData objects into human-readable strings with [command] tokens -// This is the main function for displaying messages in the editor +// Converts MessageData objects into human-readable strings with [command] +// tokens This is the main function for displaying messages in the editor // Properly handles commands with arguments to avoid parsing errors std::vector ParseMessageData( std::vector& message_data, diff --git a/src/app/editor/message/message_editor.cc b/src/app/editor/message/message_editor.cc index 1d079a28..03a8580a 100644 --- a/src/app/editor/message/message_editor.cc +++ b/src/app/editor/message/message_editor.cc @@ -1,5 +1,4 @@ #include "message_editor.h" -#include "app/editor/system/editor_card_registry.h" #include #include @@ -7,6 +6,7 @@ #include "absl/status/status.h" #include "absl/strings/str_cat.h" #include "absl/strings/str_format.h" +#include "app/editor/system/editor_card_registry.h" #include "app/gfx/core/bitmap.h" #include "app/gfx/debug/performance/performance_profiler.h" #include "app/gfx/resource/arena.h" @@ -63,8 +63,7 @@ constexpr ImGuiTableFlags kMessageTableFlags = ImGuiTableFlags_Hideable | void MessageEditor::Initialize() { // Register cards with EditorCardRegistry (dependency injection) - if (!dependencies_.card_registry) - return; + if (!dependencies_.card_registry) return; auto* card_registry = dependencies_.card_registry; @@ -139,12 +138,12 @@ absl::Status MessageEditor::Load() { } absl::Status MessageEditor::Update() { - if (!dependencies_.card_registry) - return absl::OkStatus(); + if (!dependencies_.card_registry) return absl::OkStatus(); auto* card_registry = dependencies_.card_registry; - // Message List Card - Get visibility flag and pass to Begin() for proper X button + // Message List Card - Get visibility flag and pass to Begin() for proper X + // button bool* list_visible = card_registry->GetVisibilityFlag(MakeCardId("message.message_list")); if (list_visible && *list_visible) { @@ -156,7 +155,8 @@ absl::Status MessageEditor::Update() { list_card.End(); } - // Message Editor Card - Get visibility flag and pass to Begin() for proper X button + // Message Editor Card - Get visibility flag and pass to Begin() for proper X + // button bool* editor_visible = card_registry->GetVisibilityFlag(MakeCardId("message.message_editor")); if (editor_visible && *editor_visible) { @@ -168,7 +168,8 @@ absl::Status MessageEditor::Update() { editor_card.End(); } - // Font Atlas Card - Get visibility flag and pass to Begin() for proper X button + // Font Atlas Card - Get visibility flag and pass to Begin() for proper X + // button bool* font_visible = card_registry->GetVisibilityFlag(MakeCardId("message.font_atlas")); if (font_visible && *font_visible) { @@ -181,7 +182,8 @@ absl::Status MessageEditor::Update() { font_card.End(); } - // Dictionary Card - Get visibility flag and pass to Begin() for proper X button + // Dictionary Card - Get visibility flag and pass to Begin() for proper X + // button bool* dict_visible = card_registry->GetVisibilityFlag(MakeCardId("message.dictionary")); if (dict_visible && *dict_visible) { diff --git a/src/app/editor/music/music_editor.cc b/src/app/editor/music/music_editor.cc index 91a0047c..2eb4743d 100644 --- a/src/app/editor/music/music_editor.cc +++ b/src/app/editor/music/music_editor.cc @@ -1,8 +1,8 @@ #include "music_editor.h" -#include "app/editor/system/editor_card_registry.h" #include "absl/strings/str_format.h" #include "app/editor/code/assembly_editor.h" +#include "app/editor/system/editor_card_registry.h" #include "app/emu/emulator.h" #include "app/gfx/debug/performance/performance_profiler.h" #include "app/gui/core/icons.h" @@ -14,8 +14,7 @@ namespace yaze { namespace editor { void MusicEditor::Initialize() { - if (!dependencies_.card_registry) - return; + if (!dependencies_.card_registry) return; auto* card_registry = dependencies_.card_registry; card_registry->RegisterCard({.card_id = "music.tracker", @@ -47,8 +46,7 @@ absl::Status MusicEditor::Load() { } absl::Status MusicEditor::Update() { - if (!dependencies_.card_registry) - return absl::OkStatus(); + if (!dependencies_.card_registry) return absl::OkStatus(); auto* card_registry = dependencies_.card_registry; static gui::EditorCard tracker_card("Music Tracker", ICON_MD_MUSIC_NOTE); @@ -59,7 +57,8 @@ absl::Status MusicEditor::Update() { instrument_card.SetDefaultSize(600, 500); assembly_card.SetDefaultSize(700, 600); - // Music Tracker Card - Check visibility flag exists and is true before rendering + // Music Tracker Card - Check visibility flag exists and is true before + // rendering bool* tracker_visible = card_registry->GetVisibilityFlag("music.tracker"); if (tracker_visible && *tracker_visible) { if (tracker_card.Begin(tracker_visible)) { @@ -68,7 +67,8 @@ absl::Status MusicEditor::Update() { tracker_card.End(); } - // Instrument Editor Card - Check visibility flag exists and is true before rendering + // Instrument Editor Card - Check visibility flag exists and is true before + // rendering bool* instrument_visible = card_registry->GetVisibilityFlag("music.instrument_editor"); if (instrument_visible && *instrument_visible) { @@ -78,7 +78,8 @@ absl::Status MusicEditor::Update() { instrument_card.End(); } - // Assembly View Card - Check visibility flag exists and is true before rendering + // Assembly View Card - Check visibility flag exists and is true before + // rendering bool* assembly_visible = card_registry->GetVisibilityFlag("music.assembly"); if (assembly_visible && *assembly_visible) { if (assembly_card.Begin(assembly_visible)) { @@ -120,8 +121,7 @@ static void DrawPianoStaff() { // Draw the ledger lines const int NUM_LEDGER_LINES = 3; for (int i = -NUM_LEDGER_LINES; i <= NUM_LINES + NUM_LEDGER_LINES; i++) { - if (i % 2 == 0) - continue; // skip every other line + if (i % 2 == 0) continue; // skip every other line auto line_start = ImVec2(canvas_p0.x, canvas_p0.y + i * LINE_SPACING / 2); auto line_end = ImVec2(canvas_p1.x + ImGui::GetContentRegionAvail().x, canvas_p0.y + i * LINE_SPACING / 2); @@ -315,8 +315,7 @@ void MusicEditor::PlaySong(int song_id) { } void MusicEditor::StopSong() { - if (!emulator_) - return; + if (!emulator_) return; // Write stop command to game memory try { @@ -335,8 +334,7 @@ void MusicEditor::StopSong() { } void MusicEditor::SetVolume(float volume) { - if (!emulator_) - return; + if (!emulator_) return; // Clamp volume to valid range volume = std::clamp(volume, 0.0f, 1.0f); diff --git a/src/app/editor/overworld/entity.cc b/src/app/editor/overworld/entity.cc index ae513ef8..0a2cf23d 100644 --- a/src/app/editor/overworld/entity.cc +++ b/src/app/editor/overworld/entity.cc @@ -135,7 +135,8 @@ void DrawExitInserterPopup() { gui::InputHex("Y Position", &y_pos); if (Button("Create Exit")) { - // This would need to be connected to the overworld editor to actually create the exit + // This would need to be connected to the overworld editor to actually + // create the exit ImGui::CloseCurrentPopup(); } @@ -428,7 +429,8 @@ void DrawSpriteInserterPopup() { gui::InputHex("Y Position", &y_pos); if (Button("Add Sprite")) { - // This would need to be connected to the overworld editor to actually create the sprite + // This would need to be connected to the overworld editor to actually + // create the sprite new_sprite_id = 0; x_pos = 0; y_pos = 0; diff --git a/src/app/editor/overworld/entity.h b/src/app/editor/overworld/entity.h index c9b8581c..4a8154d3 100644 --- a/src/app/editor/overworld/entity.h +++ b/src/app/editor/overworld/entity.h @@ -29,7 +29,7 @@ bool DrawItemEditorPopup(zelda3::OverworldItem& item); /** * @brief Column IDs for the sprite table. - * + * */ enum SpriteItemColumnID { SpriteItemColumnID_ID, diff --git a/src/app/editor/overworld/entity_operations.cc b/src/app/editor/overworld/entity_operations.cc index 26266af9..2486bbf6 100644 --- a/src/app/editor/overworld/entity_operations.cc +++ b/src/app/editor/overworld/entity_operations.cc @@ -9,7 +9,6 @@ namespace editor { absl::StatusOr InsertEntrance( zelda3::Overworld* overworld, ImVec2 mouse_pos, int current_map, bool is_hole) { - if (!overworld || !overworld->is_loaded()) { return absl::FailedPreconditionError("Overworld not loaded"); } @@ -78,7 +77,6 @@ absl::StatusOr InsertEntrance( absl::StatusOr InsertExit(zelda3::Overworld* overworld, ImVec2 mouse_pos, int current_map) { - if (!overworld || !overworld->is_loaded()) { return absl::FailedPreconditionError("Overworld not loaded"); } @@ -133,7 +131,6 @@ absl::StatusOr InsertSprite(zelda3::Overworld* overworld, ImVec2 mouse_pos, int current_map, int game_state, uint8_t sprite_id) { - if (!overworld || !overworld->is_loaded()) { return absl::FailedPreconditionError("Overworld not loaded"); } @@ -142,7 +139,8 @@ absl::StatusOr InsertSprite(zelda3::Overworld* overworld, return absl::InvalidArgumentError("Invalid game state (must be 0-2)"); } - // Snap to 16x16 grid and clamp to bounds (ZScream: SpriteMode.cs similar logic) + // Snap to 16x16 grid and clamp to bounds (ZScream: SpriteMode.cs similar + // logic) ImVec2 snapped_pos = ClampToOverworldBounds(SnapToEntityGrid(mouse_pos)); // Get parent map ID (ZScream: SpriteMode.cs:90-95) @@ -188,7 +186,6 @@ absl::StatusOr InsertItem(zelda3::Overworld* overworld, ImVec2 mouse_pos, int current_map, uint8_t item_id) { - if (!overworld || !overworld->is_loaded()) { return absl::FailedPreconditionError("Overworld not loaded"); } diff --git a/src/app/editor/overworld/entity_operations.h b/src/app/editor/overworld/entity_operations.h index bcbf556a..5bd30b18 100644 --- a/src/app/editor/overworld/entity_operations.h +++ b/src/app/editor/overworld/entity_operations.h @@ -14,10 +14,10 @@ namespace editor { /** * @brief Flat helper functions for entity insertion/manipulation - * - * Following ZScream's entity management pattern (EntranceMode.cs, ExitMode.cs, etc.) - * but implemented as free functions to minimize state management. - * + * + * Following ZScream's entity management pattern (EntranceMode.cs, ExitMode.cs, + * etc.) but implemented as free functions to minimize state management. + * * Key concepts from ZScream: * - Find first deleted slot for insertion * - Calculate map position from mouse coordinates @@ -27,13 +27,13 @@ namespace editor { /** * @brief Insert a new entrance at the specified position - * + * * Follows ZScream's EntranceMode.AddEntrance() logic (EntranceMode.cs:53-148): * - Finds first deleted entrance slot * - Snaps position to 16x16 grid * - Uses parent map ID for multi-area maps * - Calls UpdateMapProperties to calculate game coordinates - * + * * @param overworld Overworld data containing entrance arrays * @param mouse_pos Mouse position in canvas coordinates (world space) * @param current_map Current map index being edited @@ -46,13 +46,13 @@ absl::StatusOr InsertEntrance( /** * @brief Insert a new exit at the specified position - * + * * Follows ZScream's ExitMode.AddExit() logic (ExitMode.cs:59-124): * - Finds first deleted exit slot * - Snaps position to 16x16 grid * - Initializes exit with default scroll/camera values * - Sets room ID to 0 (needs to be configured by user) - * + * * @param overworld Overworld data containing exit arrays * @param mouse_pos Mouse position in canvas coordinates * @param current_map Current map index being edited @@ -64,12 +64,12 @@ absl::StatusOr InsertExit(zelda3::Overworld* overworld, /** * @brief Insert a new sprite at the specified position - * + * * Follows ZScream's SpriteMode sprite insertion (SpriteMode.cs:27-100): * - Adds new sprite to game state array * - Calculates map position and game coordinates * - Sets sprite ID (default 0, user configures in popup) - * + * * @param overworld Overworld data containing sprite arrays * @param mouse_pos Mouse position in canvas coordinates * @param current_map Current map index being edited @@ -84,12 +84,12 @@ absl::StatusOr InsertSprite(zelda3::Overworld* overworld, /** * @brief Insert a new item at the specified position - * + * * Follows ZScream's ItemMode item insertion (ItemMode.cs:54-113): * - Adds new item to all_items array * - Calculates map position and game coordinates * - Sets item ID (default 0, user configures in popup) - * + * * @param overworld Overworld data containing item arrays * @param mouse_pos Mouse position in canvas coordinates * @param current_map Current map index being edited @@ -103,7 +103,7 @@ absl::StatusOr InsertItem(zelda3::Overworld* overworld, /** * @brief Helper to get parent map ID for multi-area maps - * + * * Returns the parent map ID, handling the case where a map is its own parent. * Matches ZScream logic where ParentID == 255 means use current map. */ diff --git a/src/app/editor/overworld/map_properties.cc b/src/app/editor/overworld/map_properties.cc index 557e2660..d08e7ec7 100644 --- a/src/app/editor/overworld/map_properties.cc +++ b/src/app/editor/overworld/map_properties.cc @@ -30,7 +30,8 @@ void MapPropertiesSystem::DrawSimplifiedMapSettings( int& current_mode) { (void)show_overlay_editor; // Reserved for future use (void)current_mode; // Reserved for future use - // Enhanced settings table with popup buttons for quick access and integrated toolset + // Enhanced settings table with popup buttons for quick access and integrated + // toolset if (BeginTable("SimplifiedMapSettings", 9, ImGuiTableFlags_Borders | ImGuiTableFlags_SizingFixedFit, ImVec2(0, 0), -1)) { @@ -215,7 +216,6 @@ void MapPropertiesSystem::DrawMapPropertiesPanel( // Create tabs for different property categories if (ImGui::BeginTabBar("MapPropertiesTabs", ImGuiTabBarFlags_FittingPolicyScroll)) { - // Basic Properties Tab if (ImGui::BeginTabItem("Basic Properties")) { DrawBasicPropertiesTab(current_map); @@ -563,7 +563,8 @@ void MapPropertiesSystem::DrawGraphicsPopup(int current_map, int game_state) { kHexByteInputWidth)) { // CORRECT ORDER: Properties first, then graphics reload - // 1. Propagate properties to siblings FIRST (calls LoadAreaGraphics on siblings) + // 1. Propagate properties to siblings FIRST (calls LoadAreaGraphics on + // siblings) RefreshMapProperties(); // 2. Force immediate refresh of current map @@ -1358,7 +1359,8 @@ void MapPropertiesSystem::RefreshSiblingMapGraphics(int map_index, overworld_->mutable_overworld_map(sibling)->LoadAreaGraphics(); // CRITICAL FIX: Force immediate refresh on the sibling - // This will trigger the callback to OverworldEditor's RefreshChildMapOnDemand + // This will trigger the callback to OverworldEditor's + // RefreshChildMapOnDemand ForceRefreshGraphics(sibling); } } @@ -1417,7 +1419,8 @@ void MapPropertiesSystem::DrawOverlayControls(int current_map, "You can edit the tile16 data here to customize how the visual effects " "appear when referenced by other maps."); } else { - // Light World (0x00-0x3F) and Dark World (0x40-0x7F) maps support subscreen overlays + // Light World (0x00-0x3F) and Dark World (0x40-0x7F) maps support subscreen + // overlays // Comprehensive help section ImGui::TextColored(ImVec4(0.4f, 0.8f, 1.0f, 1.0f), @@ -1604,8 +1607,7 @@ void MapPropertiesSystem::DrawOverlayPreviewOnMap(int current_map, bool show_overlay_preview) { gfx::ScopedTimer timer("map_properties_draw_overlay_preview"); - if (!show_overlay_preview || !maps_bmp_ || !canvas_) - return; + if (!show_overlay_preview || !maps_bmp_ || !canvas_) return; // Get subscreen overlay information based on ROM version and map type uint16_t overlay_id = 0x00FF; @@ -1618,12 +1620,12 @@ void MapPropertiesSystem::DrawOverlayPreviewOnMap(int current_map, return; } - // Light World (0x00-0x3F) and Dark World (0x40-0x7F) maps support subscreen overlays for all versions + // Light World (0x00-0x3F) and Dark World (0x40-0x7F) maps support subscreen + // overlays for all versions overlay_id = overworld_->overworld_map(current_map)->subscreen_overlay(); has_subscreen_overlay = (overlay_id != 0x00FF); - if (!has_subscreen_overlay) - return; + if (!has_subscreen_overlay) return; // Map subscreen overlay ID to special area map for bitmap int overlay_map_index = -1; @@ -1636,8 +1638,7 @@ void MapPropertiesSystem::DrawOverlayPreviewOnMap(int current_map, // Get the subscreen overlay map's bitmap const auto& overlay_bitmap = (*maps_bmp_)[overlay_map_index]; - if (!overlay_bitmap.is_active()) - return; + if (!overlay_bitmap.is_active()) return; // Calculate position for subscreen overlay preview on the current map int current_map_x = current_map % 8; diff --git a/src/app/editor/overworld/overworld_editor.cc b/src/app/editor/overworld/overworld_editor.cc index afe3b63f..bdcbcf99 100644 --- a/src/app/editor/overworld/overworld_editor.cc +++ b/src/app/editor/overworld/overworld_editor.cc @@ -492,12 +492,12 @@ void OverworldEditor::DrawToolset() { // IMPORTANT: Don't cache version - it needs to update after ROM upgrade auto rom_version = zelda3::OverworldVersionHelper::GetVersion(*rom_); - uint8_t asm_version = (*rom_) - [zelda3:: - OverworldCustomASMHasBeenApplied]; // Still needed for badge display + uint8_t asm_version = + (*rom_)[zelda3::OverworldCustomASMHasBeenApplied]; // Still needed for + // badge display - // Don't use WidgetIdScope here - it conflicts with ImGui::Begin/End ID stack in cards - // Widgets register themselves individually instead + // Don't use WidgetIdScope here - it conflicts with ImGui::Begin/End ID stack + // in cards Widgets register themselves individually instead toolbar.Begin(); @@ -564,17 +564,21 @@ void OverworldEditor::DrawToolset() { toolbar.AddRomBadge(asm_version, [this]() { ImGui::OpenPopup("UpgradeROMVersion"); }); - // Inline map properties with icon labels - use toolbar methods for consistency + // Inline map properties with icon labels - use toolbar methods for + // consistency if (toolbar.AddProperty(ICON_MD_IMAGE, " Gfx", overworld_.mutable_overworld_map(current_map_) ->mutable_area_graphics(), [this]() { - // CORRECT ORDER: Properties first, then graphics reload + // CORRECT ORDER: Properties first, then graphics + // reload - // 1. Propagate properties to siblings FIRST (this also calls LoadAreaGraphics on siblings) + // 1. Propagate properties to siblings FIRST (this + // also calls LoadAreaGraphics on siblings) RefreshMapProperties(); - // 2. Force immediate refresh of current map and all siblings + // 2. Force immediate refresh of current map and all + // siblings maps_bmp_[current_map_].set_modified(true); RefreshChildMapOnDemand(current_map_); RefreshSiblingMapGraphics(current_map_); @@ -589,7 +593,8 @@ void OverworldEditor::DrawToolset() { overworld_.mutable_overworld_map(current_map_) ->mutable_area_palette(), [this]() { - // Palette changes also need to propagate to siblings + // Palette changes also need to propagate to + // siblings RefreshSiblingMapGraphics(current_map_); RefreshMapProperties(); status_ = RefreshMapPalette(); @@ -697,9 +702,9 @@ void OverworldEditor::DrawToolset() { ImGui::EndPopup(); } - // All editor windows are now rendered in Update() using either EditorCard system - // or MapPropertiesSystem for map-specific panels. This keeps the toolset clean - // and prevents ImGui ID stack issues. + // All editor windows are now rendered in Update() using either EditorCard + // system or MapPropertiesSystem for map-specific panels. This keeps the + // toolset clean and prevents ImGui ID stack issues. // Legacy window code removed - windows rendered in Update() include: // - Graphics Groups (EditorCard) @@ -893,7 +898,6 @@ void OverworldEditor::DrawOverworldEdits() { void OverworldEditor::RenderUpdatedMapBitmap( const ImVec2& click_position, const std::vector& tile_data) { - // Bounds checking to prevent crashes if (current_map_ < 0 || current_map_ >= static_cast(maps_bmp_.size())) { LOG_ERROR("OverworldEditor", @@ -975,7 +979,8 @@ void OverworldEditor::CheckForOverworldEdits() { // User has selected a tile they want to draw from the blockset // and clicked on the canvas. - // Note: With TileSelectorWidget, we check if a valid tile is selected instead of canvas points + // Note: With TileSelectorWidget, we check if a valid tile is selected instead + // of canvas points if (current_tile16_ >= 0 && !ow_map_canvas_.select_rect_active() && ow_map_canvas_.DrawTilemapPainter(tile16_blockset_, current_tile16_)) { DrawOverworldEdits(); @@ -1002,10 +1007,8 @@ void OverworldEditor::CheckForOverworldEdits() { int end_x = std::floor(end.x / kTile16Size) * kTile16Size; int end_y = std::floor(end.y / kTile16Size) * kTile16Size; - if (start_x > end_x) - std::swap(start_x, end_x); - if (start_y > end_y) - std::swap(start_y, end_y); + if (start_x > end_x) std::swap(start_x, end_x); + if (start_y > end_y) std::swap(start_y, end_y); constexpr int local_map_size = 512; // Size of each local map // Number of tiles per local map (since each tile is 16x16) @@ -1017,8 +1020,9 @@ void OverworldEditor::CheckForOverworldEdits() { current_tile16_); // Apply the selected tiles to each position in the rectangle - // CRITICAL FIX: Use pre-computed tile16_ids_ instead of recalculating from selected_tiles_ - // This prevents wrapping issues when dragging near boundaries + // CRITICAL FIX: Use pre-computed tile16_ids_ instead of recalculating + // from selected_tiles_ This prevents wrapping issues when dragging near + // boundaries int i = 0; for (int y = start_y; y <= end_y && i < static_cast(selected_tile16_ids_.size()); @@ -1026,7 +1030,6 @@ void OverworldEditor::CheckForOverworldEdits() { for (int x = start_x; x <= end_x && i < static_cast(selected_tile16_ids_.size()); x += kTile16Size, ++i) { - // Determine which local map (512x512) the tile is in int local_map_x = x / local_map_size; int local_map_y = y / local_map_size; @@ -1041,13 +1044,14 @@ void OverworldEditor::CheckForOverworldEdits() { // FIXED: Use pre-computed tile ID from the ORIGINAL selection int tile16_id = selected_tile16_ids_[i]; - // Bounds check for the selected world array, accounting for rectangle size - // Ensure the entire rectangle fits within the world bounds + // Bounds check for the selected world array, accounting for rectangle + // size Ensure the entire rectangle fits within the world bounds int rect_width = ((end_x - start_x) / kTile16Size) + 1; int rect_height = ((end_y - start_y) / kTile16Size) + 1; // Prevent painting from wrapping around at the edges of large maps - // Only allow painting if the entire rectangle is within the same 512x512 local map + // Only allow painting if the entire rectangle is within the same + // 512x512 local map int start_local_map_x = start_x / local_map_size; int start_local_map_y = start_y / local_map_size; int end_local_map_x = end_x / local_map_size; @@ -1061,7 +1065,8 @@ void OverworldEditor::CheckForOverworldEdits() { (index_y + rect_height - 1) < 0x200) { selected_world[index_x][index_y] = tile16_id; - // CRITICAL FIX: Also update the bitmap directly like single tile drawing + // CRITICAL FIX: Also update the bitmap directly like single tile + // drawing ImVec2 tile_position(x, y); auto tile_data = gfx::GetTilemapData(tile16_blockset_, tile16_id); if (!tile_data.empty()) { @@ -1229,13 +1234,15 @@ absl::Status OverworldEditor::Paste() { absl::Status OverworldEditor::CheckForCurrentMap() { // 4096x4096, 512x512 maps and some are larges maps 1024x1024 - // CRITICAL FIX: Use canvas hover position (not raw ImGui mouse) for proper coordinate sync - // hover_mouse_pos() already returns canvas-local coordinates (world space, not screen space) + // CRITICAL FIX: Use canvas hover position (not raw ImGui mouse) for proper + // coordinate sync hover_mouse_pos() already returns canvas-local coordinates + // (world space, not screen space) const auto mouse_position = ow_map_canvas_.hover_mouse_pos(); const int large_map_size = 1024; // Calculate which small map the mouse is currently over - // No need to subtract canvas_zero_point - mouse_position is already in world coordinates + // No need to subtract canvas_zero_point - mouse_position is already in world + // coordinates int map_x = mouse_position.x / kOverworldMapSize; int map_y = mouse_position.y / kOverworldMapSize; @@ -1322,10 +1329,11 @@ absl::Status OverworldEditor::CheckForCurrentMap() { const int highlight_parent = overworld_.overworld_map(current_highlighted_map)->parent(); - // CRITICAL FIX: Account for world offset when calculating parent coordinates - // For Dark World (0x40-0x7F), parent IDs are in range 0x40-0x7F - // For Special World (0x80-0x9F), parent IDs are in range 0x80-0x9F - // We need to subtract the world offset to get display grid coordinates (0-7) + // CRITICAL FIX: Account for world offset when calculating parent + // coordinates For Dark World (0x40-0x7F), parent IDs are in range + // 0x40-0x7F For Special World (0x80-0x9F), parent IDs are in range + // 0x80-0x9F We need to subtract the world offset to get display grid + // coordinates (0-7) int parent_map_x; int parent_map_y; if (current_world_ == 0) { @@ -1358,8 +1366,9 @@ absl::Status OverworldEditor::CheckForCurrentMap() { current_map_x = (current_highlighted_map - 0x40) % 8; current_map_y = (current_highlighted_map - 0x40) / 8; } else { - // Special World (0x80-0x9F) - use display coordinates based on current_world_ - // The special world maps are displayed in the same 8x8 grid as LW/DW + // Special World (0x80-0x9F) - use display coordinates based on + // current_world_ The special world maps are displayed in the same 8x8 + // grid as LW/DW current_map_x = (current_highlighted_map - 0x80) % 8; current_map_y = (current_highlighted_map - 0x80) / 8; } @@ -1524,7 +1533,8 @@ void OverworldEditor::CheckForMousePan() { } void OverworldEditor::DrawOverworldCanvas() { - // Simplified map settings - compact row with popup panels for detailed editing + // Simplified map settings - compact row with popup panels for detailed + // editing if (rom_->is_loaded() && overworld_.is_loaded() && map_properties_system_) { map_properties_system_->DrawSimplifiedMapSettings( current_world_, current_map_, current_map_lock_, @@ -1585,11 +1595,11 @@ void OverworldEditor::DrawOverworldCanvas() { CheckForOverworldEdits(); } // CRITICAL FIX: Use canvas hover state, not ImGui::IsItemHovered() - // IsItemHovered() checks the LAST drawn item, which could be entities/overlay, - // not the canvas InvisibleButton. ow_map_canvas_.IsMouseHovering() correctly - // tracks whether mouse is over the canvas area. - if (ow_map_canvas_.IsMouseHovering()) - status_ = CheckForCurrentMap(); + // IsItemHovered() checks the LAST drawn item, which could be + // entities/overlay, not the canvas InvisibleButton. + // ow_map_canvas_.IsMouseHovering() correctly tracks whether mouse is over + // the canvas area. + if (ow_map_canvas_.IsMouseHovering()) status_ = CheckForCurrentMap(); // --- BEGIN NEW DRAG/DROP LOGIC --- if (current_mode == EditingMode::MOUSE) { @@ -1680,7 +1690,8 @@ absl::Status OverworldEditor::DrawTile16Selector() { } // Note: We do NOT auto-scroll here because it breaks user interaction. // The canvas should only scroll when explicitly requested (e.g., when - // selecting a tile from the overworld canvas via ScrollBlocksetCanvasToCurrentTile). + // selecting a tile from the overworld canvas via + // ScrollBlocksetCanvasToCurrentTile). } if (result.tile_double_clicked) { @@ -1886,7 +1897,8 @@ absl::Status OverworldEditor::LoadGraphics() { { gfx::ScopedTimer initial_textures_timer("CreateInitialTextures"); for (int i = 0; i < initial_texture_count; ++i) { - // Queue texture creation/update for initial maps via Arena's deferred system + // Queue texture creation/update for initial maps via Arena's deferred + // system gfx::Arena::Get().QueueTextureCommand( gfx::Arena::TextureCommandType::CREATE, maps_to_texture[i]); } @@ -2035,7 +2047,7 @@ void OverworldEditor::RefreshOverworldMap() { /** * @brief On-demand map refresh that only updates what's actually needed - * + * * This method intelligently determines what needs to be refreshed based on * the type of change and only updates the necessary components, avoiding * expensive full rebuilds when possible. @@ -2051,7 +2063,8 @@ void OverworldEditor::RefreshOverworldMapOnDemand(int map_index) { // For non-current maps in non-current worlds, defer the refresh if (!is_current_map && !is_current_world) { - // Mark for deferred refresh - will be processed when the map becomes visible + // Mark for deferred refresh - will be processed when the map becomes + // visible maps_bmp_[map_index].set_modified(true); return; } @@ -2140,7 +2153,7 @@ void OverworldEditor::RefreshChildMapOnDemand(int map_index) { /** * @brief Safely refresh multi-area maps without recursion - * + * * This function handles the coordination of large, wide, and tall area maps * by using a non-recursive approach with explicit map list processing. * It respects the ZScream area size logic and prevents infinite recursion. @@ -2177,7 +2190,8 @@ void OverworldEditor::RefreshMultiAreaMapsSafely(int map_index, case AreaSizeEnum::LargeArea: { // Large Area: 2x2 grid (4 maps total) // Parent is top-left (quadrant 0), siblings are: - // +1 (top-right, quadrant 1), +8 (bottom-left, quadrant 2), +9 (bottom-right, quadrant 3) + // +1 (top-right, quadrant 1), +8 (bottom-left, quadrant 2), +9 + // (bottom-right, quadrant 3) sibling_maps = {parent_id, parent_id + 1, parent_id + 8, parent_id + 9}; LOG_DEBUG( "OverworldEditor", @@ -2243,7 +2257,8 @@ void OverworldEditor::RefreshMultiAreaMapsSafely(int map_index, : "tall", sibling, parent_id); - // Direct refresh without calling RefreshChildMapOnDemand to avoid recursion + // Direct refresh without calling RefreshChildMapOnDemand to avoid + // recursion auto* sibling_map = overworld_.mutable_overworld_map(sibling); if (sibling_map && maps_bmp_[sibling].modified()) { sibling_map->LoadAreaGraphics(); @@ -2360,8 +2375,7 @@ absl::Status OverworldEditor::RefreshMapPalette() { for (int i = 1; i < 4; i++) { int sibling_index = overworld_.overworld_map(current_map_)->parent() + i; - if (i >= 2) - sibling_index += 6; + if (i >= 2) sibling_index += 6; RETURN_IF_ERROR( overworld_.mutable_overworld_map(sibling_index)->LoadPalette()); @@ -2438,7 +2452,8 @@ void OverworldEditor::RefreshSiblingMapGraphics(int map_index, overworld_.mutable_overworld_map(sibling)->LoadAreaGraphics(); // CRITICAL FIX: Bypass visibility check - force immediate refresh - // Call RefreshChildMapOnDemand() directly instead of RefreshOverworldMapOnDemand() + // Call RefreshChildMapOnDemand() directly instead of + // RefreshOverworldMapOnDemand() RefreshChildMapOnDemand(sibling); LOG_DEBUG("OverworldEditor", @@ -2601,12 +2616,14 @@ void OverworldEditor::ScrollBlocksetCanvasToCurrentTile() { } // CRITICAL FIX: Do NOT use fallback scrolling from overworld canvas context! - // The fallback code uses ImGui::SetScrollX/Y which scrolls the CURRENT window, - // and when called from CheckForSelectRectangle() during overworld canvas rendering, - // it incorrectly scrolls the overworld canvas instead of the tile16 selector. + // The fallback code uses ImGui::SetScrollX/Y which scrolls the CURRENT + // window, and when called from CheckForSelectRectangle() during overworld + // canvas rendering, it incorrectly scrolls the overworld canvas instead of + // the tile16 selector. // // The blockset_selector_ should always be available in modern code paths. - // If it's not available, we skip scrolling rather than scroll the wrong window. + // If it's not available, we skip scrolling rather than scroll the wrong + // window. // // This fixes the bug where right-clicking to select tiles on the Dark World // causes the overworld canvas to scroll unexpectedly. @@ -2885,12 +2902,14 @@ absl::Status OverworldEditor::ApplyZSCustomOverworldASM(int target_version) { std::vector working_rom_data = original_rom_data; try { - // Determine which ASM file to apply and use GetResourcePath for proper resolution + // Determine which ASM file to apply and use GetResourcePath for proper + // resolution std::string asm_file_name = (target_version == 3) ? "asm/yaze.asm" // Master file with v3 : "asm/ZSCustomOverworld.asm"; // v2 standalone - // Use GetResourcePath to handle app bundles and various deployment scenarios + // Use GetResourcePath to handle app bundles and various deployment + // scenarios std::string asm_file_path = util::GetResourcePath(asm_file_name); LOG_DEBUG("OverworldEditor", "Using ASM file: %s", asm_file_path.c_str()); diff --git a/src/app/editor/overworld/overworld_editor.h b/src/app/editor/overworld/overworld_editor.h index 6a6986f6..c2893707 100644 --- a/src/app/editor/overworld/overworld_editor.h +++ b/src/app/editor/overworld/overworld_editor.h @@ -2,6 +2,7 @@ #define YAZE_APP_EDITOR_OVERWORLDEDITOR_H #include + #include "absl/status/status.h" #include "app/editor/editor.h" #include "app/editor/graphics/gfx_group_editor.h" @@ -65,7 +66,8 @@ class OverworldEditor : public Editor, public gfx::GfxContext { explicit OverworldEditor(Rom* rom) : rom_(rom) { type_ = EditorType::kOverworld; gfx_group_editor_.set_rom(rom); - // MapPropertiesSystem will be initialized after maps_bmp_ and canvas are ready + // MapPropertiesSystem will be initialized after maps_bmp_ and canvas are + // ready } explicit OverworldEditor(Rom* rom, const EditorDependencies& deps) @@ -103,10 +105,8 @@ class OverworldEditor : public Editor, public gfx::GfxContext { // ROM state methods (from Editor base class) bool IsRomLoaded() const override { return rom_ && rom_->is_loaded(); } std::string GetRomStatus() const override { - if (!rom_) - return "No ROM loaded"; - if (!rom_->is_loaded()) - return "ROM failed to load"; + if (!rom_) return "No ROM loaded"; + if (!rom_->is_loaded()) return "ROM failed to load"; return absl::StrFormat("ROM loaded: %s", rom_->title()); } @@ -132,11 +132,12 @@ class OverworldEditor : public Editor, public gfx::GfxContext { /** * @brief Handle entity insertion from context menu - * + * * Delegates to flat helper functions in entity_operations.cc * following ZScream's pattern for entity management. - * - * @param entity_type Type of entity to insert ("entrance", "hole", "exit", "item", "sprite") + * + * @param entity_type Type of entity to insert ("entrance", "hole", "exit", + * "item", "sprite") */ void HandleEntityInsertion(const std::string& entity_type); @@ -196,7 +197,7 @@ class OverworldEditor : public Editor, public gfx::GfxContext { /** * @brief Create textures for deferred map bitmaps on demand - * + * * This method should be called periodically to create textures for maps * that are needed but haven't had their textures created yet. This allows * for smooth loading without blocking the main thread during ROM loading. @@ -205,7 +206,7 @@ class OverworldEditor : public Editor, public gfx::GfxContext { /** * @brief Ensure a specific map has its texture created - * + * * Call this when a map becomes visible or is about to be rendered. * It will create the texture if it doesn't exist yet. */ @@ -213,7 +214,8 @@ class OverworldEditor : public Editor, public gfx::GfxContext { void DrawOverworldProperties(); void HandleMapInteraction(); - // SetupOverworldCanvasContextMenu removed (Phase 3B) - now handled by MapPropertiesSystem + // SetupOverworldCanvasContextMenu removed (Phase 3B) - now handled by + // MapPropertiesSystem // Canvas pan/zoom helpers (Overworld Refactoring) void HandleOverworldPan(); diff --git a/src/app/editor/overworld/overworld_entity_renderer.cc b/src/app/editor/overworld/overworld_entity_renderer.cc index 008c0922..0ff98ce5 100644 --- a/src/app/editor/overworld/overworld_entity_renderer.cc +++ b/src/app/editor/overworld/overworld_entity_renderer.cc @@ -1,4 +1,5 @@ #include "overworld_entity_renderer.h" + #include #include "absl/strings/str_format.h" @@ -59,7 +60,8 @@ void OverworldEntityRenderer::DrawEntrances(ImVec2 canvas_p0, ImVec2 scrolling, void OverworldEntityRenderer::DrawExits(ImVec2 canvas_p0, ImVec2 scrolling, int current_world, int current_mode) { - // Reset hover state at the start of entity rendering (DrawExits is called first) + // Reset hover state at the start of entity rendering (DrawExits is called + // first) hovered_entity_ = nullptr; int i = 0; diff --git a/src/app/editor/overworld/overworld_entity_renderer.h b/src/app/editor/overworld/overworld_entity_renderer.h index 95933e27..aa5845cd 100644 --- a/src/app/editor/overworld/overworld_entity_renderer.h +++ b/src/app/editor/overworld/overworld_entity_renderer.h @@ -16,7 +16,8 @@ class OverworldEditor; // Forward declaration /** * @class OverworldEntityRenderer - * @brief Handles visualization of all overworld entities (entrances, exits, items, sprites) + * @brief Handles visualization of all overworld entities (entrances, exits, + * items, sprites) * * This class separates entity rendering logic from the main OverworldEditor, * making it easier to maintain and test entity visualization independently. diff --git a/src/app/editor/overworld/scratch_space.cc b/src/app/editor/overworld/scratch_space.cc index a4ca0988..641d84c3 100644 --- a/src/app/editor/overworld/scratch_space.cc +++ b/src/app/editor/overworld/scratch_space.cc @@ -1,5 +1,3 @@ -#include "app/editor/overworld/overworld_editor.h" - #include #include #include @@ -12,6 +10,7 @@ #include "absl/strings/str_format.h" #include "app/editor/overworld/entity.h" #include "app/editor/overworld/map_properties.h" +#include "app/editor/overworld/overworld_editor.h" #include "app/editor/overworld/tile16_editor.h" #include "app/gfx/core/bitmap.h" #include "app/gfx/debug/performance/performance_profiler.h" @@ -43,16 +42,14 @@ absl::Status OverworldEditor::DrawScratchSpace() { // Slot selector Text("Scratch Space Slot:"); for (int i = 0; i < 4; i++) { - if (i > 0) - SameLine(); + if (i > 0) SameLine(); bool is_current = (current_scratch_slot_ == i); if (is_current) PushStyleColor(ImGuiCol_Button, ImVec4(0.4f, 0.7f, 0.4f, 1.0f)); if (Button(std::to_string(i + 1).c_str(), ImVec2(25, 25))) { current_scratch_slot_ = i; } - if (is_current) - PopStyleColor(); + if (is_current) PopStyleColor(); } SameLine(); @@ -125,7 +122,8 @@ absl::Status OverworldEditor::DrawScratchSpace() { "Select tiles from Tile16 tab or make selections in overworld, then draw " "here!"); - // Initialize scratch bitmap with proper size based on scratch space dimensions + // Initialize scratch bitmap with proper size based on scratch space + // dimensions auto& current_slot = scratch_spaces_[current_scratch_slot_]; if (!current_slot.scratch_bitmap.is_active()) { // Create bitmap based on scratch space dimensions (each tile is 16x16) @@ -232,8 +230,7 @@ void OverworldEditor::DrawScratchSpacePattern() { int pattern_width = dependencies_.shared_clipboard->overworld_width; int pattern_height = dependencies_.shared_clipboard->overworld_height; - if (tile_ids.empty()) - return; + if (tile_ids.empty()) return; auto& current_slot = scratch_spaces_[current_scratch_slot_]; int max_width = current_slot.width > 0 ? current_slot.width : 20; @@ -274,13 +271,11 @@ void OverworldEditor::UpdateScratchBitmapTile(int tile_x, int tile_y, gfx::ScopedTimer timer("overworld_update_scratch_tile"); // Use current slot if not specified - if (slot == -1) - slot = current_scratch_slot_; + if (slot == -1) slot = current_scratch_slot_; // Get the tile data from the tile16 blockset auto tile_data = gfx::GetTilemapData(tile16_blockset_, tile_id); - if (tile_data.empty()) - return; + if (tile_data.empty()) return; auto& scratch_slot = scratch_spaces_[slot]; @@ -302,7 +297,6 @@ void OverworldEditor::UpdateScratchBitmapTile(int tile_x, int tile_y, if (dst_x >= 0 && dst_x < scratch_bitmap_width && dst_y >= 0 && dst_y < scratch_bitmap_height && src_index < static_cast(tile_data.size())) { - // Write 2x2 pixel blocks to fill the 32x32 grid space for (int py = 0; py < 2 && (dst_y + py) < scratch_bitmap_height; ++py) { for (int px = 0; px < 2 && (dst_x + px) < scratch_bitmap_width; diff --git a/src/app/editor/overworld/tile16_editor.cc b/src/app/editor/overworld/tile16_editor.cc index 62feeb42..de145b22 100644 --- a/src/app/editor/overworld/tile16_editor.cc +++ b/src/app/editor/overworld/tile16_editor.cc @@ -152,8 +152,7 @@ absl::Status Tile16Editor::Update() { RETURN_IF_ERROR(SaveTile16ToScratchSpace(i)); } } - if (i < 3) - Separator(); + if (i < 3) Separator(); } EndMenu(); } @@ -373,9 +372,11 @@ absl::Status Tile16Editor::UpdateBlocksetBitmap() { int tile_x = (current_tile16_ % kTilesPerRow) * kTile16Size; int tile_y = (current_tile16_ / kTilesPerRow) * kTile16Size; - // Use dirty region tracking for efficient updates (region calculated but not used in current implementation) + // Use dirty region tracking for efficient updates (region calculated but + // not used in current implementation) - // Copy pixel data from current tile to blockset bitmap using batch operations + // Copy pixel data from current tile to blockset bitmap using batch + // operations for (int tile_y_offset = 0; tile_y_offset < kTile16Size; ++tile_y_offset) { for (int tile_x_offset = 0; tile_x_offset < kTile16Size; ++tile_x_offset) { @@ -458,20 +459,19 @@ absl::Status Tile16Editor::RegenerateTile16BitmapFromROM() { break; } - if (!tile_info) - continue; + if (!tile_info) continue; // Get the tile8 ID and properties int tile8_id = tile_info->id_; bool x_flip = tile_info->horizontal_mirror_; bool y_flip = tile_info->vertical_mirror_; - // Palette information stored in tile_info but applied via separate palette system + // Palette information stored in tile_info but applied via separate palette + // system // Get the source tile8 bitmap if (tile8_id >= 0 && tile8_id < static_cast(current_gfx_individual_.size()) && current_gfx_individual_[tile8_id].is_active()) { - const auto& source_tile8 = current_gfx_individual_[tile8_id]; // Copy the 8x8 tile into the appropriate quadrant of the 16x16 tile @@ -506,7 +506,8 @@ absl::Status Tile16Editor::RegenerateTile16BitmapFromROM() { // Set the appropriate palette using the same system as overworld if (overworld_palette_.size() >= 256) { // Use complete 256-color palette (same as overworld system) - // The pixel data already contains correct color indices for the 256-color palette + // The pixel data already contains correct color indices for the 256-color + // palette current_tile16_bmp_.SetPalette(overworld_palette_); } else { // Fallback to ROM palette @@ -564,7 +565,8 @@ absl::Status Tile16Editor::DrawToCurrentTile16(ImVec2 pos, int start_x = quadrant_x * kTile8Size; int start_y = quadrant_y * kTile8Size; - // Get source tile8 data - use provided tile if available, otherwise use current tile8 + // Get source tile8 data - use provided tile if available, otherwise use + // current tile8 const gfx::Bitmap* tile_to_use = source_tile ? source_tile : ¤t_gfx_individual_[current_tile8_]; if (tile_to_use->size() < 64) { @@ -574,8 +576,8 @@ absl::Status Tile16Editor::DrawToCurrentTile16(ImVec2 pos, // Copy tile8 into tile16 quadrant with proper transformations for (int tile_y = 0; tile_y < kTile8Size; ++tile_y) { for (int tile_x = 0; tile_x < kTile8Size; ++tile_x) { - // Apply flip transformations to source coordinates only if using original tile - // If a pre-flipped tile is provided, use direct coordinates + // Apply flip transformations to source coordinates only if using original + // tile If a pre-flipped tile is provided, use direct coordinates int src_x; int src_y; if (source_tile) { @@ -598,11 +600,10 @@ absl::Status Tile16Editor::DrawToCurrentTile16(ImVec2 pos, if (src_index >= 0 && src_index < static_cast(tile_to_use->size()) && dst_index >= 0 && dst_index < static_cast(current_tile16_bmp_.size())) { - uint8_t pixel_value = tile_to_use->data()[src_index]; - // Keep original pixel values - palette selection is handled by TileInfo metadata - // not by modifying pixel data directly + // Keep original pixel values - palette selection is handled by TileInfo + // metadata not by modifying pixel data directly current_tile16_bmp_.WriteToPixel(dst_index, pixel_value); } } @@ -619,7 +620,6 @@ absl::Status Tile16Editor::DrawToCurrentTile16(ImVec2 pos, // Update the quadrant's TileInfo based on current settings int quadrant_index = quadrant_x + (quadrant_y * 2); if (quadrant_index >= 0 && quadrant_index < 4) { - // Create new TileInfo with current settings gfx::TileInfo new_tile_info(static_cast(current_tile8_), current_palette_, y_flip, x_flip, @@ -740,7 +740,6 @@ absl::Status Tile16Editor::UpdateTile16Edit() { if (BeginChild("##BlocksetScrollable", ImVec2(0, ImGui::GetContentRegionAvail().y), true, ImGuiWindowFlags_AlwaysVerticalScrollbar)) { - blockset_canvas_.DrawBackground(); blockset_canvas_.DrawContextMenu(); @@ -789,7 +788,6 @@ absl::Status Tile16Editor::UpdateTile16Edit() { // Scrollable tile8 source if (BeginChild("##Tile8SourceScrollable", ImVec2(0, 0), true, ImGuiWindowFlags_AlwaysVerticalScrollbar)) { - tile8_source_canvas_.DrawBackground(); tile8_source_canvas_.DrawContextMenu(); @@ -842,7 +840,6 @@ absl::Status Tile16Editor::UpdateTile16Edit() { if (ImGui::BeginChild("##Tile16FixedCanvas", ImVec2(90, 90), true, ImGuiWindowFlags_NoScrollbar | ImGuiWindowFlags_NoScrollWithMouse)) { - tile16_edit_canvas_.DrawBackground(ImVec2(64, 64)); tile16_edit_canvas_.DrawContextMenu(); @@ -855,16 +852,16 @@ absl::Status Tile16Editor::UpdateTile16Edit() { if (current_tile8_ >= 0 && current_tile8_ < static_cast(current_gfx_individual_.size()) && current_gfx_individual_[current_tile8_].is_active()) { - // Create a display tile that shows the current palette selection gfx::Bitmap display_tile; - // Get the original pixel data (already has sheet offsets from ProcessGraphicsBuffer) + // Get the original pixel data (already has sheet offsets from + // ProcessGraphicsBuffer) std::vector tile_data = current_gfx_individual_[current_tile8_].vector(); - // The pixel data already contains the correct indices for the 256-color palette - // We don't need to remap - just use it as-is + // The pixel data already contains the correct indices for the 256-color + // palette We don't need to remap - just use it as-is display_tile.Create(8, 8, 8, tile_data); // Apply the complete 256-color palette @@ -900,8 +897,8 @@ absl::Status Tile16Editor::UpdateTile16Edit() { gfx::Arena::Get().QueueTextureCommand( gfx::Arena::TextureCommandType::CREATE, &display_tile); - // CRITICAL FIX: Handle tile painting with simple click instead of click+drag - // Draw the preview first + // CRITICAL FIX: Handle tile painting with simple click instead of + // click+drag Draw the preview first tile16_edit_canvas_.DrawTilePainter(display_tile, 8, 4); // Check for simple click to paint tile8 to tile16 @@ -992,8 +989,7 @@ absl::Status Tile16Editor::UpdateTile16Edit() { for (int row = 0; row < 2; ++row) { for (int col = 0; col < 4; ++col) { - if (col > 0) - ImGui::SameLine(); + if (col > 0) ImGui::SameLine(); int i = row * 4 + col; bool is_current = (current_palette_ == i); @@ -1094,13 +1090,11 @@ absl::Status Tile16Editor::UpdateTile16Edit() { Separator(); bool can_undo = !undo_stack_.empty(); - if (!can_undo) - BeginDisabled(); + if (!can_undo) BeginDisabled(); if (Button("Undo", ImVec2(-1, 0))) { RETURN_IF_ERROR(Undo()); } - if (!can_undo) - EndDisabled(); + if (!can_undo) EndDisabled(); // Advanced controls (collapsible) if (show_advanced_controls) { @@ -1188,8 +1182,7 @@ absl::Status Tile16Editor::UpdateTile16Edit() { ImGui::SetTooltip("%d:0x%04X", color_index, color.snes()); } - if ((i + 1) % 4 != 0) - ImGui::SameLine(); + if ((i + 1) % 4 != 0) ImGui::SameLine(); } } } @@ -1221,8 +1214,9 @@ absl::Status Tile16Editor::LoadTile8() { current_gfx_individual_.clear(); - // Calculate how many 8x8 tiles we can fit based on the current graphics bitmap size - // SNES graphics are typically 128 pixels wide (16 tiles of 8 pixels each) + // Calculate how many 8x8 tiles we can fit based on the current graphics + // bitmap size SNES graphics are typically 128 pixels wide (16 tiles of 8 + // pixels each) const int tiles_per_row = current_gfx_bmp_.width() / 8; const int total_rows = current_gfx_bmp_.height() / 8; const int total_tiles = tiles_per_row * total_rows; @@ -1266,7 +1260,8 @@ absl::Status Tile16Editor::LoadTile8() { // Set default palette using the same system as overworld if (overworld_palette_.size() >= 256) { // Use complete 256-color palette (same as overworld system) - // The pixel data already contains correct color indices for the 256-color palette + // The pixel data already contains correct color indices for the + // 256-color palette tile_bitmap.SetPalette(overworld_palette_); } else if (rom() && rom()->palette_group().overworld_main.size() > 0) { // Fallback to ROM palette @@ -1355,7 +1350,8 @@ absl::Status Tile16Editor::SetCurrentTile(int tile_id) { // Use the same palette system as the overworld (complete 256-color palette) if (overworld_palette_.size() >= 256) { // Use complete 256-color palette (same as overworld system) - // The pixel data already contains correct color indices for the 256-color palette + // The pixel data already contains correct color indices for the 256-color + // palette current_tile16_bmp_.SetPalette(overworld_palette_); } else if (palette_.size() >= 256) { current_tile16_bmp_.SetPalette(palette_); @@ -1378,7 +1374,8 @@ absl::Status Tile16Editor::CopyTile16ToClipboard(int tile_id) { return absl::InvalidArgumentError("Invalid tile ID"); } - // CRITICAL FIX: Extract tile data directly from atlas instead of using problematic tile cache + // CRITICAL FIX: Extract tile data directly from atlas instead of using + // problematic tile cache auto tile_data = gfx::GetTilemapData(*tile16_blockset_, tile_id); if (!tile_data.empty()) { clipboard_tile16_.Create(16, 16, 8, tile_data); @@ -1856,7 +1853,8 @@ absl::Status Tile16Editor::CommitChangesToBlockset() { absl::Status Tile16Editor::CommitChangesToOverworld() { // CRITICAL FIX: Complete workflow for tile16 changes - // This method now only commits to ROM when explicitly called (user presses Save) + // This method now only commits to ROM when explicitly called (user presses + // Save) // Step 1: Update ROM data with current tile16 changes RETURN_IF_ERROR(UpdateROMTile16Data()); @@ -1892,7 +1890,8 @@ absl::Status Tile16Editor::CommitChangesToOverworld() { gfx::Arena::TextureCommandType::UPDATE, &tile16_blockset_->atlas); } - // Step 4: Notify the parent editor (overworld editor) to regenerate its blockset + // Step 4: Notify the parent editor (overworld editor) to regenerate its + // blockset if (on_changes_committed_) { RETURN_IF_ERROR(on_changes_committed_()); } @@ -1996,9 +1995,10 @@ int Tile16Editor::GetPaletteSlotForSheet(int sheet_index) const { // NEW: Get the actual palette slot for a given palette button and sheet index int Tile16Editor::GetActualPaletteSlot(int palette_button, int sheet_index) const { - // Map palette buttons 0-7 to actual 256-color palette slots based on sheet type - // Based on the correct 256-color palette structure from SetColorsPalette() - // The 256-color palette is organized as a 16x16 grid (16 colors per row) + // Map palette buttons 0-7 to actual 256-color palette slots based on sheet + // type Based on the correct 256-color palette structure from + // SetColorsPalette() The 256-color palette is organized as a 16x16 grid (16 + // colors per row) switch (sheet_index) { case 0: // Main blockset -> AUX1 region (right side, rows 2-4, cols 9-15) @@ -2016,8 +2016,8 @@ int Tile16Editor::GetActualPaletteSlot(int palette_button, case 1: case 2: // Main graphics -> MAIN region (left side, rows 2-6, cols 1-7) - // MAIN palette: Row 2-6, cols 1-7 = slots 33-39, 49-55, 65-71, 81-87, 97-103 - // Use row 2, col 1 + palette_button offset + // MAIN palette: Row 2-6, cols 1-7 = slots 33-39, 49-55, 65-71, 81-87, + // 97-103 Use row 2, col 1 + palette_button offset return 33 + palette_button; // Row 2, col 1 = slot 33 case 7: // Animated tiles -> ANIMATED region (row 7, cols 1-7) @@ -2043,8 +2043,8 @@ int Tile16Editor::GetSheetIndexForTile8(int tile8_id) const { // NEW: Get the actual palette slot for the current tile16 being edited int Tile16Editor::GetActualPaletteSlotForCurrentTile16() const { - // For the current tile16, we need to determine which sheet the tile8s belong to - // and use the most appropriate palette region + // For the current tile16, we need to determine which sheet the tile8s belong + // to and use the most appropriate palette region if (current_tile8_ >= 0 && current_tile8_ < static_cast(current_gfx_individual_.size())) { @@ -2093,10 +2093,11 @@ absl::Status Tile16Editor::UpdateTile8Palette(int tile8_id) { current_palette_ = 0; } - // // Use the same palette system as the overworld (complete 256-color palette) - // if (display_palette.size() >= 256) { + // // Use the same palette system as the overworld (complete 256-color + // palette) if (display_palette.size() >= 256) { // // Apply complete 256-color palette (same as overworld system) - // // The pixel data already contains correct color indices for the 256-color palette + // // The pixel data already contains correct color indices for the + // 256-color palette // current_gfx_individual_[tile8_id].SetPalette(display_palette); // } else { // For smaller palettes, use SetPaletteWithTransparent with current palette @@ -2126,7 +2127,8 @@ absl::Status Tile16Editor::RefreshAllPalettes() { current_palette_ = 0; } - // CRITICAL FIX: Use the complete overworld palette for proper color coordination + // CRITICAL FIX: Use the complete overworld palette for proper color + // coordination gfx::SnesPalette display_palette; if (overworld_palette_.size() >= 256) { @@ -2152,11 +2154,13 @@ absl::Status Tile16Editor::RefreshAllPalettes() { } // CRITICAL FIX: Use the same palette system as the overworld - // The overworld system applies the complete 256-color palette to the main graphics bitmap - // Individual tile8 graphics use the same palette but with proper color mapping + // The overworld system applies the complete 256-color palette to the main + // graphics bitmap Individual tile8 graphics use the same palette but with + // proper color mapping if (current_gfx_bmp_.is_active()) { - // Apply the complete 256-color palette to the source bitmap (same as overworld) + // Apply the complete 256-color palette to the source bitmap (same as + // overworld) current_gfx_bmp_.SetPalette(display_palette); current_gfx_bmp_.set_modified(true); // Queue texture update via Arena's deferred system @@ -2181,7 +2185,8 @@ absl::Status Tile16Editor::RefreshAllPalettes() { for (size_t i = 0; i < current_gfx_individual_.size(); ++i) { if (current_gfx_individual_[i].is_active()) { // Use complete 256-color palette (same as overworld system) - // The pixel data already contains correct color indices for the 256-color palette + // The pixel data already contains correct color indices for the 256-color + // palette current_gfx_individual_[i].SetPalette(display_palette); current_gfx_individual_[i].set_modified(true); // Queue texture update via Arena's deferred system @@ -2303,8 +2308,7 @@ void Tile16Editor::DrawPaletteSettings() { ImGui::SetTooltip("Index %d: 0x%04X (%d pixels)", value, color.snes(), count); } - if (value % 8 != 7) - ImGui::SameLine(); + if (value % 8 != 7) ImGui::SameLine(); } } } @@ -2354,8 +2358,7 @@ void Tile16Editor::DrawPaletteSettings() { void Tile16Editor::DrawScratchSpace() { Text("Layout Scratch:"); for (int i = 0; i < 4; i++) { - if (i > 0) - SameLine(); + if (i > 0) SameLine(); std::string slot_name = "S" + std::to_string(i + 1); if (layout_scratch_[i].in_use) { @@ -2375,7 +2378,8 @@ absl::Status Tile16Editor::SaveLayoutToScratch(int slot) { return absl::InvalidArgumentError("Invalid scratch slot"); } - // For now, just mark as used - full implementation would save current editing state + // For now, just mark as used - full implementation would save current editing + // state layout_scratch_[slot].in_use = true; layout_scratch_[slot].name = absl::StrFormat("Layout %d", slot + 1); @@ -2468,8 +2472,7 @@ void Tile16Editor::DrawManualTile8Inputs() { ImGui::PopID(); } - if (q < 3) - ImGui::Separator(); + if (q < 3) ImGui::Separator(); } ImGui::Separator(); diff --git a/src/app/editor/overworld/tile16_editor.h b/src/app/editor/overworld/tile16_editor.h index 7b4499eb..e7495f53 100644 --- a/src/app/editor/overworld/tile16_editor.h +++ b/src/app/editor/overworld/tile16_editor.h @@ -251,7 +251,8 @@ class Tile16Editor : public gfx::GfxContext { gui::CanvasGridSize::k32x32}; gfx::Bitmap tile16_blockset_bmp_; - // Canvas for editing the selected tile - optimized for 2x2 grid of 8x8 tiles (16x16 total) + // Canvas for editing the selected tile - optimized for 2x2 grid of 8x8 tiles + // (16x16 total) gui::Canvas tile16_edit_canvas_{ "Tile16EditCanvas", ImVec2(64, 64), // Fixed 64x64 display size (16x16 pixels at 4x scale) diff --git a/src/app/editor/palette/palette_editor.cc b/src/app/editor/palette/palette_editor.cc index 15c69a69..21334fa3 100644 --- a/src/app/editor/palette/palette_editor.cc +++ b/src/app/editor/palette/palette_editor.cc @@ -1,8 +1,8 @@ #include "palette_editor.h" -#include "app/editor/system/editor_card_registry.h" #include "absl/status/status.h" #include "absl/strings/str_cat.h" +#include "app/editor/system/editor_card_registry.h" #include "app/gfx/debug/performance/performance_profiler.h" #include "app/gfx/types/snes_palette.h" #include "app/gfx/util/palette_manager.h" @@ -64,10 +64,8 @@ int CustomFormatString(char* buf, size_t buf_size, const char* fmt, ...) { int w = vsnprintf(buf, buf_size, fmt, args); #endif va_end(args); - if (buf == nullptr) - return w; - if (w == -1 || w >= (int)buf_size) - w = (int)buf_size - 1; + if (buf == nullptr) return w; + if (w == -1 || w >= (int)buf_size) w = (int)buf_size - 1; buf[w] = 0; return w; } @@ -85,14 +83,14 @@ static inline float color_saturate(float f) { * @brief Display SNES palette with enhanced ROM hacking features * @param palette SNES palette to display * @param loaded Whether the palette has been loaded from ROM - * + * * Enhanced Features: * - Real-time color preview with SNES format conversion * - Drag-and-drop color swapping for palette editing * - Color picker integration with ROM palette system * - Undo/redo support for palette modifications * - Export functionality for palette sharing - * + * * Performance Notes: * - Static color arrays to avoid repeated allocations * - Cached color conversions for fast rendering @@ -139,7 +137,8 @@ absl::Status DisplayPalette(gfx::SnesPalette& palette, bool loaded) { SameLine(); Text("Previous"); - if (Button("Update Map Palette")) {} + if (Button("Update Map Palette")) { + } ColorButton( "##current", color, @@ -158,8 +157,7 @@ absl::Status DisplayPalette(gfx::SnesPalette& palette, bool loaded) { Text("Palette"); for (int n = 0; n < IM_ARRAYSIZE(current_palette); n++) { PushID(n); - if ((n % 8) != 0) - SameLine(0.0f, GetStyle().ItemSpacing.y); + if ((n % 8) != 0) SameLine(0.0f, GetStyle().ItemSpacing.y); if (ColorButton("##palette", current_palette[n], kPalButtonFlags, ImVec2(20, 20))) @@ -186,9 +184,9 @@ absl::Status DisplayPalette(gfx::SnesPalette& palette, bool loaded) { } void PaletteEditor::Initialize() { - // Register all cards with EditorCardRegistry (done once during initialization) - if (!dependencies_.card_registry) - return; + // Register all cards with EditorCardRegistry (done once during + // initialization) + if (!dependencies_.card_registry) return; auto* card_registry = dependencies_.card_registry; card_registry->RegisterCard({.card_id = "palette.control_panel", @@ -329,7 +327,8 @@ absl::Status PaletteEditor::Update() { } // CARD-BASED EDITOR: All windows are independent top-level cards - // No parent wrapper - this allows closing control panel without affecting palettes + // No parent wrapper - this allows closing control panel without affecting + // palettes // Optional control panel (can be hidden/minimized) if (show_control_panel_) { @@ -356,70 +355,55 @@ absl::Status PaletteEditor::Update() { } // Draw all independent palette cards - // Each card has its own show_ flag that needs to be synced with our visibility flags + // Each card has its own show_ flag that needs to be synced with our + // visibility flags if (show_ow_main_card_ && ow_main_card_) { - if (!ow_main_card_->IsVisible()) - ow_main_card_->Show(); + if (!ow_main_card_->IsVisible()) ow_main_card_->Show(); ow_main_card_->Draw(); // Sync back if user closed the card with X button - if (!ow_main_card_->IsVisible()) - show_ow_main_card_ = false; + if (!ow_main_card_->IsVisible()) show_ow_main_card_ = false; } if (show_ow_animated_card_ && ow_animated_card_) { - if (!ow_animated_card_->IsVisible()) - ow_animated_card_->Show(); + if (!ow_animated_card_->IsVisible()) ow_animated_card_->Show(); ow_animated_card_->Draw(); - if (!ow_animated_card_->IsVisible()) - show_ow_animated_card_ = false; + if (!ow_animated_card_->IsVisible()) show_ow_animated_card_ = false; } if (show_dungeon_main_card_ && dungeon_main_card_) { - if (!dungeon_main_card_->IsVisible()) - dungeon_main_card_->Show(); + if (!dungeon_main_card_->IsVisible()) dungeon_main_card_->Show(); dungeon_main_card_->Draw(); - if (!dungeon_main_card_->IsVisible()) - show_dungeon_main_card_ = false; + if (!dungeon_main_card_->IsVisible()) show_dungeon_main_card_ = false; } if (show_sprite_card_ && sprite_card_) { - if (!sprite_card_->IsVisible()) - sprite_card_->Show(); + if (!sprite_card_->IsVisible()) sprite_card_->Show(); sprite_card_->Draw(); - if (!sprite_card_->IsVisible()) - show_sprite_card_ = false; + if (!sprite_card_->IsVisible()) show_sprite_card_ = false; } if (show_sprites_aux1_card_ && sprites_aux1_card_) { - if (!sprites_aux1_card_->IsVisible()) - sprites_aux1_card_->Show(); + if (!sprites_aux1_card_->IsVisible()) sprites_aux1_card_->Show(); sprites_aux1_card_->Draw(); - if (!sprites_aux1_card_->IsVisible()) - show_sprites_aux1_card_ = false; + if (!sprites_aux1_card_->IsVisible()) show_sprites_aux1_card_ = false; } if (show_sprites_aux2_card_ && sprites_aux2_card_) { - if (!sprites_aux2_card_->IsVisible()) - sprites_aux2_card_->Show(); + if (!sprites_aux2_card_->IsVisible()) sprites_aux2_card_->Show(); sprites_aux2_card_->Draw(); - if (!sprites_aux2_card_->IsVisible()) - show_sprites_aux2_card_ = false; + if (!sprites_aux2_card_->IsVisible()) show_sprites_aux2_card_ = false; } if (show_sprites_aux3_card_ && sprites_aux3_card_) { - if (!sprites_aux3_card_->IsVisible()) - sprites_aux3_card_->Show(); + if (!sprites_aux3_card_->IsVisible()) sprites_aux3_card_->Show(); sprites_aux3_card_->Draw(); - if (!sprites_aux3_card_->IsVisible()) - show_sprites_aux3_card_ = false; + if (!sprites_aux3_card_->IsVisible()) show_sprites_aux3_card_ = false; } if (show_equipment_card_ && equipment_card_) { - if (!equipment_card_->IsVisible()) - equipment_card_->Show(); + if (!equipment_card_->IsVisible()) equipment_card_->Show(); equipment_card_->Draw(); - if (!equipment_card_->IsVisible()) - show_equipment_card_ = false; + if (!equipment_card_->IsVisible()) show_equipment_card_ = false; } // Draw quick access and custom palette cards @@ -472,8 +456,7 @@ void PaletteEditor::DrawQuickAccessTab() { Text("Recently Used Colors"); for (int i = 0; i < recently_used_colors_.size(); i++) { PushID(i); - if (i % 8 != 0) - SameLine(); + if (i % 8 != 0) SameLine(); ImVec4 displayColor = gui::ConvertSnesColorToImVec4(recently_used_colors_[i]); if (ImGui::ColorButton("##recent", displayColor)) { @@ -488,14 +471,14 @@ void PaletteEditor::DrawQuickAccessTab() { /** * @brief Draw custom palette editor with enhanced ROM hacking features - * + * * Enhanced Features: * - Drag-and-drop color reordering * - Context menu for each color with advanced options * - Export/import functionality for palette sharing * - Integration with recently used colors * - Undo/redo support for palette modifications - * + * * Performance Notes: * - Efficient color conversion caching * - Minimal redraws with dirty region tracking @@ -506,8 +489,7 @@ void PaletteEditor::DrawCustomPalette() { ImGuiWindowFlags_HorizontalScrollbar)) { for (int i = 0; i < custom_palette_.size(); i++) { PushID(i); - if (i > 0) - SameLine(0.0f, GetStyle().ItemSpacing.y); + if (i > 0) SameLine(0.0f, GetStyle().ItemSpacing.y); // Enhanced color button with context menu and drag-drop support ImVec4 displayColor = gui::ConvertSnesColorToImVec4(custom_palette_[i]); @@ -613,8 +595,7 @@ absl::Status PaletteEditor::DrawPaletteGroup(int category, for (int n = 0; n < pal_size; n++) { PushID(n); - if (n > 0 && n % 8 != 0) - SameLine(0.0f, 2.0f); + if (n > 0 && n % 8 != 0) SameLine(0.0f, 2.0f); auto popup_id = absl::StrCat(kPaletteCategoryNames[category].data(), j, "_", n); @@ -686,27 +667,22 @@ absl::Status PaletteEditor::HandleColorPopup(gfx::SnesPalette& palette, int i, Separator(); - if (Button("Copy as..", ImVec2(-1, 0))) - OpenPopup("Copy"); + if (Button("Copy as..", ImVec2(-1, 0))) OpenPopup("Copy"); if (BeginPopup("Copy")) { CustomFormatString(buf, IM_ARRAYSIZE(buf), "(%.3ff, %.3ff, %.3ff)", col[0], col[1], col[2]); - if (Selectable(buf)) - SetClipboardText(buf); + if (Selectable(buf)) SetClipboardText(buf); CustomFormatString(buf, IM_ARRAYSIZE(buf), "(%d,%d,%d)", cr, cg, cb); - if (Selectable(buf)) - SetClipboardText(buf); + if (Selectable(buf)) SetClipboardText(buf); CustomFormatString(buf, IM_ARRAYSIZE(buf), "#%02X%02X%02X", cr, cg, cb); - if (Selectable(buf)) - SetClipboardText(buf); + if (Selectable(buf)) SetClipboardText(buf); // SNES Format CustomFormatString(buf, IM_ARRAYSIZE(buf), "$%04X", ConvertRgbToSnes(ImVec4(col[0], col[1], col[2], 1.0f))); - if (Selectable(buf)) - SetClipboardText(buf); + if (Selectable(buf)) SetClipboardText(buf); EndPopup(); } @@ -945,8 +921,7 @@ void PaletteEditor::DrawControlPanel() { ImGui::Separator(); // View menu section now handled by EditorCardRegistry in EditorManager - if (!dependencies_.card_registry) - return; + if (!dependencies_.card_registry) return; auto* card_registry = dependencies_.card_registry; ImGui::EndPopup(); @@ -1003,8 +978,7 @@ void PaletteEditor::DrawQuickAccessCard() { } else { for (int i = 0; i < recently_used_colors_.size(); i++) { PushID(i); - if (i % 8 != 0) - SameLine(); + if (i % 8 != 0) SameLine(); ImVec4 displayColor = gui::ConvertSnesColorToImVec4(recently_used_colors_[i]); if (ImGui::ColorButton("##recent", displayColor, kPalButtonFlags, @@ -1041,8 +1015,7 @@ void PaletteEditor::DrawCustomPaletteCard() { } else { for (int i = 0; i < custom_palette_.size(); i++) { PushID(i); - if (i > 0 && i % 16 != 0) - SameLine(0.0f, 2.0f); + if (i > 0 && i % 16 != 0) SameLine(0.0f, 2.0f); // Enhanced color button with context menu and drag-drop support ImVec4 displayColor = gui::ConvertSnesColorToImVec4(custom_palette_[i]); diff --git a/src/app/editor/palette/palette_group_card.cc b/src/app/editor/palette/palette_group_card.cc index 6fb2ec47..baf8989c 100644 --- a/src/app/editor/palette/palette_group_card.cc +++ b/src/app/editor/palette/palette_group_card.cc @@ -24,9 +24,9 @@ using gui::ThemedIconButton; PaletteGroupCard::PaletteGroupCard(const std::string& group_name, const std::string& display_name, Rom* rom) : group_name_(group_name), display_name_(display_name), rom_(rom) { - // Note: We can't call GetPaletteGroup() here because it's a pure virtual function - // and the derived class isn't fully constructed yet. Original palettes will be - // loaded on first Draw() call instead. + // Note: We can't call GetPaletteGroup() here because it's a pure virtual + // function and the derived class isn't fully constructed yet. Original + // palettes will be loaded on first Draw() call instead. } void PaletteGroupCard::Draw() { @@ -168,8 +168,7 @@ void PaletteGroupCard::DrawToolbar() { void PaletteGroupCard::DrawPaletteSelector() { auto* palette_group = GetPaletteGroup(); - if (!palette_group) - return; + if (!palette_group) return; int num_palettes = palette_group->size(); @@ -210,12 +209,10 @@ void PaletteGroupCard::DrawPaletteSelector() { } void PaletteGroupCard::DrawColorPicker() { - if (selected_color_ < 0) - return; + if (selected_color_ < 0) return; auto* palette = GetMutablePalette(selected_palette_); - if (!palette) - return; + if (!palette) return; SectionHeader("Color Editor"); @@ -269,8 +266,7 @@ void PaletteGroupCard::DrawColorPicker() { } void PaletteGroupCard::DrawColorInfo() { - if (selected_color_ < 0) - return; + if (selected_color_ < 0) return; SectionHeader("Color Information"); @@ -308,8 +304,7 @@ void PaletteGroupCard::DrawColorInfo() { void PaletteGroupCard::DrawMetadataInfo() { const auto& metadata = GetMetadata(); - if (selected_palette_ >= metadata.palettes.size()) - return; + if (selected_palette_ >= metadata.palettes.size()) return; const auto& pal_meta = metadata.palettes[selected_palette_]; @@ -612,14 +607,14 @@ gfx::PaletteGroup* OverworldMainPaletteCard::GetPaletteGroup() { } const gfx::PaletteGroup* OverworldMainPaletteCard::GetPaletteGroup() const { - // Note: rom_->palette_group() returns by value, so we need to use the mutable version + // Note: rom_->palette_group() returns by value, so we need to use the mutable + // version return const_cast(rom_)->mutable_palette_group()->get_group("ow_main"); } void OverworldMainPaletteCard::DrawPaletteGrid() { auto* palette = GetMutablePalette(selected_palette_); - if (!palette) - return; + if (!palette) return; const float button_size = 32.0f; const int colors_per_row = GetColorsPerRow(); @@ -690,8 +685,7 @@ const gfx::PaletteGroup* OverworldAnimatedPaletteCard::GetPaletteGroup() const { void OverworldAnimatedPaletteCard::DrawPaletteGrid() { auto* palette = GetMutablePalette(selected_palette_); - if (!palette) - return; + if (!palette) return; const float button_size = 32.0f; const int colors_per_row = GetColorsPerRow(); @@ -765,8 +759,7 @@ const gfx::PaletteGroup* DungeonMainPaletteCard::GetPaletteGroup() const { void DungeonMainPaletteCard::DrawPaletteGrid() { auto* palette = GetMutablePalette(selected_palette_); - if (!palette) - return; + if (!palette) return; const float button_size = 28.0f; const int colors_per_row = GetColorsPerRow(); @@ -841,8 +834,7 @@ const gfx::PaletteGroup* SpritePaletteCard::GetPaletteGroup() const { void SpritePaletteCard::DrawPaletteGrid() { auto* palette = GetMutablePalette(selected_palette_); - if (!palette) - return; + if (!palette) return; const float button_size = 28.0f; const int colors_per_row = GetColorsPerRow(); @@ -853,7 +845,8 @@ void SpritePaletteCard::DrawPaletteGrid() { ImGui::PushID(i); - // Draw transparent color indicator at start of each 16-color row (0, 16, 32, 48, ...) + // Draw transparent color indicator at start of each 16-color row (0, 16, + // 32, 48, ...) bool is_transparent_slot = (i % 16 == 0); if (is_transparent_slot) { ImGui::BeginGroup(); @@ -947,8 +940,7 @@ const gfx::PaletteGroup* EquipmentPaletteCard::GetPaletteGroup() const { void EquipmentPaletteCard::DrawPaletteGrid() { auto* palette = GetMutablePalette(selected_palette_); - if (!palette) - return; + if (!palette) return; const float button_size = 32.0f; const int colors_per_row = GetColorsPerRow(); @@ -1014,8 +1006,7 @@ const gfx::PaletteGroup* SpritesAux1PaletteCard::GetPaletteGroup() const { void SpritesAux1PaletteCard::DrawPaletteGrid() { auto* palette = GetMutablePalette(selected_palette_); - if (!palette) - return; + if (!palette) return; const float button_size = 32.0f; const int colors_per_row = GetColorsPerRow(); @@ -1081,8 +1072,7 @@ const gfx::PaletteGroup* SpritesAux2PaletteCard::GetPaletteGroup() const { void SpritesAux2PaletteCard::DrawPaletteGrid() { auto* palette = GetMutablePalette(selected_palette_); - if (!palette) - return; + if (!palette) return; const float button_size = 32.0f; const int colors_per_row = GetColorsPerRow(); @@ -1165,8 +1155,7 @@ const gfx::PaletteGroup* SpritesAux3PaletteCard::GetPaletteGroup() const { void SpritesAux3PaletteCard::DrawPaletteGrid() { auto* palette = GetMutablePalette(selected_palette_); - if (!palette) - return; + if (!palette) return; const float button_size = 32.0f; const int colors_per_row = GetColorsPerRow(); diff --git a/src/app/editor/palette/palette_group_card.h b/src/app/editor/palette/palette_group_card.h index 14fa242e..36f0553a 100644 --- a/src/app/editor/palette/palette_group_card.h +++ b/src/app/editor/palette/palette_group_card.h @@ -68,7 +68,8 @@ class PaletteGroupCard { public: /** * @brief Construct a new Palette Group Card - * @param group_name Internal palette group name (e.g., "ow_main", "dungeon_main") + * @param group_name Internal palette group name (e.g., "ow_main", + * "dungeon_main") * @param display_name Human-readable name for UI * @param rom ROM instance for reading/writing palettes */ diff --git a/src/app/editor/palette/palette_utility.cc b/src/app/editor/palette/palette_utility.cc index fa869768..93f8c7aa 100644 --- a/src/app/editor/palette/palette_utility.cc +++ b/src/app/editor/palette/palette_utility.cc @@ -75,10 +75,8 @@ bool DrawPaletteIdSelector(const char* label, int* palette_id, bool changed = ImGui::InputInt(label, palette_id); // Clamp to valid range (0-255 typically) - if (*palette_id < 0) - *palette_id = 0; - if (*palette_id > 255) - *palette_id = 255; + if (*palette_id < 0) *palette_id = 0; + if (*palette_id > 255) *palette_id = 255; // Draw jump button ImGui::SameLine(); @@ -118,8 +116,7 @@ void DrawPalettePreview(const std::string& group_name, int palette_index, // Draw colors in a row int preview_size = std::min(8, static_cast(palette.size())); for (int i = 0; i < preview_size; i++) { - if (i > 0) - ImGui::SameLine(); + if (i > 0) ImGui::SameLine(); ImGui::PushID(i); ImVec4 col = gui::ConvertSnesColorToImVec4(palette[i]); diff --git a/src/app/editor/session_types.h b/src/app/editor/session_types.h index 12408c9d..e618f35a 100644 --- a/src/app/editor/session_types.h +++ b/src/app/editor/session_types.h @@ -1,6 +1,9 @@ #ifndef YAZE_APP_EDITOR_SESSION_TYPES_H_ #define YAZE_APP_EDITOR_SESSION_TYPES_H_ +#include +#include + #include "app/editor/code/assembly_editor.h" #include "app/editor/code/memory_editor.h" #include "app/editor/dungeon/dungeon_editor_v2.h" @@ -15,9 +18,6 @@ #include "app/rom.h" #include "core/features.h" -#include -#include - namespace yaze::editor { class EditorDependencies; @@ -57,7 +57,8 @@ class EditorSet { /** * @struct RomSession - * @brief Represents a single session, containing a ROM and its associated editors. + * @brief Represents a single session, containing a ROM and its associated + * editors. */ struct RomSession { Rom rom; diff --git a/src/app/editor/sprite/sprite_editor.cc b/src/app/editor/sprite/sprite_editor.cc index fde54926..fe28951d 100644 --- a/src/app/editor/sprite/sprite_editor.cc +++ b/src/app/editor/sprite/sprite_editor.cc @@ -1,7 +1,7 @@ #include "sprite_editor.h" -#include "app/editor/system/editor_card_registry.h" #include "app/editor/sprite/zsprite.h" +#include "app/editor/system/editor_card_registry.h" #include "app/gfx/debug/performance/performance_profiler.h" #include "app/gfx/resource/arena.h" #include "app/gui/core/icons.h" @@ -26,8 +26,7 @@ using ImGui::TableSetupColumn; using ImGui::Text; void SpriteEditor::Initialize() { - if (!dependencies_.card_registry) - return; + if (!dependencies_.card_registry) return; auto* card_registry = dependencies_.card_registry; card_registry->RegisterCard({.card_id = "sprite.vanilla_editor", @@ -57,8 +56,7 @@ absl::Status SpriteEditor::Update() { sheets_loaded_ = true; } - if (!dependencies_.card_registry) - return absl::OkStatus(); + if (!dependencies_.card_registry) return absl::OkStatus(); auto* card_registry = dependencies_.card_registry; static gui::EditorCard vanilla_card("Vanilla Sprites", ICON_MD_SMART_TOY); @@ -67,7 +65,8 @@ absl::Status SpriteEditor::Update() { vanilla_card.SetDefaultSize(900, 700); custom_card.SetDefaultSize(800, 600); - // Vanilla Sprites Card - Check visibility flag exists and is true before rendering + // Vanilla Sprites Card - Check visibility flag exists and is true before + // rendering bool* vanilla_visible = card_registry->GetVisibilityFlag("sprite.vanilla_editor"); if (vanilla_visible && *vanilla_visible) { @@ -77,7 +76,8 @@ absl::Status SpriteEditor::Update() { vanilla_card.End(); } - // Custom Sprites Card - Check visibility flag exists and is true before rendering + // Custom Sprites Card - Check visibility flag exists and is true before + // rendering bool* custom_visible = card_registry->GetVisibilityFlag("sprite.custom_editor"); if (custom_visible && *custom_visible) { @@ -221,8 +221,7 @@ void SpriteEditor::DrawCurrentSheets() { for (int i = 0; i < 8; i++) { std::string sheet_label = absl::StrFormat("Sheet %d", i); gui::InputHexByte(sheet_label.c_str(), ¤t_sheets_[i]); - if (i % 2 == 0) - ImGui::SameLine(); + if (i % 2 == 0) ImGui::SameLine(); } graphics_sheet_canvas_.DrawBackground(); diff --git a/src/app/editor/system/command_manager.cc b/src/app/editor/system/command_manager.cc index b1dddf91..2336cc37 100644 --- a/src/app/editor/system/command_manager.cc +++ b/src/app/editor/system/command_manager.cc @@ -181,8 +181,7 @@ void CommandManager::ShowWhichKeyHierarchical() { // Handle keyboard input for WhichKey navigation void CommandManager::HandleWhichKeyInput() { - if (!whichkey_active_) - return; + if (!whichkey_active_) return; // Check for prefix keys (w, l, f, b, s, t, etc.) for (const auto& [shortcut, group] : commands_) { diff --git a/src/app/editor/system/command_palette.cc b/src/app/editor/system/command_palette.cc index fd42a7b8..cd4caec6 100644 --- a/src/app/editor/system/command_palette.cc +++ b/src/app/editor/system/command_palette.cc @@ -34,8 +34,7 @@ void CommandPalette::RecordUsage(const std::string& name) { int CommandPalette::FuzzyScore(const std::string& text, const std::string& query) { - if (query.empty()) - return 0; + if (query.empty()) return 0; int score = 0; size_t text_idx = 0; @@ -49,16 +48,13 @@ int CommandPalette::FuzzyScore(const std::string& text, ::tolower); // Exact match bonus - if (text_lower == query_lower) - return 1000; + if (text_lower == query_lower) return 1000; // Starts with bonus - if (text_lower.find(query_lower) == 0) - return 500; + if (text_lower.find(query_lower) == 0) return 500; // Contains bonus - if (text_lower.find(query_lower) != std::string::npos) - return 250; + if (text_lower.find(query_lower) != std::string::npos) return 250; // Fuzzy match - characters in order while (text_idx < text_lower.length() && query_idx < query_lower.length()) { @@ -70,8 +66,7 @@ int CommandPalette::FuzzyScore(const std::string& text, } // Penalty if not all characters matched - if (query_idx != query_lower.length()) - return 0; + if (query_idx != query_lower.length()) return 0; return score; } diff --git a/src/app/editor/system/editor_card_registry.cc b/src/app/editor/system/editor_card_registry.cc index 35ad5a10..5653863a 100644 --- a/src/app/editor/system/editor_card_registry.cc +++ b/src/app/editor/system/editor_card_registry.cc @@ -738,7 +738,6 @@ void EditorCardRegistry::DrawCardBrowser(size_t session_id, bool* p_open) { if (ImGui::Begin( absl::StrFormat("%s Card Browser", ICON_MD_DASHBOARD).c_str(), p_open)) { - static char search_filter[256] = ""; static std::string category_filter = "All"; @@ -772,7 +771,6 @@ void EditorCardRegistry::DrawCardBrowser(size_t session_id, bool* p_open) { if (ImGui::BeginTable("##CardTable", 4, ImGuiTableFlags_ScrollY | ImGuiTableFlags_RowBg | ImGuiTableFlags_Borders)) { - ImGui::TableSetupColumn("Visible", ImGuiTableColumnFlags_WidthFixed, 60); ImGui::TableSetupColumn("Name", ImGuiTableColumnFlags_WidthStretch); ImGui::TableSetupColumn("Category", ImGuiTableColumnFlags_WidthFixed, @@ -793,8 +791,7 @@ void EditorCardRegistry::DrawCardBrowser(size_t session_id, bool* p_open) { for (const auto& card_id : cards) { auto card_it = cards_.find(card_id); - if (card_it == cards_.end()) - continue; + if (card_it == cards_.end()) continue; const auto& card = card_it->second; diff --git a/src/app/editor/system/editor_card_registry.h b/src/app/editor/system/editor_card_registry.h index 842be657..849a18b7 100644 --- a/src/app/editor/system/editor_card_registry.h +++ b/src/app/editor/system/editor_card_registry.h @@ -18,7 +18,7 @@ class EditorCard; /** * @struct CardInfo * @brief Metadata for an editor card - * + * * Describes a registerable UI card that can be shown/hidden, * organized by category, and controlled programmatically. */ @@ -37,12 +37,13 @@ struct CardInfo { /** * @class EditorCardRegistry - * @brief Central registry for all editor cards with session awareness and dependency injection - * - * This class combines the functionality of EditorCardManager (global card management) - * and SessionCardRegistry (session-aware prefixing) into a single, dependency-injected - * component that can be passed to editors. - * + * @brief Central registry for all editor cards with session awareness and + * dependency injection + * + * This class combines the functionality of EditorCardManager (global card + * management) and SessionCardRegistry (session-aware prefixing) into a single, + * dependency-injected component that can be passed to editors. + * * Design Philosophy: * - Dependency injection (no singleton pattern) * - Session-aware card ID prefixing for multi-session support @@ -50,18 +51,18 @@ struct CardInfo { * - View menu integration * - Workspace preset system * - No direct GUI dependency in registration logic - * + * * Session-Aware Card IDs: * - Single session: "dungeon.room_selector" * - Multiple sessions: "s0.dungeon.room_selector", "s1.dungeon.room_selector" - * + * * Usage: * ```cpp * // In EditorManager: * EditorCardRegistry card_registry; * EditorDependencies deps; * deps.card_registry = &card_registry; - * + * * // In Editor: * deps.card_registry->RegisterCard(deps.session_id, { * .card_id = "dungeon.room_selector", @@ -70,7 +71,7 @@ struct CardInfo { * .category = "Dungeon", * .on_show = []() { } * }); - * + * * // Programmatic control: * deps.card_registry->ShowCard(deps.session_id, "dungeon.room_selector"); * ``` @@ -93,7 +94,7 @@ class EditorCardRegistry { /** * @brief Register a new session in the registry * @param session_id Unique session identifier - * + * * Creates internal tracking structures for the session. * Must be called before registering cards for a session. */ @@ -102,7 +103,7 @@ class EditorCardRegistry { /** * @brief Unregister a session and all its cards * @param session_id Session identifier to remove - * + * * Automatically unregisters all cards associated with the session. */ void UnregisterSession(size_t session_id); @@ -110,7 +111,7 @@ class EditorCardRegistry { /** * @brief Set the currently active session * @param session_id Session to make active - * + * * Used for determining whether to apply card ID prefixing. */ void SetActiveSession(size_t session_id); @@ -122,8 +123,9 @@ class EditorCardRegistry { /** * @brief Register a card for a specific session * @param session_id Session this card belongs to - * @param base_info Card metadata (ID will be automatically prefixed if needed) - * + * @param base_info Card metadata (ID will be automatically prefixed if + * needed) + * * The card_id in base_info should be the unprefixed ID. This method * automatically applies session prefixing when multiple sessions exist. */ @@ -150,7 +152,7 @@ class EditorCardRegistry { /** * @brief Unregister all cards with a given prefix * @param prefix Prefix to match (e.g., "s0" or "s1.dungeon") - * + * * Useful for cleaning up session cards or category cards. */ void UnregisterCardsWithPrefix(const std::string& prefix); @@ -189,7 +191,8 @@ class EditorCardRegistry { /** * @brief Get visibility flag pointer for a card - * @return Pointer to bool controlling card visibility (for passing to EditorCard::Begin) + * @return Pointer to bool controlling card visibility (for passing to + * EditorCard::Begin) */ bool* GetVisibilityFlag(size_t session_id, const std::string& base_card_id); @@ -348,7 +351,7 @@ class EditorCardRegistry { * @param session_id Session identifier * @param base_id Unprefixed card ID * @return Prefixed ID if multiple sessions, otherwise base ID - * + * * Examples: * - Single session: "dungeon.room_selector" → "dungeon.room_selector" * - Multi-session: "dungeon.room_selector" → "s0.dungeon.room_selector" diff --git a/src/app/editor/system/editor_registry.cc b/src/app/editor/system/editor_registry.cc index 662864d9..e7df6b47 100644 --- a/src/app/editor/system/editor_registry.cc +++ b/src/app/editor/system/editor_registry.cc @@ -1,6 +1,7 @@ #include "editor_registry.h" #include + #include "absl/strings/str_format.h" #include "app/editor/editor.h" diff --git a/src/app/editor/system/editor_registry.h b/src/app/editor/system/editor_registry.h index 73e4fcaf..f803723f 100644 --- a/src/app/editor/system/editor_registry.h +++ b/src/app/editor/system/editor_registry.h @@ -13,7 +13,7 @@ namespace editor { /** * @class EditorRegistry * @brief Manages editor types, categories, and lifecycle - * + * * Extracted from EditorManager to provide focused editor management: * - Editor type classification and categorization * - Editor activation and switching diff --git a/src/app/editor/system/menu_orchestrator.cc b/src/app/editor/system/menu_orchestrator.cc index 1a21e322..e26a2de7 100644 --- a/src/app/editor/system/menu_orchestrator.cc +++ b/src/app/editor/system/menu_orchestrator.cc @@ -437,13 +437,9 @@ void MenuOrchestrator::AddHelpMenuItems() { } // Menu state management -void MenuOrchestrator::ClearMenu() { - menu_builder_.Clear(); -} +void MenuOrchestrator::ClearMenu() { menu_builder_.Clear(); } -void MenuOrchestrator::RefreshMenu() { - menu_needs_refresh_ = true; -} +void MenuOrchestrator::RefreshMenu() { menu_needs_refresh_ = true; } // Menu item callbacks - delegate to appropriate managers void MenuOrchestrator::OnOpenRom() { @@ -472,9 +468,7 @@ void MenuOrchestrator::OnSaveRom() { } } -void MenuOrchestrator::OnSaveRomAs() { - popup_manager_.Show(PopupID::kSaveAs); -} +void MenuOrchestrator::OnSaveRomAs() { popup_manager_.Show(PopupID::kSaveAs); } void MenuOrchestrator::OnCreateProject() { // Delegate to EditorManager which handles the full project creation flow @@ -855,9 +849,7 @@ void MenuOrchestrator::OnShowNetworkStatus() { #endif // Help menu actions -void MenuOrchestrator::OnShowAbout() { - popup_manager_.Show(PopupID::kAbout); -} +void MenuOrchestrator::OnShowAbout() { popup_manager_.Show(PopupID::kAbout); } void MenuOrchestrator::OnShowGettingStarted() { popup_manager_.Show(PopupID::kGettingStarted); @@ -1001,11 +993,9 @@ void MenuOrchestrator::RegisterGlobalShortcuts() { void MenuOrchestrator::OnRunDataIntegrityCheck() { #ifdef YAZE_ENABLE_TESTING - if (!editor_manager_) - return; + if (!editor_manager_) return; auto* rom = editor_manager_->GetCurrentRom(); - if (!rom || !rom->is_loaded()) - return; + if (!rom || !rom->is_loaded()) return; toast_manager_.Show("Running ROM integrity tests...", ToastType::kInfo); // This would integrate with the test system in master @@ -1019,11 +1009,9 @@ void MenuOrchestrator::OnRunDataIntegrityCheck() { void MenuOrchestrator::OnTestSaveLoad() { #ifdef YAZE_ENABLE_TESTING - if (!editor_manager_) - return; + if (!editor_manager_) return; auto* rom = editor_manager_->GetCurrentRom(); - if (!rom || !rom->is_loaded()) - return; + if (!rom || !rom->is_loaded()) return; toast_manager_.Show("Running ROM save/load tests...", ToastType::kInfo); // This would integrate with the test system in master @@ -1034,11 +1022,9 @@ void MenuOrchestrator::OnTestSaveLoad() { } void MenuOrchestrator::OnCheckRomVersion() { - if (!editor_manager_) - return; + if (!editor_manager_) return; auto* rom = editor_manager_->GetCurrentRom(); - if (!rom || !rom->is_loaded()) - return; + if (!rom || !rom->is_loaded()) return; // Check ZSCustomOverworld version uint8_t version = (*rom)[zelda3::OverworldCustomASMHasBeenApplied]; @@ -1052,11 +1038,9 @@ void MenuOrchestrator::OnCheckRomVersion() { } void MenuOrchestrator::OnUpgradeRom() { - if (!editor_manager_) - return; + if (!editor_manager_) return; auto* rom = editor_manager_->GetCurrentRom(); - if (!rom || !rom->is_loaded()) - return; + if (!rom || !rom->is_loaded()) return; toast_manager_.Show("Use Overworld Editor to upgrade ROM version", ToastType::kInfo, 4.0f); @@ -1074,11 +1058,9 @@ void MenuOrchestrator::OnToggleCustomLoading() { } void MenuOrchestrator::OnToggleAsarPatch() { - if (!editor_manager_) - return; + if (!editor_manager_) return; auto* rom = editor_manager_->GetCurrentRom(); - if (!rom || !rom->is_loaded()) - return; + if (!rom || !rom->is_loaded()) return; auto& flags = core::FeatureFlags::get(); flags.overworld.kApplyZSCustomOverworldASM = diff --git a/src/app/editor/system/menu_orchestrator.h b/src/app/editor/system/menu_orchestrator.h index 9f2f5a49..f4c34e90 100644 --- a/src/app/editor/system/menu_orchestrator.h +++ b/src/app/editor/system/menu_orchestrator.h @@ -24,14 +24,14 @@ class PopupManager; /** * @class MenuOrchestrator * @brief Handles all menu building and UI coordination logic - * + * * Extracted from EditorManager to provide focused menu management: * - Menu structure and organization * - Menu item callbacks and shortcuts * - Editor-specific menu items * - Session-aware menu updates * - Menu state management - * + * * This class follows the Single Responsibility Principle by focusing solely * on menu construction and coordination, delegating actual operations to * specialized managers. diff --git a/src/app/editor/system/popup_manager.cc b/src/app/editor/system/popup_manager.cc index b1133ad9..d88da973 100644 --- a/src/app/editor/system/popup_manager.cc +++ b/src/app/editor/system/popup_manager.cc @@ -20,9 +20,10 @@ void PopupManager::Initialize() { // ============================================================================ // POPUP REGISTRATION // ============================================================================ - // All popups must be registered here BEFORE any menu callbacks can trigger them. - // This method is called in EditorManager constructor BEFORE MenuOrchestrator - // and UICoordinator are created, ensuring safe initialization order. + // All popups must be registered here BEFORE any menu callbacks can trigger + // them. This method is called in EditorManager constructor BEFORE + // MenuOrchestrator and UICoordinator are created, ensuring safe + // initialization order. // // Popup Registration Format: // popups_[PopupID::kConstant] = { @@ -36,102 +37,71 @@ void PopupManager::Initialize() { // File Operations popups_[PopupID::kSaveAs] = {PopupID::kSaveAs, PopupType::kFileOperation, - false, false, [this]() { - DrawSaveAsPopup(); - }}; - popups_[PopupID::kNewProject] = { - PopupID::kNewProject, PopupType::kFileOperation, false, false, [this]() { - DrawNewProjectPopup(); - }}; + false, false, [this]() { DrawSaveAsPopup(); }}; + popups_[PopupID::kNewProject] = {PopupID::kNewProject, + PopupType::kFileOperation, false, false, + [this]() { DrawNewProjectPopup(); }}; popups_[PopupID::kManageProject] = {PopupID::kManageProject, PopupType::kFileOperation, false, false, - [this]() { - DrawManageProjectPopup(); - }}; + [this]() { DrawManageProjectPopup(); }}; // Information popups_[PopupID::kAbout] = {PopupID::kAbout, PopupType::kInfo, false, false, - [this]() { - DrawAboutPopup(); - }}; + [this]() { DrawAboutPopup(); }}; popups_[PopupID::kRomInfo] = {PopupID::kRomInfo, PopupType::kInfo, false, - false, [this]() { - DrawRomInfoPopup(); - }}; + false, [this]() { DrawRomInfoPopup(); }}; popups_[PopupID::kSupportedFeatures] = { - PopupID::kSupportedFeatures, PopupType::kInfo, false, false, [this]() { - DrawSupportedFeaturesPopup(); - }}; + PopupID::kSupportedFeatures, PopupType::kInfo, false, false, + [this]() { DrawSupportedFeaturesPopup(); }}; popups_[PopupID::kOpenRomHelp] = {PopupID::kOpenRomHelp, PopupType::kHelp, - false, false, [this]() { - DrawOpenRomHelpPopup(); - }}; + false, false, + [this]() { DrawOpenRomHelpPopup(); }}; // Help Documentation - popups_[PopupID::kGettingStarted] = { - PopupID::kGettingStarted, PopupType::kHelp, false, false, [this]() { - DrawGettingStartedPopup(); - }}; + popups_[PopupID::kGettingStarted] = {PopupID::kGettingStarted, + PopupType::kHelp, false, false, + [this]() { DrawGettingStartedPopup(); }}; popups_[PopupID::kAsarIntegration] = { - PopupID::kAsarIntegration, PopupType::kHelp, false, false, [this]() { - DrawAsarIntegrationPopup(); - }}; + PopupID::kAsarIntegration, PopupType::kHelp, false, false, + [this]() { DrawAsarIntegrationPopup(); }}; popups_[PopupID::kBuildInstructions] = { - PopupID::kBuildInstructions, PopupType::kHelp, false, false, [this]() { - DrawBuildInstructionsPopup(); - }}; + PopupID::kBuildInstructions, PopupType::kHelp, false, false, + [this]() { DrawBuildInstructionsPopup(); }}; popups_[PopupID::kCLIUsage] = {PopupID::kCLIUsage, PopupType::kHelp, false, - false, [this]() { - DrawCLIUsagePopup(); - }}; + false, [this]() { DrawCLIUsagePopup(); }}; popups_[PopupID::kTroubleshooting] = { - PopupID::kTroubleshooting, PopupType::kHelp, false, false, [this]() { - DrawTroubleshootingPopup(); - }}; + PopupID::kTroubleshooting, PopupType::kHelp, false, false, + [this]() { DrawTroubleshootingPopup(); }}; popups_[PopupID::kContributing] = {PopupID::kContributing, PopupType::kHelp, - false, false, [this]() { - DrawContributingPopup(); - }}; + false, false, + [this]() { DrawContributingPopup(); }}; popups_[PopupID::kWhatsNew] = {PopupID::kWhatsNew, PopupType::kHelp, false, - false, [this]() { - DrawWhatsNewPopup(); - }}; + false, [this]() { DrawWhatsNewPopup(); }}; // Settings - popups_[PopupID::kDisplaySettings] = {PopupID::kDisplaySettings, - PopupType::kSettings, false, - true, // Resizable - [this]() { - DrawDisplaySettingsPopup(); - }}; + popups_[PopupID::kDisplaySettings] = { + PopupID::kDisplaySettings, PopupType::kSettings, false, + true, // Resizable + [this]() { DrawDisplaySettingsPopup(); }}; popups_[PopupID::kFeatureFlags] = { PopupID::kFeatureFlags, PopupType::kSettings, false, true, // Resizable - [this]() { - DrawFeatureFlagsPopup(); - }}; + [this]() { DrawFeatureFlagsPopup(); }}; // Workspace popups_[PopupID::kWorkspaceHelp] = {PopupID::kWorkspaceHelp, PopupType::kHelp, - false, false, [this]() { - DrawWorkspaceHelpPopup(); - }}; - popups_[PopupID::kSessionLimitWarning] = {PopupID::kSessionLimitWarning, - PopupType::kWarning, false, false, - [this]() { - DrawSessionLimitWarningPopup(); - }}; - popups_[PopupID::kLayoutResetConfirm] = {PopupID::kLayoutResetConfirm, - PopupType::kConfirmation, false, - false, [this]() { - DrawLayoutResetConfirmPopup(); - }}; + false, false, + [this]() { DrawWorkspaceHelpPopup(); }}; + popups_[PopupID::kSessionLimitWarning] = { + PopupID::kSessionLimitWarning, PopupType::kWarning, false, false, + [this]() { DrawSessionLimitWarningPopup(); }}; + popups_[PopupID::kLayoutResetConfirm] = { + PopupID::kLayoutResetConfirm, PopupType::kConfirmation, false, false, + [this]() { DrawLayoutResetConfirmPopup(); }}; // Debug/Testing popups_[PopupID::kDataIntegrity] = {PopupID::kDataIntegrity, PopupType::kInfo, false, true, // Resizable - [this]() { - DrawDataIntegrityPopup(); - }}; + [this]() { DrawDataIntegrityPopup(); }}; } void PopupManager::DrawPopups() { @@ -257,8 +227,7 @@ void PopupManager::DrawAboutPopup() { void PopupManager::DrawRomInfoPopup() { auto* current_rom = editor_manager_->GetCurrentRom(); - if (!current_rom) - return; + if (!current_rom) return; Text("Title: %s", current_rom->title().c_str()); Text("ROM Size: %s", util::HexLongLong(current_rom->size()).c_str()); diff --git a/src/app/editor/system/popup_manager.h b/src/app/editor/system/popup_manager.h index 2dc8d29d..bb676393 100644 --- a/src/app/editor/system/popup_manager.h +++ b/src/app/editor/system/popup_manager.h @@ -15,7 +15,8 @@ class EditorManager; /** * @enum PopupType - * @brief Type classification for popups to enable future filtering and organization + * @brief Type classification for popups to enable future filtering and + * organization */ enum class PopupType { kInfo, // Information display (About, ROM Info, etc.) diff --git a/src/app/editor/system/project_manager.h b/src/app/editor/system/project_manager.h index 2597b5bc..4a14c92a 100644 --- a/src/app/editor/system/project_manager.h +++ b/src/app/editor/system/project_manager.h @@ -14,7 +14,7 @@ class ToastManager; /** * @class ProjectManager * @brief Handles all project file operations - * + * * Extracted from EditorManager to provide focused project management: * - Project creation and templates * - Project loading and saving diff --git a/src/app/editor/system/proposal_drawer.cc b/src/app/editor/system/proposal_drawer.cc index 6bae5999..6aeb9f14 100644 --- a/src/app/editor/system/proposal_drawer.cc +++ b/src/app/editor/system/proposal_drawer.cc @@ -18,13 +18,10 @@ namespace yaze { namespace editor { -ProposalDrawer::ProposalDrawer() { - RefreshProposals(); -} +ProposalDrawer::ProposalDrawer() { RefreshProposals(); } void ProposalDrawer::Draw() { - if (!visible_) - return; + if (!visible_) return; // Set drawer position on the right side ImGuiIO& io = ImGui::GetIO(); @@ -189,8 +186,7 @@ void ProposalDrawer::DrawProposalList() { } void ProposalDrawer::DrawProposalDetail() { - if (!selected_proposal_) - return; + if (!selected_proposal_) return; const auto& p = *selected_proposal_; @@ -283,8 +279,7 @@ void ProposalDrawer::DrawStatusFilter() { void ProposalDrawer::DrawPolicyStatus() { #ifdef YAZE_ENABLE_POLICY_FRAMEWORK - if (!selected_proposal_) - return; + if (!selected_proposal_) return; const auto& p = *selected_proposal_; @@ -382,8 +377,7 @@ void ProposalDrawer::DrawPolicyStatus() { } void ProposalDrawer::DrawActionButtons() { - if (!selected_proposal_) - return; + if (!selected_proposal_) return; const auto& p = *selected_proposal_; bool is_pending = p.status == cli::ProposalRegistry::ProposalStatus::kPending; diff --git a/src/app/editor/system/proposal_drawer.h b/src/app/editor/system/proposal_drawer.h index b584c598..156f0ca8 100644 --- a/src/app/editor/system/proposal_drawer.h +++ b/src/app/editor/system/proposal_drawer.h @@ -17,14 +17,14 @@ namespace editor { /** * @class ProposalDrawer * @brief ImGui drawer for displaying and managing agent proposals - * + * * Provides a UI for reviewing agent-generated ROM modification proposals, * including: * - List of all proposals with status indicators * - Detailed view of selected proposal (metadata, diff, logs) * - Accept/Reject controls * - Filtering by status (Pending/Accepted/Rejected) - * + * * Integrates with the CLI ProposalRegistry service to enable * human-in-the-loop review of agentic modifications. */ diff --git a/src/app/editor/system/rom_file_manager.h b/src/app/editor/system/rom_file_manager.h index d3a9f673..10439060 100644 --- a/src/app/editor/system/rom_file_manager.h +++ b/src/app/editor/system/rom_file_manager.h @@ -14,7 +14,7 @@ class ToastManager; /** * @class RomFileManager * @brief Handles all ROM file I/O operations - * + * * Extracted from EditorManager to provide focused ROM file management: * - ROM loading and saving * - Asset loading diff --git a/src/app/editor/system/session_coordinator.cc b/src/app/editor/system/session_coordinator.cc index 3b16c5af..02c4d7af 100644 --- a/src/app/editor/system/session_coordinator.cc +++ b/src/app/editor/system/session_coordinator.cc @@ -32,8 +32,7 @@ SessionCoordinator::SessionCoordinator(void* sessions_ptr, void SessionCoordinator::CreateNewSession() { auto* sessions = GET_SESSIONS(); - if (!sessions) - return; + if (!sessions) return; if (session_count_ >= kMaxSessions) { ShowSessionLimitWarning(); @@ -55,15 +54,15 @@ void SessionCoordinator::CreateNewSession() { void SessionCoordinator::DuplicateCurrentSession() { auto* sessions = GET_SESSIONS(); - if (!sessions || sessions->empty()) - return; + if (!sessions || sessions->empty()) return; if (session_count_ >= kMaxSessions) { ShowSessionLimitWarning(); return; } - // Create new empty session (cannot actually duplicate due to non-movable editors) + // Create new empty session (cannot actually duplicate due to non-movable + // editors) // TODO: Implement proper duplication when editors become movable sessions->emplace_back(); UpdateSessionCount(); @@ -83,8 +82,7 @@ void SessionCoordinator::CloseCurrentSession() { void SessionCoordinator::CloseSession(size_t index) { auto* sessions = GET_SESSIONS(); - if (!sessions || !IsValidSessionIndex(index)) - return; + if (!sessions || !IsValidSessionIndex(index)) return; if (session_count_ <= kMinSessions) { // Don't allow closing the last session @@ -104,8 +102,9 @@ void SessionCoordinator::CloseSession(size_t index) { // TODO: Implement proper session removal when editors become movable sessions->at(index).custom_name = "[CLOSED SESSION]"; - // Note: We don't actually remove from the deque because EditorSet is not movable - // This is a temporary solution until we refactor to use unique_ptr + // Note: We don't actually remove from the deque because EditorSet is not + // movable This is a temporary solution until we refactor to use + // unique_ptr UpdateSessionCount(); // Adjust active session index @@ -119,13 +118,10 @@ void SessionCoordinator::CloseSession(size_t index) { ShowSessionOperationResult("Close Session", true); } -void SessionCoordinator::RemoveSession(size_t index) { - CloseSession(index); -} +void SessionCoordinator::RemoveSession(size_t index) { CloseSession(index); } void SessionCoordinator::SwitchToSession(size_t index) { - if (!IsValidSessionIndex(index)) - return; + if (!IsValidSessionIndex(index)) return; active_session_index_ = index; @@ -183,8 +179,7 @@ size_t SessionCoordinator::GetActiveSessionCount() const { bool SessionCoordinator::HasDuplicateSession( const std::string& filepath) const { auto* sessions = GET_SESSIONS(); - if (!sessions || filepath.empty()) - return false; + if (!sessions || filepath.empty()) return false; for (const auto& session : *sessions) { if (session.filepath == filepath) { @@ -196,11 +191,9 @@ bool SessionCoordinator::HasDuplicateSession( void SessionCoordinator::DrawSessionSwitcher() { auto* sessions = GET_SESSIONS(); - if (!sessions || sessions->empty()) - return; + if (!sessions || sessions->empty()) return; - if (!show_session_switcher_) - return; + if (!show_session_switcher_) return; ImGui::SetNextWindowSize(ImVec2(400, 300), ImGuiCond_FirstUseEver); ImGui::SetNextWindowPos(ImGui::GetMainViewport()->GetCenter(), @@ -262,11 +255,9 @@ void SessionCoordinator::DrawSessionSwitcher() { void SessionCoordinator::DrawSessionManager() { auto* sessions = GET_SESSIONS(); - if (!sessions || sessions->empty()) - return; + if (!sessions || sessions->empty()) return; - if (!show_session_manager_) - return; + if (!show_session_manager_) return; ImGui::SetNextWindowSize(ImVec2(600, 400), ImGuiCond_FirstUseEver); ImGui::SetNextWindowPos(ImGui::GetMainViewport()->GetCenter(), @@ -291,7 +282,6 @@ void SessionCoordinator::DrawSessionManager() { if (ImGui::BeginTable("SessionTable", 4, ImGuiTableFlags_Borders | ImGuiTableFlags_RowBg | ImGuiTableFlags_Resizable)) { - ImGui::TableSetupColumn("Session", ImGuiTableColumnFlags_WidthStretch, 0.3f); ImGui::TableSetupColumn("ROM File", ImGuiTableColumnFlags_WidthStretch, @@ -357,8 +347,7 @@ void SessionCoordinator::DrawSessionManager() { } void SessionCoordinator::DrawSessionRenameDialog() { - if (!show_session_rename_dialog_) - return; + if (!show_session_rename_dialog_) return; ImGui::SetNextWindowSize(ImVec2(300, 150), ImGuiCond_Always); ImGui::SetNextWindowPos(ImGui::GetMainViewport()->GetCenter(), @@ -392,8 +381,7 @@ void SessionCoordinator::DrawSessionRenameDialog() { void SessionCoordinator::DrawSessionTabs() { auto* sessions = GET_SESSIONS(); - if (!sessions || sessions->empty()) - return; + if (!sessions || sessions->empty()) return; if (ImGui::BeginTabBar("SessionTabs")) { for (size_t i = 0; i < sessions->size(); ++i) { @@ -429,8 +417,7 @@ void SessionCoordinator::DrawSessionTabs() { } void SessionCoordinator::DrawSessionIndicator() { - if (!HasMultipleSessions()) - return; + if (!HasMultipleSessions()) return; const auto& theme = gui::ThemeManager::Get().GetCurrentTheme(); ImVec4 accent_color = ConvertColorToImVec4(theme.accent); @@ -477,8 +464,7 @@ std::string SessionCoordinator::GetActiveSessionDisplayName() const { void SessionCoordinator::RenameSession(size_t index, const std::string& new_name) { auto* sessions = GET_SESSIONS(); - if (!sessions || !IsValidSessionIndex(index) || new_name.empty()) - return; + if (!sessions || !IsValidSessionIndex(index) || new_name.empty()) return; sessions->at(index).custom_name = new_name; LOG_INFO("SessionCoordinator", "Renamed session %zu to '%s'", index, @@ -570,8 +556,7 @@ size_t SessionCoordinator::GetTotalSessionCount() const { size_t SessionCoordinator::GetLoadedSessionCount() const { auto* sessions = GET_SESSIONS(); - if (!sessions) - return 0; + if (!sessions) return 0; size_t count = 0; for (const auto& session : *sessions) { @@ -637,8 +622,7 @@ absl::Status SessionCoordinator::SaveSessionAs(size_t session_index, absl::StatusOr SessionCoordinator::CreateSessionFromRom( Rom&& rom, const std::string& filepath) { auto* sessions = GET_SESSIONS(); - if (!sessions) - return absl::InternalError("Sessions not initialized"); + if (!sessions) return absl::InternalError("Sessions not initialized"); size_t new_session_id = sessions->size(); sessions->emplace_back(std::move(rom), user_settings_, new_session_id); @@ -653,8 +637,7 @@ absl::StatusOr SessionCoordinator::CreateSessionFromRom( void SessionCoordinator::CleanupClosedSessions() { auto* sessions = GET_SESSIONS(); - if (!sessions) - return; + if (!sessions) return; // Mark empty sessions as closed (except keep at least one) // TODO: Actually remove when editors become movable @@ -680,8 +663,7 @@ void SessionCoordinator::CleanupClosedSessions() { void SessionCoordinator::ClearAllSessions() { auto* sessions = GET_SESSIONS(); - if (!sessions) - return; + if (!sessions) return; // Unregister all session cards if (card_registry_) { @@ -704,8 +686,7 @@ void SessionCoordinator::ClearAllSessions() { void SessionCoordinator::FocusNextSession() { auto* sessions = GET_SESSIONS(); - if (!sessions || sessions->empty()) - return; + if (!sessions || sessions->empty()) return; size_t next_index = (active_session_index_ + 1) % sessions->size(); SwitchToSession(next_index); @@ -713,8 +694,7 @@ void SessionCoordinator::FocusNextSession() { void SessionCoordinator::FocusPreviousSession() { auto* sessions = GET_SESSIONS(); - if (!sessions || sessions->empty()) - return; + if (!sessions || sessions->empty()) return; size_t prev_index = (active_session_index_ == 0) ? sessions->size() - 1 : active_session_index_ - 1; @@ -723,15 +703,13 @@ void SessionCoordinator::FocusPreviousSession() { void SessionCoordinator::FocusFirstSession() { auto* sessions = GET_SESSIONS(); - if (!sessions || sessions->empty()) - return; + if (!sessions || sessions->empty()) return; SwitchToSession(0); } void SessionCoordinator::FocusLastSession() { auto* sessions = GET_SESSIONS(); - if (!sessions || sessions->empty()) - return; + if (!sessions || sessions->empty()) return; SwitchToSession(sessions->size() - 1); } @@ -753,8 +731,7 @@ void SessionCoordinator::ValidateSessionIndex(size_t index) const { std::string SessionCoordinator::GenerateUniqueSessionName( const std::string& base_name) const { auto* sessions = GET_SESSIONS(); - if (!sessions) - return base_name; + if (!sessions) return base_name; std::string name = base_name; int counter = 1; @@ -768,8 +745,7 @@ std::string SessionCoordinator::GenerateUniqueSessionName( } } - if (!found) - break; + if (!found) break; name = absl::StrFormat("%s %d", base_name, counter++); } @@ -797,8 +773,7 @@ void SessionCoordinator::ShowSessionOperationResult( void SessionCoordinator::DrawSessionTab(size_t index, bool is_active) { auto* sessions = GET_SESSIONS(); - if (!sessions || index >= sessions->size()) - return; + if (!sessions || index >= sessions->size()) return; const auto& session = sessions->at(index); @@ -851,8 +826,7 @@ void SessionCoordinator::DrawSessionContextMenu(size_t index) { void SessionCoordinator::DrawSessionBadge(size_t index) { auto* sessions = GET_SESSIONS(); - if (!sessions || index >= sessions->size()) - return; + if (!sessions || index >= sessions->size()) return; const auto& session = sessions->at(index); ImVec4 color = GetSessionColor(index); diff --git a/src/app/editor/system/session_coordinator.h b/src/app/editor/system/session_coordinator.h index cc76c40e..86b6cf74 100644 --- a/src/app/editor/system/session_coordinator.h +++ b/src/app/editor/system/session_coordinator.h @@ -31,11 +31,13 @@ class ToastManager; /** * @class SessionCoordinator * @brief High-level orchestrator for multi-session UI - * + * * Manages session list UI, coordinates card visibility across sessions, - * handles session activation/deactivation, and provides session-aware editor queries. - * - * This class lives in the ui/ layer and can depend on both system and gui components. + * handles session activation/deactivation, and provides session-aware editor + * queries. + * + * This class lives in the ui/ layer and can depend on both system and gui + * components. */ class SessionCoordinator { public: diff --git a/src/app/editor/system/settings_editor.cc b/src/app/editor/system/settings_editor.cc index c2a90ec4..355e4959 100644 --- a/src/app/editor/system/settings_editor.cc +++ b/src/app/editor/system/settings_editor.cc @@ -1,5 +1,8 @@ #include "app/editor/system/settings_editor.h" +#include +#include + #include "absl/status/status.h" #include "app/editor/system/editor_card_registry.h" #include "app/gfx/debug/performance/performance_profiler.h" @@ -11,9 +14,6 @@ #include "imgui/imgui.h" #include "util/log.h" -#include -#include - namespace yaze { namespace editor { @@ -29,8 +29,7 @@ using ImGui::TableSetupColumn; void SettingsEditor::Initialize() { // Register cards with EditorCardRegistry (dependency injection) - if (!dependencies_.card_registry) - return; + if (!dependencies_.card_registry) return; auto* card_registry = dependencies_.card_registry; card_registry->RegisterCard({.card_id = MakeCardId("settings.general"), @@ -80,11 +79,11 @@ absl::Status SettingsEditor::Load() { } absl::Status SettingsEditor::Update() { - if (!dependencies_.card_registry) - return absl::OkStatus(); + if (!dependencies_.card_registry) return absl::OkStatus(); auto* card_registry = dependencies_.card_registry; - // General Settings Card - Check visibility flag and pass to Begin() for proper X button + // General Settings Card - Check visibility flag and pass to Begin() for + // proper X button bool* general_visible = card_registry->GetVisibilityFlag(MakeCardId("settings.general")); if (general_visible && *general_visible) { @@ -96,7 +95,8 @@ absl::Status SettingsEditor::Update() { general_card.End(); } - // Appearance Card (Themes + Font Manager combined) - Check visibility and pass flag + // Appearance Card (Themes + Font Manager combined) - Check visibility and + // pass flag bool* appearance_visible = card_registry->GetVisibilityFlag(MakeCardId("settings.appearance")); if (appearance_visible && *appearance_visible) { @@ -461,14 +461,10 @@ void SettingsEditor::DrawAIAgentSettings() { // Get current categories std::set categories; - if (user_settings_->prefs().log_ai_requests) - categories.insert("AI"); - if (user_settings_->prefs().log_rom_operations) - categories.insert("ROM"); - if (user_settings_->prefs().log_gui_automation) - categories.insert("GUI"); - if (user_settings_->prefs().log_proposals) - categories.insert("Proposals"); + if (user_settings_->prefs().log_ai_requests) categories.insert("AI"); + if (user_settings_->prefs().log_rom_operations) categories.insert("ROM"); + if (user_settings_->prefs().log_gui_automation) categories.insert("GUI"); + if (user_settings_->prefs().log_proposals) categories.insert("Proposals"); // Reconfigure with new level util::LogManager::instance().configure( @@ -551,14 +547,10 @@ void SettingsEditor::DrawAIAgentSettings() { if (categories_changed) { // Rebuild category set std::set categories; - if (user_settings_->prefs().log_ai_requests) - categories.insert("AI"); - if (user_settings_->prefs().log_rom_operations) - categories.insert("ROM"); - if (user_settings_->prefs().log_gui_automation) - categories.insert("GUI"); - if (user_settings_->prefs().log_proposals) - categories.insert("Proposals"); + if (user_settings_->prefs().log_ai_requests) categories.insert("AI"); + if (user_settings_->prefs().log_rom_operations) categories.insert("ROM"); + if (user_settings_->prefs().log_gui_automation) categories.insert("GUI"); + if (user_settings_->prefs().log_proposals) categories.insert("Proposals"); // Reconfigure LogManager util::LogLevel level = diff --git a/src/app/editor/system/settings_editor.h b/src/app/editor/system/settings_editor.h index 42bc772f..029aeb07 100644 --- a/src/app/editor/system/settings_editor.h +++ b/src/app/editor/system/settings_editor.h @@ -51,8 +51,7 @@ static ExampleTreeNode* ExampleTree_CreateNode(const char* name, snprintf(node->Name, IM_ARRAYSIZE(node->Name), "%s", name); node->UID = uid; node->Parent = parent; - if (parent) - parent->Childs.push_back(node); + if (parent) parent->Childs.push_back(node); return node; } @@ -140,8 +139,7 @@ struct ExampleAppPropertyEditor { // Display child and data if (node_open) - for (ExampleTreeNode* child : node->Childs) - DrawTreeNode(child); + for (ExampleTreeNode* child : node->Childs) DrawTreeNode(child); if (node_open && node->HasData) { // In a typical application, the structure description would be derived // from a data-driven system. @@ -188,8 +186,7 @@ struct ExampleAppPropertyEditor { ImGui::PopID(); } } - if (node_open) - ImGui::TreePop(); + if (node_open) ImGui::TreePop(); ImGui::PopID(); } }; diff --git a/src/app/editor/system/shortcut_configurator.cc b/src/app/editor/system/shortcut_configurator.cc index 00f00ee5..ee7e15fd 100644 --- a/src/app/editor/system/shortcut_configurator.cc +++ b/src/app/editor/system/shortcut_configurator.cc @@ -208,7 +208,8 @@ void ConfigureEditorShortcuts(const ShortcutDependencies& deps, }); if (card_registry) { - // Note: Using Ctrl+Alt for card shortcuts to avoid conflicts with Save As (Ctrl+Shift+S) + // Note: Using Ctrl+Alt for card shortcuts to avoid conflicts with Save As + // (Ctrl+Shift+S) RegisterIfValid(shortcut_manager, "Show Dungeon Cards", {ImGuiMod_Ctrl, ImGuiMod_Alt, ImGuiKey_D}, [card_registry]() { @@ -309,7 +310,8 @@ void ConfigureMenuShortcuts(const ShortcutDependencies& deps, } }); - // Note: Changed from Ctrl+Shift+R to Ctrl+Alt+R to avoid conflict with Proposal Drawer + // Note: Changed from Ctrl+Shift+R to Ctrl+Alt+R to avoid conflict with + // Proposal Drawer RegisterIfValid(shortcut_manager, "Reset Layout", {ImGuiMod_Ctrl, ImGuiMod_Alt, ImGuiKey_R}, [workspace_manager]() { diff --git a/src/app/editor/system/shortcut_manager.cc b/src/app/editor/system/shortcut_manager.cc index 0271788f..f23bb18a 100644 --- a/src/app/editor/system/shortcut_manager.cc +++ b/src/app/editor/system/shortcut_manager.cc @@ -191,7 +191,6 @@ void ShortcutManager::RegisterStandardShortcuts( std::function save_callback, std::function open_callback, std::function close_callback, std::function find_callback, std::function settings_callback) { - // Ctrl+S - Save if (save_callback) { RegisterShortcut("save", {ImGuiMod_Ctrl, ImGuiKey_S}, save_callback); @@ -227,7 +226,6 @@ void ShortcutManager::RegisterWindowNavigationShortcuts( std::function focus_up, std::function focus_down, std::function close_window, std::function split_horizontal, std::function split_vertical) { - // Ctrl+Arrow keys for window navigation if (focus_left) { RegisterShortcut("focus_left", {ImGuiMod_Ctrl, ImGuiKey_LeftArrow}, diff --git a/src/app/editor/system/toast_manager.h b/src/app/editor/system/toast_manager.h index 4f67e82e..c45c4028 100644 --- a/src/app/editor/system/toast_manager.h +++ b/src/app/editor/system/toast_manager.h @@ -30,8 +30,7 @@ class ToastManager { } void Draw() { - if (toasts_.empty()) - return; + if (toasts_.empty()) return; ImGuiIO& io = ImGui::GetIO(); ImVec2 pos(io.DisplaySize.x - 10.f, 40.f); diff --git a/src/app/editor/system/user_settings.cc b/src/app/editor/system/user_settings.cc index 6881d1eb..f89e79a2 100644 --- a/src/app/editor/system/user_settings.cc +++ b/src/app/editor/system/user_settings.cc @@ -35,8 +35,7 @@ absl::Status UserSettings::Load() { std::string line; while (std::getline(ss, line)) { size_t eq_pos = line.find('='); - if (eq_pos == std::string::npos) - continue; + if (eq_pos == std::string::npos) continue; std::string key = line.substr(0, eq_pos); std::string val = line.substr(eq_pos + 1); diff --git a/src/app/editor/system/user_settings.h b/src/app/editor/system/user_settings.h index d957dca2..a43b75e8 100644 --- a/src/app/editor/system/user_settings.h +++ b/src/app/editor/system/user_settings.h @@ -2,6 +2,7 @@ #define YAZE_APP_EDITOR_SYSTEM_USER_SETTINGS_H_ #include + #include "absl/status/status.h" namespace yaze { diff --git a/src/app/editor/system/window_delegate.h b/src/app/editor/system/window_delegate.h index 3696bd6b..2ecc954b 100644 --- a/src/app/editor/system/window_delegate.h +++ b/src/app/editor/system/window_delegate.h @@ -13,13 +13,13 @@ namespace editor { /** * @class WindowDelegate * @brief Low-level window operations with minimal dependencies - * + * * Provides window management functionality extracted from EditorManager: * - Window visibility management - * - Docking operations + * - Docking operations * - Layout persistence * - Focus management - * + * * This class has minimal dependencies (only ImGui and absl) to avoid * linker issues and circular dependencies. */ diff --git a/src/app/editor/ui/editor_selection_dialog.cc b/src/app/editor/ui/editor_selection_dialog.cc index 5d1066b8..4d791990 100644 --- a/src/app/editor/ui/editor_selection_dialog.cc +++ b/src/app/editor/ui/editor_selection_dialog.cc @@ -80,15 +80,15 @@ bool EditorSelectionDialog::Show(bool* p_open) { } if (!is_open_) { - if (p_open) - *p_open = false; + if (p_open) *p_open = false; return false; } bool editor_selected = false; bool* window_open = p_open ? p_open : &is_open_; - // Set window properties immediately before Begin to prevent them from affecting tooltips + // Set window properties immediately before Begin to prevent them from + // affecting tooltips ImVec2 center = ImGui::GetMainViewport()->GetCenter(); ImGui::SetNextWindowPos(center, ImGuiCond_Appearing, ImVec2(0.5f, 0.5f)); ImGui::SetNextWindowSize( @@ -146,8 +146,7 @@ bool EditorSelectionDialog::Show(bool* p_open) { if (editor_selected) { is_open_ = false; - if (p_open) - *p_open = false; + if (p_open) *p_open = false; } return editor_selected; diff --git a/src/app/editor/ui/editor_selection_dialog.h b/src/app/editor/ui/editor_selection_dialog.h index 88a9f3b0..3b8b9bed 100644 --- a/src/app/editor/ui/editor_selection_dialog.h +++ b/src/app/editor/ui/editor_selection_dialog.h @@ -29,7 +29,7 @@ struct EditorInfo { /** * @class EditorSelectionDialog * @brief Beautiful grid-based editor selection dialog - * + * * Displays when a ROM is loaded, showing all available editors * with icons, descriptions, and quick access. */ diff --git a/src/app/editor/ui/layout_manager.cc b/src/app/editor/ui/layout_manager.cc index 9595bfdf..d53b56e2 100644 --- a/src/app/editor/ui/layout_manager.cc +++ b/src/app/editor/ui/layout_manager.cc @@ -114,7 +114,8 @@ void LayoutManager::BuildOverworldLayout(ImGuiID dockspace_id) { ImGui::DockBuilderDockWindow(" Scratch Pad", dock_right_bottom); // Note: Floating windows (Tile16 Editor, GFX Groups, etc.) are not docked - // They will appear as floating windows with their configured default positions + // They will appear as floating windows with their configured default + // positions } void LayoutManager::BuildDungeonLayout(ImGuiID dockspace_id) { diff --git a/src/app/editor/ui/layout_manager.h b/src/app/editor/ui/layout_manager.h index b30e21c1..b0243e6e 100644 --- a/src/app/editor/ui/layout_manager.h +++ b/src/app/editor/ui/layout_manager.h @@ -13,11 +13,11 @@ namespace editor { /** * @class LayoutManager * @brief Manages ImGui DockBuilder layouts for each editor type - * + * * Provides professional default layouts using ImGui's DockBuilder API, * similar to VSCode's workspace layouts. Each editor type has a custom * layout optimized for its workflow. - * + * * Features: * - Per-editor default layouts (Overworld, Dungeon, Graphics, etc.) * - Layout persistence and restoration diff --git a/src/app/editor/ui/menu_builder.cc b/src/app/editor/ui/menu_builder.cc index b3ab9ca9..775ed5b2 100644 --- a/src/app/editor/ui/menu_builder.cc +++ b/src/app/editor/ui/menu_builder.cc @@ -18,8 +18,7 @@ MenuBuilder& MenuBuilder::BeginMenu(const char* label, const char* icon) { MenuBuilder& MenuBuilder::BeginSubMenu(const char* label, const char* icon, EnabledCheck enabled) { - if (!current_menu_) - return *this; + if (!current_menu_) return *this; MenuItem item; item.type = MenuItem::Type::kSubMenuBegin; @@ -33,8 +32,7 @@ MenuBuilder& MenuBuilder::BeginSubMenu(const char* label, const char* icon, } MenuBuilder& MenuBuilder::EndMenu() { - if (!current_menu_) - return *this; + if (!current_menu_) return *this; // Check if we're ending a submenu or top-level menu // We need to track nesting depth to handle nested submenus correctly @@ -69,8 +67,7 @@ MenuBuilder& MenuBuilder::EndMenu() { MenuBuilder& MenuBuilder::Item(const char* label, const char* icon, Callback callback, const char* shortcut, EnabledCheck enabled, EnabledCheck checked) { - if (!current_menu_) - return *this; + if (!current_menu_) return *this; MenuItem item; item.type = MenuItem::Type::kItem; @@ -94,8 +91,7 @@ MenuBuilder& MenuBuilder::Item(const char* label, Callback callback, } MenuBuilder& MenuBuilder::Separator() { - if (!current_menu_) - return *this; + if (!current_menu_) return *this; MenuItem item; item.type = MenuItem::Type::kSeparator; @@ -104,8 +100,7 @@ MenuBuilder& MenuBuilder::Separator() { } MenuBuilder& MenuBuilder::DisabledItem(const char* label, const char* icon) { - if (!current_menu_) - return *this; + if (!current_menu_) return *this; MenuItem item; item.type = MenuItem::Type::kDisabled; diff --git a/src/app/editor/ui/menu_builder.h b/src/app/editor/ui/menu_builder.h index 6b2739c8..1cfc969d 100644 --- a/src/app/editor/ui/menu_builder.h +++ b/src/app/editor/ui/menu_builder.h @@ -21,9 +21,9 @@ namespace editor { /** * @class MenuBuilder * @brief Fluent interface for building ImGui menus with icons - * + * * Provides a cleaner, more maintainable way to construct menus: - * + * * MenuBuilder menu; * menu.BeginMenu("File", ICON_MD_FOLDER) * .Item("Open", ICON_MD_FILE_OPEN, []() { OpenFile(); }) diff --git a/src/app/editor/ui/ui_coordinator.cc b/src/app/editor/ui/ui_coordinator.cc index 052d22ea..3405cb7d 100644 --- a/src/app/editor/ui/ui_coordinator.cc +++ b/src/app/editor/ui/ui_coordinator.cc @@ -44,7 +44,6 @@ UICoordinator::UICoordinator( toast_manager_(toast_manager), popup_manager_(popup_manager), shortcut_manager_(shortcut_manager) { - // Initialize welcome screen with proper callbacks welcome_screen_ = std::make_unique(); @@ -97,10 +96,12 @@ UICoordinator::UICoordinator( void UICoordinator::DrawAllUI() { // Note: Theme styling is applied by ThemeManager, not here - // This is called from EditorManager::Update() - don't call menu bar stuff here + // This is called from EditorManager::Update() - don't call menu bar stuff + // here // Draw UI windows and dialogs - // Session dialogs are drawn by SessionCoordinator separately to avoid duplication + // Session dialogs are drawn by SessionCoordinator separately to avoid + // duplication DrawCommandPalette(); // Ctrl+Shift+P DrawGlobalSearch(); // Ctrl+Shift+K DrawWorkspacePresetDialogs(); // Save/Load workspace dialogs @@ -117,13 +118,11 @@ void UICoordinator::DrawRomSelector() { ImGui::SetNextItemWidth(ImGui::GetWindowWidth() / 6); if (ImGui::BeginCombo("##ROMSelector", current_rom->short_name().c_str())) { for (size_t i = 0; i < session_coordinator_.GetTotalSessionCount(); ++i) { - if (session_coordinator_.IsSessionClosed(i)) - continue; + if (session_coordinator_.IsSessionClosed(i)) continue; auto* session = static_cast(session_coordinator_.GetSession(i)); - if (!session) - continue; + if (!session) continue; Rom* rom = &session->rom; ImGui::PushID(static_cast(i)); @@ -209,10 +208,10 @@ void UICoordinator::DrawContextSensitiveCardControl() { // Get the currently active editor directly from EditorManager // This ensures we show cards for the correct editor that has focus auto* active_editor = editor_manager_->GetCurrentEditor(); - if (!active_editor) - return; + if (!active_editor) return; - // Only show card control for card-based editors (not palette, not assembly in legacy mode, etc.) + // Only show card control for card-based editors (not palette, not assembly in + // legacy mode, etc.) if (!editor_registry_.IsCardBasedEditor(active_editor->type())) { return; } @@ -284,8 +283,9 @@ void UICoordinator::SetSessionSwitcherVisible(bool visible) { // ============================================================================ void UICoordinator::DrawLayoutPresets() { - // TODO: [EditorManagerRefactor] Implement full layout preset UI with save/load - // For now, this is accessed via Window menu items that call workspace_manager directly + // TODO: [EditorManagerRefactor] Implement full layout preset UI with + // save/load For now, this is accessed via Window menu items that call + // workspace_manager directly } void UICoordinator::DrawWelcomeScreen() { @@ -342,8 +342,8 @@ void UICoordinator::DrawWelcomeScreen() { welcome_screen_manually_closed_ = true; } - // If an action was taken (ROM loaded, project opened), the welcome screen will auto-hide - // next frame when rom_is_loaded becomes true + // If an action was taken (ROM loaded, project opened), the welcome screen + // will auto-hide next frame when rom_is_loaded becomes true } void UICoordinator::DrawProjectHelp() { @@ -420,12 +420,10 @@ void UICoordinator::ShowDisplaySettings() { } void UICoordinator::HideCurrentEditorCards() { - if (!editor_manager_) - return; + if (!editor_manager_) return; auto* current_editor = editor_manager_->GetCurrentEditor(); - if (!current_editor) - return; + if (!current_editor) return; std::string category = editor_registry_.GetEditorCategory(current_editor->type()); @@ -434,13 +432,9 @@ void UICoordinator::HideCurrentEditorCards() { LOG_INFO("UICoordinator", "Hid all cards in category: %s", category.c_str()); } -void UICoordinator::ShowAllWindows() { - window_delegate_.ShowAllWindows(); -} +void UICoordinator::ShowAllWindows() { window_delegate_.ShowAllWindows(); } -void UICoordinator::HideAllWindows() { - window_delegate_.HideAllWindows(); -} +void UICoordinator::HideAllWindows() { window_delegate_.HideAllWindows(); } // Helper methods for drawing operations void UICoordinator::DrawSessionIndicator() { @@ -540,8 +534,7 @@ void UICoordinator::ApplyEditorTheme(EditorType type) { } void UICoordinator::DrawCommandPalette() { - if (!show_command_palette_) - return; + if (!show_command_palette_) return; using namespace ImGui; auto& theme = gui::ThemeManager::Get().GetCurrentTheme(); @@ -553,7 +546,6 @@ void UICoordinator::DrawCommandPalette() { bool show_palette = true; if (Begin(absl::StrFormat("%s Command Palette", ICON_MD_SEARCH).c_str(), &show_palette, ImGuiWindowFlags_NoCollapse)) { - // Search input with focus management SetNextItemWidth(-100); if (IsWindowAppearing()) { @@ -610,8 +602,7 @@ void UICoordinator::DrawCommandPalette() { } text_idx++; } - if (query_idx != query_lower.length()) - score = 0; + if (query_idx != query_lower.length()) score = 0; } if (score > 0) { @@ -635,7 +626,6 @@ void UICoordinator::DrawCommandPalette() { ImGuiTableFlags_ScrollY | ImGuiTableFlags_RowBg | ImGuiTableFlags_SizingStretchProp, ImVec2(0, -30))) { - TableSetupColumn("Command", ImGuiTableColumnFlags_WidthStretch, 0.5f); TableSetupColumn("Shortcut", ImGuiTableColumnFlags_WidthStretch, 0.3f); @@ -716,8 +706,7 @@ void UICoordinator::DrawCommandPalette() { } void UICoordinator::DrawGlobalSearch() { - if (!show_global_search_) - return; + if (!show_global_search_) return; ImGui::SetNextWindowPos(ImGui::GetMainViewport()->GetCenter(), ImGuiCond_Appearing, ImVec2(0.5f, 0.5f)); @@ -727,7 +716,6 @@ void UICoordinator::DrawGlobalSearch() { if (ImGui::Begin( absl::StrFormat("%s Global Search", ICON_MD_MANAGE_SEARCH).c_str(), &show_search, ImGuiWindowFlags_NoCollapse)) { - // Enhanced search input with focus management ImGui::SetNextItemWidth(-100); if (ImGui::IsWindowAppearing()) { @@ -749,7 +737,6 @@ void UICoordinator::DrawGlobalSearch() { // Tabbed search results for better organization if (ImGui::BeginTabBar("SearchResultTabs")) { - // Recent Files Tab if (ImGui::BeginTabItem( absl::StrFormat("%s Recent Files", ICON_MD_HISTORY).c_str())) { @@ -759,7 +746,6 @@ void UICoordinator::DrawGlobalSearch() { if (ImGui::BeginTable("RecentFilesTable", 3, ImGuiTableFlags_ScrollY | ImGuiTableFlags_RowBg | ImGuiTableFlags_SizingStretchProp)) { - ImGui::TableSetupColumn("File", ImGuiTableColumnFlags_WidthStretch, 0.6f); ImGui::TableSetupColumn("Type", ImGuiTableColumnFlags_WidthFixed, @@ -819,7 +805,6 @@ void UICoordinator::DrawGlobalSearch() { ImGuiTableFlags_ScrollY | ImGuiTableFlags_RowBg | ImGuiTableFlags_SizingStretchProp)) { - ImGui::TableSetupColumn("Type", ImGuiTableColumnFlags_WidthFixed, 100.0f); ImGui::TableSetupColumn("Label", ImGuiTableColumnFlags_WidthStretch, @@ -866,8 +851,7 @@ void UICoordinator::DrawGlobalSearch() { ++i) { std::string session_info = session_coordinator_.GetSessionDisplayName(i); - if (session_info == "[CLOSED SESSION]") - continue; + if (session_info == "[CLOSED SESSION]") continue; if (global_search_query_[0] != '\0' && session_info.find(global_search_query_) == std::string::npos) diff --git a/src/app/editor/ui/ui_coordinator.h b/src/app/editor/ui/ui_coordinator.h index 62e4be6f..b46e5a63 100644 --- a/src/app/editor/ui/ui_coordinator.h +++ b/src/app/editor/ui/ui_coordinator.h @@ -26,14 +26,14 @@ class ShortcutManager; /** * @class UICoordinator * @brief Handles all UI drawing operations and state management - * + * * Extracted from EditorManager to provide focused UI coordination: * - Drawing operations (menus, dialogs, screens) * - UI state management (visibility, focus, layout) * - Popup and dialog coordination * - Welcome screen and session UI * - Material Design theming and icons - * + * * This class follows the Single Responsibility Principle by focusing solely * on UI presentation and user interaction, delegating business logic to * specialized managers. diff --git a/src/app/editor/ui/welcome_screen.cc b/src/app/editor/ui/welcome_screen.cc index 6c727475..cfba8bbe 100644 --- a/src/app/editor/ui/welcome_screen.cc +++ b/src/app/editor/ui/welcome_screen.cc @@ -136,9 +136,7 @@ void DrawTriforceBackground(ImDrawList* draw_list, ImVec2 pos, float size, } // namespace -WelcomeScreen::WelcomeScreen() { - RefreshRecentProjects(); -} +WelcomeScreen::WelcomeScreen() { RefreshRecentProjects(); } bool WelcomeScreen::Show(bool* p_open) { // Update theme colors each frame @@ -446,7 +444,8 @@ void WelcomeScreen::UpdateAnimations() { (target - card_hover_scale_[i]) * ImGui::GetIO().DeltaTime * 10.0f; } - // Note: Triforce positions and particles are updated in Show() based on mouse position + // Note: Triforce positions and particles are updated in Show() based on mouse + // position } void WelcomeScreen::RefreshRecentProjects() { @@ -457,8 +456,7 @@ void WelcomeScreen::RefreshRecentProjects() { project::RecentFilesManager::GetInstance().GetRecentFiles(); for (const auto& filepath : recent_files) { - if (recent_projects_.size() >= kMaxRecentProjects) - break; + if (recent_projects_.size() >= kMaxRecentProjects) break; RecentProject project; project.filepath = filepath; @@ -543,15 +541,13 @@ void WelcomeScreen::DrawQuickActions() { ImGuiCol_ButtonActive, ImVec4(color.x * 1.2f, color.y * 1.2f, color.z * 1.2f, 1.0f)); - if (!enabled) - ImGui::BeginDisabled(); + if (!enabled) ImGui::BeginDisabled(); bool clicked = ImGui::Button(absl::StrFormat("%s %s", icon, text).c_str(), ImVec2(button_width, 38)); // Reduced from 45 to 38 - if (!enabled) - ImGui::EndDisabled(); + if (!enabled) ImGui::EndDisabled(); ImGui::PopStyleColor(3); @@ -851,7 +847,8 @@ void WelcomeScreen::DrawTemplatesSection() { } void WelcomeScreen::DrawTipsSection() { - // Static tip (or could rotate based on session start time rather than animation) + // Static tip (or could rotate based on session start time rather than + // animation) const char* tips[] = { "Press Ctrl+Shift+P to open the command palette", "Use z3ed agent for AI-powered ROM editing (Ctrl+Shift+A)", diff --git a/src/app/editor/ui/workspace_manager.cc b/src/app/editor/ui/workspace_manager.cc index e5663f28..dffeda89 100644 --- a/src/app/editor/ui/workspace_manager.cc +++ b/src/app/editor/ui/workspace_manager.cc @@ -1,6 +1,7 @@ #define IMGUI_DEFINE_MATH_OPERATORS #include "app/editor/ui/workspace_manager.h" + #include "absl/strings/str_format.h" #include "app/editor/system/editor_card_registry.h" #include "app/editor/system/toast_manager.h" @@ -38,8 +39,7 @@ absl::Status WorkspaceManager::ResetWorkspaceLayout() { } void WorkspaceManager::SaveWorkspacePreset(const std::string& name) { - if (name.empty()) - return; + if (name.empty()) return; std::string ini_name = absl::StrFormat("yaze_workspace_%s.ini", name.c_str()); ImGui::SaveIniSettingsToDisk(ini_name.c_str()); @@ -52,8 +52,7 @@ void WorkspaceManager::SaveWorkspacePreset(const std::string& name) { workspace_presets_.emplace_back(name); try { std::ostringstream ss; - for (const auto& n : workspace_presets_) - ss << n << "\n"; + for (const auto& n : workspace_presets_) ss << n << "\n"; // This should use a platform-agnostic path util::SaveFile("workspace_presets.txt", ss.str()); } catch (const std::exception& e) { @@ -68,8 +67,7 @@ void WorkspaceManager::SaveWorkspacePreset(const std::string& name) { } void WorkspaceManager::LoadWorkspacePreset(const std::string& name) { - if (name.empty()) - return; + if (name.empty()) return; std::string ini_name = absl::StrFormat("yaze_workspace_%s.ini", name.c_str()); ImGui::LoadIniSettingsFromDisk(ini_name.c_str()); last_workspace_preset_ = name; @@ -191,8 +189,7 @@ void WorkspaceManager::CloseAllFloatingWindows() { } size_t WorkspaceManager::GetActiveSessionCount() const { - if (!sessions_) - return 0; + if (!sessions_) return 0; size_t count = 0; for (const auto& session : *sessions_) { @@ -204,8 +201,7 @@ size_t WorkspaceManager::GetActiveSessionCount() const { } bool WorkspaceManager::HasDuplicateSession(const std::string& filepath) const { - if (!sessions_) - return false; + if (!sessions_) return false; for (const auto& session : *sessions_) { if (session.filepath == filepath && session.rom && diff --git a/src/app/editor/ui/workspace_manager.h b/src/app/editor/ui/workspace_manager.h index 2dc9196f..c6622d5a 100644 --- a/src/app/editor/ui/workspace_manager.h +++ b/src/app/editor/ui/workspace_manager.h @@ -3,6 +3,7 @@ #include #include + #include "absl/status/status.h" namespace yaze { diff --git a/src/app/emu/audio/apu.cc b/src/app/emu/audio/apu.cc index 47044e54..0197bedd 100644 --- a/src/app/emu/audio/apu.cc +++ b/src/app/emu/audio/apu.cc @@ -28,7 +28,8 @@ static constexpr uint64_t kApuCyclesDenominatorPal = // Legacy floating-point ratios (deprecated, kept for reference) // static const double apuCyclesPerMaster = (32040 * 32) / (1364 * 262 * 60.0); -// static const double apuCyclesPerMasterPal = (32040 * 32) / (1364 * 312 * 50.0); +// static const double apuCyclesPerMasterPal = (32040 * 32) / (1364 * 312 +// * 50.0); // SNES IPL ROM - Anomie's official hardware dump (64 bytes) // With our critical fixes: CMP Z flag, multi-step bstep, address preservation @@ -42,9 +43,7 @@ static const uint8_t bootRom[0x40] = { // Helper to reset the cycle tracking on emulator reset static uint64_t g_last_master_cycles = 0; -static void ResetCycleTracking() { - g_last_master_cycles = 0; -} +static void ResetCycleTracking() { g_last_master_cycles = 0; } void Apu::Init() { ram.resize(0x10000); @@ -90,8 +89,9 @@ void Apu::RunCycles(uint64_t master_cycles) { uint64_t master_delta = master_cycles - g_last_master_cycles; g_last_master_cycles = master_cycles; - // Convert CPU master cycles to APU cycles using fixed-point ratio (no floating-point drift) - // target_apu_cycles = cycles_ + (master_delta * numerator) / denominator + // Convert CPU master cycles to APU cycles using fixed-point ratio (no + // floating-point drift) target_apu_cycles = cycles_ + (master_delta * + // numerator) / denominator uint64_t numerator = memory_.pal_timing() ? kApuCyclesNumeratorPal : kApuCyclesNumerator; uint64_t denominator = @@ -107,12 +107,14 @@ void Apu::RunCycles(uint64_t master_cycles) { static bool logged_transfer_state = false; while (cycles_ < target_apu_cycles) { - // Execute one SPC700 opcode (variable cycles) then advance APU cycles accordingly. + // Execute one SPC700 opcode (variable cycles) then advance APU cycles + // accordingly. uint16_t old_pc = spc700_.PC; uint16_t current_pc = spc700_.PC; // IPL ROM protocol analysis - let it run to see what happens - // Log IPL ROM transfer loop activity (every 1000 cycles when in critical range) + // Log IPL ROM transfer loop activity (every 1000 cycles when in critical + // range) static uint64_t last_ipl_log = 0; if (rom_readable_ && current_pc >= 0xFFD6 && current_pc <= 0xFFED) { if (cycles_ - last_ipl_log > 10000) { @@ -164,7 +166,8 @@ void Apu::RunCycles(uint64_t master_cycles) { } // Advance APU cycles based on actual SPC700 instruction timing - // Each Cycle() call: ticks DSP every 32 cycles, updates timers, increments cycles_ + // Each Cycle() call: ticks DSP every 32 cycles, updates timers, increments + // cycles_ for (int i = 0; i < spc_cycles; ++i) { Cycle(); } @@ -293,8 +296,7 @@ void Apu::Write(uint16_t adr, uint8_t val) { break; } case 0xf3: { - if (dsp_adr_ < 0x80) - dsp_.Write(dsp_adr_, val); + if (dsp_adr_ < 0x80) dsp_.Write(dsp_adr_, val); break; } case 0xf4: @@ -317,7 +319,8 @@ void Apu::Write(uint16_t adr, uint8_t val) { } // Track when SPC enters transfer loop (echoes counter back) - // PC is at $FFE2 when the MOVSY write completes (CB F4 is 2 bytes at $FFE0) + // PC is at $FFE2 when the MOVSY write completes (CB F4 is 2 bytes at + // $FFE0) if (adr == 0xf4 && spc700_.PC == 0xFFE2 && rom_readable_) { // SPC is echoing counter back - we're in data transfer phase if (!in_transfer_ && ram[0x00] != 0 && ram[0x01] == 0) { @@ -359,9 +362,7 @@ void Apu::SpcWrite(uint16_t adr, uint8_t val) { Write(adr, val); } -void Apu::SpcIdle(bool waiting) { - Cycle(); -} +void Apu::SpcIdle(bool waiting) { Cycle(); } } // namespace emu } // namespace yaze diff --git a/src/app/emu/audio/audio_backend.cc b/src/app/emu/audio/audio_backend.cc index c505a343..5bf391b9 100644 --- a/src/app/emu/audio/audio_backend.cc +++ b/src/app/emu/audio/audio_backend.cc @@ -3,8 +3,10 @@ #include "app/emu/audio/audio_backend.h" #include + #include #include + #include "util/log.h" namespace yaze { @@ -15,9 +17,7 @@ namespace audio { // SDL2AudioBackend Implementation // ============================================================================ -SDL2AudioBackend::~SDL2AudioBackend() { - Shutdown(); -} +SDL2AudioBackend::~SDL2AudioBackend() { Shutdown(); } bool SDL2AudioBackend::Initialize(const AudioConfig& config) { if (initialized_) { @@ -78,8 +78,7 @@ bool SDL2AudioBackend::Initialize(const AudioConfig& config) { } void SDL2AudioBackend::Shutdown() { - if (!initialized_) - return; + if (!initialized_) return; if (audio_stream_) { SDL_FreeAudioStream(audio_stream_); @@ -100,27 +99,23 @@ void SDL2AudioBackend::Shutdown() { } void SDL2AudioBackend::Play() { - if (!initialized_) - return; + if (!initialized_) return; SDL_PauseAudioDevice(device_id_, 0); } void SDL2AudioBackend::Pause() { - if (!initialized_) - return; + if (!initialized_) return; SDL_PauseAudioDevice(device_id_, 1); } void SDL2AudioBackend::Stop() { - if (!initialized_) - return; + if (!initialized_) return; Clear(); SDL_PauseAudioDevice(device_id_, 1); } void SDL2AudioBackend::Clear() { - if (!initialized_) - return; + if (!initialized_) return; SDL_ClearQueuedAudio(device_id_); if (audio_stream_) { SDL_AudioStreamClear(audio_stream_); @@ -128,8 +123,7 @@ void SDL2AudioBackend::Clear() { } bool SDL2AudioBackend::QueueSamples(const int16_t* samples, int num_samples) { - if (!initialized_ || !samples) - return false; + if (!initialized_ || !samples) return false; // OPTIMIZATION: Skip volume scaling if volume is 100% (common case) if (volume_ == 1.0f) { @@ -174,8 +168,7 @@ bool SDL2AudioBackend::QueueSamples(const int16_t* samples, int num_samples) { } bool SDL2AudioBackend::QueueSamples(const float* samples, int num_samples) { - if (!initialized_ || !samples) - return false; + if (!initialized_ || !samples) return false; // Convert float to int16 std::vector int_samples(num_samples); @@ -242,8 +235,7 @@ bool SDL2AudioBackend::QueueSamplesNative(const int16_t* samples, AudioStatus SDL2AudioBackend::GetStatus() const { AudioStatus status; - if (!initialized_) - return status; + if (!initialized_) return status; status.is_playing = (SDL_GetAudioDeviceStatus(device_id_) == SDL_AUDIO_PLAYING); @@ -262,18 +254,13 @@ AudioStatus SDL2AudioBackend::GetStatus() const { return status; } -bool SDL2AudioBackend::IsInitialized() const { - return initialized_; -} +bool SDL2AudioBackend::IsInitialized() const { return initialized_; } -AudioConfig SDL2AudioBackend::GetConfig() const { - return config_; -} +AudioConfig SDL2AudioBackend::GetConfig() const { return config_; } void SDL2AudioBackend::SetAudioStreamResampling(bool enable, int native_rate, int channels) { - if (!initialized_) - return; + if (!initialized_) return; if (!enable) { if (audio_stream_) { @@ -320,9 +307,7 @@ void SDL2AudioBackend::SetVolume(float volume) { volume_ = std::clamp(volume, 0.0f, 1.0f); } -float SDL2AudioBackend::GetVolume() const { - return volume_; -} +float SDL2AudioBackend::GetVolume() const { return volume_; } // ============================================================================ // AudioBackendFactory Implementation diff --git a/src/app/emu/audio/audio_backend.h b/src/app/emu/audio/audio_backend.h index 82c46d95..cc3091c5 100644 --- a/src/app/emu/audio/audio_backend.h +++ b/src/app/emu/audio/audio_backend.h @@ -1,5 +1,6 @@ // audio_backend.h - Audio Backend Abstraction Layer -// Provides interface for swapping audio implementations (SDL2, SDL3, other libs) +// Provides interface for swapping audio implementations (SDL2, SDL3, other +// libs) #ifndef YAZE_APP_EMU_AUDIO_AUDIO_BACKEND_H #define YAZE_APP_EMU_AUDIO_AUDIO_BACKEND_H @@ -39,7 +40,7 @@ struct AudioStatus { /** * @brief Abstract audio backend interface - * + * * Allows swapping between SDL2, SDL3, or custom audio implementations * without changing emulator/music editor code. */ diff --git a/src/app/emu/audio/dsp.cc b/src/app/emu/audio/dsp.cc index 788c86e0..79dc946c 100644 --- a/src/app/emu/audio/dsp.cc +++ b/src/app/emu/audio/dsp.cc @@ -127,9 +127,7 @@ void Dsp::Reset() { lastFrameBoundary = 0; } -void Dsp::NewFrame() { - lastFrameBoundary = sampleOffset; -} +void Dsp::NewFrame() { lastFrameBoundary = sampleOffset; } void Dsp::Cycle() { sampleOutL = 0; @@ -158,13 +156,10 @@ static int clamp16(int val) { return val < -0x8000 ? -0x8000 : (val > 0x7fff ? 0x7fff : val); } -static int clip16(int val) { - return (int16_t)(val & 0xffff); -} +static int clip16(int val) { return (int16_t)(val & 0xffff); } bool Dsp::CheckCounter(int rate) { - if (rate == 0) - return false; + if (rate == 0) return false; return ((counter + rateOffsets[rate]) % rateValues[rate]) == 0; } @@ -225,8 +220,7 @@ void Dsp::CycleChannel(int ch) { // get current brr header and get sample address channel[ch].brrHeader = aram_[channel[ch].decodeOffset]; uint16_t samplePointer = dirPage + 4 * channel[ch].srcn; - if (channel[ch].startDelay == 0) - samplePointer += 2; + if (channel[ch].startDelay == 0) samplePointer += 2; uint16_t sampleAdr = aram_[samplePointer] | (aram_[(samplePointer + 1) & 0xffff] << 8); // handle starting of sample @@ -293,8 +287,7 @@ void Dsp::CycleChannel(int ch) { // update pitch counter channel[ch].pitchCounter &= 0x3fff; channel[ch].pitchCounter += pitch; - if (channel[ch].pitchCounter > 0x7fff) - channel[ch].pitchCounter = 0x7fff; + if (channel[ch].pitchCounter > 0x7fff) channel[ch].pitchCounter = 0x7fff; // set outputs ram[(ch << 4) | 8] = channel[ch].gain >> 4; ram[(ch << 4) | 9] = sample >> 8; @@ -367,8 +360,7 @@ void Dsp::HandleGain(int ch) { } } // store new value - if (CheckCounter(rate)) - channel[ch].gain = newGain; + if (CheckCounter(rate)) channel[ch].gain = newGain; } int16_t Dsp::GetSample(int ch) { @@ -402,8 +394,7 @@ void Dsp::DecodeBrr(int ch) { 0xffff]; s = curByte >> 4; } - if (s > 7) - s -= 16; + if (s > 7) s -= 16; if (shift <= 0xc) { s = (s << shift) >> 1; } else { @@ -425,8 +416,7 @@ void Dsp::DecodeBrr(int ch) { old = channel[ch].decodeBuffer[bOff + i] >> 1; } channel[ch].bufferOffset += 4; - if (channel[ch].bufferOffset >= 12) - channel[ch].bufferOffset = 0; + if (channel[ch].bufferOffset >= 12) channel[ch].bufferOffset = 0; } void Dsp::HandleNoise() { @@ -436,9 +426,7 @@ void Dsp::HandleNoise() { } } -uint8_t Dsp::Read(uint8_t adr) { - return ram[adr]; -} +uint8_t Dsp::Read(uint8_t adr) { return ram[adr]; } void Dsp::Write(uint8_t adr, uint8_t val) { int ch = adr >> 4; @@ -686,8 +674,7 @@ void Dsp::GetSamples(int16_t* sample_data, int samples_per_frame, location -= native_per_frame; // Ensure location is within valid range - while (location < 0) - location += 0x400; + while (location < 0) location += 0x400; for (int i = 0; i < samples_per_frame; i++) { const int idx = static_cast(location) & 0x3ff; diff --git a/src/app/emu/audio/internal/addressing.cc b/src/app/emu/audio/internal/addressing.cc index e6e71906..0f05e961 100644 --- a/src/app/emu/audio/internal/addressing.cc +++ b/src/app/emu/audio/internal/addressing.cc @@ -76,14 +76,10 @@ uint16_t Spc700::ind_p() { } // Immediate -uint16_t Spc700::imm() { - return PC++; -} +uint16_t Spc700::imm() { return PC++; } // Direct page -uint8_t Spc700::dp() { - return ReadOpcode() | (PSW.P << 8); -} +uint8_t Spc700::dp() { return ReadOpcode() | (PSW.P << 8); } // Direct page indexed by X uint8_t Spc700::dp_plus_x() { @@ -118,18 +114,14 @@ uint16_t Spc700::dp_dp(uint8_t* src) { return ReadOpcode() | (PSW.P << 8); } -uint16_t Spc700::abs() { - return ReadOpcodeWord(); -} +uint16_t Spc700::abs() { return ReadOpcodeWord(); } int8_t Spc700::rel() { PC++; return static_cast(read(PC)); } -uint8_t Spc700::i() { - return read((PSW.P << 8) + X); -} +uint8_t Spc700::i() { return read((PSW.P << 8) + X); } uint8_t Spc700::i_postinc() { uint8_t value = read((PSW.P << 8) + X); diff --git a/src/app/emu/audio/internal/instructions.cc b/src/app/emu/audio/internal/instructions.cc index 50ae5e10..f26d1dbc 100644 --- a/src/app/emu/audio/internal/instructions.cc +++ b/src/app/emu/audio/internal/instructions.cc @@ -382,59 +382,45 @@ void Spc700::DIV(uint8_t operand) { // Note: Branch timing is handled in DoBranch() in spc700.cc // These helpers are only used by old code paths -void Spc700::BRA(int8_t offset) { - PC += offset; -} +void Spc700::BRA(int8_t offset) { PC += offset; } void Spc700::BEQ(int8_t offset) { - if (PSW.Z) - PC += offset; + if (PSW.Z) PC += offset; } void Spc700::BNE(int8_t offset) { - if (!PSW.Z) - PC += offset; + if (!PSW.Z) PC += offset; } void Spc700::BCS(int8_t offset) { - if (PSW.C) - PC += offset; + if (PSW.C) PC += offset; } void Spc700::BCC(int8_t offset) { - if (!PSW.C) - PC += offset; + if (!PSW.C) PC += offset; } void Spc700::BVS(int8_t offset) { - if (PSW.V) - PC += offset; + if (PSW.V) PC += offset; } void Spc700::BVC(int8_t offset) { - if (!PSW.V) - PC += offset; + if (!PSW.V) PC += offset; } void Spc700::BMI(int8_t offset) { - if (PSW.N) - PC += offset; + if (PSW.N) PC += offset; } void Spc700::BPL(int8_t offset) { - if (!PSW.N) - PC += offset; + if (!PSW.N) PC += offset; } void Spc700::BBS(uint8_t bit, uint8_t operand) { - if (operand & (1 << bit)) - PC += rel(); + if (operand & (1 << bit)) PC += rel(); } void Spc700::BBC(uint8_t bit, uint8_t operand) { - if (!(operand & (1 << bit))) - PC += rel(); + if (!(operand & (1 << bit))) PC += rel(); } // --------------------------------------------------------------------------- // Jump and Call Instructions // --------------------------------------------------------------------------- -void Spc700::JMP(uint16_t address) { - PC = address; -} +void Spc700::JMP(uint16_t address) { PC = address; } void Spc700::CALL(uint16_t address) { uint16_t return_address = PC + 2; @@ -465,9 +451,7 @@ void Spc700::BRK() { PC = read_word(0xFFDE); } -void Spc700::RET() { - PC = pull_word(); -} +void Spc700::RET() { PC = pull_word(); } void Spc700::RETI() { PSW = ByteToFlags(pull_byte()); @@ -478,25 +462,17 @@ void Spc700::RETI() { // Stack Instructions // --------------------------------------------------------------------------- -void Spc700::PUSH(uint8_t operand) { - push_byte(operand); -} +void Spc700::PUSH(uint8_t operand) { push_byte(operand); } -void Spc700::POP(uint8_t& operand) { - operand = pull_byte(); -} +void Spc700::POP(uint8_t& operand) { operand = pull_byte(); } // --------------------------------------------------------------------------- // Bit Manipulation Instructions // --------------------------------------------------------------------------- -void Spc700::SET1(uint8_t bit, uint8_t& operand) { - operand |= (1 << bit); -} +void Spc700::SET1(uint8_t bit, uint8_t& operand) { operand |= (1 << bit); } -void Spc700::CLR1(uint8_t bit, uint8_t& operand) { - operand &= ~(1 << bit); -} +void Spc700::CLR1(uint8_t bit, uint8_t& operand) { operand &= ~(1 << bit); } void Spc700::TSET1(uint8_t bit, uint8_t& operand) { PSW.C = (operand & (1 << bit)) != 0; @@ -541,31 +517,17 @@ void Spc700::MOV1(uint8_t bit, uint8_t& operand) { // Flag Instructions // --------------------------------------------------------------------------- -void Spc700::CLRC() { - PSW.C = false; -} -void Spc700::SETC() { - PSW.C = true; -} -void Spc700::NOTC() { - PSW.C = !PSW.C; -} +void Spc700::CLRC() { PSW.C = false; } +void Spc700::SETC() { PSW.C = true; } +void Spc700::NOTC() { PSW.C = !PSW.C; } void Spc700::CLRV() { PSW.V = false; PSW.H = false; } -void Spc700::CLRP() { - PSW.P = false; -} -void Spc700::SETP() { - PSW.P = true; -} -void Spc700::EI() { - PSW.I = true; -} -void Spc700::DI() { - PSW.I = false; -} +void Spc700::CLRP() { PSW.P = false; } +void Spc700::SETP() { PSW.P = true; } +void Spc700::EI() { PSW.I = true; } +void Spc700::DI() { PSW.I = false; } // --------------------------------------------------------------------------- // Special Instructions diff --git a/src/app/emu/audio/internal/spc700_accurate_cycles.h b/src/app/emu/audio/internal/spc700_accurate_cycles.h index 4e52189a..42599a96 100644 --- a/src/app/emu/audio/internal/spc700_accurate_cycles.h +++ b/src/app/emu/audio/internal/spc700_accurate_cycles.h @@ -1,4 +1,5 @@ -// spc700_accurate_cycles.h - Cycle counts based on https://snes.nesdev.org/wiki/SPC-700_instruction_set +// spc700_accurate_cycles.h - Cycle counts based on +// https://snes.nesdev.org/wiki/SPC-700_instruction_set #pragma once diff --git a/src/app/emu/audio/spc700.cc b/src/app/emu/audio/spc700.cc index 10edf581..9b8ccbe0 100644 --- a/src/app/emu/audio/spc700.cc +++ b/src/app/emu/audio/spc700.cc @@ -4,19 +4,20 @@ #include #include #include -#include "core/features.h" -#include "util/log.h" #include "app/emu/audio/internal/opcodes.h" #include "app/emu/audio/internal/spc700_accurate_cycles.h" +#include "core/features.h" +#include "util/log.h" namespace yaze { namespace emu { void Spc700::Reset(bool hard) { if (hard) { - // DON'T set PC = 0 here! The reset sequence in Step() will load PC from the reset vector. - // Setting PC = 0 here would overwrite the correct value loaded from $FFFE-$FFFF. + // DON'T set PC = 0 here! The reset sequence in Step() will load PC from the + // reset vector. Setting PC = 0 here would overwrite the correct value + // loaded from $FFFE-$FFFF. A = 0; X = 0; Y = 0; @@ -951,8 +952,7 @@ void Spc700::ExecuteInstructions(uint8_t opcode) { } case 0x9e: { // div imp read(PC); - for (int i = 0; i < 10; i++) - callbacks_.idle(false); + for (int i = 0; i < 10; i++) callbacks_.idle(false); PSW.H = (X & 0xf) <= (Y & 0xf); int yva = (Y << 8) | A; int x = X << 9; @@ -960,10 +960,8 @@ void Spc700::ExecuteInstructions(uint8_t opcode) { yva <<= 1; yva |= (yva & 0x20000) ? 1 : 0; yva &= 0x1ffff; - if (yva >= x) - yva ^= 1; - if (yva & 1) - yva -= x; + if (yva >= x) yva ^= 1; + if (yva & 1) yva -= x; yva &= 0x1ffff; } Y = yva >> 9; @@ -1190,8 +1188,7 @@ void Spc700::ExecuteInstructions(uint8_t opcode) { } case 0xcf: { // mul imp read(PC); - for (int i = 0; i < 7; i++) - callbacks_.idle(false); + for (int i = 0; i < 7; i++) callbacks_.idle(false); uint16_t result = A * Y; A = result & 0xff; Y = result >> 8; @@ -1216,7 +1213,8 @@ void Spc700::ExecuteInstructions(uint8_t opcode) { break; } case 0xd7: { // movs idy - // CRITICAL: Only call idy() once in bstep=0, reuse saved address in bstep=1 + // CRITICAL: Only call idy() once in bstep=0, reuse saved address in + // bstep=1 if (bstep == 0) { adr = idy(); // Save address for bstep=1 } @@ -1363,8 +1361,7 @@ void Spc700::ExecuteInstructions(uint8_t opcode) { PC - 1); } read(PC); - for (int i = 0; i < 4; ++i) - callbacks_.idle(true); + for (int i = 0; i < 4; ++i) callbacks_.idle(true); break; } case 0xf0: { // beq rel diff --git a/src/app/emu/audio/spc700.h b/src/app/emu/audio/spc700.h index 38304f16..f6f11432 100644 --- a/src/app/emu/audio/spc700.h +++ b/src/app/emu/audio/spc700.h @@ -140,8 +140,8 @@ class Spc700 { void RunOpcode(); - // New atomic step function - executes one complete instruction and returns cycles consumed - // This is the preferred method for cycle-accurate emulation + // New atomic step function - executes one complete instruction and returns + // cycles consumed This is the preferred method for cycle-accurate emulation int Step(); // Get the number of cycles consumed by the last opcode execution diff --git a/src/app/emu/cpu/cpu.cc b/src/app/emu/cpu/cpu.cc index 97060a04..990073ee 100644 --- a/src/app/emu/cpu/cpu.cc +++ b/src/app/emu/cpu/cpu.cc @@ -169,8 +169,9 @@ void Cpu::RunOpcode() { } // LoadSongBank routine ($8888-$88FF) - This is where handshake happens! - // LOGIC: Track CPU's journey through audio initialization to identify where it gets stuck. - // We log key waypoints to understand if CPU reaches handshake write instructions. + // LOGIC: Track CPU's journey through audio initialization to identify + // where it gets stuck. We log key waypoints to understand if CPU reaches + // handshake write instructions. if (cur_pc >= 0x8888 && cur_pc <= 0x88FF) { // Log entry if (cur_pc == 0x8888) { @@ -179,8 +180,9 @@ void Cpu::RunOpcode() { X); } - // DISCOVERY: Log every unique PC in this range to see the execution path - // This helps identify if CPU is looping, stuck, or simply not reaching write instructions + // DISCOVERY: Log every unique PC in this range to see the execution + // path This helps identify if CPU is looping, stuck, or simply not + // reaching write instructions static int exec_count_8888 = 0; if (exec_count_8888++ < 100 && !logged_routines[cur_pc]) { LOG_INFO("CPU_AUDIO", @@ -221,7 +223,8 @@ void Cpu::RunOpcode() { PB, PC - 1, opcode); } - // Debug: Log if stuck at same PC for extended period (after first 200 instructions) + // Debug: Log if stuck at same PC for extended period (after first 200 + // instructions) static uint16_t last_stuck_pc = 0xFFFF; static int stuck_count = 0; if (instruction_count >= 200) { @@ -273,8 +276,7 @@ void Cpu::ExecuteInstruction(uint8_t opcode) { case 0x00: { // brk imm(s) uint32_t vector = (E) ? 0xfffe : 0xffe6; ReadOpcode(); - if (!E) - PushByte(PB); + if (!E) PushByte(PB); PushWord(PC, false); PushByte(status); SetInterruptFlag(true); @@ -292,8 +294,7 @@ void Cpu::ExecuteInstruction(uint8_t opcode) { case 0x02: { // cop imm(s) uint32_t vector = (E) ? 0xfff4 : 0xffe4; ReadOpcode(); - if (!E) - PushByte(PB); + if (!E) PushByte(PB); PushWord(PC, false); PushByte(status); SetInterruptFlag(true); @@ -1977,8 +1978,9 @@ void Cpu::ExecuteInstruction(uint8_t opcode) { break; } } - // REMOVED: Old log_instructions_ check - now using on_instruction_executed_ callback - // which is more efficient and always active (records to DisassemblyViewer) + // REMOVED: Old log_instructions_ check - now using on_instruction_executed_ + // callback which is more efficient and always active (records to + // DisassemblyViewer) LogInstructions(cache_pc, opcode, operand, immediate, accumulator_mode); } @@ -2012,7 +2014,8 @@ void Cpu::LogInstructions(uint16_t PC, uint8_t opcode, uint16_t operand, const std::string& mnemonic = opcode_to_mnemonic.at(opcode); // ALWAYS record to DisassemblyViewer (sparse, Mesen-style, zero cost) - // The callback only fires if set, and DisassemblyViewer only stores unique addresses + // The callback only fires if set, and DisassemblyViewer only stores unique + // addresses // - First execution: Add to map (O(log n)) // - Subsequent: Increment counter (O(log n)) // - Total overhead: ~0.1% even with millions of instructions diff --git a/src/app/emu/cpu/cpu.h b/src/app/emu/cpu/cpu.h index d1faa6e1..d47a4651 100644 --- a/src/app/emu/cpu/cpu.h +++ b/src/app/emu/cpu/cpu.h @@ -166,8 +166,7 @@ class Cpu { uint16_t ReadOpcodeWord(bool int_check = false) { uint8_t value = ReadOpcode(); - if (int_check) - CheckInt(); + if (int_check) CheckInt(); return value | (ReadOpcode() << 8); } @@ -181,12 +180,12 @@ class Cpu { return low | (high << 8); } - // Read 16-bit value from two separate addresses (for wrapping/crossing boundaries) + // Read 16-bit value from two separate addresses (for wrapping/crossing + // boundaries) uint16_t ReadWord(uint32_t address, uint32_t address_high, bool int_check = false) { uint8_t value = ReadByte(address); - if (int_check) - CheckInt(); + if (int_check) CheckInt(); uint8_t value2 = ReadByte(address_high); return value | (value2 << 8); } @@ -205,13 +204,11 @@ class Cpu { bool reversed = false, bool int_check = false) { if (reversed) { callbacks_.write_byte(address_high, value >> 8); - if (int_check) - CheckInt(); + if (int_check) CheckInt(); callbacks_.write_byte(address, value & 0xFF); } else { callbacks_.write_byte(address, value & 0xFF); - if (int_check) - CheckInt(); + if (int_check) CheckInt(); callbacks_.write_byte(address_high, value >> 8); } } @@ -224,13 +221,11 @@ class Cpu { void PushByte(uint8_t value) { callbacks_.write_byte(SP(), value); SetSP(SP() - 1); - if (E) - SetSP((SP() & 0xff) | 0x100); + if (E) SetSP((SP() & 0xff) | 0x100); } void PushWord(uint16_t value, bool int_check = false) { PushByte(value >> 8); - if (int_check) - CheckInt(); + if (int_check) CheckInt(); PushByte(value & 0xFF); } void PushLong(uint32_t value) { // Push 24-bit value @@ -240,14 +235,12 @@ class Cpu { uint8_t PopByte() { SetSP(SP() + 1); - if (E) - SetSP((SP() & 0xff) | 0x100); + if (E) SetSP((SP() & 0xff) | 0x100); return ReadByte(SP()); } uint16_t PopWord(bool int_check = false) { uint8_t low = PopByte(); - if (int_check) - CheckInt(); + if (int_check) CheckInt(); return low | (PopByte() << 8); } uint32_t PopLong() { // Pop 24-bit value @@ -257,8 +250,7 @@ class Cpu { } void DoBranch(bool check) { - if (!check) - CheckInt(); + if (!check) CheckInt(); uint8_t value = ReadOpcode(); if (check) { CheckInt(); diff --git a/src/app/emu/cpu/internal/addressing.cc b/src/app/emu/cpu/internal/addressing.cc index 7422a252..2f7ed8ef 100644 --- a/src/app/emu/cpu/internal/addressing.cc +++ b/src/app/emu/cpu/internal/addressing.cc @@ -27,8 +27,7 @@ uint32_t Cpu::Immediate(uint32_t* low, bool xFlag) { uint32_t Cpu::AdrDpx(uint32_t* low) { uint8_t adr = ReadOpcode(); - if (D & 0xff) - callbacks_.idle(false); // dpr not 0: 1 extra cycle + if (D & 0xff) callbacks_.idle(false); // dpr not 0: 1 extra cycle callbacks_.idle(false); *low = (D + adr + X) & 0xffff; return (D + adr + X + 1) & 0xffff; @@ -36,8 +35,7 @@ uint32_t Cpu::AdrDpx(uint32_t* low) { uint32_t Cpu::AdrDpy(uint32_t* low) { uint8_t adr = ReadOpcode(); - if (D & 0xff) - callbacks_.idle(false); // dpr not 0: 1 extra cycle + if (D & 0xff) callbacks_.idle(false); // dpr not 0: 1 extra cycle callbacks_.idle(false); *low = (D + adr + Y) & 0xffff; return (D + adr + Y + 1) & 0xffff; @@ -45,8 +43,7 @@ uint32_t Cpu::AdrDpy(uint32_t* low) { uint32_t Cpu::AdrIdp(uint32_t* low) { uint8_t adr = ReadOpcode(); - if (D & 0xff) - callbacks_.idle(false); // dpr not 0: 1 extra cycle + if (D & 0xff) callbacks_.idle(false); // dpr not 0: 1 extra cycle uint16_t pointer = ReadWord((D + adr) & 0xffff); *low = (DB << 16) + pointer; return ((DB << 16) + pointer + 1) & 0xffffff; @@ -54,8 +51,7 @@ uint32_t Cpu::AdrIdp(uint32_t* low) { uint32_t Cpu::AdrIdy(uint32_t* low, bool write) { uint8_t adr = ReadOpcode(); - if (D & 0xff) - callbacks_.idle(false); // dpr not 0: 1 extra cycle + if (D & 0xff) callbacks_.idle(false); // dpr not 0: 1 extra cycle uint16_t pointer = ReadWord((D + adr) & 0xffff); // writing opcode or x = 0 or page crossed: 1 extra cycle if (write || !GetIndexSize() || ((pointer >> 8) != ((pointer + Y) >> 8))) @@ -66,8 +62,7 @@ uint32_t Cpu::AdrIdy(uint32_t* low, bool write) { uint32_t Cpu::AdrIdl(uint32_t* low) { uint8_t adr = ReadOpcode(); - if (D & 0xff) - callbacks_.idle(false); // dpr not 0: 1 extra cycle + if (D & 0xff) callbacks_.idle(false); // dpr not 0: 1 extra cycle uint32_t pointer = ReadWord((D + adr) & 0xffff); pointer |= ReadByte((D + adr + 2) & 0xffff) << 16; *low = pointer; @@ -76,8 +71,7 @@ uint32_t Cpu::AdrIdl(uint32_t* low) { uint32_t Cpu::AdrIly(uint32_t* low) { uint8_t adr = ReadOpcode(); - if (D & 0xff) - callbacks_.idle(false); // dpr not 0: 1 extra cycle + if (D & 0xff) callbacks_.idle(false); // dpr not 0: 1 extra cycle uint32_t pointer = ReadWord((D + adr) & 0xffff); pointer |= ReadByte((D + adr + 2) & 0xffff) << 16; *low = (pointer + Y) & 0xffffff; @@ -140,8 +134,7 @@ uint32_t Cpu::AdrAlx(uint32_t* low) { uint32_t Cpu::AdrDp(uint32_t* low) { uint8_t adr = ReadOpcode(); - if (D & 0xff) - callbacks_.idle(false); // dpr not 0: 1 extra cycle + if (D & 0xff) callbacks_.idle(false); // dpr not 0: 1 extra cycle *low = (D + adr) & 0xffff; return (D + adr + 1) & 0xffff; } @@ -164,8 +157,7 @@ uint16_t Cpu::DirectPageIndexedY() { uint32_t Cpu::AdrIdx(uint32_t* low) { uint8_t adr = ReadOpcode(); - if (D & 0xff) - callbacks_.idle(false); + if (D & 0xff) callbacks_.idle(false); callbacks_.idle(false); uint16_t pointer = ReadWord((D + adr + X) & 0xffff); *low = (DB << 16) + pointer; diff --git a/src/app/emu/cpu/internal/instructions.cc b/src/app/emu/cpu/internal/instructions.cc index 2ea6b2d1..720b3dd5 100644 --- a/src/app/emu/cpu/internal/instructions.cc +++ b/src/app/emu/cpu/internal/instructions.cc @@ -34,16 +34,14 @@ void Cpu::Adc(uint32_t low, uint32_t high) { int result = 0; if (GetDecimalFlag()) { result = (A & 0xf) + (value & 0xf) + GetCarryFlag(); - if (result > 0x9) - result = ((result + 0x6) & 0xf) + 0x10; + if (result > 0x9) result = ((result + 0x6) & 0xf) + 0x10; result = (A & 0xf0) + (value & 0xf0) + result; } else { result = (A & 0xff) + value + GetCarryFlag(); } SetOverflowFlag((A & 0x80) == (value & 0x80) && (value & 0x80) != (result & 0x80)); - if (GetDecimalFlag() && result > 0x9f) - result += 0x60; + if (GetDecimalFlag() && result > 0x9f) result += 0x60; SetCarryFlag(result > 0xff); A = (A & 0xff00) | (result & 0xff); } else { @@ -51,22 +49,18 @@ void Cpu::Adc(uint32_t low, uint32_t high) { int result = 0; if (GetDecimalFlag()) { result = (A & 0xf) + (value & 0xf) + GetCarryFlag(); - if (result > 0x9) - result = ((result + 0x6) & 0xf) + 0x10; + if (result > 0x9) result = ((result + 0x6) & 0xf) + 0x10; result = (A & 0xf0) + (value & 0xf0) + result; - if (result > 0x9f) - result = ((result + 0x60) & 0xff) + 0x100; + if (result > 0x9f) result = ((result + 0x60) & 0xff) + 0x100; result = (A & 0xf00) + (value & 0xf00) + result; - if (result > 0x9ff) - result = ((result + 0x600) & 0xfff) + 0x1000; + if (result > 0x9ff) result = ((result + 0x600) & 0xfff) + 0x1000; result = (A & 0xf000) + (value & 0xf000) + result; } else { result = A + value + GetCarryFlag(); } SetOverflowFlag((A & 0x8000) == (value & 0x8000) && (value & 0x8000) != (result & 0x8000)); - if (GetDecimalFlag() && result > 0x9fff) - result += 0x6000; + if (GetDecimalFlag() && result > 0x9fff) result += 0x6000; SetCarryFlag(result > 0xffff); A = result; } @@ -88,8 +82,7 @@ void Cpu::Sbc(uint32_t low, uint32_t high) { } SetOverflowFlag((A & 0x80) == (value & 0x80) && (value & 0x80) != (result & 0x80)); - if (GetDecimalFlag() && result < 0x100) - result -= 0x60; + if (GetDecimalFlag() && result < 0x100) result -= 0x60; SetCarryFlag(result > 0xff); A = (A & 0xff00) | (result & 0xff); } else { @@ -111,8 +104,7 @@ void Cpu::Sbc(uint32_t low, uint32_t high) { } SetOverflowFlag((A & 0x8000) == (value & 0x8000) && (value & 0x8000) != (result & 0x8000)); - if (GetDecimalFlag() && result < 0x10000) - result -= 0x6000; + if (GetDecimalFlag() && result < 0x10000) result -= 0x6000; SetCarryFlag(result > 0xffff); A = result; } diff --git a/src/app/emu/debug/apu_debugger.cc b/src/app/emu/debug/apu_debugger.cc index 84e2a9da..14c63f4f 100644 --- a/src/app/emu/debug/apu_debugger.cc +++ b/src/app/emu/debug/apu_debugger.cc @@ -9,9 +9,7 @@ namespace yaze { namespace emu { namespace debug { -ApuHandshakeTracker::ApuHandshakeTracker() { - Reset(); -} +ApuHandshakeTracker::ApuHandshakeTracker() { Reset(); } void ApuHandshakeTracker::Reset() { phase_ = Phase::RESET; @@ -31,8 +29,7 @@ void ApuHandshakeTracker::Reset() { void ApuHandshakeTracker::OnCpuPortWrite(uint8_t port, uint8_t value, uint32_t pc) { - if (port > 3) - return; + if (port > 3) return; cpu_ports_[port] = value; @@ -68,8 +65,7 @@ void ApuHandshakeTracker::OnCpuPortWrite(uint8_t port, uint8_t value, void ApuHandshakeTracker::OnSpcPortWrite(uint8_t port, uint8_t value, uint16_t pc) { - if (port > 3) - return; + if (port > 3) return; spc_ports_[port] = value; diff --git a/src/app/emu/debug/apu_debugger.h b/src/app/emu/debug/apu_debugger.h index f598f8f4..08e731ea 100644 --- a/src/app/emu/debug/apu_debugger.h +++ b/src/app/emu/debug/apu_debugger.h @@ -14,7 +14,7 @@ namespace debug { /** * @brief IPL ROM handshake tracker - * + * * Monitors CPU-APU communication during audio program upload to diagnose * handshake failures and transfer issues. */ diff --git a/src/app/emu/debug/breakpoint_manager.cc b/src/app/emu/debug/breakpoint_manager.cc index 001051fa..4b652f37 100644 --- a/src/app/emu/debug/breakpoint_manager.cc +++ b/src/app/emu/debug/breakpoint_manager.cc @@ -1,6 +1,7 @@ #include "app/emu/debug/breakpoint_manager.h" #include + #include "util/log.h" namespace yaze { diff --git a/src/app/emu/debug/breakpoint_manager.h b/src/app/emu/debug/breakpoint_manager.h index 1ee23d54..d0d81fc6 100644 --- a/src/app/emu/debug/breakpoint_manager.h +++ b/src/app/emu/debug/breakpoint_manager.h @@ -13,14 +13,14 @@ namespace emu { /** * @class BreakpointManager * @brief Manages CPU and SPC700 breakpoints for debugging - * + * * Provides comprehensive breakpoint support including: * - Execute breakpoints (break when PC reaches address) * - Read breakpoints (break when memory address is read) * - Write breakpoints (break when memory address is written) * - Access breakpoints (break on read OR write) * - Conditional breakpoints (break when expression is true) - * + * * Inspired by Mesen2's debugging capabilities. */ class BreakpointManager { diff --git a/src/app/emu/debug/disassembly_viewer.cc b/src/app/emu/debug/disassembly_viewer.cc index 4434b00f..4d8d0ade 100644 --- a/src/app/emu/debug/disassembly_viewer.cc +++ b/src/app/emu/debug/disassembly_viewer.cc @@ -177,10 +177,8 @@ void DisassemblyViewer::RenderDisassemblyTable( // Calculate column count based on optional columns int column_count = 4; // BP, Address, Mnemonic, Operand (always shown) - if (show_hex_dump_) - column_count++; - if (show_execution_counts_) - column_count++; + if (show_hex_dump_) column_count++; + if (show_execution_counts_) column_count++; if (!ImGui::BeginTable("##DisasmTable", column_count, flags, ImVec2(0.0f, 0.0f))) { diff --git a/src/app/emu/debug/disassembly_viewer.h b/src/app/emu/debug/disassembly_viewer.h index ab8e3efe..ac6e5139 100644 --- a/src/app/emu/debug/disassembly_viewer.h +++ b/src/app/emu/debug/disassembly_viewer.h @@ -42,8 +42,9 @@ struct DisassemblyEntry { }; /** - * @brief Advanced disassembly viewer with sparse storage and interactive features - * + * @brief Advanced disassembly viewer with sparse storage and interactive + * features + * * This viewer provides a professional disassembly interface similar to modern * debuggers and ROM hacking tools. Features include: * - Sparse address-based storage (only stores executed instructions) diff --git a/src/app/emu/debug/watchpoint_manager.cc b/src/app/emu/debug/watchpoint_manager.cc index b32bb97e..bd04bb16 100644 --- a/src/app/emu/debug/watchpoint_manager.cc +++ b/src/app/emu/debug/watchpoint_manager.cc @@ -2,6 +2,7 @@ #include #include + #include "absl/strings/str_format.h" #include "util/log.h" diff --git a/src/app/emu/debug/watchpoint_manager.h b/src/app/emu/debug/watchpoint_manager.h index 0386e698..dbf0cfe7 100644 --- a/src/app/emu/debug/watchpoint_manager.h +++ b/src/app/emu/debug/watchpoint_manager.h @@ -13,14 +13,14 @@ namespace emu { /** * @class WatchpointManager * @brief Manages memory watchpoints for debugging - * + * * Watchpoints track memory accesses (reads/writes) and can break execution * when specific memory locations are accessed. This is crucial for: * - Finding where variables are modified * - Detecting buffer overflows * - Tracking down corruption bugs * - Understanding data flow - * + * * Inspired by Mesen2's memory debugging capabilities. */ class WatchpointManager { @@ -56,7 +56,8 @@ class WatchpointManager { /** * @brief Add a memory watchpoint * @param start_address Starting address of range to watch - * @param end_address Ending address (inclusive), or same as start for single byte + * @param end_address Ending address (inclusive), or same as start for single + * byte * @param track_reads Track read accesses * @param track_writes Track write accesses * @param break_on_access Pause emulation when accessed diff --git a/src/app/emu/emulator.cc b/src/app/emu/emulator.cc index 3736eaad..8c25286f 100644 --- a/src/app/emu/emulator.cc +++ b/src/app/emu/emulator.cc @@ -181,7 +181,8 @@ void Emulator::Run(Rom* rom) { } } - // Initialize SNES with ROM data (either from Initialize() or from rom parameter) + // Initialize SNES with ROM data (either from Initialize() or from rom + // parameter) if (rom_data_.empty()) { rom_data_ = rom->vector(); } @@ -190,7 +191,8 @@ void Emulator::Run(Rom* rom) { // Note: DisassemblyViewer recording is always enabled via callback // No explicit setup needed - callback is set in Initialize() - // Note: PPU pixel format set to 1 (XBGR) in Init() which matches ARGB8888 texture + // Note: PPU pixel format set to 1 (XBGR) in Init() which matches ARGB8888 + // texture wanted_frames_ = 1.0 / (snes_.memory().pal_timing() ? 50.0 : 60.0); wanted_samples_ = 48000 / (snes_.memory().pal_timing() ? 50 : 60); @@ -255,7 +257,8 @@ void Emulator::Run(Rom* rom) { } if (snes_initialized_ && frames_to_process > 0) { - // Process frames (skip rendering for all but last frame if falling behind) + // Process frames (skip rendering for all but last frame if falling + // behind) for (int i = 0; i < frames_to_process; i++) { bool should_render = (i == frames_to_process - 1); @@ -277,8 +280,9 @@ void Emulator::Run(Rom* rom) { // Only render and handle audio on the last frame if (should_render) { // SMOOTH AUDIO BUFFERING - // Strategy: Always queue samples, never drop. Use dynamic rate control - // to keep buffer at target level. This prevents pops and glitches. + // Strategy: Always queue samples, never drop. Use dynamic rate + // control to keep buffer at target level. This prevents pops and + // glitches. if (audio_backend_) { if (audio_stream_config_dirty_) { @@ -357,9 +361,10 @@ void Emulator::Run(Rom* rom) { snes_.SetPixels(static_cast(ppu_pixels_)); renderer_->UnlockTexture(ppu_texture_); - // WORKAROUND: Tiny delay after texture unlock to prevent macOS Metal crash - // macOS CoreAnimation/Metal driver bug in layer_presented() callback - // Without this, rapid texture updates corrupt Metal's frame tracking + // WORKAROUND: Tiny delay after texture unlock to prevent macOS + // Metal crash macOS CoreAnimation/Metal driver bug in + // layer_presented() callback Without this, rapid texture updates + // corrupt Metal's frame tracking SDL_Delay(1); } } @@ -372,8 +377,7 @@ void Emulator::Run(Rom* rom) { void Emulator::RenderEmulatorInterface() { try { - if (!card_registry_) - return; // Card registry must be injected + if (!card_registry_) return; // Card registry must be injected static gui::EditorCard cpu_card("CPU Debugger", ICON_MD_MEMORY); static gui::EditorCard ppu_card("PPU Viewer", ICON_MD_VIDEOGAME_ASSET); @@ -392,8 +396,9 @@ void Emulator::RenderEmulatorInterface() { breakpoints_card.SetDefaultSize(400, 350); performance_card.SetDefaultSize(350, 300); - // Get visibility flags from registry and pass them to Begin() for proper X button functionality - // This ensures each card window can be closed by the user via the window close button + // Get visibility flags from registry and pass them to Begin() for proper X + // button functionality This ensures each card window can be closed by the + // user via the window close button bool* cpu_visible = card_registry_->GetVisibilityFlag("emulator.cpu_debugger"); if (cpu_visible && *cpu_visible) { @@ -507,8 +512,9 @@ void Emulator::RenderNavBar() { } // REMOVED: HandleEvents() - replaced by ui::InputHandler::Poll() -// The old ImGui::IsKeyPressed/Released approach was event-based and didn't work properly -// for continuous game input. Now using SDL_GetKeyboardState() for proper polling. +// The old ImGui::IsKeyPressed/Released approach was event-based and didn't work +// properly for continuous game input. Now using SDL_GetKeyboardState() for +// proper polling. void Emulator::RenderBreakpointList() { // Delegate to UI layer @@ -535,8 +541,7 @@ void Emulator::RenderModernCpuDebugger() { } ImGui::SameLine(); if (ImGui::Button(ICON_MD_SKIP_NEXT " Step")) { - if (!running_) - snes_.cpu().RunOpcode(); + if (!running_) snes_.cpu().RunOpcode(); } ImGui::SameLine(); if (ImGui::Button(ICON_MD_REFRESH)) { diff --git a/src/app/emu/emulator.h b/src/app/emu/emulator.h index 324085b0..25464cb1 100644 --- a/src/app/emu/emulator.h +++ b/src/app/emu/emulator.h @@ -27,7 +27,8 @@ class EditorCardRegistry; namespace emu { // REMOVED: EmulatorKeybindings (ImGuiKey-based) -// Now using ui::InputHandler with SDL_GetKeyboardState() for proper continuous polling +// Now using ui::InputHandler with SDL_GetKeyboardState() for proper continuous +// polling /** * @class Emulator diff --git a/src/app/emu/input/input_backend.cc b/src/app/emu/input/input_backend.cc index a7696124..530048a1 100644 --- a/src/app/emu/input/input_backend.cc +++ b/src/app/emu/input/input_backend.cc @@ -53,8 +53,7 @@ class SDL2InputBackend : public IInputBackend { } ControllerState Poll(int player) override { - if (!initialized_) - return ControllerState{}; + if (!initialized_) return ControllerState{}; ControllerState state; @@ -118,8 +117,7 @@ class SDL2InputBackend : public IInputBackend { } void ProcessEvent(void* event) override { - if (!initialized_ || !event) - return; + if (!initialized_ || !event) return; SDL_Event* sdl_event = static_cast(event); diff --git a/src/app/emu/input/input_backend.h b/src/app/emu/input/input_backend.h index 87f7b31c..2251eaea 100644 --- a/src/app/emu/input/input_backend.h +++ b/src/app/emu/input/input_backend.h @@ -77,7 +77,7 @@ struct InputConfig { /** * @brief Abstract input backend interface - * + * * Allows swapping between SDL2, SDL3, or custom input implementations * without changing emulator code. */ diff --git a/src/app/emu/input/input_manager.cc b/src/app/emu/input/input_manager.cc index d273b070..232f2b08 100644 --- a/src/app/emu/input/input_manager.cc +++ b/src/app/emu/input/input_manager.cc @@ -45,8 +45,7 @@ void InputManager::Shutdown() { } void InputManager::Poll(Snes* snes, int player) { - if (!snes || !backend_) - return; + if (!snes || !backend_) return; ControllerState physical_state = backend_->Poll(player); diff --git a/src/app/emu/input/input_manager.h b/src/app/emu/input/input_manager.h index e1acea77..b67d0cb5 100644 --- a/src/app/emu/input/input_manager.h +++ b/src/app/emu/input/input_manager.h @@ -2,6 +2,7 @@ #define YAZE_APP_EMU_INPUT_INPUT_MANAGER_H_ #include + #include "app/emu/input/input_backend.h" namespace yaze { diff --git a/src/app/emu/memory/dma.cc b/src/app/emu/memory/dma.cc index b1e4e6c6..8ddcc1d7 100644 --- a/src/app/emu/memory/dma.cc +++ b/src/app/emu/memory/dma.cc @@ -163,8 +163,7 @@ void DoDma(Snes* snes, MemoryImpl* memory, int cpuCycles) { // full transfer overhead WaitCycle(snes, memory); for (int i = 0; i < 8; i++) { - if (!channel[i].dma_active) - continue; + if (!channel[i].dma_active) continue; // do channel i WaitCycle(snes, memory); // overhead per channel int offIndex = 0; @@ -208,10 +207,8 @@ void HandleDma(Snes* snes, MemoryImpl* memory, int cpu_cycles) { void WaitCycle(Snes* snes, MemoryImpl* memory) { // run hdma if requested, no sync (already sycned due to dma) - if (memory->hdma_init_requested()) - InitHdma(snes, memory, false, 0); - if (memory->hdma_run_requested()) - DoHdma(snes, memory, false, 0); + if (memory->hdma_init_requested()) InitHdma(snes, memory, false, 0); + if (memory->hdma_run_requested()) DoHdma(snes, memory, false, 0); snes->RunCycles(8); } @@ -222,16 +219,13 @@ void InitHdma(Snes* snes, MemoryImpl* memory, bool do_sync, int cpu_cycles) { bool hdmaEnabled = false; // check if a channel is enabled, and do reset for (int i = 0; i < 8; i++) { - if (channel[i].hdma_active) - hdmaEnabled = true; + if (channel[i].hdma_active) hdmaEnabled = true; channel[i].do_transfer = false; channel[i].terminated = false; } - if (!hdmaEnabled) - return; + if (!hdmaEnabled) return; snes->cpu().set_int_delay(true); - if (do_sync) - snes->SyncCycles(true, 8); + if (do_sync) snes->SyncCycles(true, 8); // full transfer overhead snes->RunCycles(8); @@ -244,8 +238,7 @@ void InitHdma(Snes* snes, MemoryImpl* memory, bool do_sync, int cpu_cycles) { channel[i].table_addr = channel[i].a_addr; channel[i].rep_count = snes->Read((channel[i].a_bank << 16) | channel[i].table_addr++); - if (channel[i].rep_count == 0) - channel[i].terminated = true; + if (channel[i].rep_count == 0) channel[i].terminated = true; if (channel[i].indirect) { snes->RunCycles(8); channel[i].size = @@ -258,8 +251,7 @@ void InitHdma(Snes* snes, MemoryImpl* memory, bool do_sync, int cpu_cycles) { channel[i].do_transfer = true; } } - if (do_sync) - snes->SyncCycles(false, cpu_cycles); + if (do_sync) snes->SyncCycles(false, cpu_cycles); } void DoHdma(Snes* snes, MemoryImpl* memory, bool do_sync, int cycles) { @@ -270,25 +262,21 @@ void DoHdma(Snes* snes, MemoryImpl* memory, bool do_sync, int cycles) { for (int i = 0; i < 8; i++) { if (channel[i].hdma_active) { hdmaActive = true; - if (!channel[i].terminated) - lastActive = i; + if (!channel[i].terminated) lastActive = i; } } - if (!hdmaActive) - return; + if (!hdmaActive) return; snes->cpu().set_int_delay(true); - if (do_sync) - snes->SyncCycles(true, 8); + if (do_sync) snes->SyncCycles(true, 8); // full transfer overhead snes->RunCycles(8); // do all copies for (int i = 0; i < 8; i++) { // terminate any dma - if (channel[i].hdma_active) - channel[i].dma_active = false; + if (channel[i].hdma_active) channel[i].dma_active = false; if (channel[i].hdma_active && !channel[i].terminated) { // do the hdma if (channel[i].do_transfer) { @@ -334,15 +322,13 @@ void DoHdma(Snes* snes, MemoryImpl* memory, bool do_sync, int cycles) { snes->Read((channel[i].a_bank << 16) | channel[i].table_addr++) << 8; } - if (channel[i].rep_count == 0) - channel[i].terminated = true; + if (channel[i].rep_count == 0) channel[i].terminated = true; channel[i].do_transfer = true; } } } - if (do_sync) - snes->SyncCycles(false, cycles); + if (do_sync) snes->SyncCycles(false, cycles); } void TransferByte(Snes* snes, MemoryImpl* memory, uint16_t aAdr, uint8_t aBank, @@ -359,13 +345,11 @@ void TransferByte(Snes* snes, MemoryImpl* memory, uint16_t aAdr, uint8_t aBank, (aAdr >= 0x2100 && aAdr < 0x2200))); if (fromB) { uint8_t val = validB ? snes->ReadBBus(bAdr) : memory->open_bus(); - if (validA) - snes->Write((aBank << 16) | aAdr, val); + if (validA) snes->Write((aBank << 16) | aAdr, val); } else { uint8_t val = validA ? snes->Read((aBank << 16) | aAdr) : memory->open_bus(); - if (validB) - snes->WriteBBus(bAdr, val); + if (validB) snes->WriteBBus(bAdr, val); } } diff --git a/src/app/emu/memory/memory.cc b/src/app/emu/memory/memory.cc index fcb5bbcb..3dc48c88 100644 --- a/src/app/emu/memory/memory.cc +++ b/src/app/emu/memory/memory.cc @@ -129,7 +129,8 @@ void MemoryImpl::cart_writeHirom(uint8_t bank, uint16_t adr, uint8_t val) { uint32_t MemoryImpl::GetMappedAddress(uint32_t address) const { // NOTE: This function is only used by ROM editor via Memory interface. // The emulator core uses cart_read/cart_write instead. - // Returns identity mapping for now - full implementation not needed for emulator. + // Returns identity mapping for now - full implementation not needed for + // emulator. return address; } diff --git a/src/app/emu/snes.cc b/src/app/emu/snes.cc index a2566151..cd586007 100644 --- a/src/app/emu/snes.cc +++ b/src/app/emu/snes.cc @@ -26,8 +26,7 @@ void input_latch(Input* input, bool value) { } uint8_t input_read(Input* input) { - if (input->latch_line_) - input->latched_state_ = input->current_state_; + if (input->latch_line_) input->latched_state_ = input->current_state_; uint8_t ret = input->latched_state_ & 1; input->latched_state_ >>= 1; @@ -67,8 +66,7 @@ void Snes::Reset(bool hard) { input2.current_state_ = 0; // Clear current button states input1.latched_state_ = 0; input2.latched_state_ = 0; - if (hard) - memset(ram, 0, sizeof(ram)); + if (hard) memset(ram, 0, sizeof(ram)); ram_adr_ = 0; memory_.set_h_pos(0); memory_.set_v_pos(0); @@ -204,18 +202,15 @@ void Snes::RunCycle() { switch (memory_.h_pos()) { case 16: { next_horiz_event = 512; - if (memory_.v_pos() == 0) - memory_.init_hdma_request(); + if (memory_.v_pos() == 0) memory_.init_hdma_request(); } break; case 512: { next_horiz_event = 1104; // render the line halfway of the screen for better compatibility - if (!in_vblank_ && memory_.v_pos() > 0) - ppu_.RunLine(memory_.v_pos()); + if (!in_vblank_ && memory_.v_pos() > 0) ppu_.RunLine(memory_.v_pos()); } break; case 1104: { - if (!in_vblank_) - memory_.run_hdma_request(); + if (!in_vblank_) memory_.run_hdma_request(); if (!memory_.pal_timing()) { // line 240 of odd frame with no interlace is 4 cycles shorter next_horiz_event = (memory_.v_pos() == 240 && !ppu_.even_frame && @@ -276,8 +271,7 @@ void Snes::RunCycle() { } else if (memory_.v_pos() == 240) { // if we are not yet in vblank, we had an overscan frame, set // starting_vblank - if (!in_vblank_) - starting_vblank = true; + if (!in_vblank_) starting_vblank = true; } if (starting_vblank) { // catch up the apu at end of emulated frame (we end frame @ start of @@ -329,8 +323,7 @@ void Snes::RunCycle() { } } // handle auto_joy_read_-timer - if (auto_joy_timer_ > 0) - auto_joy_timer_ -= 2; + if (auto_joy_timer_ > 0) auto_joy_timer_ -= 2; } void Snes::RunCycles(int cycles) { @@ -372,10 +365,8 @@ uint8_t Snes::ReadBBus(uint8_t adr) { "[AFTER CatchUp: APU_cycles=%llu CPU_cycles=%llu]", 0x40 + (adr & 0x3), (adr & 0x3) + 4, val, cpu_.PB, cpu_.PC, apu_.GetCycles(), cycles_); - if ((adr & 0x3) == 0) - last_f4 = val; - if ((adr & 0x3) == 1) - last_f5 = val; + if ((adr & 0x3) == 0) last_f4 = val; + if ((adr & 0x3) == 1) last_f5 = val; } return val; } @@ -525,8 +516,9 @@ void Snes::WriteBBus(uint8_t adr, uint8_t val) { 0x40 + (adr & 0x3), (adr & 0x3) + 4, val, cpu_.PB, cpu_.PC); } - // NOTE: Auto-reset disabled - relying on complete IPL ROM with counter protocol - // The IPL ROM will handle multi-upload sequences via its transfer loop + // NOTE: Auto-reset disabled - relying on complete IPL ROM with counter + // protocol The IPL ROM will handle multi-upload sequences via its transfer + // loop return; } @@ -566,8 +558,7 @@ void Snes::WriteReg(uint16_t adr, uint8_t val) { } auto_joy_read_ = val & 0x1; - if (!auto_joy_read_) - auto_joy_timer_ = 0; + if (!auto_joy_read_) auto_joy_timer_ = 0; // Debug: Log when auto-joy-read is enabled/disabled static int auto_joy_log = 0; @@ -699,11 +690,9 @@ int Snes::GetAccessTime(uint32_t adr) { adr &= 0xffff; if ((bank < 0x40 || (bank >= 0x80 && bank < 0xc0)) && adr < 0x8000) { // 00-3f,80-bf:0-7fff - if (adr < 0x2000 || adr >= 0x6000) - return 8; // 0-1fff, 6000-7fff - if (adr < 0x4000 || adr >= 0x4200) - return 6; // 2000-3fff, 4200-5fff - return 12; // 4000-41ff + if (adr < 0x2000 || adr >= 0x6000) return 8; // 0-1fff, 6000-7fff + if (adr < 0x4000 || adr >= 0x4200) return 6; // 2000-3fff, 4200-5fff + return 12; // 4000-41ff } // 40-7f,co-ff:0000-ffff, 00-3f,80-bf:8000-ffff return (fast_mem_ && bank >= 0x80) ? 6 @@ -739,9 +728,7 @@ void Snes::SetSamples(int16_t* sample_data, int wanted_samples) { apu_.dsp().GetSamples(sample_data, wanted_samples, memory_.pal_timing()); } -void Snes::SetPixels(uint8_t* pixel_data) { - ppu_.PutPixels(pixel_data); -} +void Snes::SetPixels(uint8_t* pixel_data) { ppu_.PutPixels(pixel_data); } void Snes::SetButtonState(int player, int button, bool pressed) { // Select the appropriate input based on player number @@ -752,8 +739,7 @@ void Snes::SetButtonState(int player, int button, bool pressed) { // Bit 4: Up, Bit 5: Down, Bit 6: Left, Bit 7: Right // Bit 8: A, Bit 9: X, Bit 10: L, Bit 11: R - if (button < 0 || button > 11) - return; // Validate button range + if (button < 0 || button > 11) return; // Validate button range uint16_t old_state = input->current_state_; diff --git a/src/app/emu/snes.h b/src/app/emu/snes.h index 189a0507..c50164e3 100644 --- a/src/app/emu/snes.h +++ b/src/app/emu/snes.h @@ -29,15 +29,11 @@ class Snes { input1 = {}; input2 = {}; - cpu_.callbacks().read_byte = [this](uint32_t adr) { - return CpuRead(adr); - }; + cpu_.callbacks().read_byte = [this](uint32_t adr) { return CpuRead(adr); }; cpu_.callbacks().write_byte = [this](uint32_t adr, uint8_t val) { CpuWrite(adr, val); }; - cpu_.callbacks().idle = [this](bool waiting) { - CpuIdle(waiting); - }; + cpu_.callbacks().idle = [this](bool waiting) { CpuIdle(waiting); }; } ~Snes() = default; diff --git a/src/app/emu/ui/debugger_ui.cc b/src/app/emu/ui/debugger_ui.cc index 7c309b8a..dd1be083 100644 --- a/src/app/emu/ui/debugger_ui.cc +++ b/src/app/emu/ui/debugger_ui.cc @@ -36,8 +36,7 @@ void AddSectionSpacing() { } // namespace void RenderModernCpuDebugger(Emulator* emu) { - if (!emu) - return; + if (!emu) return; auto& theme_manager = ThemeManager::Get(); const auto& theme = theme_manager.GetCurrentTheme(); @@ -231,8 +230,7 @@ void RenderModernCpuDebugger(Emulator* emu) { } void RenderBreakpointList(Emulator* emu) { - if (!emu) - return; + if (!emu) return; auto& theme_manager = ThemeManager::Get(); const auto& theme = theme_manager.GetCurrentTheme(); @@ -288,8 +286,7 @@ void RenderBreakpointList(Emulator* emu) { } void RenderMemoryViewer(Emulator* emu) { - if (!emu) - return; + if (!emu) return; auto& theme_manager = ThemeManager::Get(); const auto& theme = theme_manager.GetCurrentTheme(); @@ -327,8 +324,7 @@ void RenderMemoryViewer(Emulator* emu) { } void RenderCpuInstructionLog(Emulator* emu, uint32_t log_size) { - if (!emu) - return; + if (!emu) return; auto& theme_manager = ThemeManager::Get(); const auto& theme = theme_manager.GetCurrentTheme(); @@ -362,8 +358,7 @@ void RenderCpuInstructionLog(Emulator* emu, uint32_t log_size) { } void RenderApuDebugger(Emulator* emu) { - if (!emu) - return; + if (!emu) return; auto& theme_manager = ThemeManager::Get(); const auto& theme = theme_manager.GetCurrentTheme(); @@ -588,8 +583,7 @@ void RenderApuDebugger(Emulator* emu) { } void RenderAIAgentPanel(Emulator* emu) { - if (!emu) - return; + if (!emu) return; auto& theme_manager = ThemeManager::Get(); const auto& theme = theme_manager.GetCurrentTheme(); diff --git a/src/app/emu/ui/debugger_ui.h b/src/app/emu/ui/debugger_ui.h index 5141bf99..333f8892 100644 --- a/src/app/emu/ui/debugger_ui.h +++ b/src/app/emu/ui/debugger_ui.h @@ -2,6 +2,7 @@ #define YAZE_APP_EMU_UI_DEBUGGER_UI_H_ #include + #include "imgui/imgui.h" namespace yaze { diff --git a/src/app/emu/ui/emulator_ui.cc b/src/app/emu/ui/emulator_ui.cc index 300444be..66abe310 100644 --- a/src/app/emu/ui/emulator_ui.cc +++ b/src/app/emu/ui/emulator_ui.cc @@ -39,8 +39,7 @@ void AddSectionSpacing() { } // namespace void RenderNavBar(Emulator* emu) { - if (!emu) - return; + if (!emu) return; auto& theme_manager = ThemeManager::Get(); const auto& theme = theme_manager.GetCurrentTheme(); @@ -176,7 +175,8 @@ void RenderNavBar(Emulator* emu) { // emu->disassembly_viewer().SetRecording(recording); // } // if (ImGui::IsItemHovered()) { - // ImGui::SetTooltip("Record instructions to Disassembly Viewer\n(Lightweight - uses sparse address map)"); + // ImGui::SetTooltip("Record instructions to Disassembly + // Viewer\n(Lightweight - uses sparse address map)"); // } ImGui::SameLine(); @@ -267,8 +267,7 @@ void RenderNavBar(Emulator* emu) { } void RenderSnesPpu(Emulator* emu) { - if (!emu) - return; + if (!emu) return; auto& theme_manager = ThemeManager::Get(); const auto& theme = theme_manager.GetCurrentTheme(); @@ -337,8 +336,7 @@ void RenderSnesPpu(Emulator* emu) { } void RenderPerformanceMonitor(Emulator* emu) { - if (!emu) - return; + if (!emu) return; auto& theme_manager = ThemeManager::Get(); const auto& theme = theme_manager.GetCurrentTheme(); @@ -388,8 +386,7 @@ void RenderPerformanceMonitor(Emulator* emu) { } void RenderKeyboardShortcuts(bool* show) { - if (!show || !*show) - return; + if (!show || !*show) return; auto& theme_manager = ThemeManager::Get(); const auto& theme = theme_manager.GetCurrentTheme(); @@ -494,8 +491,7 @@ void RenderKeyboardShortcuts(bool* show) { } void RenderEmulatorInterface(Emulator* emu) { - if (!emu) - return; + if (!emu) return; auto& theme_manager = ThemeManager::Get(); const auto& theme = theme_manager.GetCurrentTheme(); diff --git a/src/app/emu/ui/input_handler.cc b/src/app/emu/ui/input_handler.cc index 0b6e4f94..e51e5840 100644 --- a/src/app/emu/ui/input_handler.cc +++ b/src/app/emu/ui/input_handler.cc @@ -10,8 +10,7 @@ namespace emu { namespace ui { void RenderKeyboardConfig(input::InputManager* manager) { - if (!manager || !manager->backend()) - return; + if (!manager || !manager->backend()) return; auto config = manager->GetConfig(); diff --git a/src/app/emu/video/ppu.cc b/src/app/emu/video/ppu.cc index b5d21479..f1e04953 100644 --- a/src/app/emu/video/ppu.cc +++ b/src/app/emu/video/ppu.cc @@ -146,11 +146,9 @@ void Ppu::RunLine(int line) { // called for lines 1-224/239 // evaluate sprites obj_pixel_buffer_.fill(0); - if (!forced_blank_) - EvaluateSprites(line - 1); + if (!forced_blank_) EvaluateSprites(line - 1); // actual line - if (mode == 7) - CalculateMode7Starts(line); + if (mode == 7) CalculateMode7Starts(line); for (int x = 0; x < 256; x++) { HandlePixel(x, line); } @@ -195,18 +193,12 @@ void Ppu::HandlePixel(int x, int y) { g >>= 1; b >>= 1; } - if (r > 31) - r = 31; - if (g > 31) - g = 31; - if (b > 31) - b = 31; - if (r < 0) - r = 0; - if (g < 0) - g = 0; - if (b < 0) - b = 0; + if (r > 31) r = 31; + if (g > 31) g = 31; + if (b > 31) b = 31; + if (r < 0) r = 0; + if (g < 0) g = 0; + if (b < 0) b = 0; } if (!(pseudo_hires_ || mode == 5 || mode == 6)) { r2 = r; @@ -218,8 +210,8 @@ void Ppu::HandlePixel(int x, int y) { // SDL_PIXELFORMAT_ARGB8888 with pixelOutputFormat=0 (BGRX) // Memory layout: [B][G][R][A] at offsets 0,1,2,3 respectively - // Convert 5-bit SNES color (0-31) to 8-bit (0-255) via (val << 3) | (val >> 2) - // Two pixels per X position for hi-res support: + // Convert 5-bit SNES color (0-31) to 8-bit (0-255) via (val << 3) | (val >> + // 2) Two pixels per X position for hi-res support: // pixel1 at x*8 + 0..3, pixel2 at x*8 + 4..7 // Apply brightness @@ -335,15 +327,13 @@ int Ppu::GetPixelForMode7(int x, int layer, bool priority) { bool outsideMap = xPos < 0 || xPos >= 1024 || yPos < 0 || yPos >= 1024; xPos &= 0x3ff; yPos &= 0x3ff; - if (!m7largeField) - outsideMap = false; + if (!m7largeField) outsideMap = false; uint8_t tile = outsideMap ? 0 : vram[(yPos >> 3) * 128 + (xPos >> 3)] & 0xff; uint8_t pixel = outsideMap && !m7charFill ? 0 : vram[tile * 64 + (yPos & 7) * 8 + (xPos & 7)] >> 8; if (layer == 1) { - if (((bool)(pixel & 0x80)) != priority) - return 0; + if (((bool)(pixel & 0x80)) != priority) return 0; return pixel & 0x7f; } return pixel; @@ -364,10 +354,8 @@ bool Ppu::GetWindowState(int layer, int x) { } bool test1 = x >= window1left && x <= window1right; bool test2 = x >= window2left && x <= window2right; - if (windowLayer[layer].window1inversed) - test1 = !test1; - if (windowLayer[layer].window2inversed) - test2 = !test2; + if (windowLayer[layer].window1inversed) test1 = !test1; + if (windowLayer[layer].window2inversed) test2 = !test2; switch (windowLayer[layer].maskLogic) { case 0: return test1 || test2; @@ -408,8 +396,7 @@ void Ppu::HandleOPT(int layer, int* lx, int* ly) { if (hOffset & valid) *lx = (((hOffset & 0x3f8) + (column * 8)) * 2) | (x & 0xf); } else { - if (hOffset & valid) - *lx = ((hOffset & 0x3f8) + (column * 8)) | (x & 0x7); + if (hOffset & valid) *lx = ((hOffset & 0x3f8) + (column * 8)) | (x & 0x7); } // TODO: not sure if correct for interlace if (vOffset & valid) @@ -425,8 +412,7 @@ uint16_t Ppu::GetOffsetValue(int col, int row) { uint16_t tilemapAdr = bg_layer_[2].tilemapAdr + (((y >> tileBits) & 0x1f) << 5 | ((x >> tileBits) & 0x1f)); - if ((x & tileHighBit) && bg_layer_[2].tilemapWider) - tilemapAdr += 0x400; + if ((x & tileHighBit) && bg_layer_[2].tilemapWider) tilemapAdr += 0x400; if ((y & tileHighBit) && bg_layer_[2].tilemapHigher) tilemapAdr += bg_layer_[2].tilemapWider ? 0x800 : 0x400; return vram[tilemapAdr & 0x7fff]; @@ -442,14 +428,12 @@ int Ppu::GetPixelForBgLayer(int x, int y, int layer, bool priority) { uint16_t tilemapAdr = bg_layer_[layer].tilemapAdr + (((y >> tileBitsY) & 0x1f) << 5 | ((x >> tileBitsX) & 0x1f)); - if ((x & tileHighBitX) && bg_layer_[layer].tilemapWider) - tilemapAdr += 0x400; + if ((x & tileHighBitX) && bg_layer_[layer].tilemapWider) tilemapAdr += 0x400; if ((y & tileHighBitY) && bg_layer_[layer].tilemapHigher) tilemapAdr += bg_layer_[layer].tilemapWider ? 0x800 : 0x400; uint16_t tile = vram[tilemapAdr & 0x7fff]; // check priority, get palette - if (((bool)(tile & 0x2000)) != priority) - return 0; // wrong priority + if (((bool)(tile & 0x2000)) != priority) return 0; // wrong priority int paletteNum = (tile & 0x1c00) >> 10; // figure out position within tile int row = (tile & 0x8000) ? 7 - (y & 0x7) : (y & 0x7); @@ -457,18 +441,15 @@ int Ppu::GetPixelForBgLayer(int x, int y, int layer, bool priority) { int tileNum = tile & 0x3ff; if (wideTiles) { // if unflipped right half of tile, or flipped left half of tile - if (((bool)(x & 8)) ^ ((bool)(tile & 0x4000))) - tileNum += 1; + if (((bool)(x & 8)) ^ ((bool)(tile & 0x4000))) tileNum += 1; } if (bg_layer_[layer].bigTiles) { // if unflipped bottom half of tile, or flipped upper half of tile - if (((bool)(y & 8)) ^ ((bool)(tile & 0x8000))) - tileNum += 0x10; + if (((bool)(y & 8)) ^ ((bool)(tile & 0x8000))) tileNum += 0x10; } // read tiledata, ajust palette for mode 0 int bitDepth = kBitDepthsPerMode[mode][layer]; - if (mode == 0) - paletteNum += 8 * layer; + if (mode == 0) paletteNum += 8 * layer; // plane 1 (always) int paletteSize = 4; uint16_t plane1 = vram[(bg_layer_[layer].tileAdr + @@ -523,8 +504,7 @@ void Ppu::EvaluateSprites(int line) { // in y-range, get the x location, using the high bit as well int x = oam[index] & 0xff; x |= ((high_oam_[index >> 3] >> (index & 7)) & 1) << 8; - if (x > 255) - x -= 512; + if (x > 255) x -= 512; // if in x-range, record if (x > -spriteSize) { // break if we found 32 sprites already @@ -549,18 +529,15 @@ void Ppu::EvaluateSprites(int line) { [(high_oam_[index >> 3] >> ((index & 7) + 1)) & 1]; int x = oam[index] & 0xff; x |= ((high_oam_[index >> 3] >> (index & 7)) & 1) << 8; - if (x > 255) - x -= 512; + if (x > 255) x -= 512; if (x > -spriteSize) { // update row according to obj-interlace - if (obj_interlace_) - row = row * 2 + (even_frame ? 0 : 1); + if (obj_interlace_) row = row * 2 + (even_frame ? 0 : 1); // get some data for the sprite and y-flip row if needed int tile = oam[index + 1] & 0xff; int palette = (oam[index + 1] & 0xe00) >> 9; bool hFlipped = oam[index + 1] & 0x4000; - if (oam[index + 1] & 0x8000) - row = spriteSize - 1 - row; + if (oam[index + 1] & 0x8000) row = spriteSize - 1 - row; // fetch all tiles in x-range for (int col = 0; col < spriteSize; col += 8) { if (col + x > -8 && col + x < 256) { @@ -676,16 +653,14 @@ uint8_t Ppu::Read(uint8_t adr, bool latch) { ret = high_oam_[((oam_adr_ & 0xf) << 1) | oam_second_write_]; if (oam_second_write_) { oam_adr_++; - if (oam_adr_ == 0) - oam_in_high_ = false; + if (oam_adr_ == 0) oam_in_high_ = false; } } else { if (!oam_second_write_) { ret = oam[oam_adr_] & 0xff; } else { ret = oam[oam_adr_++] >> 8; - if (oam_adr_ == 0) - oam_in_high_ = true; + if (oam_adr_ == 0) oam_in_high_ = true; } } oam_second_write_ = !oam_second_write_; @@ -806,16 +781,14 @@ void Ppu::Write(uint8_t adr, uint8_t val) { high_oam_[((oam_adr_ & 0xf) << 1) | oam_second_write_] = val; if (oam_second_write_) { oam_adr_++; - if (oam_adr_ == 0) - oam_in_high_ = false; + if (oam_adr_ == 0) oam_in_high_ = false; } } else { if (!oam_second_write_) { oam_buffer_ = val; } else { oam[oam_adr_++] = (val << 8) | oam_buffer_; - if (oam_adr_ == 0) - oam_in_high_ = true; + if (oam_adr_ == 0) oam_in_high_ = true; } } oam_second_write_ = !oam_second_write_; @@ -911,15 +884,13 @@ void Ppu::Write(uint8_t adr, uint8_t val) { // TODO: vram access during rendering (also cgram and oam) uint16_t vramAdr = GetVramRemap(); vram[vramAdr & 0x7fff] = (vram[vramAdr & 0x7fff] & 0xff00) | val; - if (!vram_increment_on_high_) - vram_pointer += vram_increment_; + if (!vram_increment_on_high_) vram_pointer += vram_increment_; break; } case 0x19: { uint16_t vramAdr = GetVramRemap(); vram[vramAdr & 0x7fff] = (vram[vramAdr & 0x7fff] & 0x00ff) | (val << 8); - if (vram_increment_on_high_) - vram_pointer += vram_increment_; + if (vram_increment_on_high_) vram_pointer += vram_increment_; break; } case 0x1a: { @@ -1046,12 +1017,9 @@ void Ppu::Write(uint8_t adr, uint8_t val) { break; } case 0x32: { - if (val & 0x80) - fixed_color_b_ = val & 0x1f; - if (val & 0x40) - fixed_color_g_ = val & 0x1f; - if (val & 0x20) - fixed_color_r_ = val & 0x1f; + if (val & 0x80) fixed_color_b_ = val & 0x1f; + if (val & 0x40) fixed_color_g_ = val & 0x1f; + if (val & 0x20) fixed_color_r_ = val & 0x1f; break; } case 0x33: { diff --git a/src/app/gfx/backend/irenderer.h b/src/app/gfx/backend/irenderer.h index fcd3cbdc..4dd8f134 100644 --- a/src/app/gfx/backend/irenderer.h +++ b/src/app/gfx/backend/irenderer.h @@ -1,11 +1,13 @@ #pragma once #include + #include #include // Forward declarations prevent circular dependencies and speed up compilation. -// Instead of including the full header, we just tell the compiler that these types exist. +// Instead of including the full header, we just tell the compiler that these +// types exist. namespace yaze { namespace gfx { class Bitmap; @@ -17,9 +19,10 @@ namespace gfx { /** * @brief An abstract handle representing a texture. - * - * This typedef allows the underlying texture implementation (e.g., SDL_Texture*, - * an OpenGL texture ID, etc.) to be hidden from the application logic. + * + * This typedef allows the underlying texture implementation (e.g., + * SDL_Texture*, an OpenGL texture ID, etc.) to be hidden from the application + * logic. */ using TextureHandle = void*; @@ -27,10 +30,12 @@ using TextureHandle = void*; * @interface IRenderer * @brief Defines an abstract interface for all rendering operations. * - * This interface decouples the application from any specific rendering API (like SDL2, SDL3, OpenGL, etc.). - * It provides a contract for creating textures, managing their lifecycle, and performing - * primitive drawing operations. The goal is to program against this interface, allowing the - * concrete rendering backend to be swapped out with minimal changes to the application code. + * This interface decouples the application from any specific rendering API + * (like SDL2, SDL3, OpenGL, etc.). It provides a contract for creating + * textures, managing their lifecycle, and performing primitive drawing + * operations. The goal is to program against this interface, allowing the + * concrete rendering backend to be swapped out with minimal changes to the + * application code. */ class IRenderer { public: @@ -39,50 +44,53 @@ class IRenderer { // --- Initialization and Lifecycle --- /** - * @brief Initializes the renderer with a given window. - * @param window A pointer to the SDL_Window to render into. - * @return True if initialization was successful, false otherwise. - */ + * @brief Initializes the renderer with a given window. + * @param window A pointer to the SDL_Window to render into. + * @return True if initialization was successful, false otherwise. + */ virtual bool Initialize(SDL_Window* window) = 0; /** - * @brief Shuts down the renderer and releases all associated resources. - */ + * @brief Shuts down the renderer and releases all associated resources. + */ virtual void Shutdown() = 0; // --- Texture Management --- /** - * @brief Creates a new, empty texture. - * @param width The width of the texture in pixels. - * @param height The height of the texture in pixels. - * @return An abstract TextureHandle to the newly created texture, or nullptr on failure. - */ + * @brief Creates a new, empty texture. + * @param width The width of the texture in pixels. + * @param height The height of the texture in pixels. + * @return An abstract TextureHandle to the newly created texture, or nullptr + * on failure. + */ virtual TextureHandle CreateTexture(int width, int height) = 0; /** - * @brief Creates a new texture with a specific pixel format. - * @param width The width of the texture in pixels. - * @param height The height of the texture in pixels. - * @param format The SDL pixel format (e.g., SDL_PIXELFORMAT_ARGB8888). - * @param access The texture access pattern (e.g., SDL_TEXTUREACCESS_STREAMING). - * @return An abstract TextureHandle to the newly created texture, or nullptr on failure. - */ + * @brief Creates a new texture with a specific pixel format. + * @param width The width of the texture in pixels. + * @param height The height of the texture in pixels. + * @param format The SDL pixel format (e.g., SDL_PIXELFORMAT_ARGB8888). + * @param access The texture access pattern (e.g., + * SDL_TEXTUREACCESS_STREAMING). + * @return An abstract TextureHandle to the newly created texture, or nullptr + * on failure. + */ virtual TextureHandle CreateTextureWithFormat(int width, int height, uint32_t format, int access) = 0; /** - * @brief Updates a texture with the pixel data from a Bitmap. - * @param texture The handle of the texture to update. - * @param bitmap The Bitmap containing the new pixel data. - */ + * @brief Updates a texture with the pixel data from a Bitmap. + * @param texture The handle of the texture to update. + * @param bitmap The Bitmap containing the new pixel data. + */ virtual void UpdateTexture(TextureHandle texture, const Bitmap& bitmap) = 0; /** - * @brief Destroys a texture and frees its associated resources. - * @param texture The handle of the texture to destroy. - */ + * @brief Destroys a texture and frees its associated resources. + * @param texture The handle of the texture to destroy. + */ virtual void DestroyTexture(TextureHandle texture) = 0; // --- Direct Pixel Access --- @@ -93,47 +101,53 @@ class IRenderer { // --- Rendering Primitives --- /** - * @brief Clears the entire render target with the current draw color. - */ + * @brief Clears the entire render target with the current draw color. + */ virtual void Clear() = 0; /** - * @brief Presents the back buffer to the screen, making the rendered content visible. - */ + * @brief Presents the back buffer to the screen, making the rendered content + * visible. + */ virtual void Present() = 0; /** - * @brief Copies a portion of a texture to the current render target. - * @param texture The source texture handle. - * @param srcrect A pointer to the source rectangle, or nullptr for the entire texture. - * @param dstrect A pointer to the destination rectangle, or nullptr for the entire render target. - */ + * @brief Copies a portion of a texture to the current render target. + * @param texture The source texture handle. + * @param srcrect A pointer to the source rectangle, or nullptr for the entire + * texture. + * @param dstrect A pointer to the destination rectangle, or nullptr for the + * entire render target. + */ virtual void RenderCopy(TextureHandle texture, const SDL_Rect* srcrect, const SDL_Rect* dstrect) = 0; /** - * @brief Sets the render target for subsequent drawing operations. - * @param texture The texture to set as the render target, or nullptr to set it back to the default (the window). - */ + * @brief Sets the render target for subsequent drawing operations. + * @param texture The texture to set as the render target, or nullptr to set + * it back to the default (the window). + */ virtual void SetRenderTarget(TextureHandle texture) = 0; /** - * @brief Sets the color used for drawing operations (e.g., Clear). - * @param color The SDL_Color to use. - */ + * @brief Sets the color used for drawing operations (e.g., Clear). + * @param color The SDL_Color to use. + */ virtual void SetDrawColor(SDL_Color color) = 0; // --- Backend-specific Access --- /** - * @brief Provides an escape hatch to get the underlying, concrete renderer object. - * - * This is necessary for integrating with third-party libraries like ImGui that are tied - * to a specific rendering backend (e.g., SDL_Renderer*, ID3D11Device*). - * - * @return A void pointer to the backend-specific renderer object. The caller is responsible - * for casting it to the correct type. - */ + * @brief Provides an escape hatch to get the underlying, concrete renderer + * object. + * + * This is necessary for integrating with third-party libraries like ImGui + * that are tied to a specific rendering backend (e.g., SDL_Renderer*, + * ID3D11Device*). + * + * @return A void pointer to the backend-specific renderer object. The caller + * is responsible for casting it to the correct type. + */ virtual void* GetBackendRenderer() = 0; }; diff --git a/src/app/gfx/backend/sdl2_renderer.cc b/src/app/gfx/backend/sdl2_renderer.cc index a0e269e9..5cdf750f 100644 --- a/src/app/gfx/backend/sdl2_renderer.cc +++ b/src/app/gfx/backend/sdl2_renderer.cc @@ -1,4 +1,5 @@ #include "app/gfx/backend/sdl2_renderer.h" + #include "absl/strings/str_format.h" #include "app/gfx/core/bitmap.h" @@ -7,13 +8,12 @@ namespace gfx { SDL2Renderer::SDL2Renderer() = default; -SDL2Renderer::~SDL2Renderer() { - Shutdown(); -} +SDL2Renderer::~SDL2Renderer() { Shutdown(); } /** * @brief Initializes the SDL2 renderer. - * This function creates an accelerated SDL2 renderer and attaches it to the given window. + * This function creates an accelerated SDL2 renderer and attaches it to the + * given window. */ bool SDL2Renderer::Initialize(SDL_Window* window) { // Create an SDL2 renderer with hardware acceleration. @@ -33,15 +33,15 @@ bool SDL2Renderer::Initialize(SDL_Window* window) { /** * @brief Shuts down the renderer. - * The underlying SDL_Renderer is managed by a unique_ptr, so its destruction is handled automatically. + * The underlying SDL_Renderer is managed by a unique_ptr, so its destruction is + * handled automatically. */ -void SDL2Renderer::Shutdown() { - renderer_.reset(); -} +void SDL2Renderer::Shutdown() { renderer_.reset(); } /** * @brief Creates an SDL_Texture. - * The texture is created with streaming access, which is suitable for textures that are updated frequently. + * The texture is created with streaming access, which is suitable for textures + * that are updated frequently. */ TextureHandle SDL2Renderer::CreateTexture(int width, int height) { // The TextureHandle is a void*, so we cast the SDL_Texture* to it. @@ -51,8 +51,8 @@ TextureHandle SDL2Renderer::CreateTexture(int width, int height) { } /** - * @brief Creates an SDL_Texture with a specific pixel format and access pattern. - * This is useful for specialized textures like emulator PPU output. + * @brief Creates an SDL_Texture with a specific pixel format and access + * pattern. This is useful for specialized textures like emulator PPU output. */ TextureHandle SDL2Renderer::CreateTextureWithFormat(int width, int height, uint32_t format, @@ -63,7 +63,8 @@ TextureHandle SDL2Renderer::CreateTextureWithFormat(int width, int height, /** * @brief Updates an SDL_Texture with data from a Bitmap. - * This involves converting the bitmap's surface to the correct format and updating the texture. + * This involves converting the bitmap's surface to the correct format and + * updating the texture. */ void SDL2Renderer::UpdateTexture(TextureHandle texture, const Bitmap& bitmap) { SDL_Surface* surface = bitmap.surface(); @@ -78,7 +79,8 @@ void SDL2Renderer::UpdateTexture(TextureHandle texture, const Bitmap& bitmap) { return; } - // Convert the bitmap's surface to RGBA8888 format for compatibility with the texture. + // Convert the bitmap's surface to RGBA8888 format for compatibility with the + // texture. auto converted_surface = std::unique_ptr( SDL_ConvertSurfaceFormat(surface, SDL_PIXELFORMAT_RGBA8888, 0)); @@ -114,16 +116,12 @@ void SDL2Renderer::UnlockTexture(TextureHandle texture) { /** * @brief Clears the screen with the current draw color. */ -void SDL2Renderer::Clear() { - SDL_RenderClear(renderer_.get()); -} +void SDL2Renderer::Clear() { SDL_RenderClear(renderer_.get()); } /** * @brief Presents the rendered frame to the screen. */ -void SDL2Renderer::Present() { - SDL_RenderPresent(renderer_.get()); -} +void SDL2Renderer::Present() { SDL_RenderPresent(renderer_.get()); } /** * @brief Copies a texture to the render target. diff --git a/src/app/gfx/backend/sdl2_renderer.h b/src/app/gfx/backend/sdl2_renderer.h index fe831eb2..bc448bb3 100644 --- a/src/app/gfx/backend/sdl2_renderer.h +++ b/src/app/gfx/backend/sdl2_renderer.h @@ -10,10 +10,10 @@ namespace gfx { * @class SDL2Renderer * @brief A concrete implementation of the IRenderer interface using SDL2. * - * This class encapsulates all rendering logic that is specific to the SDL2_render API. - * It translates the abstract calls from the IRenderer interface into concrete SDL2 commands. - * This is the first step in abstracting the renderer, allowing the rest of the application - * to be independent of SDL2. + * This class encapsulates all rendering logic that is specific to the + * SDL2_render API. It translates the abstract calls from the IRenderer + * interface into concrete SDL2 commands. This is the first step in abstracting + * the renderer, allowing the rest of the application to be independent of SDL2. */ class SDL2Renderer : public IRenderer { public: @@ -45,13 +45,14 @@ class SDL2Renderer : public IRenderer { void SetDrawColor(SDL_Color color) override; /** - * @brief Provides access to the underlying SDL_Renderer*. - * @return A void pointer that can be safely cast to an SDL_Renderer*. - */ + * @brief Provides access to the underlying SDL_Renderer*. + * @return A void pointer that can be safely cast to an SDL_Renderer*. + */ void* GetBackendRenderer() override { return renderer_.get(); } private: - // The core SDL2 renderer object, managed by a unique_ptr with a custom deleter. + // The core SDL2 renderer object, managed by a unique_ptr with a custom + // deleter. std::unique_ptr renderer_; }; diff --git a/src/app/gfx/core/bitmap.cc b/src/app/gfx/core/bitmap.cc index ade11833..cf222a12 100644 --- a/src/app/gfx/core/bitmap.cc +++ b/src/app/gfx/core/bitmap.cc @@ -24,7 +24,7 @@ class BitmapError : public std::runtime_error { * @brief Convert bitmap format enum to SDL pixel format * @param format Bitmap format (0=indexed, 1=4BPP, 2=8BPP) * @return SDL pixel format constant - * + * * SNES Graphics Format Mapping: * - Format 0: Indexed 8-bit (most common for SNES graphics) * - Format 1: 4-bit per pixel (used for some SNES backgrounds) @@ -175,7 +175,7 @@ void Bitmap::Create(int width, int height, int depth, * @param depth Color depth in bits per pixel * @param format Pixel format (0=indexed, 1=4BPP, 2=8BPP) * @param data Raw pixel data - * + * * Performance Notes: * - Uses Arena for efficient surface allocation * - Copies data to avoid external pointer dependencies @@ -209,8 +209,9 @@ void Bitmap::Create(int width, int height, int depth, int format, return; } - // CRITICAL FIX: Use proper SDL surface operations instead of direct pointer assignment - // Direct assignment breaks SDL's memory management and causes malloc errors on shutdown + // CRITICAL FIX: Use proper SDL surface operations instead of direct pointer + // assignment Direct assignment breaks SDL's memory management and causes + // malloc errors on shutdown if (surface_ && data_.size() > 0) { SDL_LockSurface(surface_); memcpy(surface_->pixels, pixel_data_, data_.size()); @@ -228,7 +229,8 @@ void Bitmap::Reformat(int format) { surface_ = Arena::Get().AllocateSurface(width_, height_, depth_, GetSnesPixelFormat(format)); - // CRITICAL FIX: Use proper SDL surface operations instead of direct pointer assignment + // CRITICAL FIX: Use proper SDL surface operations instead of direct pointer + // assignment if (surface_ && data_.size() > 0) { SDL_LockSurface(surface_); memcpy(surface_->pixels, pixel_data_, data_.size()); @@ -248,16 +250,16 @@ void Bitmap::UpdateTexture() { /** * @brief Apply the stored palette to the SDL surface - * + * * This method applies the palette_ member to the SDL surface's palette. - * + * * IMPORTANT: Transparency handling * - ROM palette data does NOT have transparency flags set * - Transparency is only applied if explicitly marked (via set_transparent) - * - For SNES rendering, use SetPaletteWithTransparent which creates + * - For SNES rendering, use SetPaletteWithTransparent which creates * transparent color 0 automatically * - This method preserves the transparency state of each color - * + * * Color format notes: * - SnesColor.rgb() returns 0-255 values stored in ImVec4 (unconventional!) * - We cast these directly to Uint8 for SDL @@ -344,18 +346,20 @@ void Bitmap::SetPalette(const SnesPalette& palette) { /** * @brief Apply palette using metadata-driven strategy - * + * * Uses bitmap metadata to determine the appropriate palette application method: * - palette_format == 0: Full palette (SetPalette) - * - palette_format == 1: Sub-palette with transparent color 0 (SetPaletteWithTransparent) - * + * - palette_format == 1: Sub-palette with transparent color 0 + * (SetPaletteWithTransparent) + * * This ensures correct rendering for different bitmap types: * - 3BPP graphics sheets → sub-palette with transparent * - 4BPP full palettes → full palette * - Mode 7 graphics → full palette - * + * * @param palette Source palette to apply - * @param sub_palette_index Index within palette for sub-palette extraction (default 0) + * @param sub_palette_index Index within palette for sub-palette extraction + * (default 0) */ void Bitmap::ApplyPaletteByMetadata(const SnesPalette& palette, int sub_palette_index) { @@ -372,31 +376,31 @@ void Bitmap::ApplyPaletteByMetadata(const SnesPalette& palette, /** * @brief Apply a sub-palette with automatic transparency for SNES rendering - * + * * This method extracts a sub-palette from a larger palette and applies it * to the SDL surface with proper SNES transparency handling. - * + * * SNES Transparency Model: * - The SNES hardware automatically treats palette index 0 as transparent * - This is a hardware feature, not stored in ROM data * - This method creates a transparent color 0 for proper SNES emulation - * + * * Usage: * - Extract 8-color sub-palette from position 'index' in source palette * - Color 0: Always set to transparent black (0,0,0,0) * - Colors 1-7: Taken from palette[index] through palette[index+6] * - If palette has fewer than 7 colors, fills with opaque black - * + * * Example: * palette has colors [c0, c1, c2, c3, c4, c5, c6, c7, c8, ...] * SetPaletteWithTransparent(palette, 0, 7) creates: * [transparent_black, c0, c1, c2, c3, c4, c5, c6] - * + * * IMPORTANT: Source palette data is NOT modified * - The full palette is stored in palette_ member for reference * - Only the SDL surface palette is updated with the 8-color subset * - This allows proper palette editing while maintaining SNES rendering - * + * * @param palette Source palette (can be 7, 8, 64, 128, or 256 colors) * @param index Start index in source palette (0-based) * @param length Number of colors to extract (default 7, max 7) @@ -614,13 +618,13 @@ void Bitmap::Get16x16Tile(int tile_x, int tile_y, * @param x X coordinate (0 to width-1) * @param y Y coordinate (0 to height-1) * @param color SNES color (15-bit RGB format) - * + * * Performance Notes: * - Bounds checking for safety * - O(1) palette lookup using hash map cache (100x faster than linear search) * - Dirty region tracking for efficient texture updates * - Direct pixel data manipulation for speed - * + * * Optimizations Applied: * - Hash map palette lookup instead of linear search * - Dirty region tracking to minimize texture update area @@ -697,7 +701,7 @@ void Bitmap::Resize(int new_width, int new_height) { * @brief Hash a color for cache lookup * @param color ImVec4 color to hash * @return 32-bit hash value - * + * * Performance Notes: * - Simple hash combining RGBA components * - Fast integer operations for cache key generation @@ -716,8 +720,9 @@ uint32_t Bitmap::HashColor(const ImVec4& color) { /** * @brief Invalidate the palette lookup cache (call when palette changes) - * @note This must be called whenever the palette is modified to maintain cache consistency - * + * @note This must be called whenever the palette is modified to maintain cache + * consistency + * * Performance Notes: * - Clears existing cache to force rebuild * - Rebuilds cache with current palette colors @@ -738,7 +743,7 @@ void Bitmap::InvalidatePaletteCache() { * @param color SNES color to find index for * @return Palette index (0 if not found) * @note O(1) lookup time vs O(n) linear search - * + * * Performance Notes: * - Hash map lookup for O(1) performance * - 100x faster than linear search for large palettes @@ -761,7 +766,8 @@ void Bitmap::set_data(const std::vector& data) { data_ = data; pixel_data_ = data_.data(); - // CRITICAL FIX: Use proper SDL surface operations instead of direct pointer assignment + // CRITICAL FIX: Use proper SDL surface operations instead of direct pointer + // assignment if (surface_ && !data_.empty()) { SDL_LockSurface(surface_); memcpy(surface_->pixels, pixel_data_, data_.size()); diff --git a/src/app/gfx/core/bitmap.h b/src/app/gfx/core/bitmap.h index 504d02c9..acd29ee4 100644 --- a/src/app/gfx/core/bitmap.h +++ b/src/app/gfx/core/bitmap.h @@ -41,21 +41,22 @@ enum BitmapFormat { * @brief Represents a bitmap image optimized for SNES ROM hacking. * * The `Bitmap` class provides functionality to create, manipulate, and display - * bitmap images specifically designed for Link to the Past ROM editing. It supports: - * + * bitmap images specifically designed for Link to the Past ROM editing. It + * supports: + * * Key Features: * - SNES-specific pixel formats (4BPP, 8BPP, indexed) * - Palette management with transparent color support * - Tile extraction (8x8, 16x16) for ROM tile editing * - Memory-efficient surface/texture management via Arena * - Real-time editing with immediate visual feedback - * + * * Performance Optimizations: * - Lazy texture creation (textures only created when needed) * - Modified flag tracking to avoid unnecessary updates * - Arena-based resource pooling to reduce allocation overhead * - Direct pixel data manipulation for fast editing operations - * + * * ROM Hacking Specific: * - SNES color format conversion (15-bit RGB to 8-bit indexed) * - Tile-based editing for 8x8 and 16x16 SNES tiles @@ -68,8 +69,10 @@ class Bitmap { /** * @brief Create a bitmap with the given dimensions and raw pixel data - * @param width Width in pixels (typically 128, 256, or 512 for SNES tilesheets) - * @param height Height in pixels (typically 32, 64, or 128 for SNES tilesheets) + * @param width Width in pixels (typically 128, 256, or 512 for SNES + * tilesheets) + * @param height Height in pixels (typically 32, 64, or 128 for SNES + * tilesheets) * @param depth Color depth in bits per pixel (4, 8, or 16 for SNES) * @param data Raw pixel data (indexed color values for SNES graphics) */ @@ -78,7 +81,7 @@ class Bitmap { /** * @brief Create a bitmap with the given dimensions, data, and SNES palette * @param width Width in pixels - * @param height Height in pixels + * @param height Height in pixels * @param depth Color depth in bits per pixel * @param data Raw pixel data (indexed color values) * @param palette SNES palette for color mapping (15-bit RGB format) @@ -202,9 +205,10 @@ class Bitmap { /** * @brief Set a pixel at the given x,y coordinates with SNES color * @param x X coordinate (0 to width-1) - * @param y Y coordinate (0 to height-1) + * @param y Y coordinate (0 to height-1) * @param color SNES color (15-bit RGB format) - * @note Automatically finds closest palette index and marks bitmap as modified + * @note Automatically finds closest palette index and marks bitmap as + * modified */ void SetPixel(int x, int y, const SnesColor& color); @@ -218,7 +222,8 @@ class Bitmap { /** * @brief Invalidate the palette lookup cache (call when palette changes) - * @note This must be called whenever the palette is modified to maintain cache consistency + * @note This must be called whenever the palette is modified to maintain + * cache consistency */ void InvalidatePaletteCache(); diff --git a/src/app/gfx/debug/graphics_optimizer.cc b/src/app/gfx/debug/graphics_optimizer.cc index 71585d36..b52cdeaa 100644 --- a/src/app/gfx/debug/graphics_optimizer.cc +++ b/src/app/gfx/debug/graphics_optimizer.cc @@ -201,7 +201,6 @@ std::unordered_map GraphicsOptimizer::GetOptimizationRecommendations( const std::unordered_map>& sheets, const std::unordered_map& palettes) { - std::unordered_map recommendations; for (const auto& [sheet_id, sheet_data] : sheets) { @@ -221,7 +220,6 @@ OptimizationResult GraphicsOptimizer::ApplyOptimizations( const std::unordered_map& recommendations, std::unordered_map>& sheets, std::unordered_map& palettes) { - ScopedTimer timer("graphics_apply_optimizations"); OptimizationResult result; @@ -310,33 +308,25 @@ BppFormat GraphicsOptimizer::DetermineOptimalFormat( // Determine optimal format based on color usage and strategy switch (strategy) { case OptimizationStrategy::kMemoryOptimized: - if (colors_used <= 4) - return BppFormat::kBpp2; - if (colors_used <= 8) - return BppFormat::kBpp3; - if (colors_used <= 16) - return BppFormat::kBpp4; + if (colors_used <= 4) return BppFormat::kBpp2; + if (colors_used <= 8) return BppFormat::kBpp3; + if (colors_used <= 16) return BppFormat::kBpp4; break; case OptimizationStrategy::kPerformanceOptimized: // Prefer formats that work well with atlas rendering - if (colors_used <= 16) - return BppFormat::kBpp4; + if (colors_used <= 16) return BppFormat::kBpp4; break; case OptimizationStrategy::kQualityOptimized: // Only optimize if significant memory savings - if (colors_used <= 4) - return BppFormat::kBpp2; + if (colors_used <= 4) return BppFormat::kBpp2; break; case OptimizationStrategy::kBalanced: - if (colors_used <= 4) - return BppFormat::kBpp2; - if (colors_used <= 8) - return BppFormat::kBpp3; - if (colors_used <= 16) - return BppFormat::kBpp4; + if (colors_used <= 4) return BppFormat::kBpp2; + if (colors_used <= 8) return BppFormat::kBpp3; + if (colors_used <= 16) return BppFormat::kBpp4; break; } @@ -346,8 +336,7 @@ BppFormat GraphicsOptimizer::DetermineOptimalFormat( float GraphicsOptimizer::CalculateQualityLoss( BppFormat from_format, BppFormat to_format, const std::vector& data) { - if (from_format == to_format) - return 0.0f; + if (from_format == to_format) return 0.0f; // Higher BPP to lower BPP conversions may lose quality if (static_cast(from_format) > static_cast(to_format)) { @@ -362,8 +351,7 @@ float GraphicsOptimizer::CalculateQualityLoss( size_t GraphicsOptimizer::CalculateMemorySavings( BppFormat from_format, BppFormat to_format, const std::vector& data) { - if (from_format == to_format) - return 0; + if (from_format == to_format) return 0; const auto& from_info = BppFormatManager::Get().GetFormatInfo(from_format); const auto& to_info = BppFormatManager::Get().GetFormatInfo(to_format); @@ -377,8 +365,7 @@ size_t GraphicsOptimizer::CalculateMemorySavings( float GraphicsOptimizer::CalculatePerformanceGain(BppFormat from_format, BppFormat to_format) { - if (from_format == to_format) - return 0.0f; + if (from_format == to_format) return 0.0f; // Lower BPP formats generally render faster if (static_cast(from_format) > static_cast(to_format)) { @@ -392,8 +379,7 @@ float GraphicsOptimizer::CalculatePerformanceGain(BppFormat from_format, bool GraphicsOptimizer::ShouldOptimize(const SheetOptimizationData& data, OptimizationStrategy strategy) { - if (!data.is_convertible) - return false; + if (!data.is_convertible) return false; switch (strategy) { case OptimizationStrategy::kMemoryOptimized: @@ -439,8 +425,7 @@ int GraphicsOptimizer::CountUsedColors(const std::vector& data, int count = 0; for (bool used : used_colors) { - if (used) - count++; + if (used) count++; } return count; diff --git a/src/app/gfx/debug/graphics_optimizer.h b/src/app/gfx/debug/graphics_optimizer.h index 9ff54460..82c49d09 100644 --- a/src/app/gfx/debug/graphics_optimizer.h +++ b/src/app/gfx/debug/graphics_optimizer.h @@ -67,11 +67,11 @@ struct SheetOptimizationData { /** * @brief Comprehensive graphics optimization system for YAZE ROM hacking - * + * * The GraphicsOptimizer provides intelligent optimization of graphics data * for Link to the Past ROM hacking workflows, balancing memory usage, * performance, and visual quality. - * + * * Key Features: * - Intelligent BPP format optimization based on actual color usage * - Graphics sheet analysis and conversion recommendations @@ -79,13 +79,13 @@ struct SheetOptimizationData { * - Performance optimization through atlas rendering * - Batch processing for multiple graphics sheets * - Quality analysis and loss estimation - * + * * Optimization Strategies: * - Memory Optimized: Minimize ROM size by using optimal BPP formats * - Performance Optimized: Maximize rendering speed through atlas optimization * - Quality Optimized: Preserve visual fidelity while optimizing * - Balanced: Optimal balance of memory, performance, and quality - * + * * ROM Hacking Specific: * - SNES-specific optimization patterns * - Graphics sheet format analysis and conversion tracking diff --git a/src/app/gfx/debug/performance/performance_dashboard.cc b/src/app/gfx/debug/performance/performance_dashboard.cc index d15ceef8..e1cdfe55 100644 --- a/src/app/gfx/debug/performance/performance_dashboard.cc +++ b/src/app/gfx/debug/performance/performance_dashboard.cc @@ -66,18 +66,12 @@ PerformanceSummary PerformanceDashboard::GetSummary() const { // Calculate optimization score (0-100) int score = 0; - if (optimization_status_.palette_lookup_optimized) - score += 20; - if (optimization_status_.dirty_region_tracking_enabled) - score += 20; - if (optimization_status_.resource_pooling_active) - score += 15; - if (optimization_status_.batch_operations_enabled) - score += 15; - if (optimization_status_.atlas_rendering_enabled) - score += 15; - if (optimization_status_.memory_pool_active) - score += 15; + if (optimization_status_.palette_lookup_optimized) score += 20; + if (optimization_status_.dirty_region_tracking_enabled) score += 20; + if (optimization_status_.resource_pooling_active) score += 15; + if (optimization_status_.batch_operations_enabled) score += 15; + if (optimization_status_.atlas_rendering_enabled) score += 15; + if (optimization_status_.memory_pool_active) score += 15; summary.optimization_score = score; @@ -474,8 +468,7 @@ void PerformanceDashboard::AnalyzePerformance() { double PerformanceDashboard::CalculateAverage( const std::vector& values) { - if (values.empty()) - return 0.0; + if (values.empty()) return 0.0; double sum = 0.0; for (double value : values) { @@ -486,8 +479,7 @@ double PerformanceDashboard::CalculateAverage( double PerformanceDashboard::CalculatePercentile( const std::vector& values, double percentile) { - if (values.empty()) - return 0.0; + if (values.empty()) return 0.0; std::vector sorted_values = values; std::sort(sorted_values.begin(), sorted_values.end()); diff --git a/src/app/gfx/debug/performance/performance_dashboard.h b/src/app/gfx/debug/performance/performance_dashboard.h index c0a95239..63ae90cd 100644 --- a/src/app/gfx/debug/performance/performance_dashboard.h +++ b/src/app/gfx/debug/performance/performance_dashboard.h @@ -32,12 +32,14 @@ struct PerformanceSummary { }; /** - * @brief Comprehensive performance monitoring dashboard for YAZE graphics system - * - * The PerformanceDashboard provides real-time monitoring and analysis of graphics - * performance in the YAZE ROM hacking editor. It displays key metrics, optimization - * status, and provides recommendations for performance improvements. - * + * @brief Comprehensive performance monitoring dashboard for YAZE graphics + * system + * + * The PerformanceDashboard provides real-time monitoring and analysis of + * graphics performance in the YAZE ROM hacking editor. It displays key metrics, + * optimization status, and provides recommendations for performance + * improvements. + * * Key Features: * - Real-time performance metrics display * - Optimization status monitoring @@ -45,14 +47,14 @@ struct PerformanceSummary { * - Frame rate analysis * - Performance regression detection * - Optimization recommendations - * + * * Performance Metrics: * - Operation timing statistics * - Memory allocation patterns * - Cache hit/miss ratios * - Texture update efficiency * - Batch operation effectiveness - * + * * ROM Hacking Specific: * - Graphics editing performance analysis * - Palette operation efficiency diff --git a/src/app/gfx/debug/performance/performance_profiler.cc b/src/app/gfx/debug/performance/performance_profiler.cc index 298056d9..cadcbb2b 100644 --- a/src/app/gfx/debug/performance/performance_profiler.cc +++ b/src/app/gfx/debug/performance/performance_profiler.cc @@ -31,15 +31,13 @@ PerformanceProfiler::PerformanceProfiler() } void PerformanceProfiler::StartTimer(const std::string& operation_name) { - if (!enabled_ || is_shutting_down_) - return; + if (!enabled_ || is_shutting_down_) return; active_timers_[operation_name] = std::chrono::high_resolution_clock::now(); } void PerformanceProfiler::EndTimer(const std::string& operation_name) { - if (!enabled_ || is_shutting_down_) - return; + if (!enabled_ || is_shutting_down_) return; auto timer_iter = active_timers_.find(operation_name); if (timer_iter == active_timers_.end()) { @@ -110,8 +108,7 @@ std::string PerformanceProfiler::GenerateReport(bool log_to_sdl) const { << (total_bytes / (1024.0 * 1024.0)) << " MB\n\n"; for (const auto& [operation, times] : operation_times_) { - if (times.empty()) - continue; + if (times.empty()) continue; auto stats = GetStats(operation); report << "Operation: " << operation << "\n"; @@ -247,8 +244,7 @@ void PerformanceProfiler::PrintSummary() const { std::cout << std::string(72, '-') << "\n"; for (const auto& [operation_name, times] : operation_times_) { - if (times.empty()) - continue; + if (times.empty()) continue; auto total_it = operation_totals_.find(operation_name); auto count_it = operation_counts_.find(operation_name); diff --git a/src/app/gfx/debug/performance/performance_profiler.h b/src/app/gfx/debug/performance/performance_profiler.h index b0081dd0..070ce82a 100644 --- a/src/app/gfx/debug/performance/performance_profiler.h +++ b/src/app/gfx/debug/performance/performance_profiler.h @@ -1,24 +1,24 @@ #ifndef YAZE_APP_GFX_PERFORMANCE_PERFORMANCE_PROFILER_H #define YAZE_APP_GFX_PERFORMANCE_PERFORMANCE_PROFILER_H +#include + #include #include #include #include -#include - namespace yaze { namespace gfx { /** * @brief Unified performance profiler for all YAZE operations - * + * * The PerformanceProfiler class provides comprehensive timing and performance * measurement capabilities for the entire YAZE application. It tracks operation - * times, calculates statistics, provides detailed performance reports, and integrates - * with the memory pool for efficient data storage. - * + * times, calculates statistics, provides detailed performance reports, and + * integrates with the memory pool for efficient data storage. + * * Key Features: * - High-resolution timing for microsecond precision * - Automatic statistics calculation (min, max, average, median) @@ -27,14 +27,14 @@ namespace gfx { * - Performance regression detection * - Enable/disable functionality for zero-overhead when disabled * - Unified interface for both core and graphics operations - * + * * Performance Optimizations: * - Memory pool allocation for reduced fragmentation * - Minimal overhead timing measurements * - Efficient data structures for fast lookups * - Configurable sampling rates * - Automatic cleanup of old measurements - * + * * Usage Examples: * - Measure ROM loading performance * - Track graphics operation efficiency @@ -47,7 +47,7 @@ class PerformanceProfiler { /** * @brief Enable or disable performance monitoring - * + * * When disabled, ScopedTimer operations become no-ops for better performance * in production builds or when monitoring is not needed. */ @@ -178,7 +178,7 @@ class PerformanceProfiler { /** * @brief RAII timer for automatic timing management - * + * * Usage: * { * ScopedTimer timer("operation_name"); diff --git a/src/app/gfx/render/atlas_renderer.cc b/src/app/gfx/render/atlas_renderer.cc index f56ab71e..3fb5e601 100644 --- a/src/app/gfx/render/atlas_renderer.cc +++ b/src/app/gfx/render/atlas_renderer.cc @@ -2,6 +2,7 @@ #include #include + #include "app/gfx/util/bpp_format_manager.h" namespace yaze { @@ -167,8 +168,7 @@ void AtlasRenderer::RenderBatch( // Render each atlas group for (const auto& [atlas_index, commands] : atlas_groups) { - if (commands.empty()) - continue; + if (commands.empty()) continue; auto& atlas = *atlases_[atlas_index]; @@ -178,8 +178,7 @@ void AtlasRenderer::RenderBatch( // Render all commands for this atlas for (const auto* cmd : commands) { auto it = atlas_lookup_.find(cmd->atlas_id); - if (it == atlas_lookup_.end()) - continue; + if (it == atlas_lookup_.end()) continue; AtlasEntry* entry = it->second; @@ -211,8 +210,7 @@ void AtlasRenderer::RenderBatchWithBppOptimization( // Render each BPP group separately for optimal performance for (const auto& [bpp_format, command_indices] : bpp_groups) { - if (command_indices.empty()) - continue; + if (command_indices.empty()) continue; // Group commands by atlas for this BPP format std::unordered_map> atlas_groups; @@ -239,8 +237,7 @@ void AtlasRenderer::RenderBatchWithBppOptimization( // Render each atlas group for this BPP format for (const auto& [atlas_index, commands] : atlas_groups) { - if (commands.empty()) - continue; + if (commands.empty()) continue; auto& atlas = *atlases_[atlas_index]; @@ -250,8 +247,7 @@ void AtlasRenderer::RenderBatchWithBppOptimization( // Render all commands for this atlas and BPP format for (const auto* cmd : commands) { auto it = atlas_lookup_.find(cmd->atlas_id); - if (it == atlas_lookup_.end()) - continue; + if (it == atlas_lookup_.end()) continue; AtlasEntry* entry = it->second; @@ -324,9 +320,7 @@ void AtlasRenderer::Clear() { current_atlas_ = 0; } -AtlasRenderer::~AtlasRenderer() { - Clear(); -} +AtlasRenderer::~AtlasRenderer() { Clear(); } void AtlasRenderer::RenderBitmap(int atlas_id, float x, float y, float scale_x, float scale_y) { diff --git a/src/app/gfx/render/atlas_renderer.h b/src/app/gfx/render/atlas_renderer.h index 0a92cd4e..7cce1f60 100644 --- a/src/app/gfx/render/atlas_renderer.h +++ b/src/app/gfx/render/atlas_renderer.h @@ -2,6 +2,7 @@ #define YAZE_APP_GFX_ATLAS_RENDERER_H #include + #include #include #include @@ -57,24 +58,24 @@ struct AtlasStats { /** * @brief Atlas-based rendering system for efficient graphics operations - * + * * The AtlasRenderer class provides efficient rendering by combining multiple * graphics elements into a single texture atlas, reducing draw calls and * improving performance for ROM hacking workflows. - * + * * Key Features: * - Single draw call for multiple tiles/graphics * - Automatic atlas management and packing * - Dynamic atlas resizing and reorganization * - UV coordinate mapping for efficient rendering * - Memory-efficient texture management - * + * * Performance Optimizations: * - Reduces draw calls from N to 1 for multiple elements * - Minimizes GPU state changes * - Efficient texture packing algorithm * - Automatic atlas defragmentation - * + * * ROM Hacking Specific: * - Optimized for SNES tile rendering (8x8, 16x16) * - Support for graphics sheet atlasing diff --git a/src/app/gfx/render/background_buffer.cc b/src/app/gfx/render/background_buffer.cc index 05cdfad7..8e29cfad 100644 --- a/src/app/gfx/render/background_buffer.cc +++ b/src/app/gfx/render/background_buffer.cc @@ -18,26 +18,21 @@ BackgroundBuffer::BackgroundBuffer(int width, int height) } void BackgroundBuffer::SetTileAt(int x, int y, uint16_t value) { - if (x < 0 || y < 0) - return; + if (x < 0 || y < 0) return; int tiles_w = width_ / 8; int tiles_h = height_ / 8; - if (x >= tiles_w || y >= tiles_h) - return; + if (x >= tiles_w || y >= tiles_h) return; buffer_[y * tiles_w + x] = value; } uint16_t BackgroundBuffer::GetTileAt(int x, int y) const { int tiles_w = width_ / 8; int tiles_h = height_ / 8; - if (x < 0 || y < 0 || x >= tiles_w || y >= tiles_h) - return 0; + if (x < 0 || y < 0 || x >= tiles_w || y >= tiles_h) return 0; return buffer_[y * tiles_w + x]; } -void BackgroundBuffer::ClearBuffer() { - std::ranges::fill(buffer_, 0); -} +void BackgroundBuffer::ClearBuffer() { std::ranges::fill(buffer_, 0); } void BackgroundBuffer::DrawTile(const TileInfo& tile, uint8_t* canvas, const uint8_t* tiledata, int indexoffset) { @@ -91,7 +86,8 @@ void BackgroundBuffer::DrawTile(const TileInfo& tile, uint8_t* canvas, uint8_t pixel_index = tiledata[src_index]; // Apply palette offset and write to canvas - // For 3BPP: final color = base_pixel (0-7) + palette_offset (0, 8, 16, 24, ...) + // For 3BPP: final color = base_pixel (0-7) + palette_offset (0, 8, 16, + // 24, ...) if (pixel_index == 0) { continue; } @@ -109,8 +105,8 @@ void BackgroundBuffer::DrawBackground(std::span gfx16_data) { buffer_.resize(tiles_w * tiles_h); } - // NEVER recreate bitmap here - it should be created by DrawFloor or initialized earlier - // If bitmap doesn't exist, create it ONCE with zeros + // NEVER recreate bitmap here - it should be created by DrawFloor or + // initialized earlier If bitmap doesn't exist, create it ONCE with zeros if (!bitmap_.is_active() || bitmap_.width() == 0) { bitmap_.Create(width_, height_, 8, std::vector(width_ * height_, 0)); @@ -154,7 +150,8 @@ void BackgroundBuffer::DrawBackground(std::span gfx16_data) { } } // CRITICAL: Sync bitmap data back to SDL surface! - // DrawTile() writes to bitmap_.mutable_data(), but the SDL surface needs updating + // DrawTile() writes to bitmap_.mutable_data(), but the SDL surface needs + // updating if (bitmap_.surface() && bitmap_.mutable_data().size() > 0) { SDL_LockSurface(bitmap_.surface()); memcpy(bitmap_.surface()->pixels, bitmap_.mutable_data().data(), @@ -201,8 +198,8 @@ void BackgroundBuffer::DrawFloor(const std::vector& rom_data, gfx::TileInfo floorTile8(rom_data[tile_address_floor + f + 6], rom_data[tile_address_floor + f + 7]); - // Floor tiles specify which 8-color sub-palette from the 90-color dungeon palette - // e.g., palette 6 = colors 48-55 (6 * 8 = 48) + // Floor tiles specify which 8-color sub-palette from the 90-color dungeon + // palette e.g., palette 6 = colors 48-55 (6 * 8 = 48) // Draw the floor tiles in a pattern // Convert TileInfo to 16-bit words with palette information diff --git a/src/app/gfx/render/texture_atlas.cc b/src/app/gfx/render/texture_atlas.cc index bab89821..3dad7d21 100644 --- a/src/app/gfx/render/texture_atlas.cc +++ b/src/app/gfx/render/texture_atlas.cc @@ -56,8 +56,8 @@ absl::Status TextureAtlas::PackBitmap(const Bitmap& src, return absl::InvalidArgumentError("Region too small for bitmap"); } - // TODO: Implement pixel copying from src to atlas_bitmap_ at region coordinates - // For now, just return OK (stub implementation) + // TODO: Implement pixel copying from src to atlas_bitmap_ at region + // coordinates For now, just return OK (stub implementation) LOG_DEBUG("[TextureAtlas]", "Packed %dx%d bitmap into region at (%d,%d) for source %d", diff --git a/src/app/gfx/render/texture_atlas.h b/src/app/gfx/render/texture_atlas.h index 20463af5..42ac0ed3 100644 --- a/src/app/gfx/render/texture_atlas.h +++ b/src/app/gfx/render/texture_atlas.h @@ -13,17 +13,19 @@ namespace gfx { /** * @class TextureAtlas - * @brief Manages multiple textures packed into a single large texture for performance - * - * Future-proof infrastructure for combining multiple room textures into one atlas. - * This reduces GPU state changes and improves rendering performance when many rooms are open. - * + * @brief Manages multiple textures packed into a single large texture for + * performance + * + * Future-proof infrastructure for combining multiple room textures into one + * atlas. This reduces GPU state changes and improves rendering performance when + * many rooms are open. + * * Benefits: * - Fewer texture binds per frame * - Better memory locality * - Reduced VRAM fragmentation * - Easier batch rendering - * + * * Usage (Future): * TextureAtlas atlas(2048, 2048); * auto region = atlas.AllocateRegion(room_id, 512, 512); @@ -57,8 +59,9 @@ class TextureAtlas { * @param width Required width in pixels * @param height Required height in pixels * @return Pointer to allocated region, or nullptr if no space - * - * Uses simple rect packing algorithm. Future: implement more efficient packing. + * + * Uses simple rect packing algorithm. Future: implement more efficient + * packing. */ AtlasRegion* AllocateRegion(int source_id, int width, int height); @@ -67,7 +70,7 @@ class TextureAtlas { * @param src Source bitmap to pack * @param region Region to pack into (must be pre-allocated) * @return Status of packing operation - * + * * Copies pixel data from source bitmap into atlas at region coordinates. */ absl::Status PackBitmap(const Bitmap& src, const AtlasRegion& region); @@ -78,7 +81,7 @@ class TextureAtlas { * @param dest_x Destination X coordinate * @param dest_y Destination Y coordinate * @return Status of drawing operation - * + * * Future: Integrate with renderer to draw atlas regions. */ absl::Status DrawRegion(int source_id, int dest_x, int dest_y); diff --git a/src/app/gfx/render/tilemap.cc b/src/app/gfx/render/tilemap.cc index 308a49c9..7658c938 100644 --- a/src/app/gfx/render/tilemap.cc +++ b/src/app/gfx/render/tilemap.cc @@ -242,7 +242,6 @@ void ComposeTile16(Tilemap& tilemap, const std::vector& data, } std::vector GetTilemapData(Tilemap& tilemap, int tile_id) { - // Comprehensive validation to prevent crashes if (tile_id < 0) { SDL_Log("GetTilemapData: Invalid tile_id %d (negative)", tile_id); diff --git a/src/app/gfx/render/tilemap.h b/src/app/gfx/render/tilemap.h index 47abe9ea..8c305e41 100644 --- a/src/app/gfx/render/tilemap.h +++ b/src/app/gfx/render/tilemap.h @@ -1,14 +1,14 @@ #ifndef YAZE_GFX_TILEMAP_H #define YAZE_GFX_TILEMAP_H +#include +#include + #include "absl/container/flat_hash_map.h" #include "app/gfx/backend/irenderer.h" #include "app/gfx/core/bitmap.h" #include "app/gfx/types/snes_tile.h" -#include -#include - namespace yaze { namespace gfx { @@ -22,7 +22,7 @@ struct Pair { /** * @brief Smart tile cache with LRU eviction for efficient memory management - * + * * Performance Optimizations: * - LRU eviction policy to keep frequently used tiles in memory * - Configurable cache size to balance memory usage and performance @@ -84,22 +84,22 @@ struct TileCache { /** * @brief Tilemap structure for SNES tile-based graphics management - * + * * The Tilemap class provides comprehensive tile management for ROM hacking: - * + * * Key Features: * - Atlas bitmap containing all tiles in a single texture * - Smart tile cache with LRU eviction for optimal memory usage * - Tile metadata storage (mirroring, palette, etc.) * - Support for both 8x8 and 16x16 tile sizes * - Efficient tile lookup and rendering - * + * * Performance Optimizations: * - Hash map storage for O(1) tile access * - LRU tile caching to minimize memory usage * - Atlas-based rendering to minimize draw calls * - Tile metadata caching for fast property access - * + * * ROM Hacking Specific: * - SNES tile format support (4BPP, 8BPP) * - Tile mirroring and flipping support @@ -147,7 +147,8 @@ std::vector GetTilemapData(Tilemap& tilemap, int tile_id); * @param tilemap Tilemap containing tiles to render * @param tile_ids Vector of tile IDs to render * @param positions Vector of screen positions for each tile - * @param scales Vector of scale factors for each tile (optional, defaults to 1.0) + * @param scales Vector of scale factors for each tile (optional, defaults + * to 1.0) * @note This function uses atlas rendering to reduce draw calls significantly */ void RenderTilesBatch(IRenderer* renderer, Tilemap& tilemap, diff --git a/src/app/gfx/resource/arena.cc b/src/app/gfx/resource/arena.cc index aca1b01d..72f063a5 100644 --- a/src/app/gfx/resource/arena.cc +++ b/src/app/gfx/resource/arena.cc @@ -1,6 +1,7 @@ #include "app/gfx/resource/arena.h" #include + #include #include "app/gfx/backend/irenderer.h" @@ -10,9 +11,7 @@ namespace yaze { namespace gfx { -void Arena::Initialize(IRenderer* renderer) { - renderer_ = renderer; -} +void Arena::Initialize(IRenderer* renderer) { renderer_ = renderer; } Arena& Arena::Get() { static Arena instance; @@ -58,17 +57,17 @@ void Arena::ProcessTextureQueue(IRenderer* renderer) { bool should_remove = true; // CRITICAL: Replicate the exact short-circuit evaluation from working code - // We MUST check command.bitmap AND command.bitmap->surface() in one expression - // to avoid dereferencing invalid pointers + // We MUST check command.bitmap AND command.bitmap->surface() in one + // expression to avoid dereferencing invalid pointers switch (command.type) { case TextureCommandType::CREATE: { // Create a new texture and update it with bitmap data - // Use short-circuit evaluation - if bitmap is invalid, never call ->surface() + // Use short-circuit evaluation - if bitmap is invalid, never call + // ->surface() if (command.bitmap && command.bitmap->surface() && command.bitmap->surface()->format && command.bitmap->is_active() && command.bitmap->width() > 0 && command.bitmap->height() > 0) { - try { auto texture = active_renderer->CreateTexture( command.bitmap->width(), command.bitmap->height()); @@ -153,8 +152,7 @@ SDL_Surface* Arena::AllocateSurface(int width, int height, int depth, } void Arena::FreeSurface(SDL_Surface* surface) { - if (!surface) - return; + if (!surface) return; // Return surface to pool if space available if (surface_pool_.available_surfaces_.size() < surface_pool_.MAX_POOL_SIZE) { diff --git a/src/app/gfx/resource/arena.h b/src/app/gfx/resource/arena.h index fdbee7ce..795a03c6 100644 --- a/src/app/gfx/resource/arena.h +++ b/src/app/gfx/resource/arena.h @@ -18,23 +18,23 @@ namespace gfx { /** * @brief Resource management arena for efficient graphics memory handling - * + * * The Arena class provides centralized management of SDL textures and surfaces * for the YAZE ROM hacking editor. It implements several key optimizations: - * + * * Key Features: * - Singleton pattern for global access across all graphics components * - Automatic resource cleanup with RAII-style management * - Memory pooling to reduce allocation overhead * - Support for 223 graphics sheets (YAZE's full graphics space) * - Background buffer management for SNES layer rendering - * + * * Performance Optimizations: * - Unique_ptr with custom deleters for automatic SDL resource cleanup * - Hash map storage for O(1) texture/surface lookup * - Batch resource management to minimize SDL calls * - Pre-allocated graphics sheet array for fast access - * + * * ROM Hacking Specific: * - Fixed-size graphics sheet array (223 sheets) matching YAZE's graphics space * - Background buffer support for SNES layer 1 and layer 2 rendering diff --git a/src/app/gfx/resource/memory_pool.cc b/src/app/gfx/resource/memory_pool.cc index 60cd4396..309000ae 100644 --- a/src/app/gfx/resource/memory_pool.cc +++ b/src/app/gfx/resource/memory_pool.cc @@ -33,9 +33,7 @@ MemoryPool::MemoryPool() (20 * kLargeBlockSize) + (10 * kHugeBlockSize); } -MemoryPool::~MemoryPool() { - Clear(); -} +MemoryPool::~MemoryPool() { Clear(); } void* MemoryPool::Allocate(size_t size) { total_allocations_++; @@ -59,8 +57,7 @@ void* MemoryPool::Allocate(size_t size) { } void MemoryPool::Deallocate(void* ptr) { - if (!ptr) - return; + if (!ptr) return; total_deallocations_++; @@ -156,14 +153,10 @@ void MemoryPool::InitializeBlockPool(std::vector& pool, } size_t MemoryPool::GetPoolIndex(size_t size) const { - if (size <= kSmallBlockSize) - return 0; - if (size <= kMediumBlockSize) - return 1; - if (size <= kLargeBlockSize) - return 2; - if (size <= kHugeBlockSize) - return 3; + if (size <= kSmallBlockSize) return 0; + if (size <= kMediumBlockSize) return 1; + if (size <= kLargeBlockSize) return 2; + if (size <= kHugeBlockSize) return 3; return 4; // Too large for any pool } diff --git a/src/app/gfx/resource/memory_pool.h b/src/app/gfx/resource/memory_pool.h index 72f10390..612dd500 100644 --- a/src/app/gfx/resource/memory_pool.h +++ b/src/app/gfx/resource/memory_pool.h @@ -11,24 +11,24 @@ namespace gfx { /** * @brief High-performance memory pool allocator for graphics data - * - * The MemoryPool class provides efficient memory management for graphics operations - * in the YAZE ROM hacking editor. It reduces memory fragmentation and allocation - * overhead through pre-allocated memory blocks. - * + * + * The MemoryPool class provides efficient memory management for graphics + * operations in the YAZE ROM hacking editor. It reduces memory fragmentation + * and allocation overhead through pre-allocated memory blocks. + * * Key Features: * - Pre-allocated memory blocks for common graphics sizes * - O(1) allocation and deallocation * - Automatic block size management * - Memory usage tracking and statistics * - Thread-safe operations - * + * * Performance Optimizations: * - Eliminates malloc/free overhead for graphics data * - Reduces memory fragmentation * - Fast allocation for common sizes (8x8, 16x16, 32x32 tiles) * - Automatic block reuse and recycling - * + * * ROM Hacking Specific: * - Optimized for SNES tile sizes (8x8, 16x16) * - Support for graphics sheet buffers (128x128, 256x256) diff --git a/src/app/gfx/types/snes_color.h b/src/app/gfx/types/snes_color.h index ed3d26ce..346cecd6 100644 --- a/src/app/gfx/types/snes_color.h +++ b/src/app/gfx/types/snes_color.h @@ -103,7 +103,8 @@ constexpr float kColorByteMaxF = 255.f; * * When getting RGB for display: * - Use rgb() to get raw values (0-255 in ImVec4 - unusual!) - * - Convert to standard ImVec4 (0-1) using: ImVec4(rgb.x/255, rgb.y/255, rgb.z/255, 1.0) + * - Convert to standard ImVec4 (0-1) using: ImVec4(rgb.x/255, rgb.y/255, + * rgb.z/255, 1.0) * - Or use the helper: ConvertSnesColorToImVec4() in color.cc */ class SnesColor { diff --git a/src/app/gfx/types/snes_palette.cc b/src/app/gfx/types/snes_palette.cc index a1316d07..26498376 100644 --- a/src/app/gfx/types/snes_palette.cc +++ b/src/app/gfx/types/snes_palette.cc @@ -277,23 +277,25 @@ uint32_t GetPaletteAddress(const std::string& group_name, size_t palette_index, /** * @brief Read a palette from ROM data - * + * * SNES ROM stores colors in 15-bit BGR format (2 bytes each): * - Byte 0: rrrrrggg (low byte) * - Byte 1: 0bbbbbgg (high byte) * - Full format: 0bbbbbgggggrrrrr - * + * * This function: * 1. Reads SNES 15-bit colors from ROM * 2. Converts to RGB 0-255 range (multiply by 8 to expand 5-bit to 8-bit) * 3. Creates SnesColor objects that store all formats - * + * * IMPORTANT: Transparency is NOT marked here! - * - The SNES hardware automatically treats color index 0 of each sub-palette as transparent + * - The SNES hardware automatically treats color index 0 of each sub-palette as + * transparent * - This is a rendering concern, not a data property * - ROM palette data stores actual color values, including at index 0 - * - Transparency is applied later during rendering (in SetPaletteWithTransparent or SDL) - * + * - Transparency is applied later during rendering (in + * SetPaletteWithTransparent or SDL) + * * @param offset ROM offset to start reading * @param num_colors Number of colors to read * @param rom Pointer to ROM data @@ -351,15 +353,15 @@ absl::StatusOr CreatePaletteGroupFromColFile( /** * @brief Create a PaletteGroup by dividing a large palette into sub-palettes - * + * * Takes a large palette (e.g., 256 colors) and divides it into smaller * palettes of num_colors each (typically 8 colors for SNES). - * + * * IMPORTANT: Does NOT mark colors as transparent! * - Color data is preserved as-is from the source palette * - Transparency is a rendering concern handled by SetPaletteWithTransparent * - The SNES hardware handles color 0 transparency automatically - * + * * @param palette Source palette to divide * @param num_colors Number of colors per sub-palette (default 8) * @return PaletteGroup containing the sub-palettes diff --git a/src/app/gfx/types/snes_tile.cc b/src/app/gfx/types/snes_tile.cc index ed60e3c1..5fdf309b 100644 --- a/src/app/gfx/types/snes_tile.cc +++ b/src/app/gfx/types/snes_tile.cc @@ -83,8 +83,7 @@ std::vector PackBppTile(const snes_tile8& tile, const uint32_t bpp) { } // 1bpp format - if (bpp == 1) - output[row] += (uint8_t)((color & 1) << (7 - col)); + if (bpp == 1) output[row] += (uint8_t)((color & 1) << (7 - col)); // 2bpp format if (bpp >= 2) { @@ -93,8 +92,7 @@ std::vector PackBppTile(const snes_tile8& tile, const uint32_t bpp) { } // 3bpp format - if (bpp == 3) - output[16 + row] += (((color & 4) == 4) << (7 - col)); + if (bpp == 3) output[16 + row] += (((color & 4) == 4) << (7 - col)); // 4bpp format if (bpp >= 4) { diff --git a/src/app/gfx/util/bpp_format_manager.cc b/src/app/gfx/util/bpp_format_manager.cc index f173eb06..74f01f7c 100644 --- a/src/app/gfx/util/bpp_format_manager.cc +++ b/src/app/gfx/util/bpp_format_manager.cc @@ -400,8 +400,7 @@ int BppFormatManager::CountUsedColors(const std::vector& data, int count = 0; for (bool used : used_colors) { - if (used) - count++; + if (used) count++; } return count; @@ -410,8 +409,7 @@ int BppFormatManager::CountUsedColors(const std::vector& data, float BppFormatManager::CalculateCompressionRatio( const std::vector& original, const std::vector& compressed) { - if (compressed.empty()) - return 1.0f; + if (compressed.empty()) return 1.0f; return static_cast(original.size()) / static_cast(compressed.size()); } diff --git a/src/app/gfx/util/bpp_format_manager.h b/src/app/gfx/util/bpp_format_manager.h index 7a375ca8..b26f5f76 100644 --- a/src/app/gfx/util/bpp_format_manager.h +++ b/src/app/gfx/util/bpp_format_manager.h @@ -2,6 +2,7 @@ #define YAZE_APP_GFX_BPP_FORMAT_MANAGER_H #include + #include #include #include @@ -80,11 +81,11 @@ struct GraphicsSheetAnalysis { /** * @brief Comprehensive BPP format management system for SNES ROM hacking - * + * * The BppFormatManager provides advanced BPP format handling, conversion, * and analysis capabilities specifically designed for Link to the Past * ROM hacking workflows. - * + * * Key Features: * - Multi-format BPP support (2BPP, 3BPP, 4BPP, 8BPP) * - Intelligent format detection and analysis @@ -92,13 +93,13 @@ struct GraphicsSheetAnalysis { * - Graphics sheet analysis and conversion history tracking * - Palette depth analysis and optimization * - Memory-efficient conversion algorithms - * + * * Performance Optimizations: * - Cached conversion results to avoid redundant processing * - SIMD-optimized conversion algorithms where possible * - Lazy evaluation for expensive analysis operations * - Memory pool integration for efficient temporary allocations - * + * * ROM Hacking Specific: * - SNES-specific BPP format handling * - Graphics sheet format analysis and conversion tracking diff --git a/src/app/gfx/util/compression.cc b/src/app/gfx/util/compression.cc index 07b03e1f..302ecfb9 100644 --- a/src/app/gfx/util/compression.cc +++ b/src/app/gfx/util/compression.cc @@ -36,11 +36,9 @@ std::vector HyruleMagicCompress(uint8_t const* const src, m = oldsize - j; for (n = 0; n < m; n++) - if (src[n + j] != src[n + i]) - break; + if (src[n + j] != src[n + i]) break; - if (n > k) - k = n, o = j; + if (n > k) k = n, o = j; } } @@ -62,13 +60,11 @@ std::vector HyruleMagicCompress(uint8_t const* const src, m = src[i + 1]; for (n = i + 2; n < oldsize; n++) { - if (src[n] != l) - break; + if (src[n] != l) break; n++; - if (src[n] != m) - break; + if (src[n] != m) break; } n -= i; @@ -79,8 +75,7 @@ std::vector HyruleMagicCompress(uint8_t const* const src, m = oldsize - i; for (n = 1; n < m; n++) - if (src[i + n] != l + n) - break; + if (src[i + n] != l + n) break; if (n > 1 + r) p = 3; @@ -89,8 +84,7 @@ std::vector HyruleMagicCompress(uint8_t const* const src, } } - if (k > 3 + r && k > n + (p & 1)) - p = 4, n = k; + if (k > 3 + r && k > n + (p & 1)) p = 4, n = k; if (!p) q++, i++; @@ -185,8 +179,7 @@ std::vector HyruleMagicDecompress(uint8_t const* src, int* const size, a = *(src++); // end the decompression routine if we encounter 0xff. - if (a == 0xff) - break; + if (a == 0xff) break; // examine the top 3 bits of a. b = (a >> 5); @@ -298,8 +291,7 @@ std::vector HyruleMagicDecompress(uint8_t const* src, int* const size, b2 = (unsigned char*)realloc(b2, bd); - if (size) - (*size) = bd; + if (size) (*size) = bd; // return the unsigned char* buffer b2, which contains the uncompressed data. std::vector decompressed_data(b2, b2 + bd); @@ -1373,8 +1365,7 @@ void memfill(const uint8_t* data, std::vector& buffer, int buffer_pos, auto b = data[offset + 1]; for (int i = 0; i < length; i = i + 2) { buffer[buffer_pos + i] = a; - if ((i + 1) < length) - buffer[buffer_pos + i + 1] = b; + if ((i + 1) < length) buffer[buffer_pos + i + 1] = b; } } diff --git a/src/app/gui/app/agent_chat_widget.cc b/src/app/gui/app/agent_chat_widget.cc index a8be6f3b..a050f2e8 100644 --- a/src/app/gui/app/agent_chat_widget.cc +++ b/src/app/gui/app/agent_chat_widget.cc @@ -127,8 +127,7 @@ void AgentChatWidget::RenderToolbar() { void AgentChatWidget::RenderChatHistory() { #ifdef Z3ED_AI_AVAILABLE - if (!agent_service_) - return; + if (!agent_service_) return; const auto& history = agent_service_->GetHistory(); @@ -239,8 +238,7 @@ void AgentChatWidget::RenderInputArea() { void AgentChatWidget::SendMessage(const std::string& message) { #ifdef Z3ED_AI_AVAILABLE - if (!agent_service_) - return; + if (!agent_service_) return; // Send message through agent service auto result = agent_service_->SendMessage(message); @@ -278,8 +276,8 @@ absl::Status AgentChatWidget::LoadHistory(const std::string& filepath) { file >> j; // Parse and load messages - // Note: This would require exposing a LoadHistory method in ConversationalAgentService - // For now, we'll just return success + // Note: This would require exposing a LoadHistory method in + // ConversationalAgentService For now, we'll just return success return absl::OkStatus(); } catch (const nlohmann::json::exception& e) { @@ -332,9 +330,7 @@ absl::Status AgentChatWidget::SaveHistory(const std::string& filepath) { #endif } -void AgentChatWidget::ScrollToBottom() { - scroll_to_bottom_ = true; -} +void AgentChatWidget::ScrollToBottom() { scroll_to_bottom_ = true; } } // namespace gui diff --git a/src/app/gui/app/agent_chat_widget.h b/src/app/gui/app/agent_chat_widget.h index d5f5fc8e..75e0f261 100644 --- a/src/app/gui/app/agent_chat_widget.h +++ b/src/app/gui/app/agent_chat_widget.h @@ -16,7 +16,7 @@ namespace gui { /** * @class AgentChatWidget * @brief ImGui widget for conversational AI agent interaction - * + * * Provides a chat-like interface in the YAZE GUI for interacting with the * z3ed AI agent. Shares the same backend as the TUI chat interface. */ diff --git a/src/app/gui/app/collaboration_panel.cc b/src/app/gui/app/collaboration_panel.cc index 06e00556..82a97b4c 100644 --- a/src/app/gui/app/collaboration_panel.cc +++ b/src/app/gui/app/collaboration_panel.cc @@ -23,7 +23,6 @@ CollaborationPanel::CollaborationPanel() show_snapshot_preview_(true), auto_scroll_(true), filter_pending_only_(false) { - // Initialize search filter search_filter_[0] = '\0'; @@ -466,26 +465,18 @@ std::string CollaborationPanel::FormatFileSize(size_t bytes) { const char* CollaborationPanel::GetProposalStatusIcon( const std::string& status) { - if (status == "pending") - return "[◷]"; - if (status == "approved") - return "[✓]"; - if (status == "rejected") - return "[✗]"; - if (status == "applied") - return "[✦]"; + if (status == "pending") return "[◷]"; + if (status == "approved") return "[✓]"; + if (status == "rejected") return "[✗]"; + if (status == "applied") return "[✦]"; return "[?]"; } ImVec4 CollaborationPanel::GetProposalStatusColor(const std::string& status) { - if (status == "pending") - return colors_.proposal_pending; - if (status == "approved") - return colors_.proposal_approved; - if (status == "rejected") - return colors_.proposal_rejected; - if (status == "applied") - return colors_.proposal_applied; + if (status == "pending") return colors_.proposal_pending; + if (status == "approved") return colors_.proposal_approved; + if (status == "rejected") return colors_.proposal_rejected; + if (status == "applied") return colors_.proposal_applied; return ImVec4(0.7f, 0.7f, 0.7f, 1.0f); } @@ -667,12 +658,14 @@ void CollaborationPanel::RenderApprovalProposal( // Voting actions if (ImGui::Button("✓ Approve")) { // TODO: Send approval vote - // approval_mgr_->VoteOnProposal(status.proposal_id, "current_user", true); + // approval_mgr_->VoteOnProposal(status.proposal_id, "current_user", + // true); } ImGui::SameLine(); if (ImGui::Button("✗ Reject")) { // TODO: Send rejection vote - // approval_mgr_->VoteOnProposal(status.proposal_id, "current_user", false); + // approval_mgr_->VoteOnProposal(status.proposal_id, "current_user", + // false); } ImGui::SameLine(); if (ImGui::Button("↩️ Rollback")) { diff --git a/src/app/gui/app/collaboration_panel.h b/src/app/gui/app/collaboration_panel.h index eb2270ba..1ba7a5fb 100644 --- a/src/app/gui/app/collaboration_panel.h +++ b/src/app/gui/app/collaboration_panel.h @@ -52,7 +52,7 @@ struct SnapshotEntry { }; /** - * @struct ProposalEntry + * @struct ProposalEntry * @brief Represents an AI-generated proposal */ struct ProposalEntry { @@ -71,7 +71,7 @@ struct ProposalEntry { /** * @class CollaborationPanel * @brief ImGui panel for collaboration features - * + * * Displays: * - ROM sync history and status * - Shared snapshots gallery diff --git a/src/app/gui/app/editor_layout.cc b/src/app/gui/app/editor_layout.cc index af31b0c1..7f3e8995 100644 --- a/src/app/gui/app/editor_layout.cc +++ b/src/app/gui/app/editor_layout.cc @@ -185,15 +185,12 @@ bool Toolset::AddAction(const char* icon, const char* tooltip) { bool Toolset::BeginCollapsibleSection(const char* label, bool* p_open) { ImGui::NewLine(); // Start on new line bool is_open = ImGui::CollapsingHeader(label, ImGuiTreeNodeFlags_None); - if (p_open) - *p_open = is_open; + if (p_open) *p_open = is_open; in_section_ = is_open; return is_open; } -void Toolset::EndCollapsibleSection() { - in_section_ = false; -} +void Toolset::EndCollapsibleSection() { in_section_ = false; } void Toolset::AddV3StatusBadge(uint8_t version, std::function on_settings) { @@ -241,9 +238,7 @@ void EditorCard::SetDefaultSize(float width, float height) { default_size_ = ImVec2(width, height); } -void EditorCard::SetPosition(Position pos) { - position_ = pos; -} +void EditorCard::SetPosition(Position pos) { position_ = pos; } bool EditorCard::Begin(bool* p_open) { // Check visibility flag first - if provided and false, don't show the card @@ -404,13 +399,9 @@ void EditorLayout::BeginMainCanvas() { ImGui::BeginChild("##MainCanvas", ImVec2(0, 0), false); } -void EditorLayout::EndMainCanvas() { - ImGui::EndChild(); -} +void EditorLayout::EndMainCanvas() { ImGui::EndChild(); } -void EditorLayout::RegisterCard(EditorCard* card) { - cards_.push_back(card); -} +void EditorLayout::RegisterCard(EditorCard* card) { cards_.push_back(card); } } // namespace gui } // namespace yaze diff --git a/src/app/gui/app/editor_layout.h b/src/app/gui/app/editor_layout.h index 83df3104..f806a7d2 100644 --- a/src/app/gui/app/editor_layout.h +++ b/src/app/gui/app/editor_layout.h @@ -13,15 +13,16 @@ namespace gui { /** * @class Toolset * @brief Ultra-compact toolbar that merges mode buttons with settings - * + * * Design Philosophy: * - Single horizontal bar with everything inline * - Small icon-only buttons for modes * - Inline property editing (InputHex with scroll) * - No wasted vertical space * - Beautiful, modern appearance - * - * Layout: [Mode Icons] | [ROM Badge] [World] [GFX] [Pal] [Spr] ... | [Quick Actions] + * + * Layout: [Mode Icons] | [ROM Badge] [World] [GFX] [Pal] [Spr] ... | [Quick + * Actions] */ class Toolset { public: @@ -84,20 +85,20 @@ class Toolset { /** * @class EditorCard * @brief Draggable, dockable card for editor sub-windows - * + * * Replaces traditional child windows with modern cards that can be: * - Dragged and positioned freely * - Docked to edges (optional) * - Minimized to title bar * - Resized responsively * - Themed beautifully - * + * * Usage: * ```cpp * EditorCard tile_card("Tile Selector", ICON_MD_GRID_VIEW); * tile_card.SetDefaultSize(300, 400); * tile_card.SetPosition(CardPosition::Right); - * + * * if (tile_card.Begin()) { * // Draw tile selector content when visible * } @@ -170,7 +171,7 @@ class EditorCard { /** * @class EditorLayout * @brief Modern layout manager for editor components - * + * * Manages the overall editor layout with: * - Compact toolbar at top * - Main canvas in center diff --git a/src/app/gui/automation/widget_auto_register.h b/src/app/gui/automation/widget_auto_register.h index 0140c540..17cbfd90 100644 --- a/src/app/gui/automation/widget_auto_register.h +++ b/src/app/gui/automation/widget_auto_register.h @@ -9,7 +9,8 @@ /** * @file widget_auto_register.h - * @brief Automatic widget registration helpers for ImGui Test Engine integration + * @brief Automatic widget registration helpers for ImGui Test Engine + * integration * * This file provides inline wrappers and RAII helpers that automatically * register ImGui widgets with the WidgetIdRegistry for test automation. @@ -58,7 +59,8 @@ class AutoWidgetScope { * Captures widget type, bounds, visibility, and enabled state. * * @param widget_type Type of widget ("button", "input", "checkbox", etc.) - * @param explicit_label Optional explicit label (uses ImGui::GetItemLabel() if empty) + * @param explicit_label Optional explicit label (uses ImGui::GetItemLabel() if + * empty) * @param description Optional description for the test harness */ void AutoRegisterLastItem(const std::string& widget_type, diff --git a/src/app/gui/automation/widget_id_registry.cc b/src/app/gui/automation/widget_id_registry.cc index 44ad4652..6ff9b0c7 100644 --- a/src/app/gui/automation/widget_id_registry.cc +++ b/src/app/gui/automation/widget_id_registry.cc @@ -24,7 +24,8 @@ thread_local std::vector WidgetIdScope::id_stack_; WidgetIdScope::WidgetIdScope(const std::string& name) : name_(name) { // Only push ID if we're in an active ImGui frame with a valid window - // This prevents crashes during editor initialization before ImGui begins its frame + // This prevents crashes during editor initialization before ImGui begins its + // frame ImGuiContext* ctx = ImGui::GetCurrentContext(); if (ctx && ctx->CurrentWindow && !ctx->Windows.empty()) { ImGui::PushID(name.c_str()); @@ -292,8 +293,7 @@ std::string WidgetIdRegistry::ExportCatalog(const std::string& format) const { bool first = true; for (const auto& [path, info] : widgets_) { - if (!first) - ss << ",\n"; + if (!first) ss << ",\n"; first = false; ss << " {\n"; diff --git a/src/app/gui/automation/widget_measurement.cc b/src/app/gui/automation/widget_measurement.cc index 16835403..4a4e353d 100644 --- a/src/app/gui/automation/widget_measurement.cc +++ b/src/app/gui/automation/widget_measurement.cc @@ -55,8 +55,7 @@ void WidgetMeasurement::BeginToolbarMeasurement(const std::string& toolbar_id) { } void WidgetMeasurement::EndToolbarMeasurement() { - if (current_toolbar_id_.empty()) - return; + if (current_toolbar_id_.empty()) return; // Calculate total width from cursor movement float end_x = ImGui::GetCursorPosX(); @@ -105,8 +104,7 @@ std::string WidgetMeasurement::ExportMetricsJSON() const { bool first_toolbar = true; for (const auto& [toolbar_id, metrics] : toolbar_metrics_) { - if (!first_toolbar) - json += ",\n"; + if (!first_toolbar) json += ",\n"; first_toolbar = false; json += absl::StrFormat(" \"%s\": {\n", toolbar_id); @@ -116,8 +114,7 @@ std::string WidgetMeasurement::ExportMetricsJSON() const { bool first_widget = true; for (const auto& metric : metrics) { - if (!first_widget) - json += ",\n"; + if (!first_widget) json += ",\n"; first_widget = false; json += " {\n"; diff --git a/src/app/gui/automation/widget_measurement.h b/src/app/gui/automation/widget_measurement.h index 887adecd..0ae5026d 100644 --- a/src/app/gui/automation/widget_measurement.h +++ b/src/app/gui/automation/widget_measurement.h @@ -14,7 +14,7 @@ namespace gui { /** * @class WidgetMeasurement * @brief Tracks widget dimensions for debugging and test automation - * + * * Integrates with ImGui Test Engine to provide accurate measurements * of UI elements, helping prevent layout issues and enabling automated * testing of widget sizes and positions. diff --git a/src/app/gui/automation/widget_state_capture.cc b/src/app/gui/automation/widget_state_capture.cc index 95e996f9..c504d4b5 100644 --- a/src/app/gui/automation/widget_state_capture.cc +++ b/src/app/gui/automation/widget_state_capture.cc @@ -61,9 +61,7 @@ std::string EscapeJsonString(const std::string& value) { return escaped; } -const char* BoolToJson(bool value) { - return value ? "true" : "false"; -} +const char* BoolToJson(bool value) { return value ? "true" : "false"; } std::string FormatFloat(float value) { // Match typical JSON formatting without trailing zeros when possible. diff --git a/src/app/gui/canvas/bpp_format_ui.cc b/src/app/gui/canvas/bpp_format_ui.cc index 561546bb..c3122a9e 100644 --- a/src/app/gui/canvas/bpp_format_ui.cc +++ b/src/app/gui/canvas/bpp_format_ui.cc @@ -24,8 +24,7 @@ BppFormatUI::BppFormatUI(const std::string& id) bool BppFormatUI::RenderFormatSelector( gfx::Bitmap* bitmap, const gfx::SnesPalette& palette, std::function on_format_changed) { - if (!bitmap) - return false; + if (!bitmap) return false; format_changed_ = false; @@ -136,8 +135,7 @@ void BppFormatUI::RenderAnalysisPanel(const gfx::Bitmap& bitmap, int used_colors = 0; for (int count : color_usage) { - if (count > 0) - used_colors++; + if (count > 0) used_colors++; } ImGui::Text("Colors Used: %d / %d", used_colors, @@ -175,8 +173,7 @@ void BppFormatUI::RenderAnalysisPanel(const gfx::Bitmap& bitmap, current_bytes); for (auto format : gfx::BppFormatManager::Get().GetAvailableFormats()) { - if (format == detected_format) - continue; + if (format == detected_format) continue; const auto& info = gfx::BppFormatManager::Get().GetFormatInfo(format); int format_bytes = @@ -276,8 +273,7 @@ void BppFormatUI::RenderSheetAnalysis(const std::vector& sheet_data, } auto it = cached_analysis_.find(sheet_id); - if (it == cached_analysis_.end()) - return; + if (it == cached_analysis_.end()) return; const auto& analysis = it->second; @@ -357,8 +353,7 @@ bool BppFormatUI::IsConversionAvailable(gfx::BppFormat from_format, int BppFormatUI::GetConversionEfficiency(gfx::BppFormat from_format, gfx::BppFormat to_format) const { // Calculate efficiency based on format compatibility - if (from_format == to_format) - return 100; + if (from_format == to_format) return 100; // Higher BPP to lower BPP conversions may lose quality if (static_cast(from_format) > static_cast(to_format)) { @@ -383,8 +378,7 @@ void BppFormatUI::RenderFormatInfo(const gfx::BppFormatInfo& info) { void BppFormatUI::RenderColorUsageChart(const std::vector& color_usage) { // Find maximum usage for scaling int max_usage = *std::max_element(color_usage.begin(), color_usage.end()); - if (max_usage == 0) - return; + if (max_usage == 0) return; // Render simple bar chart ImGui::Text("Color Usage Distribution:"); @@ -451,14 +445,12 @@ void BppConversionDialog::Show( } bool BppConversionDialog::Render() { - if (!is_open_) - return false; + if (!is_open_) return false; ImGui::OpenPopup("BPP Format Conversion"); if (ImGui::BeginPopupModal("BPP Format Conversion", &is_open_, ImGuiWindowFlags_AlwaysAutoResize)) { - RenderFormatSelector(); ImGui::Separator(); RenderOptions(); @@ -478,8 +470,7 @@ bool BppConversionDialog::Render() { } void BppConversionDialog::UpdatePreview() { - if (preview_valid_) - return; + if (preview_valid_) return; gfx::BppFormat current_format = gfx::BppFormatManager::Get().DetectFormat( source_bitmap_.vector(), source_bitmap_.width(), source_bitmap_.height()); @@ -572,8 +563,7 @@ void BppComparisonTool::SetSource(const gfx::Bitmap& bitmap, } void BppComparisonTool::Render() { - if (!is_open_ || !has_source_) - return; + if (!is_open_ || !has_source_) return; ImGui::Begin("BPP Format Comparison", &is_open_); @@ -625,8 +615,7 @@ void BppComparisonTool::RenderComparisonGrid() { for (auto format : gfx::BppFormatManager::Get().GetAvailableFormats()) { auto it = comparison_bitmaps_.find(format); - if (it == comparison_bitmaps_.end() || !comparison_valid_[format]) - continue; + if (it == comparison_bitmaps_.end() || !comparison_valid_[format]) continue; const auto& bitmap = it->second; const auto& format_info = @@ -649,8 +638,7 @@ void BppComparisonTool::RenderMetrics() { ImGui::Text("Format Metrics:"); for (auto format : gfx::BppFormatManager::Get().GetAvailableFormats()) { - if (!comparison_valid_[format]) - continue; + if (!comparison_valid_[format]) continue; const auto& format_info = gfx::BppFormatManager::Get().GetFormatInfo(format); diff --git a/src/app/gui/canvas/bpp_format_ui.h b/src/app/gui/canvas/bpp_format_ui.h index 52140e13..d689dfb3 100644 --- a/src/app/gui/canvas/bpp_format_ui.h +++ b/src/app/gui/canvas/bpp_format_ui.h @@ -14,9 +14,9 @@ namespace gui { /** * @brief BPP format selection and conversion UI component - * - * Provides a comprehensive UI for BPP format management in the YAZE ROM hacking editor. - * Includes format selection, conversion preview, and analysis tools. + * + * Provides a comprehensive UI for BPP format management in the YAZE ROM hacking + * editor. Includes format selection, conversion preview, and analysis tools. */ class BppFormatUI { public: diff --git a/src/app/gui/canvas/canvas.cc b/src/app/gui/canvas/canvas.cc index d6fbfd2e..04f0d53c 100644 --- a/src/app/gui/canvas/canvas.cc +++ b/src/app/gui/canvas/canvas.cc @@ -2,6 +2,7 @@ #include #include + #include "app/gfx/core/bitmap.h" #include "app/gfx/debug/performance/performance_profiler.h" #include "app/gfx/util/bpp_format_manager.h" @@ -12,12 +13,11 @@ namespace yaze::gui { -// Define constructors and destructor in .cc to avoid incomplete type issues with unique_ptr +// Define constructors and destructor in .cc to avoid incomplete type issues +// with unique_ptr // Default constructor -Canvas::Canvas() : renderer_(nullptr) { - InitializeDefaults(); -} +Canvas::Canvas() : renderer_(nullptr) { InitializeDefaults(); } // Legacy constructors (renderer is optional for backward compatibility) Canvas::Canvas(const std::string& id) @@ -307,9 +307,7 @@ bool Canvas::BeginTableCanvas(const std::string& label) { return result; } -void Canvas::EndTableCanvas() { - ImGui::EndChild(); -} +void Canvas::EndTableCanvas() { ImGui::EndChild(); } // Improved interaction detection methods bool Canvas::HasValidSelection() const { @@ -599,9 +597,7 @@ void Canvas::AddContextMenuItem(const gui::CanvasMenuItem& item) { } } -void Canvas::ClearContextMenuItems() { - editor_menu_.sections.clear(); -} +void Canvas::ClearContextMenuItems() { editor_menu_.sections.clear(); } void Canvas::OpenPersistentPopup(const std::string& popup_id, std::function render_callback) { @@ -620,8 +616,7 @@ void Canvas::RenderPersistentPopups() { } void Canvas::SetZoomToFit(const gfx::Bitmap& bitmap) { - if (!bitmap.is_active()) - return; + if (!bitmap.is_active()) return; ImVec2 available = ImGui::GetContentRegionAvail(); float scale_x = available.x / bitmap.width(); @@ -629,8 +624,7 @@ void Canvas::SetZoomToFit(const gfx::Bitmap& bitmap) { config_.global_scale = std::min(scale_x, scale_y); // Ensure minimum readable scale - if (config_.global_scale < 0.25f) - config_.global_scale = 0.25f; + if (config_.global_scale < 0.25f) config_.global_scale = 0.25f; global_scale_ = config_.global_scale; // Legacy compatibility @@ -762,7 +756,6 @@ bool Canvas::DrawTilemapPainter(gfx::Tilemap& tilemap, int current_tile) { // Simple bounds check if (tile_x >= 0 && tile_x < tilemap.atlas.width() && tile_y >= 0 && tile_y < tilemap.atlas.height()) { - // Draw directly from atlas texture ImVec2 uv0 = ImVec2(static_cast(tile_x) / tilemap.atlas.width(), @@ -970,10 +963,8 @@ void Canvas::DrawSelectRect(int current_map, int tile_size, float scale) { int end_y = std::floor(drag_end_pos.y / scaled_size) * tile16_size; // Swap the start and end positions if they are in the wrong order - if (start_x > end_x) - std::swap(start_x, end_x); - if (start_y > end_y) - std::swap(start_y, end_y); + if (start_x > end_x) std::swap(start_x, end_x); + if (start_y > end_y) std::swap(start_y, end_y); selected_tiles_.clear(); selected_tiles_.reserve(((end_x - start_x) / tile16_size + 1) * @@ -1030,7 +1021,8 @@ void Canvas::DrawBitmap(Bitmap& bitmap, int x_offset, int y_offset, float scale, bitmap_ = &bitmap; // Update content size for table integration - // CRITICAL: Store UNSCALED bitmap size as content - scale is applied during rendering + // CRITICAL: Store UNSCALED bitmap size as content - scale is applied during + // rendering config_.content_size = ImVec2(bitmap.width(), bitmap.height()); // Phase 1: Use rendering helper @@ -1094,7 +1086,8 @@ void Canvas::DrawBitmapGroup(std::vector& group, gfx::Tilemap& tilemap, return; } - // OPTIMIZATION: Use optimized rendering for large groups to improve performance + // OPTIMIZATION: Use optimized rendering for large groups to improve + // performance bool use_optimized_rendering = group.size() > 128; // Optimize for large selections @@ -1121,10 +1114,8 @@ void Canvas::DrawBitmapGroup(std::vector& group, gfx::Tilemap& tilemap, int end_tile_y = static_cast(std::floor(rect_bottom_right.y / (tile_size * scale))); - if (start_tile_x > end_tile_x) - std::swap(start_tile_x, end_tile_x); - if (start_tile_y > end_tile_y) - std::swap(start_tile_y, end_tile_y); + if (start_tile_x > end_tile_x) std::swap(start_tile_x, end_tile_x); + if (start_tile_y > end_tile_y) std::swap(start_tile_y, end_tile_y); // Calculate the size of the rectangle in 16x16 grid form int rect_width = (end_tile_x - start_tile_x) * tile_size; @@ -1150,7 +1141,8 @@ void Canvas::DrawBitmapGroup(std::vector& group, gfx::Tilemap& tilemap, int tile_pos_x = (x + start_tile_x) * tile_size * scale; int tile_pos_y = (y + start_tile_y) * tile_size * scale; - // OPTIMIZATION: Use pre-calculated values for better performance with large selections + // OPTIMIZATION: Use pre-calculated values for better performance with + // large selections if (tilemap.atlas.is_active() && tilemap.atlas.texture() && atlas_tiles_per_row > 0) { int atlas_tile_x = @@ -1161,7 +1153,6 @@ void Canvas::DrawBitmapGroup(std::vector& group, gfx::Tilemap& tilemap, // Simple bounds check if (atlas_tile_x >= 0 && atlas_tile_x < tilemap.atlas.width() && atlas_tile_y >= 0 && atlas_tile_y < tilemap.atlas.height()) { - // Calculate UV coordinates once for efficiency const float atlas_width = static_cast(tilemap.atlas.width()); const float atlas_height = @@ -1200,15 +1191,18 @@ void Canvas::DrawBitmapGroup(std::vector& group, gfx::Tilemap& tilemap, } } - // Performance optimization completed - tiles are now rendered with pre-calculated values + // Performance optimization completed - tiles are now rendered with + // pre-calculated values - // Reposition rectangle to follow mouse, but clamp to prevent wrapping across map boundaries + // Reposition rectangle to follow mouse, but clamp to prevent wrapping across + // map boundaries const ImGuiIO& io = GetIO(); const ImVec2 origin(canvas_p0_.x + scrolling_.x, canvas_p0_.y + scrolling_.y); const ImVec2 mouse_pos(io.MousePos.x - origin.x, io.MousePos.y - origin.y); // CRITICAL FIX: Clamp BEFORE grid alignment for smoother dragging behavior - // This prevents the rectangle from even attempting to cross boundaries during drag + // This prevents the rectangle from even attempting to cross boundaries during + // drag ImVec2 clamped_mouse_pos = mouse_pos; if (config_.clamp_rect_to_local_maps) { @@ -1216,7 +1210,8 @@ void Canvas::DrawBitmapGroup(std::vector& group, gfx::Tilemap& tilemap, int mouse_local_map_x = static_cast(mouse_pos.x) / small_map; int mouse_local_map_y = static_cast(mouse_pos.y) / small_map; - // Calculate where the rectangle END would be if we place it at mouse position + // Calculate where the rectangle END would be if we place it at mouse + // position float potential_end_x = mouse_pos.x + rect_width; float potential_end_y = mouse_pos.y + rect_height; @@ -1273,8 +1268,7 @@ void Canvas::DrawInfoGrid(float grid_step, int tile_id_offset, int label_id) { // Draw grid + all lines in the canvas draw_list_->PushClipRect(canvas_p0_, canvas_p1_, true); if (enable_grid_) { - if (custom_step_ != 0.f) - grid_step = custom_step_; + if (custom_step_ != 0.f) grid_step = custom_step_; grid_step *= global_scale_; // Apply global scale to grid step DrawGridLines(grid_step); @@ -1312,8 +1306,7 @@ void Canvas::DrawCustomHighlight(float grid_step) { } void Canvas::DrawGrid(float grid_step, int tile_id_offset) { - if (config_.grid_step != 0.f) - grid_step = config_.grid_step; + if (config_.grid_step != 0.f) grid_step = config_.grid_step; // Create render context for utilities CanvasUtils::CanvasRenderContext ctx = { @@ -1350,7 +1343,8 @@ void Canvas::DrawOverlay() { .enable_hex_labels = config_.enable_hex_labels, .grid_step = config_.grid_step}; - // Use high-level utility function with local points (synchronized from interaction handler) + // Use high-level utility function with local points (synchronized from + // interaction handler) CanvasUtils::DrawCanvasOverlay(ctx, points_, selected_points_); // Render any persistent popups from context menu actions @@ -1815,8 +1809,7 @@ void Canvas::ShowBppConversionDialog() { } bool Canvas::ConvertBitmapFormat(gfx::BppFormat target_format) { - if (!bitmap_) - return false; + if (!bitmap_) return false; gfx::BppFormat current_format = GetCurrentBppFormat(); if (current_format == target_format) { @@ -1843,8 +1836,7 @@ bool Canvas::ConvertBitmapFormat(gfx::BppFormat target_format) { } gfx::BppFormat Canvas::GetCurrentBppFormat() const { - if (!bitmap_) - return gfx::BppFormat::kBpp8; + if (!bitmap_) return gfx::BppFormat::kBpp8; return gfx::BppFormatManager::Get().DetectFormat( bitmap_->vector(), bitmap_->width(), bitmap_->height()); diff --git a/src/app/gui/canvas/canvas.h b/src/app/gui/canvas/canvas.h index 235bcc92..ad638ac3 100644 --- a/src/app/gui/canvas/canvas.h +++ b/src/app/gui/canvas/canvas.h @@ -51,7 +51,7 @@ enum class CanvasGridSize { k8x8, k16x16, k32x32, k64x64 }; * * Following ImGui design patterns, this Canvas class provides: * - Modular configuration through CanvasConfig - * - Separate selection state management + * - Separate selection state management * - Enhanced palette management integration * - Performance-optimized rendering * - Comprehensive context menu system @@ -106,14 +106,10 @@ class Canvas { void SetCanvasGridSize(CanvasGridSize grid_size) { SetGridSize(grid_size); } CanvasGridSize grid_size() const { - if (config_.grid_step == 8.0f) - return CanvasGridSize::k8x8; - if (config_.grid_step == 16.0f) - return CanvasGridSize::k16x16; - if (config_.grid_step == 32.0f) - return CanvasGridSize::k32x32; - if (config_.grid_step == 64.0f) - return CanvasGridSize::k64x64; + if (config_.grid_step == 8.0f) return CanvasGridSize::k8x8; + if (config_.grid_step == 16.0f) return CanvasGridSize::k16x16; + if (config_.grid_step == 32.0f) return CanvasGridSize::k32x32; + if (config_.grid_step == 64.0f) return CanvasGridSize::k64x64; return CanvasGridSize::k16x16; // Default } @@ -129,13 +125,13 @@ class Canvas { /** * @brief Begin canvas rendering (ImGui-style) - * + * * Modern alternative to DrawBackground(). Handles: * - Background and border rendering * - Size calculation * - Scroll/drag setup * - Context menu - * + * * Usage: * ```cpp * canvas.Begin(); @@ -148,13 +144,14 @@ class Canvas { /** * @brief End canvas rendering (ImGui-style) - * + * * Modern alternative to manual DrawGrid() + DrawOverlay(). * Automatically draws grid and overlay if enabled. */ void End(); - // ==================== Legacy Interface (Backward Compatible) ==================== + // ==================== Legacy Interface (Backward Compatible) + // ==================== // Background for the Canvas represents region without any content drawn to // it, but can be controlled by the user. @@ -302,7 +299,8 @@ class Canvas { void ZoomIn() { global_scale_ += 0.25f; } void ZoomOut() { global_scale_ -= 0.25f; } - // Points accessors - points_ is maintained separately for custom overlay drawing + // Points accessors - points_ is maintained separately for custom overlay + // drawing const ImVector& points() const { return points_; } ImVector* mutable_points() { return &points_; } auto push_back(ImVec2 pos) { points_.push_back(pos); } @@ -370,8 +368,10 @@ class Canvas { * @param tilemap Tilemap containing the tiles * @param tile_size Size of each tile (default 16) * @param scale Rendering scale (default 1.0) - * @param local_map_size Size of local map in pixels (default 512 for standard maps) - * @param total_map_size Total map size for boundary clamping (default 4096x4096) + * @param local_map_size Size of local map in pixels (default 512 for standard + * maps) + * @param total_map_size Total map size for boundary clamping (default + * 4096x4096) */ void DrawBitmapGroup(std::vector& group, gfx::Tilemap& tilemap, int tile_size, float scale = 1.0f, @@ -460,7 +460,8 @@ class Canvas { ImVec2 mouse_pos_in_canvas_; // Drawing and labeling - // NOTE: points_ synchronized from interaction_handler_ for backward compatibility + // NOTE: points_ synchronized from interaction_handler_ for backward + // compatibility ImVector points_; ImVector> labels_; @@ -502,10 +503,10 @@ void TableCanvasPipeline(gui::Canvas& canvas, gfx::Bitmap& bitmap, /** * @class ScopedCanvas * @brief RAII wrapper for Canvas (ImGui-style) - * + * * Automatically calls Begin() on construction and End() on destruction, * preventing forgotten End() calls and ensuring proper cleanup. - * + * * Usage: * ```cpp * { @@ -516,7 +517,7 @@ void TableCanvasPipeline(gui::Canvas& canvas, gfx::Bitmap& bitmap, * } * } // Automatic End() and cleanup * ``` - * + * * Or wrap existing canvas: * ```cpp * Canvas my_canvas("Editor"); @@ -529,7 +530,8 @@ void TableCanvasPipeline(gui::Canvas& canvas, gfx::Bitmap& bitmap, class ScopedCanvas { public: /** - * @brief Construct and begin a new canvas (legacy constructor without renderer) + * @brief Construct and begin a new canvas (legacy constructor without + * renderer) */ explicit ScopedCanvas(const std::string& id, ImVec2 canvas_size = ImVec2(0, 0)) diff --git a/src/app/gui/canvas/canvas_automation_api.cc b/src/app/gui/canvas/canvas_automation_api.cc index 319bcbba..ae329d37 100644 --- a/src/app/gui/canvas/canvas_automation_api.cc +++ b/src/app/gui/canvas/canvas_automation_api.cc @@ -71,10 +71,8 @@ void CanvasAutomationAPI::SelectTile(int x, int y) { void CanvasAutomationAPI::SelectTileRect(int x1, int y1, int x2, int y2) { // Ensure x1 <= x2 and y1 <= y2 - if (x1 > x2) - std::swap(x1, x2); - if (y1 > y2) - std::swap(y1, y2); + if (x1 > x2) std::swap(x1, x2); + if (y1 > y2) std::swap(y1, y2); if (!IsInBounds(x1, y1) || !IsInBounds(x2, y2)) { return; @@ -181,9 +179,7 @@ void CanvasAutomationAPI::SetZoom(float zoom) { canvas_->set_global_scale(zoom); } -float CanvasAutomationAPI::GetZoom() const { - return canvas_->global_scale(); -} +float CanvasAutomationAPI::GetZoom() const { return canvas_->global_scale(); } // ============================================================================ // Query Operations diff --git a/src/app/gui/canvas/canvas_automation_api.h b/src/app/gui/canvas/canvas_automation_api.h index 1e93863d..08268c5b 100644 --- a/src/app/gui/canvas/canvas_automation_api.h +++ b/src/app/gui/canvas/canvas_automation_api.h @@ -17,7 +17,8 @@ class Canvas; * @brief Programmatic interface for controlling canvas operations. * * Enables z3ed CLI, AI agents, GUI automation, and remote control via gRPC. - * All operations work with logical tile coordinates, independent of zoom/scroll. + * All operations work with logical tile coordinates, independent of + * zoom/scroll. */ class CanvasAutomationAPI { public: diff --git a/src/app/gui/canvas/canvas_context_menu.cc b/src/app/gui/canvas/canvas_context_menu.cc index 837d28dd..fd959873 100644 --- a/src/app/gui/canvas/canvas_context_menu.cc +++ b/src/app/gui/canvas/canvas_context_menu.cc @@ -68,8 +68,7 @@ void CanvasContextMenu::Render( const gfx::Bitmap* bitmap, const gfx::SnesPalette* /* palette */, const std::function& command_handler, CanvasConfig current_config, Canvas* canvas) { - if (!enabled_) - return; + if (!enabled_) return; // Context menu (under default mouse threshold) if (ImVec2 drag_delta = ImGui::GetMouseDragDelta(ImGuiMouseButton_Right); @@ -173,8 +172,7 @@ void CanvasContextMenu::RenderMenuSection( const std::string& title, const std::vector& items, std::function)> popup_callback) { - if (items.empty()) - return; + if (items.empty()) return; ImGui::TextColored(ImVec4(0.7F, 0.7F, 0.7F, 1.0F), "%s", title.c_str()); for (const auto& item : items) { @@ -273,8 +271,7 @@ void CanvasContextMenu::RenderCanvasPropertiesMenu( } void CanvasContextMenu::RenderBitmapOperationsMenu(gfx::Bitmap* bitmap) { - if (!bitmap) - return; + if (!bitmap) return; if (ImGui::BeginMenu(ICON_MD_IMAGE " Bitmap Properties")) { ImGui::Text("Size: %d x %d", bitmap->width(), bitmap->height()); @@ -309,8 +306,7 @@ void CanvasContextMenu::RenderBitmapOperationsMenu(gfx::Bitmap* bitmap) { void CanvasContextMenu::RenderPaletteOperationsMenu(Rom* rom, gfx::Bitmap* bitmap) { - if (!bitmap) - return; + if (!bitmap) return; if (ImGui::BeginMenu(ICON_MD_PALETTE " Palette Operations")) { if (ImGui::MenuItem("Edit Palette...")) { @@ -391,8 +387,7 @@ void CanvasContextMenu::RenderPaletteOperationsMenu(Rom* rom, } void CanvasContextMenu::DrawROMPaletteSelector() { - if (!palette_editor_) - return; + if (!palette_editor_) return; palette_editor_->DrawROMPaletteSelector(); } diff --git a/src/app/gui/canvas/canvas_events.h b/src/app/gui/canvas/canvas_events.h index 38eb105d..0baa0c39 100644 --- a/src/app/gui/canvas/canvas_events.h +++ b/src/app/gui/canvas/canvas_events.h @@ -2,6 +2,7 @@ #define YAZE_APP_GUI_CANVAS_CANVAS_EVENTS_H #include + #include "imgui/imgui.h" namespace yaze { @@ -9,7 +10,7 @@ namespace gui { /** * @brief Event payload for tile painting operations - * + * * Represents a single tile paint action, either from a click or drag operation. * Canvas-space coordinates are provided for positioning. */ @@ -31,9 +32,10 @@ struct TilePaintEvent { /** * @brief Event payload for rectangle selection operations - * - * Represents a multi-tile rectangular selection, typically from right-click drag. - * Provides both the rectangle bounds and the individual selected tile positions. + * + * Represents a multi-tile rectangular selection, typically from right-click + * drag. Provides both the rectangle bounds and the individual selected tile + * positions. */ struct RectSelectionEvent { std::vector @@ -62,7 +64,7 @@ struct RectSelectionEvent { /** * @brief Event payload for single tile selection - * + * * Represents selecting a single tile, typically from a right-click. */ struct TileSelectionEvent { @@ -79,7 +81,7 @@ struct TileSelectionEvent { /** * @brief Event payload for entity interactions - * + * * Represents various entity interaction events (hover, click, drag). * Used for exits, entrances, sprites, items, etc. */ @@ -124,7 +126,7 @@ struct EntityInteractionEvent { /** * @brief Event payload for hover preview - * + * * Represents hover state for overlay rendering. */ struct HoverEvent { @@ -141,7 +143,7 @@ struct HoverEvent { /** * @brief Combined interaction result for a frame - * + * * Aggregates all possible interaction events for a single frame update. * Handlers populate relevant events, consumers check which events occurred. */ diff --git a/src/app/gui/canvas/canvas_geometry.cc b/src/app/gui/canvas/canvas_geometry.cc index 5b01b774..70824a28 100644 --- a/src/app/gui/canvas/canvas_geometry.cc +++ b/src/app/gui/canvas/canvas_geometry.cc @@ -1,6 +1,7 @@ #include "canvas_geometry.h" #include + #include "app/gui/canvas/canvas_utils.h" namespace yaze { @@ -10,7 +11,6 @@ CanvasGeometry CalculateCanvasGeometry(const CanvasConfig& config, ImVec2 requested_size, ImVec2 cursor_screen_pos, ImVec2 content_region_avail) { - CanvasGeometry geometry; // Set canvas top-left position (screen space) @@ -51,7 +51,6 @@ CanvasGeometry CalculateCanvasGeometry(const CanvasConfig& config, ImVec2 CalculateMouseInCanvas(const CanvasGeometry& geometry, ImVec2 mouse_screen_pos) { - // Calculate origin (locked scrolled origin as used throughout canvas.cc) ImVec2 origin = GetCanvasOrigin(geometry); @@ -60,7 +59,6 @@ ImVec2 CalculateMouseInCanvas(const CanvasGeometry& geometry, } bool IsPointInCanvasBounds(const CanvasGeometry& geometry, ImVec2 point) { - return point.x >= geometry.canvas_p0.x && point.x <= geometry.canvas_p1.x && point.y >= geometry.canvas_p0.y && point.y <= geometry.canvas_p1.y; } diff --git a/src/app/gui/canvas/canvas_geometry.h b/src/app/gui/canvas/canvas_geometry.h index 477c7267..76d7afc4 100644 --- a/src/app/gui/canvas/canvas_geometry.h +++ b/src/app/gui/canvas/canvas_geometry.h @@ -10,15 +10,17 @@ namespace gui { /** * @brief Calculate canvas geometry from configuration and ImGui context - * + * * Extracts the geometry calculation logic from Canvas::DrawBackground(). * Computes screen-space positions, sizes, and scroll offsets for a canvas * based on its configuration and the current ImGui layout state. - * + * * @param config Canvas configuration (size, scale, custom size flag) * @param requested_size Explicitly requested canvas size (0,0 = use config) - * @param cursor_screen_pos Current ImGui cursor position (from GetCursorScreenPos) - * @param content_region_avail Available content region (from GetContentRegionAvail) + * @param cursor_screen_pos Current ImGui cursor position (from + * GetCursorScreenPos) + * @param content_region_avail Available content region (from + * GetContentRegionAvail) * @return Calculated geometry for this frame */ CanvasGeometry CalculateCanvasGeometry(const CanvasConfig& config, @@ -28,11 +30,11 @@ CanvasGeometry CalculateCanvasGeometry(const CanvasConfig& config, /** * @brief Calculate mouse position in canvas space - * + * * Converts screen-space mouse coordinates to canvas-space coordinates, * accounting for canvas position and scroll offset. This is the correct * coordinate system for tile/entity placement calculations. - * + * * @param geometry Canvas geometry (must be current frame) * @param mouse_screen_pos Mouse position in screen space * @return Mouse position in canvas space @@ -42,10 +44,10 @@ ImVec2 CalculateMouseInCanvas(const CanvasGeometry& geometry, /** * @brief Check if a point is within canvas bounds - * + * * Tests whether a screen-space point lies within the canvas rectangle. * Useful for hit testing and hover detection. - * + * * @param geometry Canvas geometry (must be current frame) * @param point Point in screen space to test * @return True if point is within canvas bounds @@ -54,9 +56,9 @@ bool IsPointInCanvasBounds(const CanvasGeometry& geometry, ImVec2 point); /** * @brief Apply scroll delta to geometry - * + * * Updates the scroll offset in the geometry. Used for pan operations. - * + * * @param geometry Canvas geometry to update * @param delta Scroll delta (typically ImGui::GetIO().MouseDelta) */ @@ -64,10 +66,10 @@ void ApplyScrollDelta(CanvasGeometry& geometry, ImVec2 delta); /** * @brief Get origin point (canvas top-left + scroll offset) - * + * * Computes the "locked scrolled origin" used throughout canvas rendering. * This is the reference point for all canvas-space to screen-space conversions. - * + * * @param geometry Canvas geometry * @return Origin point in screen space */ diff --git a/src/app/gui/canvas/canvas_interaction.cc b/src/app/gui/canvas/canvas_interaction.cc index d4fe050c..dadeb51b 100644 --- a/src/app/gui/canvas/canvas_interaction.cc +++ b/src/app/gui/canvas/canvas_interaction.cc @@ -2,6 +2,7 @@ #include #include + #include "imgui/imgui.h" namespace yaze { @@ -9,7 +10,8 @@ namespace gui { namespace { -// Static state for rectangle selection (temporary until we have proper state management) +// Static state for rectangle selection (temporary until we have proper state +// management) struct SelectRectState { ImVec2 drag_start_pos = ImVec2(-1, -1); bool is_dragging = false; @@ -60,7 +62,6 @@ RectSelectionEvent HandleRectangleSelection(const CanvasGeometry& geometry, int current_map, float tile_size, ImDrawList* draw_list, ImGuiMouseButton mouse_button) { - RectSelectionEvent event; event.current_map = current_map; @@ -149,10 +150,8 @@ RectSelectionEvent HandleRectangleSelection(const CanvasGeometry& geometry, int end_y = static_cast(std::floor(drag_end_pos.y / scaled_size)) * kTile16Size; - if (start_x > end_x) - std::swap(start_x, end_x); - if (start_y > end_y) - std::swap(start_y, end_y); + if (start_x > end_x) std::swap(start_x, end_x); + if (start_y > end_y) std::swap(start_y, end_y); constexpr int kTilesPerLocalMap = kSmallMapSize / 16; @@ -179,7 +178,6 @@ RectSelectionEvent HandleRectangleSelection(const CanvasGeometry& geometry, TileSelectionEvent HandleTileSelection(const CanvasGeometry& geometry, int current_map, float tile_size, ImGuiMouseButton mouse_button) { - TileSelectionEvent event; if (!IsMouseInCanvas(geometry) || !ImGui::IsMouseClicked(mouse_button)) { @@ -228,7 +226,6 @@ TileSelectionEvent HandleTileSelection(const CanvasGeometry& geometry, TilePaintEvent HandleTilePaint(const CanvasGeometry& geometry, int tile_id, float tile_size, ImGuiMouseButton mouse_button) { - TilePaintEvent event; event.tile_id = tile_id; @@ -261,7 +258,6 @@ TilePaintEvent HandleTilePaintWithPreview(const CanvasGeometry& geometry, float tile_size, ImDrawList* draw_list, ImGuiMouseButton mouse_button) { - TilePaintEvent event; if (!IsMouseInCanvas(geometry)) { @@ -304,7 +300,6 @@ TilePaintEvent HandleTilemapPaint(const CanvasGeometry& geometry, const gfx::Tilemap& tilemap, int current_tile, ImDrawList* draw_list, ImGuiMouseButton mouse_button) { - TilePaintEvent event; event.tile_id = current_tile; @@ -361,7 +356,6 @@ HoverEvent HandleHover(const CanvasGeometry& geometry, float tile_size) { void RenderHoverPreview(const CanvasGeometry& geometry, const HoverEvent& hover, float tile_size, ImDrawList* draw_list, ImU32 color) { - if (!hover.is_valid || !draw_list) { return; } @@ -386,7 +380,6 @@ void RenderHoverPreview(const CanvasGeometry& geometry, const HoverEvent& hover, EntityInteractionEvent HandleEntityInteraction(const CanvasGeometry& geometry, int entity_id, ImVec2 entity_position) { - EntityInteractionEvent event; event.entity_id = entity_id; event.position = entity_position; diff --git a/src/app/gui/canvas/canvas_interaction.h b/src/app/gui/canvas/canvas_interaction.h index 7ca8cf29..4e41265c 100644 --- a/src/app/gui/canvas/canvas_interaction.h +++ b/src/app/gui/canvas/canvas_interaction.h @@ -13,11 +13,11 @@ namespace gui { /** * @file canvas_interaction.h * @brief Free functions for canvas interaction handling - * + * * Phase 2 of Canvas refactoring: Extract interaction logic into event-driven * free functions. These functions replace the stateful CanvasInteractionHandler * methods with pure functions that return event payloads. - * + * * Design Pattern: * - Input: Canvas geometry, mouse state, interaction parameters * - Output: Event payload struct (TilePaintEvent, RectSelectionEvent, etc.) @@ -31,10 +31,10 @@ namespace gui { /** * @brief Handle rectangle selection interaction - * + * * Processes right-click drag to select multiple tiles in a rectangular region. * Returns event when selection completes. - * + * * @param geometry Canvas geometry (position, size, scale) * @param current_map Current map ID for coordinate calculation * @param tile_size Logical tile size (before scaling) @@ -49,9 +49,9 @@ RectSelectionEvent HandleRectangleSelection( /** * @brief Handle single tile selection (right-click) - * + * * Processes single right-click to select one tile. - * + * * @param geometry Canvas geometry * @param current_map Current map ID * @param tile_size Logical tile size @@ -68,10 +68,10 @@ TileSelectionEvent HandleTileSelection( /** * @brief Handle tile painting interaction - * + * * Processes left-click/drag to paint tiles on tilemap. * Returns event when paint action occurs. - * + * * @param geometry Canvas geometry * @param tile_id Current tile ID to paint * @param tile_size Logical tile size @@ -84,9 +84,9 @@ TilePaintEvent HandleTilePaint( /** * @brief Handle tile painter with bitmap preview - * + * * Renders preview of tile at hover position and handles paint interaction. - * + * * @param geometry Canvas geometry * @param bitmap Tile bitmap to paint * @param tile_size Logical tile size @@ -101,9 +101,9 @@ TilePaintEvent HandleTilePaintWithPreview( /** * @brief Handle tilemap painting interaction - * + * * Processes painting with tilemap data (multiple tiles). - * + * * @param geometry Canvas geometry * @param tilemap Tilemap containing tile data * @param current_tile Current tile index in tilemap @@ -122,9 +122,9 @@ TilePaintEvent HandleTilemapPaint( /** * @brief Update hover state for canvas - * + * * Calculates hover position and grid-aligned preview position. - * + * * @param geometry Canvas geometry * @param tile_size Logical tile size * @return HoverEvent with hover state @@ -133,9 +133,9 @@ HoverEvent HandleHover(const CanvasGeometry& geometry, float tile_size); /** * @brief Render hover preview overlay - * + * * Draws preview rectangle at hover position. - * + * * @param geometry Canvas geometry * @param hover Hover event from HandleHover * @param tile_size Logical tile size @@ -152,9 +152,9 @@ void RenderHoverPreview(const CanvasGeometry& geometry, const HoverEvent& hover, /** * @brief Handle entity interaction (hover, click, drag) - * + * * Processes entity manipulation events. - * + * * @param geometry Canvas geometry * @param entity_id Entity being interacted with * @param entity_position Current entity position @@ -170,9 +170,9 @@ EntityInteractionEvent HandleEntityInteraction(const CanvasGeometry& geometry, /** * @brief Align position to grid - * + * * Snaps canvas position to nearest grid cell. - * + * * @param pos Canvas position * @param grid_step Grid cell size * @return Grid-aligned position @@ -181,9 +181,9 @@ ImVec2 AlignToGrid(ImVec2 pos, float grid_step); /** * @brief Get mouse position in canvas space - * + * * Converts screen-space mouse position to canvas-space coordinates. - * + * * @param geometry Canvas geometry (includes origin) * @return Mouse position in canvas space */ @@ -191,7 +191,7 @@ ImVec2 GetMouseInCanvasSpace(const CanvasGeometry& geometry); /** * @brief Check if mouse is in canvas bounds - * + * * @param geometry Canvas geometry * @return True if mouse is within canvas */ @@ -199,7 +199,7 @@ bool IsMouseInCanvas(const CanvasGeometry& geometry); /** * @brief Calculate tile grid indices from canvas position - * + * * @param canvas_pos Canvas-space position * @param tile_size Logical tile size * @param global_scale Canvas scale factor diff --git a/src/app/gui/canvas/canvas_interaction_handler.cc b/src/app/gui/canvas/canvas_interaction_handler.cc index fc0c418f..497bd5d9 100644 --- a/src/app/gui/canvas/canvas_interaction_handler.cc +++ b/src/app/gui/canvas/canvas_interaction_handler.cc @@ -1,6 +1,7 @@ #include "canvas_interaction_handler.h" #include + #include "app/gui/canvas/canvas_interaction.h" #include "imgui/imgui.h" @@ -35,7 +36,6 @@ void CanvasInteractionHandler::ClearState() { TileInteractionResult CanvasInteractionHandler::Update( ImVec2 canvas_p0, ImVec2 scrolling, float /*global_scale*/, float /*tile_size*/, ImVec2 /*canvas_size*/, bool is_hovered) { - TileInteractionResult result; if (!is_hovered) { @@ -48,8 +48,8 @@ TileInteractionResult CanvasInteractionHandler::Update( mouse_pos_in_canvas_ = ImVec2(imgui_io.MousePos.x - origin.x, imgui_io.MousePos.y - origin.y); - // Update based on current mode - each mode is handled by its specific Draw method - // This method exists for future state updates if needed + // Update based on current mode - each mode is handled by its specific Draw + // method This method exists for future state updates if needed (void)current_mode_; // Suppress unused warning return result; @@ -58,7 +58,6 @@ TileInteractionResult CanvasInteractionHandler::Update( bool CanvasInteractionHandler::DrawTilePainter( const gfx::Bitmap& bitmap, ImDrawList* draw_list, ImVec2 canvas_p0, ImVec2 scrolling, float global_scale, float tile_size, bool is_hovered) { - const ImGuiIO& imgui_io = ImGui::GetIO(); const ImVec2 origin(canvas_p0.x + scrolling.x, canvas_p0.y + scrolling.y); const ImVec2 mouse_pos(imgui_io.MousePos.x - origin.x, @@ -104,7 +103,6 @@ bool CanvasInteractionHandler::DrawTilePainter( bool CanvasInteractionHandler::DrawTilemapPainter( gfx::Tilemap& tilemap, int current_tile, ImDrawList* draw_list, ImVec2 canvas_p0, ImVec2 scrolling, float global_scale, bool is_hovered) { - const ImGuiIO& imgui_io = ImGui::GetIO(); const ImVec2 origin(canvas_p0.x + scrolling.x, canvas_p0.y + scrolling.y); const ImVec2 mouse_pos(imgui_io.MousePos.x - origin.x, @@ -140,7 +138,6 @@ bool CanvasInteractionHandler::DrawTilemapPainter( if (tile_x >= 0 && tile_x < tilemap.atlas.width() && tile_y >= 0 && tile_y < tilemap.atlas.height()) { - ImVec2 uv0 = ImVec2(static_cast(tile_x) / tilemap.atlas.width(), static_cast(tile_y) / tilemap.atlas.height()); @@ -171,7 +168,6 @@ bool CanvasInteractionHandler::DrawTilemapPainter( bool CanvasInteractionHandler::DrawSolidTilePainter( const ImVec4& color, ImDrawList* draw_list, ImVec2 canvas_p0, ImVec2 scrolling, float global_scale, float tile_size, bool is_hovered) { - const ImGuiIO& imgui_io = ImGui::GetIO(); const ImVec2 origin(canvas_p0.x + scrolling.x, canvas_p0.y + scrolling.y); const ImVec2 mouse_pos(imgui_io.MousePos.x - origin.x, @@ -224,7 +220,6 @@ bool CanvasInteractionHandler::DrawTileSelector(ImDrawList* /*draw_list*/, ImVec2 scrolling, float tile_size, bool is_hovered) { - const ImGuiIO& imgui_io = ImGui::GetIO(); const ImVec2 origin(canvas_p0.x + scrolling.x, canvas_p0.y + scrolling.y); const ImVec2 mouse_pos(imgui_io.MousePos.x - origin.x, @@ -250,7 +245,6 @@ bool CanvasInteractionHandler::DrawTileSelector(ImDrawList* /*draw_list*/, bool CanvasInteractionHandler::DrawSelectRect( int current_map, ImDrawList* draw_list, ImVec2 canvas_p0, ImVec2 scrolling, float global_scale, float tile_size, bool is_hovered) { - if (!is_hovered) { return false; } @@ -290,8 +284,8 @@ bool CanvasInteractionHandler::DrawSelectRect( return false; } -// Helper methods - these are thin wrappers that could be static but kept as instance -// methods for potential future state access +// Helper methods - these are thin wrappers that could be static but kept as +// instance methods for potential future state access ImVec2 CanvasInteractionHandler::AlignPosToGrid(ImVec2 pos, float grid_step) { return AlignToGridLocal(pos, grid_step); } diff --git a/src/app/gui/canvas/canvas_interaction_handler.h b/src/app/gui/canvas/canvas_interaction_handler.h index 27122ef7..1c00277c 100644 --- a/src/app/gui/canvas/canvas_interaction_handler.h +++ b/src/app/gui/canvas/canvas_interaction_handler.h @@ -2,6 +2,7 @@ #define YAZE_APP_GUI_CANVAS_CANVAS_INTERACTION_HANDLER_H #include + #include "app/gfx/core/bitmap.h" #include "app/gfx/render/tilemap.h" #include "imgui/imgui.h" @@ -40,11 +41,11 @@ struct TileInteractionResult { /** * @brief Handles all tile-based interactions for Canvas - * + * * Consolidates tile painting, selection, and multi-selection logic * that was previously scattered across Canvas methods. Provides a * unified interface for common tile interaction patterns. - * + * * Key Features: * - Single tile painting with preview * - Drag painting for continuous tile placement diff --git a/src/app/gui/canvas/canvas_menu.h b/src/app/gui/canvas/canvas_menu.h index 76ec36df..3db582e9 100644 --- a/src/app/gui/canvas/canvas_menu.h +++ b/src/app/gui/canvas/canvas_menu.h @@ -13,7 +13,7 @@ namespace gui { /** * @brief Menu section priority for controlling rendering order - * + * * Lower values render first in the context menu: * - Editor-specific items (0) appear at the top * - Bitmap/palette operations (10) in the middle @@ -29,7 +29,7 @@ enum class MenuSectionPriority { /** * @brief Declarative popup definition for menu items - * + * * Links a menu item to a persistent popup that should open when the menu * item is selected. This separates popup definition from popup rendering. */ @@ -37,7 +37,8 @@ struct CanvasPopupDefinition { // Unique popup identifier for ImGui std::string popup_id; - // Callback that renders the popup content (should call ImGui::BeginPopup/EndPopup) + // Callback that renders the popup content (should call + // ImGui::BeginPopup/EndPopup) std::function render_callback; // Whether to automatically open the popup when menu item is selected @@ -56,7 +57,7 @@ struct CanvasPopupDefinition { /** * @brief Declarative menu item definition - * + * * Pure data structure representing a menu item with optional popup linkage. * Can be composed into hierarchical menus via subitems. */ @@ -77,14 +78,10 @@ struct CanvasMenuItem { std::optional popup; // Condition to determine if menu item is enabled - std::function enabled_condition = []() { - return true; - }; + std::function enabled_condition = []() { return true; }; // Condition to determine if menu item is visible - std::function visible_condition = []() { - return true; - }; + std::function visible_condition = []() { return true; }; // Nested submenu items std::vector subitems; @@ -116,9 +113,7 @@ struct CanvasMenuItem { static CanvasMenuItem Disabled(const std::string& lbl) { CanvasMenuItem item; item.label = lbl; - item.enabled_condition = []() { - return false; - }; + item.enabled_condition = []() { return false; }; return item; } @@ -146,7 +141,7 @@ struct CanvasMenuItem { /** * @brief Menu section grouping related menu items - * + * * Provides visual organization of menu items with optional section titles. * Sections are rendered in priority order. */ @@ -186,7 +181,7 @@ struct CanvasMenuSection { /** * @brief Complete menu definition - * + * * Aggregates menu sections for a complete context menu or popup menu. */ struct CanvasMenuDefinition { @@ -221,9 +216,9 @@ struct CanvasMenuDefinition { /** * @brief Render a single menu item - * + * * Handles visibility, enabled state, subitems, and popup linkage. - * + * * @param item Menu item to render * @param popup_opened_callback Optional callback invoked when popup is opened */ @@ -234,9 +229,9 @@ void RenderMenuItem( /** * @brief Render a menu section - * + * * Renders section title (if present), all items, and separator. - * + * * @param section Menu section to render * @param popup_opened_callback Optional callback invoked when popup is opened */ @@ -247,10 +242,10 @@ void RenderMenuSection( /** * @brief Render a complete menu definition - * + * * Renders all sections in order. Does not handle ImGui::BeginPopup/EndPopup - * caller is responsible for popup context. - * + * * @param menu Menu definition to render * @param popup_opened_callback Optional callback invoked when popup is opened */ diff --git a/src/app/gui/canvas/canvas_menu_builder.h b/src/app/gui/canvas/canvas_menu_builder.h index 200fcdda..51abcb7b 100644 --- a/src/app/gui/canvas/canvas_menu_builder.h +++ b/src/app/gui/canvas/canvas_menu_builder.h @@ -12,9 +12,9 @@ namespace gui { /** * @brief Builder pattern for constructing canvas menus fluently - * + * * Phase 4: Simplifies menu construction with chainable methods. - * + * * Example usage: * @code * CanvasMenuBuilder builder; @@ -22,7 +22,7 @@ namespace gui { * .AddItem("Cut", ICON_MD_CONTENT_CUT, []() { DoCut(); }) * .AddItem("Copy", ICON_MD_CONTENT_COPY, []() { DoCopy(); }) * .AddSeparator() - * .AddPopupItem("Properties", ICON_MD_SETTINGS, "props_popup", + * .AddPopupItem("Properties", ICON_MD_SETTINGS, "props_popup", * []() { RenderPropertiesPopup(); }) * .Build(); * @endcode diff --git a/src/app/gui/canvas/canvas_modals.cc b/src/app/gui/canvas/canvas_modals.cc index 9047cc20..24eb5f00 100644 --- a/src/app/gui/canvas/canvas_modals.cc +++ b/src/app/gui/canvas/canvas_modals.cc @@ -19,22 +19,19 @@ namespace { inline void DispatchConfig( const std::function& callback, const CanvasConfig& config) { - if (callback) - callback(config); + if (callback) callback(config); } inline void DispatchScale( const std::function& callback, const CanvasConfig& config) { - if (callback) - callback(config); + if (callback) callback(config); } } // namespace void CanvasModals::ShowAdvancedProperties(const std::string& canvas_id, const CanvasConfig& config, const gfx::Bitmap* bitmap) { - std::string modal_id = canvas_id + "_advanced_properties"; auto render_func = [=]() mutable { @@ -50,7 +47,6 @@ void CanvasModals::ShowAdvancedProperties(const std::string& canvas_id, void CanvasModals::ShowScalingControls(const std::string& canvas_id, const CanvasConfig& config, const gfx::Bitmap* bitmap) { - std::string modal_id = canvas_id + "_scaling_controls"; auto render_func = [=]() mutable { @@ -65,48 +61,36 @@ void CanvasModals::ShowScalingControls(const std::string& canvas_id, void CanvasModals::ShowBppConversionDialog( const std::string& canvas_id, const BppConversionOptions& options) { - std::string modal_id = canvas_id + "_bpp_conversion"; - auto render_func = [=]() { - RenderBppConversionModal(modal_id, options); - }; + auto render_func = [=]() { RenderBppConversionModal(modal_id, options); }; OpenModal(modal_id, render_func); } void CanvasModals::ShowPaletteEditor(const std::string& canvas_id, const PaletteEditorOptions& options) { - std::string modal_id = canvas_id + "_palette_editor"; - auto render_func = [=]() { - RenderPaletteEditorModal(modal_id, options); - }; + auto render_func = [=]() { RenderPaletteEditorModal(modal_id, options); }; OpenModal(modal_id, render_func); } void CanvasModals::ShowColorAnalysis(const std::string& canvas_id, const ColorAnalysisOptions& options) { - std::string modal_id = canvas_id + "_color_analysis"; - auto render_func = [=]() { - RenderColorAnalysisModal(modal_id, options); - }; + auto render_func = [=]() { RenderColorAnalysisModal(modal_id, options); }; OpenModal(modal_id, render_func); } void CanvasModals::ShowPerformanceIntegration( const std::string& canvas_id, const PerformanceOptions& options) { - std::string modal_id = canvas_id + "_performance"; - auto render_func = [=]() { - RenderPerformanceModal(modal_id, options); - }; + auto render_func = [=]() { RenderPerformanceModal(modal_id, options); }; OpenModal(modal_id, render_func); } @@ -133,13 +117,11 @@ bool CanvasModals::IsAnyModalOpen() const { void CanvasModals::RenderAdvancedPropertiesModal(const std::string& canvas_id, CanvasConfig& config, const gfx::Bitmap* bitmap) { - std::string modal_title = "Advanced Canvas Properties"; ImGui::SetNextWindowSize(ImVec2(600, 500), ImGuiCond_FirstUseEver); if (ImGui::BeginPopupModal(modal_title.c_str(), nullptr, ImGuiWindowFlags_AlwaysAutoResize)) { - // Header with icon ImGui::Text("%s %s", ICON_MD_SETTINGS, modal_title.c_str()); ImGui::Separator(); @@ -220,8 +202,7 @@ void CanvasModals::RenderAdvancedPropertiesModal(const std::string& canvas_id, const float preset_values[] = {0.25f, 0.5f, 1.0f, 2.0f, 4.0f, 8.0f}; for (int i = 0; i < 6; ++i) { - if (i > 0) - ImGui::SameLine(); + if (i > 0) ImGui::SameLine(); if (ImGui::Button(preset_labels[i])) { config.global_scale = preset_values[i]; DispatchConfig(config.on_config_changed, config); @@ -306,13 +287,11 @@ void CanvasModals::RenderAdvancedPropertiesModal(const std::string& canvas_id, void CanvasModals::RenderScalingControlsModal(const std::string& canvas_id, CanvasConfig& config, const gfx::Bitmap* bitmap) { - std::string modal_title = "Canvas Scaling Controls"; ImGui::SetNextWindowSize(ImVec2(500, 400), ImGuiCond_FirstUseEver); if (ImGui::BeginPopupModal(modal_title.c_str(), nullptr, ImGuiWindowFlags_AlwaysAutoResize)) { - // Header with icon ImGui::Text("%s %s", ICON_MD_ZOOM_IN, modal_title.c_str()); ImGui::Separator(); @@ -328,8 +307,7 @@ void CanvasModals::RenderScalingControlsModal(const std::string& canvas_id, const float preset_values[] = {0.25f, 0.5f, 1.0f, 2.0f, 4.0f, 8.0f}; for (int i = 0; i < 6; ++i) { - if (i > 0) - ImGui::SameLine(); + if (i > 0) ImGui::SameLine(); if (ImGui::Button(preset_labels[i])) { config.global_scale = preset_values[i]; DispatchScale(config.on_scale_changed, config); @@ -349,8 +327,7 @@ void CanvasModals::RenderScalingControlsModal(const std::string& canvas_id, const float grid_values[] = {8.0f, 16.0f, 32.0f, 64.0f}; for (int i = 0; i < 4; ++i) { - if (i > 0) - ImGui::SameLine(); + if (i > 0) ImGui::SameLine(); if (ImGui::Button(grid_labels[i])) { config.grid_step = grid_values[i]; DispatchScale(config.on_scale_changed, config); @@ -395,13 +372,11 @@ void CanvasModals::RenderScalingControlsModal(const std::string& canvas_id, void CanvasModals::RenderBppConversionModal( const std::string& canvas_id, const BppConversionOptions& options) { - std::string modal_title = "BPP Format Conversion"; ImGui::SetNextWindowSize(ImVec2(600, 500), ImGuiCond_FirstUseEver); if (ImGui::BeginPopupModal(modal_title.c_str(), nullptr, ImGuiWindowFlags_AlwaysAutoResize)) { - // Header with icon ImGui::Text("%s %s", ICON_MD_SWAP_HORIZ, modal_title.c_str()); ImGui::Separator(); @@ -430,14 +405,12 @@ void CanvasModals::RenderBppConversionModal( void CanvasModals::RenderPaletteEditorModal( const std::string& canvas_id, const PaletteEditorOptions& options) { - std::string modal_title = options.title.empty() ? "Palette Editor" : options.title; ImGui::SetNextWindowSize(ImVec2(800, 600), ImGuiCond_FirstUseEver); if (ImGui::BeginPopupModal(modal_title.c_str(), nullptr, ImGuiWindowFlags_AlwaysAutoResize)) { - // Header with icon ImGui::Text("%s %s", ICON_MD_PALETTE, modal_title.c_str()); ImGui::Separator(); @@ -464,13 +437,11 @@ void CanvasModals::RenderPaletteEditorModal( void CanvasModals::RenderColorAnalysisModal( const std::string& canvas_id, const ColorAnalysisOptions& options) { - std::string modal_title = "Color Analysis"; ImGui::SetNextWindowSize(ImVec2(700, 500), ImGuiCond_FirstUseEver); if (ImGui::BeginPopupModal(modal_title.c_str(), nullptr, ImGuiWindowFlags_AlwaysAutoResize)) { - // Header with icon ImGui::Text("%s %s", ICON_MD_ZOOM_IN, modal_title.c_str()); ImGui::Separator(); @@ -497,13 +468,11 @@ void CanvasModals::RenderColorAnalysisModal( void CanvasModals::RenderPerformanceModal(const std::string& canvas_id, const PerformanceOptions& options) { - std::string modal_title = "Canvas Performance"; ImGui::SetNextWindowSize(ImVec2(500, 300), ImGuiCond_FirstUseEver); if (ImGui::BeginPopupModal(modal_title.c_str(), nullptr, ImGuiWindowFlags_AlwaysAutoResize)) { - // Header with icon ImGui::Text("%s %s", ICON_MD_TRENDING_UP, modal_title.c_str()); ImGui::Separator(); diff --git a/src/app/gui/canvas/canvas_modals.h b/src/app/gui/canvas/canvas_modals.h index c09c609d..ce72269a 100644 --- a/src/app/gui/canvas/canvas_modals.h +++ b/src/app/gui/canvas/canvas_modals.h @@ -4,6 +4,7 @@ #include #include #include + #include "app/gfx/core/bitmap.h" #include "app/gfx/types/snes_palette.h" #include "app/gfx/util/bpp_format_manager.h" diff --git a/src/app/gui/canvas/canvas_performance_integration.cc b/src/app/gui/canvas/canvas_performance_integration.cc index 7fde965c..28c0f860 100644 --- a/src/app/gui/canvas/canvas_performance_integration.cc +++ b/src/app/gui/canvas/canvas_performance_integration.cc @@ -27,8 +27,7 @@ void CanvasPerformanceIntegration::Initialize(const std::string& canvas_id) { } void CanvasPerformanceIntegration::StartMonitoring() { - if (!monitoring_enabled_) - return; + if (!monitoring_enabled_) return; // Start frame timer frame_timer_active_ = true; @@ -65,8 +64,7 @@ void CanvasPerformanceIntegration::StopMonitoring() { } void CanvasPerformanceIntegration::UpdateMetrics() { - if (!monitoring_enabled_) - return; + if (!monitoring_enabled_) return; // Update frame time UpdateFrameTime(); @@ -95,8 +93,7 @@ void CanvasPerformanceIntegration::UpdateMetrics() { void CanvasPerformanceIntegration::RecordOperation( const std::string& operation_name, double time_ms, CanvasUsage usage_mode) { - if (!monitoring_enabled_) - return; + if (!monitoring_enabled_) return; // Update operation counts based on usage mode switch (usage_mode) { @@ -120,7 +117,8 @@ void CanvasPerformanceIntegration::RecordOperation( } // Record operation timing in internal metrics - // Note: PerformanceProfiler uses StartTimer/EndTimer pattern, not RecordOperation + // Note: PerformanceProfiler uses StartTimer/EndTimer pattern, not + // RecordOperation // Update usage tracker if available if (usage_tracker_) { @@ -143,7 +141,8 @@ void CanvasPerformanceIntegration::RecordCachePerformance(int hits, CalculateCacheHitRatio(); } -// These methods are already defined in the header as inline, removing duplicates +// These methods are already defined in the header as inline, removing +// duplicates std::string CanvasPerformanceIntegration::GetPerformanceSummary() const { std::ostringstream summary; @@ -294,8 +293,7 @@ std::string CanvasPerformanceIntegration::ExportPerformanceReport() const { } void CanvasPerformanceIntegration::RenderPerformanceUI() { - if (!monitoring_enabled_) - return; + if (!monitoring_enabled_) return; if (ImGui::Begin("Canvas Performance", &show_performance_ui_)) { // Performance overview @@ -384,8 +382,7 @@ void CanvasPerformanceIntegration::SaveCurrentMetrics() { void CanvasPerformanceIntegration::AnalyzePerformance() { // Analyze performance trends and patterns - if (performance_history_.size() < 2) - return; + if (performance_history_.size() < 2) return; // Calculate trends double frame_time_trend = 0.0; diff --git a/src/app/gui/canvas/canvas_performance_integration.h b/src/app/gui/canvas/canvas_performance_integration.h index 9888a1e6..0900b0e5 100644 --- a/src/app/gui/canvas/canvas_performance_integration.h +++ b/src/app/gui/canvas/canvas_performance_integration.h @@ -6,6 +6,7 @@ #include #include #include + #include "app/gfx/debug/performance/performance_dashboard.h" #include "app/gfx/debug/performance/performance_profiler.h" #include "canvas_usage_tracker.h" diff --git a/src/app/gui/canvas/canvas_popup.cc b/src/app/gui/canvas/canvas_popup.cc index a638c2ff..752998c0 100644 --- a/src/app/gui/canvas/canvas_popup.cc +++ b/src/app/gui/canvas/canvas_popup.cc @@ -59,7 +59,8 @@ void PopupRegistry::RenderAll() { // Call the render callback which should handle BeginPopup/EndPopup it->render_callback(); - // Check if popup was closed by user (clicking outside, pressing Escape, etc.) + // Check if popup was closed by user (clicking outside, pressing Escape, + // etc.) if (!ImGui::IsPopupOpen(it->popup_id.c_str())) { it->is_open = false; } diff --git a/src/app/gui/canvas/canvas_popup.h b/src/app/gui/canvas/canvas_popup.h index a3620342..74219a18 100644 --- a/src/app/gui/canvas/canvas_popup.h +++ b/src/app/gui/canvas/canvas_popup.h @@ -12,7 +12,7 @@ namespace gui { /** * @brief State for a single persistent popup - * + * * POD struct representing the state of a popup that persists across frames. * Popups remain open until explicitly closed or the user dismisses them. */ @@ -40,10 +40,10 @@ struct PopupState { /** * @brief Registry for managing persistent popups - * + * * Maintains a collection of popups and their lifecycle. Handles opening, * closing, and rendering popups across frames. - * + * * This class is designed to be embedded in Canvas or used standalone for * testing and custom UI components. */ @@ -53,10 +53,10 @@ class PopupRegistry { /** * @brief Open a persistent popup - * + * * If the popup already exists, updates its callback and reopens it. * If the popup is new, adds it to the registry and opens it. - * + * * @param popup_id Unique identifier for the popup * @param render_callback Function that renders the popup content */ @@ -64,17 +64,17 @@ class PopupRegistry { /** * @brief Close a persistent popup - * + * * Marks the popup as closed. It will be removed from the registry on the * next render pass. - * + * * @param popup_id Identifier of the popup to close */ void Close(const std::string& popup_id); /** * @brief Check if a popup is currently open - * + * * @param popup_id Identifier of the popup to check * @return true if popup is open, false otherwise */ @@ -82,10 +82,10 @@ class PopupRegistry { /** * @brief Render all active popups - * + * * Iterates through all open popups and calls their render callbacks. * Automatically removes popups that have been closed by the user. - * + * * This should be called once per frame, typically at the end of the * frame after all other rendering is complete. */ @@ -93,14 +93,14 @@ class PopupRegistry { /** * @brief Get the number of active popups - * + * * @return Number of open popups in the registry */ size_t GetActiveCount() const; /** * @brief Clear all popups from the registry - * + * * Closes all popups and removes them from the registry. * Useful for cleanup or resetting state. */ @@ -108,7 +108,7 @@ class PopupRegistry { /** * @brief Get direct access to the popup list (for migration/debugging) - * + * * @return Reference to the internal popup vector */ std::vector& GetPopups() { return popups_; } diff --git a/src/app/gui/canvas/canvas_rendering.cc b/src/app/gui/canvas/canvas_rendering.cc index be9082a8..2e826b46 100644 --- a/src/app/gui/canvas/canvas_rendering.cc +++ b/src/app/gui/canvas/canvas_rendering.cc @@ -2,6 +2,7 @@ #include #include + #include "app/gui/canvas/canvas_utils.h" namespace yaze { @@ -15,7 +16,6 @@ constexpr uint32_t kWhiteColor = IM_COL32(255, 255, 255, 255); void RenderCanvasBackground(ImDrawList* draw_list, const CanvasGeometry& geometry) { - // Draw border and background color (extracted from Canvas::DrawBackground) draw_list->AddRectFilled(geometry.canvas_p0, geometry.canvas_p1, kRectangleColor); @@ -24,12 +24,12 @@ void RenderCanvasBackground(ImDrawList* draw_list, void RenderCanvasGrid(ImDrawList* draw_list, const CanvasGeometry& geometry, const CanvasConfig& config, int highlight_tile_id) { - if (!config.enable_grid) { return; } - // Create render context for utility functions (extracted from Canvas::DrawGrid) + // Create render context for utility functions (extracted from + // Canvas::DrawGrid) CanvasUtils::CanvasRenderContext ctx = { .draw_list = draw_list, .canvas_p0 = geometry.canvas_p0, @@ -48,8 +48,8 @@ void RenderCanvasOverlay(ImDrawList* draw_list, const CanvasGeometry& geometry, const CanvasConfig& config, const ImVector& points, const ImVector& selected_points) { - - // Create render context for utility functions (extracted from Canvas::DrawOverlay) + // Create render context for utility functions (extracted from + // Canvas::DrawOverlay) CanvasUtils::CanvasRenderContext ctx = { .draw_list = draw_list, .canvas_p0 = geometry.canvas_p0, @@ -68,7 +68,6 @@ void RenderCanvasLabels(ImDrawList* draw_list, const CanvasGeometry& geometry, const CanvasConfig& config, const ImVector>& labels, int current_labels, int tile_id_offset) { - if (!config.enable_custom_labels || current_labels >= labels.size()) { return; } @@ -96,7 +95,6 @@ void RenderCanvasLabels(ImDrawList* draw_list, const CanvasGeometry& geometry, void RenderBitmapOnCanvas(ImDrawList* draw_list, const CanvasGeometry& geometry, gfx::Bitmap& bitmap, int /*border_offset*/, float scale) { - if (!bitmap.is_active()) { return; } @@ -112,7 +110,6 @@ void RenderBitmapOnCanvas(ImDrawList* draw_list, const CanvasGeometry& geometry, void RenderBitmapOnCanvas(ImDrawList* draw_list, const CanvasGeometry& geometry, gfx::Bitmap& bitmap, int x_offset, int y_offset, float scale, int alpha) { - if (!bitmap.is_active()) { return; } @@ -139,7 +136,6 @@ void RenderBitmapOnCanvas(ImDrawList* draw_list, const CanvasGeometry& geometry, void RenderBitmapOnCanvas(ImDrawList* draw_list, const CanvasGeometry& geometry, gfx::Bitmap& bitmap, ImVec2 dest_pos, ImVec2 dest_size, ImVec2 src_pos, ImVec2 src_size) { - if (!bitmap.is_active()) { return; } @@ -160,7 +156,6 @@ void RenderBitmapGroup(ImDrawList* draw_list, const CanvasGeometry& geometry, std::vector& group, gfx::Tilemap& tilemap, int tile_size, float scale, int local_map_size, ImVec2 total_map_size) { - // Extracted from Canvas::DrawBitmapGroup (lines 1148-1264) // This is used for multi-tile selection preview in overworld editor @@ -168,16 +163,17 @@ void RenderBitmapGroup(ImDrawList* draw_list, const CanvasGeometry& geometry, return; } - // OPTIMIZATION: Use optimized rendering for large groups to improve performance + // OPTIMIZATION: Use optimized rendering for large groups to improve + // performance bool use_optimized_rendering = group.size() > 128; // Pre-calculate common values to avoid repeated computation const float tile_scale = tile_size * scale; const int atlas_tiles_per_row = tilemap.atlas.width() / tilemap.tile_size.x; - // Get selected points (note: this assumes selected_points are available in context) - // For now, we'll just render tiles at their grid positions - // The full implementation would need the selected_points passed in + // Get selected points (note: this assumes selected_points are available in + // context) For now, we'll just render tiles at their grid positions The full + // implementation would need the selected_points passed in int i = 0; for (const auto tile_id : group) { @@ -202,7 +198,6 @@ void RenderBitmapGroup(ImDrawList* draw_list, const CanvasGeometry& geometry, // Simple bounds check if (atlas_tile_x >= 0 && atlas_tile_x < tilemap.atlas.width() && atlas_tile_y >= 0 && atlas_tile_y < tilemap.atlas.height()) { - // Calculate UV coordinates once for efficiency const float atlas_width = static_cast(tilemap.atlas.width()); const float atlas_height = static_cast(tilemap.atlas.height()); diff --git a/src/app/gui/canvas/canvas_rendering.h b/src/app/gui/canvas/canvas_rendering.h index 3f339eda..a752fec4 100644 --- a/src/app/gui/canvas/canvas_rendering.h +++ b/src/app/gui/canvas/canvas_rendering.h @@ -3,6 +3,7 @@ #include #include + #include "app/gfx/core/bitmap.h" #include "app/gfx/render/tilemap.h" #include "app/gui/canvas/canvas_state.h" @@ -14,10 +15,11 @@ namespace gui { /** * @brief Render canvas background and border - * + * * Draws the canvas background rectangle (dark) and border (white) - * at the calculated geometry positions. Extracted from Canvas::DrawBackground(). - * + * at the calculated geometry positions. Extracted from + * Canvas::DrawBackground(). + * * @param draw_list ImGui draw list for rendering * @param geometry Canvas geometry for this frame */ @@ -26,10 +28,10 @@ void RenderCanvasBackground(ImDrawList* draw_list, /** * @brief Render canvas grid with optional highlighting - * + * * Draws grid lines, hex labels, and optional tile highlighting. * Extracted from Canvas::DrawGrid(). - * + * * @param draw_list ImGui draw list for rendering * @param geometry Canvas geometry * @param config Canvas configuration (grid settings) @@ -40,10 +42,10 @@ void RenderCanvasGrid(ImDrawList* draw_list, const CanvasGeometry& geometry, /** * @brief Render canvas overlay (hover and selection points) - * + * * Draws hover preview points and selection rectangle points. * Extracted from Canvas::DrawOverlay(). - * + * * @param draw_list ImGui draw list for rendering * @param geometry Canvas geometry * @param config Canvas configuration (scale) @@ -57,10 +59,10 @@ void RenderCanvasOverlay(ImDrawList* draw_list, const CanvasGeometry& geometry, /** * @brief Render canvas labels on grid - * + * * Draws custom text labels on canvas tiles. * Extracted from Canvas::DrawInfoGrid(). - * + * * @param draw_list ImGui draw list for rendering * @param geometry Canvas geometry * @param config Canvas configuration @@ -75,10 +77,10 @@ void RenderCanvasLabels(ImDrawList* draw_list, const CanvasGeometry& geometry, /** * @brief Render bitmap on canvas (border offset variant) - * + * * Draws a bitmap with a border offset from canvas origin. * Extracted from Canvas::DrawBitmap(). - * + * * @param draw_list ImGui draw list * @param geometry Canvas geometry * @param bitmap Bitmap to render @@ -90,10 +92,10 @@ void RenderBitmapOnCanvas(ImDrawList* draw_list, const CanvasGeometry& geometry, /** * @brief Render bitmap on canvas (x/y offset variant) - * + * * Draws a bitmap at specified x/y offset with optional alpha. * Extracted from Canvas::DrawBitmap(). - * + * * @param draw_list ImGui draw list * @param geometry Canvas geometry * @param bitmap Bitmap to render @@ -108,10 +110,10 @@ void RenderBitmapOnCanvas(ImDrawList* draw_list, const CanvasGeometry& geometry, /** * @brief Render bitmap on canvas (custom source/dest regions) - * + * * Draws a bitmap with explicit source and destination rectangles. * Extracted from Canvas::DrawBitmap(). - * + * * @param draw_list ImGui draw list * @param geometry Canvas geometry * @param bitmap Bitmap to render @@ -126,10 +128,10 @@ void RenderBitmapOnCanvas(ImDrawList* draw_list, const CanvasGeometry& geometry, /** * @brief Render group of bitmaps from tilemap - * + * * Draws multiple tiles for multi-tile selection preview. * Extracted from Canvas::DrawBitmapGroup(). - * + * * @param draw_list ImGui draw list * @param geometry Canvas geometry * @param group Vector of tile IDs to draw diff --git a/src/app/gui/canvas/canvas_state.h b/src/app/gui/canvas/canvas_state.h index a45684d5..29cc13e6 100644 --- a/src/app/gui/canvas/canvas_state.h +++ b/src/app/gui/canvas/canvas_state.h @@ -2,6 +2,7 @@ #define YAZE_APP_GUI_CANVAS_CANVAS_STATE_H #include + #include "app/gui/canvas/canvas_utils.h" #include "imgui/imgui.h" @@ -10,7 +11,7 @@ namespace gui { /** * @brief Canvas geometry calculated per-frame - * + * * Represents the position, size, and scroll state of a canvas * in both screen space and scaled space. Used by rendering * functions to correctly position elements. @@ -32,11 +33,11 @@ struct CanvasGeometry { /** * @brief Complete canvas state snapshot - * + * * Aggregates all canvas state into a single POD for easier * refactoring and testing. Designed to replace the scattered * state members in the Canvas class gradually. - * + * * Usage Pattern: * - Geometry recalculated every frame in DrawBackground() * - Configuration updated via user interaction diff --git a/src/app/gui/canvas/canvas_usage_tracker.cc b/src/app/gui/canvas/canvas_usage_tracker.cc index c1e20265..9cb55b09 100644 --- a/src/app/gui/canvas/canvas_usage_tracker.cc +++ b/src/app/gui/canvas/canvas_usage_tracker.cc @@ -113,7 +113,8 @@ void CanvasUsageTracker::UpdateCanvasState(const ImVec2& canvas_size, last_activity_ = std::chrono::steady_clock::now(); } -// These methods are already defined in the header as inline, removing duplicates +// These methods are already defined in the header as inline, removing +// duplicates std::string CanvasUsageTracker::GetUsageModeName(CanvasUsage usage) const { switch (usage) { diff --git a/src/app/gui/canvas/canvas_usage_tracker.h b/src/app/gui/canvas/canvas_usage_tracker.h index 5f7b968a..fec69cfd 100644 --- a/src/app/gui/canvas/canvas_usage_tracker.h +++ b/src/app/gui/canvas/canvas_usage_tracker.h @@ -6,6 +6,7 @@ #include #include #include + #include "imgui/imgui.h" namespace yaze { @@ -23,7 +24,8 @@ enum class CanvasUsage { kPaletteEditing, // Palette editing mode kBppConversion, // BPP format conversion kPerformanceMode, // Performance monitoring mode - kEntityManipulation, // Generic entity manipulation (insertion/editing/deletion) + kEntityManipulation, // Generic entity manipulation + // (insertion/editing/deletion) kUnknown // Unknown or mixed usage }; diff --git a/src/app/gui/canvas/canvas_utils.cc b/src/app/gui/canvas/canvas_utils.cc index acde4c0c..f3770f78 100644 --- a/src/app/gui/canvas/canvas_utils.cc +++ b/src/app/gui/canvas/canvas_utils.cc @@ -1,6 +1,7 @@ #include "canvas_utils.h" #include + #include "app/gfx/resource/arena.h" #include "app/gfx/types/snes_palette.h" #include "util/log.h" @@ -16,8 +17,7 @@ ImVec2 AlignToGrid(ImVec2 pos, float grid_step) { float CalculateEffectiveScale(ImVec2 canvas_size, ImVec2 content_size, float global_scale) { - if (content_size.x <= 0 || content_size.y <= 0) - return global_scale; + if (content_size.x <= 0 || content_size.y <= 0) return global_scale; float scale_x = (canvas_size.x * global_scale) / content_size.x; float scale_y = (canvas_size.y * global_scale) / content_size.y; @@ -96,8 +96,7 @@ bool LoadROMPaletteGroups(Rom* rom, CanvasPaletteManager& palette_manager) { bool ApplyPaletteGroup(gfx::IRenderer* renderer, gfx::Bitmap* bitmap, CanvasPaletteManager& palette_manager, int group_index, int palette_index) { - if (!bitmap) - return false; + if (!bitmap) return false; if (group_index < 0 || group_index >= palette_manager.rom_palette_groups.size()) { @@ -106,7 +105,8 @@ bool ApplyPaletteGroup(gfx::IRenderer* renderer, gfx::Bitmap* bitmap, const auto& palette = palette_manager.rom_palette_groups[group_index]; - // Apply the full palette or use SetPaletteWithTransparent if palette_index is specified + // Apply the full palette or use SetPaletteWithTransparent if palette_index is + // specified if (palette_index == 0) { bitmap->SetPalette(palette); } else { @@ -208,8 +208,7 @@ void DrawCanvasGridLines(ImDrawList* draw_list, ImVec2 canvas_p0, void DrawCustomHighlight(ImDrawList* draw_list, ImVec2 canvas_p0, ImVec2 scrolling, int highlight_tile_id, float grid_step) { - if (highlight_tile_id == -1) - return; + if (highlight_tile_id == -1) return; int tile_x = highlight_tile_id % 8; int tile_y = highlight_tile_id / 8; @@ -309,8 +308,7 @@ void SetNextCanvasSize(ImVec2 size, bool auto_resize) { // High-level composite operations void DrawCanvasGrid(const CanvasRenderContext& ctx, int highlight_tile_id) { - if (!ctx.enable_grid) - return; + if (!ctx.enable_grid) return; ctx.draw_list->PushClipRect(ctx.canvas_p0, ctx.canvas_p1, true); @@ -364,8 +362,7 @@ void DrawCanvasOverlay(const CanvasRenderContext& ctx, void DrawCanvasLabels(const CanvasRenderContext& ctx, const ImVector>& labels, int current_labels, int tile_id_offset) { - if (current_labels >= labels.size()) - return; + if (current_labels >= labels.size()) return; float scaled_grid_step = ctx.grid_step * ctx.global_scale; diff --git a/src/app/gui/canvas/canvas_utils.h b/src/app/gui/canvas/canvas_utils.h index f4a0c5f8..36cc327b 100644 --- a/src/app/gui/canvas/canvas_utils.h +++ b/src/app/gui/canvas/canvas_utils.h @@ -3,6 +3,7 @@ #include #include + #include "app/gfx/resource/arena.h" #include "app/gfx/types/snes_palette.h" #include "app/gui/canvas/canvas_usage_tracker.h" @@ -14,7 +15,7 @@ namespace gui { /** * @brief Unified configuration for canvas display and interaction - * + * * Consolidates all canvas configuration into a single struct, including * display settings, interaction state, and optional callbacks for updates. */ @@ -104,9 +105,7 @@ struct CanvasContextMenuItem { std::string label; std::string shortcut; std::function callback; - std::function enabled_condition = []() { - return true; - }; + std::function enabled_condition = []() { return true; }; std::vector subitems; }; diff --git a/src/app/gui/core/background_renderer.cc b/src/app/gui/core/background_renderer.cc index d021df96..63964d30 100644 --- a/src/app/gui/core/background_renderer.cc +++ b/src/app/gui/core/background_renderer.cc @@ -24,8 +24,7 @@ void BackgroundRenderer::RenderDockingBackground(ImDrawList* draw_list, const ImVec2& window_pos, const ImVec2& window_size, const Color& theme_color) { - if (!draw_list) - return; + if (!draw_list) return; UpdateAnimation(TimingManager::Get().GetDeltaTime()); @@ -78,8 +77,7 @@ void BackgroundRenderer::RenderGridBackground(ImDrawList* draw_list, const ImVec2& window_pos, const ImVec2& window_size, const Color& grid_color) { - if (!draw_list || grid_settings_.grid_size <= 0) - return; + if (!draw_list || grid_settings_.grid_size <= 0) return; // Grid parameters with optional animation float grid_size = grid_settings_.grid_size; @@ -211,8 +209,7 @@ void BackgroundRenderer::RenderRadialGradient(ImDrawList* draw_list, float radius, const Color& inner_color, const Color& outer_color) { - if (!draw_list) - return; + if (!draw_list) return; const int segments = 32; const int rings = 8; @@ -263,7 +260,8 @@ void BackgroundRenderer::UpdateAnimation(float delta_time) { void BackgroundRenderer::UpdateForTheme(const Color& primary_color, const Color& background_color) { - // Create a grid color that's a subtle blend of the theme's primary and background + // Create a grid color that's a subtle blend of the theme's primary and + // background cached_grid_color_ = { (primary_color.red * 0.3f + background_color.red * 0.7f), (primary_color.green * 0.3f + background_color.green * 0.7f), @@ -394,7 +392,8 @@ void DockSpaceRenderer::BeginEnhancedDockSpace(ImGuiID dockspace_id, // Create the actual dockspace first ImGui::DockSpace(dockspace_id, size, flags); - // NOW draw the background effects on the foreground draw list so they're visible + // NOW draw the background effects on the foreground draw list so they're + // visible if (background_enabled_) { ImDrawList* fg_draw_list = ImGui::GetForegroundDrawList(); auto& theme_manager = ThemeManager::Get(); diff --git a/src/app/gui/core/background_renderer.h b/src/app/gui/core/background_renderer.h index d419b8e2..caff624f 100644 --- a/src/app/gui/core/background_renderer.h +++ b/src/app/gui/core/background_renderer.h @@ -3,10 +3,10 @@ #include #include -#include "imgui/imgui.h" #include "app/gui/core/color.h" #include "app/rom.h" +#include "imgui/imgui.h" namespace yaze { namespace gui { diff --git a/src/app/gui/core/color.cc b/src/app/gui/core/color.cc index a3c30e36..665ce8e5 100644 --- a/src/app/gui/core/color.cc +++ b/src/app/gui/core/color.cc @@ -9,10 +9,10 @@ namespace gui { /** * @brief Convert SnesColor to standard ImVec4 for display - * + * * IMPORTANT: SnesColor.rgb() returns 0-255 values in ImVec4 (unconventional!) * This function converts them to standard ImGui format (0.0-1.0) - * + * * @param color SnesColor with internal 0-255 storage * @return ImVec4 with standard 0.0-1.0 RGBA values for ImGui */ @@ -25,7 +25,7 @@ ImVec4 ConvertSnesColorToImVec4(const gfx::SnesColor& color) { /** * @brief Convert standard ImVec4 to SnesColor - * + * * @param color ImVec4 with standard 0.0-1.0 RGBA values * @return SnesColor with converted values */ @@ -63,7 +63,8 @@ IMGUI_API bool SnesColorEdit4(absl::string_view label, gfx::SnesColor* color, // Only update if the user actually changed the color if (changed) { // set_rgb() handles conversion from 0-1 (ImGui) to 0-255 (internal) - // and automatically calculates snes_ value - no need to call set_snes separately + // and automatically calculates snes_ value - no need to call set_snes + // separately color->set_rgb(displayColor); } @@ -273,8 +274,7 @@ IMGUI_API bool DisplayPalette(gfx::SnesPalette& palette, bool loaded) { ImGui::Text("Palette"); for (int n = 0; n < IM_ARRAYSIZE(saved_palette); n++) { ImGui::PushID(n); - if ((n % 4) != 0) - ImGui::SameLine(0.0f, ImGui::GetStyle().ItemSpacing.y); + if ((n % 4) != 0) ImGui::SameLine(0.0f, ImGui::GetStyle().ItemSpacing.y); ImGuiColorEditFlags palette_button_flags = ImGuiColorEditFlags_NoAlpha | ImGuiColorEditFlags_NoPicker | diff --git a/src/app/gui/core/color.h b/src/app/gui/core/color.h index d7c7f10e..d6c16f2d 100644 --- a/src/app/gui/core/color.h +++ b/src/app/gui/core/color.h @@ -2,9 +2,9 @@ #define YAZE_GUI_COLOR_H #include -#include "absl/strings/str_format.h" #include "absl/status/status.h" +#include "absl/strings/str_format.h" #include "app/gfx/types/snes_palette.h" #include "imgui/imgui.h" diff --git a/src/app/gui/core/icons.h b/src/app/gui/core/icons.h index 7abe2698..7e40d425 100644 --- a/src/app/gui/core/icons.h +++ b/src/app/gui/core/icons.h @@ -1,6 +1,8 @@ -// Generated by https://github.com/juliettef/IconFontCppHeaders script GenerateIconFontCppHeaders.py for languages C and C++ -// from https://github.com/google/material-design-icons/raw/master/font/MaterialIcons-Regular.codepoints -// for use with https://github.com/google/material-design-icons/blob/master/font/MaterialIcons-Regular.ttf +// Generated by https://github.com/juliettef/IconFontCppHeaders script +// GenerateIconFontCppHeaders.py for languages C and C++ from +// https://github.com/google/material-design-icons/raw/master/font/MaterialIcons-Regular.codepoints +// for use with +// https://github.com/google/material-design-icons/blob/master/font/MaterialIcons-Regular.ttf #pragma once #define FONT_ICON_FILE_NAME_MD "MaterialIcons-Regular.ttf" diff --git a/src/app/gui/core/input.cc b/src/app/gui/core/input.cc index 901a727d..ae955084 100644 --- a/src/app/gui/core/input.cc +++ b/src/app/gui/core/input.cc @@ -39,14 +39,12 @@ bool InputScalarLeft(const char* label, ImGuiDataType data_type, void* p_data, const char* format, float input_width, ImGuiInputTextFlags flags, bool no_step = false) { ImGuiWindow* window = ImGui::GetCurrentWindow(); - if (window->SkipItems) - return false; + if (window->SkipItems) return false; ImGuiContext& g = *GImGui; ImGuiStyle& style = g.Style; - if (format == NULL) - format = DataTypeGetInfo(data_type)->PrintFmt; + if (format == NULL) format = DataTypeGetInfo(data_type)->PrintFmt; char buf[64]; DataTypeFormatString(buf, IM_ARRAYSIZE(buf), data_type, p_data, format); @@ -60,7 +58,8 @@ bool InputScalarLeft(const char* label, ImGuiDataType data_type, void* p_data, bool value_changed = false; const float button_size = GetFrameHeight(); - // Support invisible labels (##) by not rendering the label, but still using it for ID + // Support invisible labels (##) by not rendering the label, but still using + // it for ID bool invisible_label = IsInvisibleLabel(label); if (!invisible_label) { @@ -116,8 +115,7 @@ bool InputScalarLeft(const char* label, ImGuiDataType data_type, void* p_data, const ImVec2 backup_frame_padding = style.FramePadding; style.FramePadding.x = style.FramePadding.y; ImGuiButtonFlags button_flags = ImGuiButtonFlags_PressedOnClick; - if (flags & ImGuiInputTextFlags_ReadOnly) - BeginDisabled(); + if (flags & ImGuiInputTextFlags_ReadOnly) BeginDisabled(); SameLine(0, style.ItemInnerSpacing.x); if (ButtonEx("-", ImVec2(button_size, button_size), button_flags)) { DataTypeApplyOp(data_type, '-', p_data, p_data, @@ -131,8 +129,7 @@ bool InputScalarLeft(const char* label, ImGuiDataType data_type, void* p_data, value_changed = true; } - if (flags & ImGuiInputTextFlags_ReadOnly) - EndDisabled(); + if (flags & ImGuiInputTextFlags_ReadOnly) EndDisabled(); style.FramePadding = backup_frame_padding; } @@ -140,8 +137,7 @@ bool InputScalarLeft(const char* label, ImGuiDataType data_type, void* p_data, EndGroup(); ImGui::PopStyleVar(2); - if (value_changed) - MarkItemEdited(g.LastItemData.ID); + if (value_changed) MarkItemEdited(g.LastItemData.ID); return value_changed; } @@ -275,8 +271,7 @@ void ItemLabel(absl::string_view title, ItemLabelFlags flags) { ImGui::CalcTextSize(title.data(), title.data() + title.size()); ImRect textRect; textRect.Min = ImGui::GetCursorScreenPos(); - if (flags & ItemLabelFlag::Right) - textRect.Min.x = textRect.Min.x + itemWidth; + if (flags & ItemLabelFlag::Right) textRect.Min.x = textRect.Min.x + itemWidth; textRect.Max = textRect.Min; textRect.Max.x += fullWidth - itemWidth; textRect.Max.y += textSize.y; @@ -336,9 +331,7 @@ bool InputTileInfo(const char* label, gfx::TileInfo* tile_info) { return changed; } -ImGuiID GetID(const std::string& id) { - return ImGui::GetID(id.c_str()); -} +ImGuiID GetID(const std::string& id) { return ImGui::GetID(id.c_str()); } ImGuiKey MapKeyToImGuiKey(char key) { switch (key) { diff --git a/src/app/gui/core/layout_helpers.cc b/src/app/gui/core/layout_helpers.cc index cfd50cfa..bb1caf4d 100644 --- a/src/app/gui/core/layout_helpers.cc +++ b/src/app/gui/core/layout_helpers.cc @@ -231,9 +231,7 @@ void LayoutHelpers::BeginPropertyGrid(const char* label) { } } -void LayoutHelpers::EndPropertyGrid() { - ImGui::EndTable(); -} +void LayoutHelpers::EndPropertyGrid() { ImGui::EndTable(); } bool LayoutHelpers::InputToolbarField(const char* label, char* buf, size_t buf_size) { diff --git a/src/app/gui/core/style.cc b/src/app/gui/core/style.cc index 6d965673..adf9f95f 100644 --- a/src/app/gui/core/style.cc +++ b/src/app/gui/core/style.cc @@ -192,8 +192,7 @@ static const char* const kIdentifiers[] = { TextEditor::LanguageDefinition GetAssemblyLanguageDef() { TextEditor::LanguageDefinition language_65816; - for (auto& k : kKeywords) - language_65816.mKeywords.emplace(k); + for (auto& k : kKeywords) language_65816.mKeywords.emplace(k); for (auto& k : kIdentifiers) { TextEditor::Identifier id; @@ -275,25 +274,19 @@ void BeginPadding(int i) { ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(i, i)); ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(i, i)); } -void EndPadding() { - EndNoPadding(); -} +void EndPadding() { EndNoPadding(); } void BeginNoPadding() { ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(0, 0)); ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(0, 0)); } -void EndNoPadding() { - ImGui::PopStyleVar(2); -} +void EndNoPadding() { ImGui::PopStyleVar(2); } void BeginChildWithScrollbar(const char* str_id) { // Get available region but ensure minimum size for proper scrolling ImVec2 available = ImGui::GetContentRegionAvail(); - if (available.x < 64.0f) - available.x = 64.0f; - if (available.y < 64.0f) - available.y = 64.0f; + if (available.x < 64.0f) available.x = 64.0f; + if (available.y < 64.0f) available.y = 64.0f; ImGui::BeginChild(str_id, available, true, ImGuiWindowFlags_AlwaysVerticalScrollbar); @@ -307,10 +300,8 @@ void BeginChildWithScrollbar(const char* str_id, ImVec2 content_size) { // Get available region but ensure minimum size for proper scrolling ImVec2 available = ImGui::GetContentRegionAvail(); - if (available.x < 64.0f) - available.x = 64.0f; - if (available.y < 64.0f) - available.y = 64.0f; + if (available.x < 64.0f) available.x = 64.0f; + if (available.y < 64.0f) available.y = 64.0f; ImGui::BeginChild(str_id, available, true, ImGuiWindowFlags_AlwaysVerticalScrollbar); @@ -333,16 +324,14 @@ void BeginTableCanvas(const char* table_id, int columns, ImVec2 canvas_size) { ImVec2 outer_size = ImVec2(0, 0); if (canvas_size.x > 0 || canvas_size.y > 0) { outer_size = canvas_size; - flags |= - ImGuiTableFlags_NoHostExtendY; // Prevent auto-extending past canvas size + flags |= ImGuiTableFlags_NoHostExtendY; // Prevent auto-extending past + // canvas size } ImGui::BeginTable(table_id, columns, flags, outer_size); } -void EndTableCanvas() { - ImGui::EndTable(); -} +void EndTableCanvas() { ImGui::EndTable(); } void SetupCanvasTableColumn(const char* label, float width_ratio) { if (width_ratio > 0) { @@ -364,7 +353,8 @@ void BeginCanvasTableCell(ImVec2 min_size) { // Reserve space for the canvas ImGui::Dummy(actual_size); - // ImGui::SetCursorPos(ImGui::GetCursorPos() - actual_size); // Reset cursor for drawing + // ImGui::SetCursorPos(ImGui::GetCursorPos() - actual_size); // Reset cursor + // for drawing } } @@ -377,11 +367,9 @@ void DrawDisplaySettings(ImGuiStyle* ref) { // Default to using internal storage as reference static bool init = true; - if (init && ref == NULL) - ref_saved_style = style; + if (init && ref == NULL) ref_saved_style = style; init = false; - if (ref == NULL) - ref = &ref_saved_style; + if (ref == NULL) ref = &ref_saved_style; ImGui::PushItemWidth(ImGui::GetWindowWidth() * 0.50f); @@ -428,7 +416,6 @@ void DrawDisplaySettings(ImGuiStyle* ref) { "ThemeSelectionTable", 3, ImGuiTableFlags_SizingStretchProp | ImGuiTableFlags_NoHostExtendY, ImVec2(0, 80))) { - ImGui::TableSetupColumn("Built-in", ImGuiTableColumnFlags_WidthStretch, 0.3f); ImGui::TableSetupColumn("File Themes", ImGuiTableColumnFlags_WidthStretch, @@ -519,8 +506,7 @@ void DrawDisplaySettings(ImGuiStyle* ref) { ImGui::Separator(); - if (ImGui::ShowStyleSelector("Colors##Selector")) - ref_saved_style = style; + if (ImGui::ShowStyleSelector("Colors##Selector")) ref_saved_style = style; ImGui::ShowFontSelector("Fonts##Selector"); // Simplified Settings (expose floating-pointer border sizes as boolean @@ -551,11 +537,9 @@ void DrawDisplaySettings(ImGuiStyle* ref) { } // Save/Revert button - if (ImGui::Button("Save Ref")) - *ref = ref_saved_style = style; + if (ImGui::Button("Save Ref")) *ref = ref_saved_style = style; ImGui::SameLine(); - if (ImGui::Button("Revert Ref")) - style = *ref; + if (ImGui::Button("Revert Ref")) style = *ref; ImGui::SameLine(); ImGui::Separator(); @@ -726,8 +710,7 @@ void DrawDisplaySettings(ImGuiStyle* ref) { ImGui::PushItemWidth(ImGui::GetFontSize() * -12); for (int i = 0; i < ImGuiCol_COUNT; i++) { const char* name = ImGui::GetStyleColorName(i); - if (!filter.PassFilter(name)) - continue; + if (!filter.PassFilter(name)) continue; ImGui::PushID(i); ImGui::ColorEdit4("##color", (float*)&style.Colors[i], ImGuiColorEditFlags_AlphaBar | alpha_flags); @@ -804,8 +787,7 @@ void DrawDisplaySettings(ImGuiStyle* ref) { &style.CircleTessellationMaxError, 0.005f, 0.10f, 5.0f, "%.2f", ImGuiSliderFlags_AlwaysClamp); const bool show_samples = ImGui::IsItemActive(); - if (show_samples) - ImGui::SetNextWindowPos(ImGui::GetCursorScreenPos()); + if (show_samples) ImGui::SetNextWindowPos(ImGui::GetCursorScreenPos()); if (show_samples && ImGui::BeginTooltip()) { ImGui::TextUnformatted("(R = radius, N = number of segments)"); ImGui::Spacing(); @@ -872,11 +854,9 @@ void DrawDisplaySettingsForPopup(ImGuiStyle* ref) { // Default to using internal storage as reference static bool init = true; - if (init && ref == NULL) - ref_saved_style = style; + if (init && ref == NULL) ref_saved_style = style; init = false; - if (ref == NULL) - ref = &ref_saved_style; + if (ref == NULL) ref = &ref_saved_style; ImGui::PushItemWidth(ImGui::GetWindowWidth() * 0.50f); @@ -979,8 +959,7 @@ void DrawDisplaySettingsForPopup(ImGuiStyle* ref) { ImGui::Separator(); - if (ImGui::ShowStyleSelector("Colors##Selector")) - ref_saved_style = style; + if (ImGui::ShowStyleSelector("Colors##Selector")) ref_saved_style = style; ImGui::ShowFontSelector("Fonts##Selector"); // Quick style controls before the tabbed section @@ -1007,17 +986,14 @@ void DrawDisplaySettingsForPopup(ImGuiStyle* ref) { } // Save/Revert buttons - if (ImGui::Button("Save Ref")) - *ref = ref_saved_style = style; + if (ImGui::Button("Save Ref")) *ref = ref_saved_style = style; ImGui::SameLine(); - if (ImGui::Button("Revert Ref")) - style = *ref; + if (ImGui::Button("Revert Ref")) style = *ref; ImGui::Separator(); // Add the comprehensive tabbed settings from the original DrawDisplaySettings if (ImGui::BeginTabBar("DisplaySettingsTabs", ImGuiTabBarFlags_None)) { - if (ImGui::BeginTabItem("Sizes")) { ImGui::SeparatorText("Main"); ImGui::SliderFloat2("WindowPadding", (float*)&style.WindowPadding, 0.0f, @@ -1183,8 +1159,7 @@ void DrawDisplaySettingsForPopup(ImGuiStyle* ref) { ImGui::PushItemWidth(ImGui::GetFontSize() * -12); for (int i = 0; i < ImGuiCol_COUNT; i++) { const char* name = ImGui::GetStyleColorName(i); - if (!filter.PassFilter(name)) - continue; + if (!filter.PassFilter(name)) continue; ImGui::PushID(i); ImGui::ColorEdit4("##color", (float*)&style.Colors[i], ImGuiColorEditFlags_AlphaBar | alpha_flags); @@ -1261,8 +1236,7 @@ void DrawDisplaySettingsForPopup(ImGuiStyle* ref) { &style.CircleTessellationMaxError, 0.005f, 0.10f, 5.0f, "%.2f", ImGuiSliderFlags_AlwaysClamp); const bool show_samples = ImGui::IsItemActive(); - if (show_samples) - ImGui::SetNextWindowPos(ImGui::GetCursorScreenPos()); + if (show_samples) ImGui::SetNextWindowPos(ImGui::GetCursorScreenPos()); if (show_samples && ImGui::BeginTooltip()) { ImGui::TextUnformatted("(R = radius, N = number of segments)"); ImGui::Spacing(); diff --git a/src/app/gui/core/theme_manager.cc b/src/app/gui/core/theme_manager.cc index 74625107..6ba05b6b 100644 --- a/src/app/gui/core/theme_manager.cc +++ b/src/app/gui/core/theme_manager.cc @@ -153,7 +153,8 @@ void ThemeManager::InitializeBuiltInThemes() { } void ThemeManager::CreateFallbackYazeClassic() { - // Fallback theme that matches the original ColorsYaze() function colors but in theme format + // Fallback theme that matches the original ColorsYaze() function colors but + // in theme format EnhancedTheme theme; theme.name = "YAZE Tre"; theme.description = "YAZE theme resource edition"; @@ -390,13 +391,11 @@ Color ThemeManager::GetWelcomeScreenAccent() const { } void ThemeManager::ShowThemeSelector(bool* p_open) { - if (!p_open || !*p_open) - return; + if (!p_open || !*p_open) return; if (ImGui::Begin( absl::StrFormat("%s Theme Selector", ICON_MD_PALETTE).c_str(), p_open)) { - // Add subtle particle effects to theme selector static float theme_animation_time = 0.0f; theme_animation_time += ImGui::GetIO().DeltaTime; @@ -478,8 +477,8 @@ void ThemeManager::ShowThemeSelector(bool* p_open) { name.c_str()) .c_str(), ImVec2(-1, 40))) { - auto status = LoadTheme( - name); // Use LoadTheme instead of ApplyTheme to ensure correct tracking + auto status = LoadTheme(name); // Use LoadTheme instead of ApplyTheme + // to ensure correct tracking if (!status.ok()) { LOG_ERROR("Theme Manager", "Failed to load theme %s", name.c_str()); } @@ -563,8 +562,7 @@ absl::Status ThemeManager::ParseThemeFile(const std::string& content, while (std::getline(stream, line)) { // Skip empty lines and comments - if (line.empty() || line[0] == '#') - continue; + if (line.empty() || line[0] == '#') continue; // Check for section headers [section_name] if (line[0] == '[' && line.back() == ']') { @@ -573,8 +571,7 @@ absl::Status ThemeManager::ParseThemeFile(const std::string& content, } size_t eq_pos = line.find('='); - if (eq_pos == std::string::npos) - continue; + if (eq_pos == std::string::npos) continue; std::string key = line.substr(0, eq_pos); std::string value = line.substr(eq_pos + 1); @@ -1016,7 +1013,8 @@ void ThemeManager::ApplyClassicYazeTheme() { "Original YAZE theme (direct ColorsYaze() function)"; classic_theme.author = "YAZE Team"; - // Extract ALL the colors that ColorsYaze() sets (copy from CreateFallbackYazeClassic) + // Extract ALL the colors that ColorsYaze() sets (copy from + // CreateFallbackYazeClassic) classic_theme.primary = RGBA(92, 115, 92); // allttpLightGreen classic_theme.secondary = RGBA(71, 92, 71); // alttpMidGreen classic_theme.accent = RGBA(89, 119, 89); // TabActive @@ -1175,14 +1173,12 @@ void ThemeManager::ApplyClassicYazeTheme() { } void ThemeManager::ShowSimpleThemeEditor(bool* p_open) { - if (!p_open || !*p_open) - return; + if (!p_open || !*p_open) return; ImGui::SetNextWindowSize(ImVec2(800, 600), ImGuiCond_FirstUseEver); if (ImGui::Begin(absl::StrFormat("%s Theme Editor", ICON_MD_PALETTE).c_str(), p_open, ImGuiWindowFlags_MenuBar)) { - // Add gentle particle effects to theme editor background static float editor_animation_time = 0.0f; editor_animation_time += ImGui::GetIO().DeltaTime; @@ -1305,7 +1301,8 @@ void ThemeManager::ShowSimpleThemeEditor(bool* p_open) { original_theme = current_theme_; theme_backup_made = true; } - // Apply the edit theme directly to ImGui without changing theme manager state + // Apply the edit theme directly to ImGui without changing theme manager + // state edit_theme.ApplyToImGui(); } }; @@ -1368,7 +1365,6 @@ void ThemeManager::ShowSimpleThemeEditor(bool* p_open) { // Enhanced theme editing with tabs for better organization if (ImGui::BeginTabBar("ThemeEditorTabs", ImGuiTabBarFlags_None)) { - // Apply live preview on first frame if enabled static bool first_frame = true; if (first_frame && live_preview) { @@ -1569,28 +1565,23 @@ void ThemeManager::ShowSimpleThemeEditor(bool* p_open) { if (ImGui::SliderFloat("Window Rounding", &edit_theme.window_rounding, 0.0f, 20.0f)) { - if (live_preview) - ApplyTheme(edit_theme); + if (live_preview) ApplyTheme(edit_theme); } if (ImGui::SliderFloat("Frame Rounding", &edit_theme.frame_rounding, 0.0f, 20.0f)) { - if (live_preview) - ApplyTheme(edit_theme); + if (live_preview) ApplyTheme(edit_theme); } if (ImGui::SliderFloat("Scrollbar Rounding", &edit_theme.scrollbar_rounding, 0.0f, 20.0f)) { - if (live_preview) - ApplyTheme(edit_theme); + if (live_preview) ApplyTheme(edit_theme); } if (ImGui::SliderFloat("Tab Rounding", &edit_theme.tab_rounding, 0.0f, 20.0f)) { - if (live_preview) - ApplyTheme(edit_theme); + if (live_preview) ApplyTheme(edit_theme); } if (ImGui::SliderFloat("Grab Rounding", &edit_theme.grab_rounding, 0.0f, 20.0f)) { - if (live_preview) - ApplyTheme(edit_theme); + if (live_preview) ApplyTheme(edit_theme); } ImGui::Separator(); @@ -1598,13 +1589,11 @@ void ThemeManager::ShowSimpleThemeEditor(bool* p_open) { if (ImGui::SliderFloat("Window Border Size", &edit_theme.window_border_size, 0.0f, 3.0f)) { - if (live_preview) - ApplyTheme(edit_theme); + if (live_preview) ApplyTheme(edit_theme); } if (ImGui::SliderFloat("Frame Border Size", &edit_theme.frame_border_size, 0.0f, 3.0f)) { - if (live_preview) - ApplyTheme(edit_theme); + if (live_preview) ApplyTheme(edit_theme); } ImGui::Separator(); @@ -1612,8 +1601,7 @@ void ThemeManager::ShowSimpleThemeEditor(bool* p_open) { if (ImGui::Checkbox("Enable Animations", &edit_theme.enable_animations)) { - if (live_preview) - ApplyTheme(edit_theme); + if (live_preview) ApplyTheme(edit_theme); } if (edit_theme.enable_animations) { if (ImGui::SliderFloat("Animation Speed", &edit_theme.animation_speed, @@ -1623,8 +1611,7 @@ void ThemeManager::ShowSimpleThemeEditor(bool* p_open) { } if (ImGui::Checkbox("Enable Glow Effects", &edit_theme.enable_glow_effects)) { - if (live_preview) - ApplyTheme(edit_theme); + if (live_preview) ApplyTheme(edit_theme); } ImGui::EndTabItem(); @@ -2172,8 +2159,8 @@ void ThemeManager::ShowSimpleThemeEditor(bool* p_open) { // Reset backup state since we're back to current theme if (theme_backup_made) { theme_backup_made = false; - current_theme_ - .ApplyToImGui(); // Apply current theme to clear any preview changes + current_theme_.ApplyToImGui(); // Apply current theme to clear any + // preview changes } } @@ -2282,7 +2269,8 @@ std::vector ThemeManager::GetThemeSearchPaths() const { // Platform-specific resource paths #ifdef __APPLE__ - // macOS bundle resource path (this should be the primary path for bundled apps) + // macOS bundle resource path (this should be the primary path for bundled + // apps) std::string bundle_themes = util::GetResourcePath("assets/themes/"); if (!bundle_themes.empty()) { search_paths.push_back(bundle_themes); @@ -2342,7 +2330,6 @@ std::vector ThemeManager::DiscoverAvailableThemeFiles() const { auto search_paths = GetThemeSearchPaths(); for (const auto& search_path : search_paths) { - try { // Use platform-specific file discovery instead of glob #ifdef __APPLE__ diff --git a/src/app/gui/core/theme_manager.h b/src/app/gui/core/theme_manager.h index 04ab3feb..f574256b 100644 --- a/src/app/gui/core/theme_manager.h +++ b/src/app/gui/core/theme_manager.h @@ -190,8 +190,9 @@ class ThemeManager { absl::Status SaveThemeToFile(const EnhancedTheme& theme, const std::string& filepath) const; - // Dynamic theme discovery - replaces hardcoded theme lists with automatic discovery - // This works across development builds, macOS app bundles, and other deployment scenarios + // Dynamic theme discovery - replaces hardcoded theme lists with automatic + // discovery This works across development builds, macOS app bundles, and + // other deployment scenarios std::vector DiscoverAvailableThemeFiles() const; absl::Status LoadAllAvailableThemes(); absl::Status RefreshAvailableThemes(); // Public method to refresh at runtime @@ -272,21 +273,13 @@ inline ImVec4 GetThemeColorVec4(const std::string& color_name) { } // Material Design color accessors -inline Color GetPrimary() { - return ThemeManager::Get().GetPrimary(); -} -inline Color GetPrimaryHover() { - return ThemeManager::Get().GetPrimaryHover(); -} +inline Color GetPrimary() { return ThemeManager::Get().GetPrimary(); } +inline Color GetPrimaryHover() { return ThemeManager::Get().GetPrimaryHover(); } inline Color GetPrimaryActive() { return ThemeManager::Get().GetPrimaryActive(); } -inline Color GetSecondary() { - return ThemeManager::Get().GetSecondary(); -} -inline Color GetSurface() { - return ThemeManager::Get().GetSurface(); -} +inline Color GetSecondary() { return ThemeManager::Get().GetSecondary(); } +inline Color GetSurface() { return ThemeManager::Get().GetSurface(); } inline Color GetSurfaceVariant() { return ThemeManager::Get().GetSurfaceVariant(); } @@ -299,41 +292,27 @@ inline Color GetSurfaceContainerHigh() { inline Color GetSurfaceContainerHighest() { return ThemeManager::Get().GetSurfaceContainerHighest(); } -inline Color GetOnSurface() { - return ThemeManager::Get().GetOnSurface(); -} +inline Color GetOnSurface() { return ThemeManager::Get().GetOnSurface(); } inline Color GetOnSurfaceVariant() { return ThemeManager::Get().GetOnSurfaceVariant(); } -inline Color GetOnPrimary() { - return ThemeManager::Get().GetOnPrimary(); -} -inline Color GetOutline() { - return ThemeManager::Get().GetOutline(); -} +inline Color GetOnPrimary() { return ThemeManager::Get().GetOnPrimary(); } +inline Color GetOutline() { return ThemeManager::Get().GetOutline(); } inline Color GetTextSecondary() { return ThemeManager::Get().GetTextSecondary(); } -inline Color GetTextDisabled() { - return ThemeManager::Get().GetTextDisabled(); -} -inline Color GetShadow() { - return ThemeManager::Get().GetShadow(); -} +inline Color GetTextDisabled() { return ThemeManager::Get().GetTextDisabled(); } +inline Color GetShadow() { return ThemeManager::Get().GetShadow(); } // ImVec4 versions for direct ImGui usage -inline ImVec4 GetPrimaryVec4() { - return ConvertColorToImVec4(GetPrimary()); -} +inline ImVec4 GetPrimaryVec4() { return ConvertColorToImVec4(GetPrimary()); } inline ImVec4 GetPrimaryHoverVec4() { return ConvertColorToImVec4(GetPrimaryHover()); } inline ImVec4 GetPrimaryActiveVec4() { return ConvertColorToImVec4(GetPrimaryActive()); } -inline ImVec4 GetSurfaceVec4() { - return ConvertColorToImVec4(GetSurface()); -} +inline ImVec4 GetSurfaceVec4() { return ConvertColorToImVec4(GetSurface()); } inline ImVec4 GetSurfaceVariantVec4() { return ConvertColorToImVec4(GetSurfaceVariant()); } @@ -355,18 +334,14 @@ inline ImVec4 GetOnSurfaceVariantVec4() { inline ImVec4 GetOnPrimaryVec4() { return ConvertColorToImVec4(GetOnPrimary()); } -inline ImVec4 GetOutlineVec4() { - return ConvertColorToImVec4(GetOutline()); -} +inline ImVec4 GetOutlineVec4() { return ConvertColorToImVec4(GetOutline()); } inline ImVec4 GetTextSecondaryVec4() { return ConvertColorToImVec4(GetTextSecondary()); } inline ImVec4 GetTextDisabledVec4() { return ConvertColorToImVec4(GetTextDisabled()); } -inline ImVec4 GetShadowVec4() { - return ConvertColorToImVec4(GetShadow()); -} +inline ImVec4 GetShadowVec4() { return ConvertColorToImVec4(GetShadow()); } } // namespace gui } // namespace yaze diff --git a/src/app/gui/core/ui_helpers.cc b/src/app/gui/core/ui_helpers.cc index ed02f7da..cc2c4f52 100644 --- a/src/app/gui/core/ui_helpers.cc +++ b/src/app/gui/core/ui_helpers.cc @@ -14,9 +14,7 @@ namespace gui { // Theme and Semantic Colors // ============================================================================ -ImVec4 GetThemeColor(ImGuiCol idx) { - return ImGui::GetStyle().Colors[idx]; -} +ImVec4 GetThemeColor(ImGuiCol idx) { return ImGui::GetStyle().Colors[idx]; } ImVec4 GetSuccessColor() { const auto& theme = ThemeManager::Get().GetCurrentTheme(); @@ -120,9 +118,7 @@ bool BeginPropertyTable(const char* id, int columns, return false; } -void EndPropertyTable() { - ImGui::EndTable(); -} +void EndPropertyTable() { ImGui::EndTable(); } void PropertyRow(const char* label, const char* value) { ImGui::TableNextColumn(); @@ -209,8 +205,7 @@ bool ToggleIconButton(const char* icon_on, const char* icon_off, bool* state, bool result = ImGui::SmallButton(icon); ImGui::PopStyleColor(); - if (result) - *state = !*state; + if (result) *state = !*state; if (tooltip && ImGui::IsItemHovered()) { ImGui::SetTooltip("%s", tooltip); @@ -230,9 +225,7 @@ void HelpMarker(const char* desc) { } } -void SeparatorText(const char* label) { - ImGui::SeparatorText(label); -} +void SeparatorText(const char* label) { ImGui::SeparatorText(label); } void StatusBadge(const char* text, ButtonType type) { ImVec4 color; @@ -285,8 +278,7 @@ void ToolsetButton(const char* icon, bool selected, const char* tooltip, } if (ImGui::Button(icon)) { - if (on_click) - on_click(); + if (on_click) on_click(); } if (selected) { @@ -304,9 +296,7 @@ void BeginCanvasContainer(const char* id, bool scrollable) { ImGui::BeginChild(id, ImVec2(0, 0), true, flags); } -void EndCanvasContainer() { - ImGui::EndChild(); -} +void EndCanvasContainer() { ImGui::EndChild(); } bool EditorTabItem(const char* icon, const char* label, bool* p_open) { char tab_label[256]; @@ -386,9 +376,7 @@ void LockIndicator(bool locked, const char* label) { // Spacing and Alignment // ============================================================================ -void VerticalSpacing(float pixels) { - ImGui::Dummy(ImVec2(0, pixels)); -} +void VerticalSpacing(float pixels) { ImGui::Dummy(ImVec2(0, pixels)); } void HorizontalSpacing(float pixels) { ImGui::Dummy(ImVec2(pixels, 0)); @@ -439,9 +427,7 @@ void PushPulseEffect(float speed) { ImGui::GetStyle().Alpha * GetPulseAlpha(speed)); } -void PopPulseEffect() { - ImGui::PopStyleVar(); -} +void PopPulseEffect() { ImGui::PopStyleVar(); } void LoadingSpinner(const char* label, float radius) { ImDrawList* draw_list = ImGui::GetWindowDrawList(); @@ -475,10 +461,8 @@ float GetResponsiveWidth(float min_width, float max_width, float ratio) { float available = ImGui::GetContentRegionAvail().x; float target = available * ratio; - if (target < min_width) - return min_width; - if (target > max_width) - return max_width; + if (target < min_width) return min_width; + if (target > max_width) return max_width; return target; } @@ -515,9 +499,7 @@ void BeginTwoColumns(const char* id, float split_ratio) { } } -void SwitchColumn() { - ImGui::TableNextColumn(); -} +void SwitchColumn() { ImGui::TableNextColumn(); } void EndTwoColumns() { ImGui::EndTable(); diff --git a/src/app/gui/core/ui_helpers.h b/src/app/gui/core/ui_helpers.h index 8556b764..1b83a143 100644 --- a/src/app/gui/core/ui_helpers.h +++ b/src/app/gui/core/ui_helpers.h @@ -3,6 +3,7 @@ #include #include + #include "imgui/imgui.h" namespace yaze { diff --git a/src/app/gui/widgets/asset_browser.cc b/src/app/gui/widgets/asset_browser.cc index 1fac8027..9f36665f 100644 --- a/src/app/gui/widgets/asset_browser.cc +++ b/src/app/gui/widgets/asset_browser.cc @@ -87,8 +87,7 @@ void GfxSheetAssetBrowser::Draw( // - Enable box-select (in 2D mode, so that changing box-select rectangle // X1/X2 boundaries will affect clipped items) - if (AllowBoxSelect) - ms_flags |= ImGuiMultiSelectFlags_BoxSelect2d; + if (AllowBoxSelect) ms_flags |= ImGuiMultiSelectFlags_BoxSelect2d; // - This feature allows dragging an unselected item without selecting it // (rarely used) @@ -181,12 +180,10 @@ void GfxSheetAssetBrowser::Draw( // Update our selection state immediately (without waiting for // EndMultiSelect() requests) because we use this to alter the color // of our text/icon. - if (IsItemToggledSelection()) - item_is_selected = !item_is_selected; + if (IsItemToggledSelection()) item_is_selected = !item_is_selected; // Focus (for after deletion) - if (item_curr_idx_to_focus == item_idx) - SetKeyboardFocusHere(-1); + if (item_curr_idx_to_focus == item_idx) SetKeyboardFocusHere(-1); // Drag and drop if (BeginDragDropSource()) { @@ -266,26 +263,22 @@ void GfxSheetAssetBrowser::Draw( if (MenuItem("Unsorted")) { void* it = NULL; ImGuiID id = 0; - while (Selection.GetNextSelectedItem(&it, &id)) - Items[id].Type = 0; + while (Selection.GetNextSelectedItem(&it, &id)) Items[id].Type = 0; } if (MenuItem("Dungeon")) { void* it = NULL; ImGuiID id = 0; - while (Selection.GetNextSelectedItem(&it, &id)) - Items[id].Type = 1; + while (Selection.GetNextSelectedItem(&it, &id)) Items[id].Type = 1; } if (MenuItem("Overworld")) { void* it = NULL; ImGuiID id = 0; - while (Selection.GetNextSelectedItem(&it, &id)) - Items[id].Type = 2; + while (Selection.GetNextSelectedItem(&it, &id)) Items[id].Type = 2; } if (MenuItem("Sprite")) { void* it = NULL; ImGuiID id = 0; - while (Selection.GetNextSelectedItem(&it, &id)) - Items[id].Type = 3; + while (Selection.GetNextSelectedItem(&it, &id)) Items[id].Type = 3; } EndMenu(); } @@ -301,8 +294,7 @@ void GfxSheetAssetBrowser::Draw( Selection.ApplyDeletionPostLoop(ms_io, Items, item_curr_idx_to_focus); // Zooming with CTRL+Wheel - if (IsWindowAppearing()) - ZoomWheelAccum = 0.0f; + if (IsWindowAppearing()) ZoomWheelAccum = 0.0f; if (IsWindowHovered() && io.MouseWheel != 0.0f && IsKeyDown(ImGuiMod_Ctrl) && IsAnyItemActive() == false) { ZoomWheelAccum += io.MouseWheel; diff --git a/src/app/gui/widgets/asset_browser.h b/src/app/gui/widgets/asset_browser.h index 9edf2446..291ecf95 100644 --- a/src/app/gui/widgets/asset_browser.h +++ b/src/app/gui/widgets/asset_browser.h @@ -31,8 +31,7 @@ struct ExampleSelectionWithDeletion : ImGuiSelectionBasicStorage { // FIXME-MULTISELECT: Doesn't take account of the possibility focus target // will be moved during deletion. Need refocus or scroll offset. int ApplyDeletionPreLoop(ImGuiMultiSelectIO* ms_io, int items_count) { - if (Size == 0) - return -1; + if (Size == 0) return -1; // If focused item is not selected... const int focused_idx = @@ -51,14 +50,12 @@ struct ExampleSelectionWithDeletion : ImGuiSelectionBasicStorage { // If focused item is selected: land on first unselected item after focused // item. for (int idx = focused_idx + 1; idx < items_count; idx++) - if (!Contains(GetStorageIdFromIndex(idx))) - return idx; + if (!Contains(GetStorageIdFromIndex(idx))) return idx; // If focused item is selected: otherwise return last unselected item before // focused item. for (int idx = IM_MIN(focused_idx, items_count) - 1; idx >= 0; idx--) - if (!Contains(GetStorageIdFromIndex(idx))) - return idx; + if (!Contains(GetStorageIdFromIndex(idx))) return idx; return -1; } @@ -198,8 +195,7 @@ struct GfxSheetAssetBrowser { } void AddItems(int count) { - if (Items.Size == 0) - NextItemId = 0; + if (Items.Size == 0) NextItemId = 0; Items.reserve(Items.Size + count); for (int n = 0; n < count; n++, NextItemId++) Items.push_back(AssetObject(NextItemId, (NextItemId % 20) < 15 ? 0 diff --git a/src/app/gui/widgets/dungeon_object_emulator_preview.cc b/src/app/gui/widgets/dungeon_object_emulator_preview.cc index 09579520..bad501d2 100644 --- a/src/app/gui/widgets/dungeon_object_emulator_preview.cc +++ b/src/app/gui/widgets/dungeon_object_emulator_preview.cc @@ -1,7 +1,8 @@ #include "app/gui/widgets/dungeon_object_emulator_preview.h" -#include "app/gfx/backend/irenderer.h" #include + +#include "app/gfx/backend/irenderer.h" #include "app/gui/automation/widget_auto_register.h" #include "app/platform/window.h" #include "zelda3/dungeon/room.h" @@ -32,8 +33,7 @@ void DungeonObjectEmulatorPreview::Initialize(gfx::IRenderer* renderer, } void DungeonObjectEmulatorPreview::Render() { - if (!show_window_) - return; + if (!show_window_) return; if (ImGui::Begin("Dungeon Object Emulator Preview", &show_window_, ImGuiWindowFlags_AlwaysAutoResize)) { diff --git a/src/app/gui/widgets/palette_editor_widget.cc b/src/app/gui/widgets/palette_editor_widget.cc index 852e418e..f1df9a7f 100644 --- a/src/app/gui/widgets/palette_editor_widget.cc +++ b/src/app/gui/widgets/palette_editor_widget.cc @@ -160,8 +160,7 @@ void PaletteEditorWidget::ShowPaletteEditor(gfx::SnesPalette& palette, } void PaletteEditorWidget::ShowROMPaletteManager() { - if (!show_rom_manager_) - return; + if (!show_rom_manager_) return; if (ImGui::Begin("ROM Palette Manager", &show_rom_manager_)) { if (!rom_) { @@ -191,8 +190,7 @@ void PaletteEditorWidget::ShowROMPaletteManager() { void PaletteEditorWidget::ShowColorAnalysis(const gfx::Bitmap& bitmap, const std::string& title) { - if (!show_color_analysis_) - return; + if (!show_color_analysis_) return; if (ImGui::Begin(title.c_str(), &show_color_analysis_)) { ImGui::Text("Bitmap Color Analysis"); @@ -297,8 +295,7 @@ bool PaletteEditorWidget::RestorePaletteBackup(gfx::SnesPalette& palette) { // Unified grid drawing function void PaletteEditorWidget::DrawPaletteGrid(gfx::SnesPalette& palette, int cols) { for (int i = 0; i < static_cast(palette.size()); i++) { - if (i % cols != 0) - ImGui::SameLine(); + if (i % cols != 0) ImGui::SameLine(); auto color = palette[i]; ImVec4 display_color = color.rgb(); @@ -377,13 +374,13 @@ void PaletteEditorWidget::DrawROMPaletteSelector() { "##PaletteGroup", ¤t_group_index_, [](void* data, int idx, const char** out_text) -> bool { auto* names = static_cast*>(data); - if (idx < 0 || idx >= static_cast(names->size())) - return false; + if (idx < 0 || idx >= static_cast(names->size())) return false; *out_text = (*names)[idx].c_str(); return true; }, &palette_group_names_, - static_cast(palette_group_names_.size()))) {} + static_cast(palette_group_names_.size()))) { + } ImGui::Text("Palette Index:"); ImGui::SliderInt("##PaletteIndex", ¤t_palette_index_, 0, 7, "%d"); @@ -393,8 +390,7 @@ void PaletteEditorWidget::DrawROMPaletteSelector() { const auto& preview_palette = rom_palette_groups_[current_group_index_]; for (int i = 0; i < 8 && i < static_cast(preview_palette.size()); i++) { - if (i > 0) - ImGui::SameLine(); + if (i > 0) ImGui::SameLine(); auto color = preview_palette[i]; ImVec4 display_color = color.rgb(); ImGui::ColorButton(("##preview" + std::to_string(i)).c_str(), @@ -491,8 +487,7 @@ void PaletteEditorWidget::DrawPaletteAnalysis(const gfx::SnesPalette& palette) { } void PaletteEditorWidget::LoadROMPalettes() { - if (!rom_ || rom_palettes_loaded_) - return; + if (!rom_ || rom_palettes_loaded_) return; try { const auto& palette_groups = rom_->palette_group(); diff --git a/src/app/gui/widgets/text_editor.cc b/src/app/gui/widgets/text_editor.cc index 5691460c..7fdb4413 100644 --- a/src/app/gui/widgets/text_editor.cc +++ b/src/app/gui/widgets/text_editor.cc @@ -16,8 +16,7 @@ template bool equals(InputIt1 first1, InputIt1 last1, InputIt2 first2, InputIt2 last2, BinaryPredicate p) { for (; first1 != last1 && first2 != last2; ++first1, ++first2) { - if (!p(*first1, *first2)) - return false; + if (!p(*first1, *first2)) return false; } return first1 == last1 && first2 == last2; } @@ -66,9 +65,7 @@ void TextEditor::SetLanguageDefinition(const LanguageDefinition& aLanguageDef) { Colorize(); } -void TextEditor::SetPalette(const Palette& aValue) { - mPaletteBase = aValue; -} +void TextEditor::SetPalette(const Palette& aValue) { mPaletteBase = aValue; } std::string TextEditor::GetText(const Coordinates& aStart, const Coordinates& aEnd) const { @@ -80,14 +77,12 @@ std::string TextEditor::GetText(const Coordinates& aStart, auto iend = GetCharacterIndex(aEnd); size_t s = 0; - for (size_t i = lstart; i < lend; i++) - s += mLines[i].size(); + for (size_t i = lstart; i < lend; i++) s += mLines[i].size(); result.reserve(s + s / 8); while (istart < iend || lstart < lend) { - if (lstart >= (int)mLines.size()) - break; + if (lstart >= (int)mLines.size()) break; auto& line = mLines[lstart]; if (istart < (int)line.size()) { @@ -130,10 +125,8 @@ TextEditor::Coordinates TextEditor::SanitizeCoordinates( // We assume that the char is a standalone character (<128) or a leading byte of // an UTF-8 code sequence (non-10xxxxxx code) static int UTF8CharLength(TextEditor::Char c) { - if ((c & 0xFE) == 0xFC) - return 6; - if ((c & 0xFC) == 0xF8) - return 5; + if ((c & 0xFE) == 0xFC) return 6; + if ((c & 0xFC) == 0xF8) return 5; if ((c & 0xF8) == 0xF0) return 4; else if ((c & 0xF0) == 0xE0) @@ -150,8 +143,7 @@ static inline int ImTextCharToUtf8(char* buf, int buf_size, unsigned int c) { return 1; } if (c < 0x800) { - if (buf_size < 2) - return 0; + if (buf_size < 2) return 0; buf[0] = (char)(0xc0 + (c >> 6)); buf[1] = (char)(0x80 + (c & 0x3f)); return 2; @@ -160,8 +152,7 @@ static inline int ImTextCharToUtf8(char* buf, int buf_size, unsigned int c) { return 0; } if (c >= 0xd800 && c < 0xdc00) { - if (buf_size < 4) - return 0; + if (buf_size < 4) return 0; buf[0] = (char)(0xf0 + (c >> 18)); buf[1] = (char)(0x80 + ((c >> 12) & 0x3f)); buf[2] = (char)(0x80 + ((c >> 6) & 0x3f)); @@ -170,8 +161,7 @@ static inline int ImTextCharToUtf8(char* buf, int buf_size, unsigned int c) { } // else if (c < 0x10000) { - if (buf_size < 3) - return 0; + if (buf_size < 3) return 0; buf[0] = (char)(0xe0 + (c >> 12)); buf[1] = (char)(0x80 + ((c >> 6) & 0x3f)); buf[2] = (char)(0x80 + ((c) & 0x3f)); @@ -203,8 +193,7 @@ void TextEditor::DeleteRange(const Coordinates& aStart, // printf("D(%d.%d)-(%d.%d)\n", aStart.mLine, aStart.mColumn, aEnd.mLine, // aEnd.mColumn); - if (aEnd == aStart) - return; + if (aEnd == aStart) return; auto start = GetCharacterIndex(aStart); auto end = GetCharacterIndex(aEnd); @@ -226,8 +215,7 @@ void TextEditor::DeleteRange(const Coordinates& aStart, if (aStart.mLine < aEnd.mLine) firstLine.insert(firstLine.end(), lastLine.begin(), lastLine.end()); - if (aStart.mLine < aEnd.mLine) - RemoveLine(aStart.mLine + 1, aEnd.mLine + 1); + if (aStart.mLine < aEnd.mLine) RemoveLine(aStart.mLine + 1, aEnd.mLine + 1); } mTextChanged = true; @@ -278,13 +266,13 @@ void TextEditor::AddUndo(UndoRecord& aValue) { assert(!mReadOnly); // printf("AddUndo: (@%d.%d) +\'%s' [%d.%d .. %d.%d], -\'%s', [%d.%d .. %d.%d] // (@%d.%d)\n", aValue.mBefore.mCursorPosition.mLine, - //aValue.mBefore.mCursorPosition.mColumn, aValue.mAdded.c_str(), - //aValue.mAddedStart.mLine, aValue.mAddedStart.mColumn, - //aValue.mAddedEnd.mLine, aValue.mAddedEnd.mColumn, aValue.mRemoved.c_str(), - //aValue.mRemovedStart.mLine, aValue.mRemovedStart.mColumn, - //aValue.mRemovedEnd.mLine, aValue.mRemovedEnd.mColumn, + // aValue.mBefore.mCursorPosition.mColumn, aValue.mAdded.c_str(), + // aValue.mAddedStart.mLine, aValue.mAddedStart.mColumn, + // aValue.mAddedEnd.mLine, aValue.mAddedEnd.mColumn, aValue.mRemoved.c_str(), + // aValue.mRemovedStart.mLine, aValue.mRemovedStart.mColumn, + // aValue.mRemovedEnd.mLine, aValue.mRemovedEnd.mColumn, // aValue.mAfter.mCursorPosition.mLine, - //aValue.mAfter.mCursorPosition.mColumn + // aValue.mAfter.mCursorPosition.mColumn // ); mUndoBuffer.resize((size_t)(mUndoIndex + 1)); @@ -320,8 +308,7 @@ TextEditor::Coordinates TextEditor::ScreenPosToCoordinates( (float(mTabSize) * spaceSize))) * (float(mTabSize) * spaceSize); columnWidth = newColumnX - oldX; - if (mTextStart + columnX + columnWidth * 0.5f > local.x) - break; + if (mTextStart + columnX + columnWidth * 0.5f > local.x) break; columnX = newColumnX; columnCoord = (columnCoord / mTabSize) * mTabSize + mTabSize; columnIndex++; @@ -329,15 +316,13 @@ TextEditor::Coordinates TextEditor::ScreenPosToCoordinates( char buf[7]; auto d = UTF8CharLength(line[columnIndex].mChar); int i = 0; - while (i < 6 && d-- > 0) - buf[i++] = line[columnIndex++].mChar; + while (i < 6 && d-- > 0) buf[i++] = line[columnIndex++].mChar; buf[i] = '\0'; columnWidth = ImGui::GetFont() ->CalcTextSizeA(ImGui::GetFontSize(), FLT_MAX, -1.0f, buf) .x; - if (mTextStart + columnX + columnWidth * 0.5f > local.x) - break; + if (mTextStart + columnX + columnWidth * 0.5f > local.x) break; columnX += columnWidth; columnCoord++; } @@ -350,17 +335,14 @@ TextEditor::Coordinates TextEditor::ScreenPosToCoordinates( TextEditor::Coordinates TextEditor::FindWordStart( const Coordinates& aFrom) const { Coordinates at = aFrom; - if (at.mLine >= (int)mLines.size()) - return at; + if (at.mLine >= (int)mLines.size()) return at; auto& line = mLines[at.mLine]; auto cindex = GetCharacterIndex(at); - if (cindex >= (int)line.size()) - return at; + if (cindex >= (int)line.size()) return at; - while (cindex > 0 && isspace(line[cindex].mChar)) - --cindex; + while (cindex > 0 && isspace(line[cindex].mChar)) --cindex; auto cstart = (PaletteIndex)line[cindex].mColorIndex; while (cindex > 0) { @@ -371,8 +353,7 @@ TextEditor::Coordinates TextEditor::FindWordStart( cindex++; break; } - if (cstart != (PaletteIndex)line[size_t(cindex - 1)].mColorIndex) - break; + if (cstart != (PaletteIndex)line[size_t(cindex - 1)].mColorIndex) break; } --cindex; } @@ -382,22 +363,19 @@ TextEditor::Coordinates TextEditor::FindWordStart( TextEditor::Coordinates TextEditor::FindWordEnd( const Coordinates& aFrom) const { Coordinates at = aFrom; - if (at.mLine >= (int)mLines.size()) - return at; + if (at.mLine >= (int)mLines.size()) return at; auto& line = mLines[at.mLine]; auto cindex = GetCharacterIndex(at); - if (cindex >= (int)line.size()) - return at; + if (cindex >= (int)line.size()) return at; bool prevspace = (bool)isspace(line[cindex].mChar); auto cstart = (PaletteIndex)line[cindex].mColorIndex; while (cindex < (int)line.size()) { auto c = line[cindex].mChar; auto d = UTF8CharLength(c); - if (cstart != (PaletteIndex)line[cindex].mColorIndex) - break; + if (cstart != (PaletteIndex)line[cindex].mColorIndex) break; if (prevspace != !!isspace(c)) { if (isspace(c)) @@ -413,8 +391,7 @@ TextEditor::Coordinates TextEditor::FindWordEnd( TextEditor::Coordinates TextEditor::FindNextWord( const Coordinates& aFrom) const { Coordinates at = aFrom; - if (at.mLine >= (int)mLines.size()) - return at; + if (at.mLine >= (int)mLines.size()) return at; // skip to the next non-word character auto cindex = GetCharacterIndex(aFrom); @@ -439,8 +416,7 @@ TextEditor::Coordinates TextEditor::FindNextWord( if (isword && !skip) return Coordinates(at.mLine, GetCharacterColumn(at.mLine, cindex)); - if (!isword) - skip = false; + if (!isword) skip = false; cindex++; } else { @@ -455,8 +431,7 @@ TextEditor::Coordinates TextEditor::FindNextWord( } int TextEditor::GetCharacterIndex(const Coordinates& aCoordinates) const { - if (aCoordinates.mLine >= mLines.size()) - return -1; + if (aCoordinates.mLine >= mLines.size()) return -1; auto& line = mLines[aCoordinates.mLine]; int c = 0; int i = 0; @@ -471,8 +446,7 @@ int TextEditor::GetCharacterIndex(const Coordinates& aCoordinates) const { } int TextEditor::GetCharacterColumn(int aLine, int aIndex) const { - if (aLine >= mLines.size()) - return 0; + if (aLine >= mLines.size()) return 0; auto& line = mLines[aLine]; int col = 0; int i = 0; @@ -488,18 +462,15 @@ int TextEditor::GetCharacterColumn(int aLine, int aIndex) const { } int TextEditor::GetLineCharacterCount(int aLine) const { - if (aLine >= mLines.size()) - return 0; + if (aLine >= mLines.size()) return 0; auto& line = mLines[aLine]; int c = 0; - for (unsigned i = 0; i < line.size(); c++) - i += UTF8CharLength(line[i].mChar); + for (unsigned i = 0; i < line.size(); c++) i += UTF8CharLength(line[i].mChar); return c; } int TextEditor::GetLineMaxColumn(int aLine) const { - if (aLine >= mLines.size()) - return 0; + if (aLine >= mLines.size()) return 0; auto& line = mLines[aLine]; int col = 0; for (unsigned i = 0; i < line.size();) { @@ -514,13 +485,11 @@ int TextEditor::GetLineMaxColumn(int aLine) const { } bool TextEditor::IsOnWordBoundary(const Coordinates& aAt) const { - if (aAt.mLine >= (int)mLines.size() || aAt.mColumn == 0) - return true; + if (aAt.mLine >= (int)mLines.size() || aAt.mColumn == 0) return true; auto& line = mLines[aAt.mLine]; auto cindex = GetCharacterIndex(aAt); - if (cindex >= (int)line.size()) - return true; + if (cindex >= (int)line.size()) return true; if (mColorizerEnabled) return line[cindex].mColorIndex != line[size_t(cindex - 1)].mColorIndex; @@ -537,16 +506,14 @@ void TextEditor::RemoveLine(int aStart, int aEnd) { for (auto& i : mErrorMarkers) { ErrorMarkers::value_type e(i.first >= aStart ? i.first - 1 : i.first, i.second); - if (e.first >= aStart && e.first <= aEnd) - continue; + if (e.first >= aStart && e.first <= aEnd) continue; etmp.insert(e); } mErrorMarkers = std::move(etmp); Breakpoints btmp; for (auto i : mBreakpoints) { - if (i >= aStart && i <= aEnd) - continue; + if (i >= aStart && i <= aEnd) continue; btmp.insert(i >= aStart ? i - 1 : i); } mBreakpoints = std::move(btmp); @@ -565,16 +532,14 @@ void TextEditor::RemoveLine(int aIndex) { for (auto& i : mErrorMarkers) { ErrorMarkers::value_type e(i.first > aIndex ? i.first - 1 : i.first, i.second); - if (e.first - 1 == aIndex) - continue; + if (e.first - 1 == aIndex) continue; etmp.insert(e); } mErrorMarkers = std::move(etmp); Breakpoints btmp; for (auto i : mBreakpoints) { - if (i == aIndex) - continue; + if (i == aIndex) continue; btmp.insert(i >= aIndex ? i - 1 : i); } mBreakpoints = std::move(btmp); @@ -597,8 +562,7 @@ TextEditor::Line& TextEditor::InsertLine(int aIndex) { mErrorMarkers = std::move(etmp); Breakpoints btmp; - for (auto i : mBreakpoints) - btmp.insert(i >= aIndex ? i + 1 : i); + for (auto i : mBreakpoints) btmp.insert(i >= aIndex ? i + 1 : i); mBreakpoints = std::move(btmp); return result; @@ -625,10 +589,8 @@ std::string TextEditor::GetWordAt(const Coordinates& aCoords) const { } ImU32 TextEditor::GetGlyphColor(const Glyph& aGlyph) const { - if (!mColorizerEnabled) - return mPalette[(int)PaletteIndex::Default]; - if (aGlyph.mComment) - return mPalette[(int)PaletteIndex::Comment]; + if (!mColorizerEnabled) return mPalette[(int)PaletteIndex::Default]; + if (aGlyph.mComment) return mPalette[(int)PaletteIndex::Comment]; if (aGlyph.mMultiLineComment) return mPalette[(int)PaletteIndex::MultiLineComment]; auto const color = mPalette[(int)aGlyph.mColorIndex]; @@ -720,8 +682,7 @@ void TextEditor::HandleKeyboardInputs() { if (!IsReadOnly() && !io.InputQueueCharacters.empty()) { for (int i = 0; i < io.InputQueueCharacters.Size; i++) { auto c = io.InputQueueCharacters[i]; - if (c != 0 && (c == '\n' || c >= 32)) - EnterCharacter(c, shift); + if (c != 0 && (c == '\n' || c >= 32)) EnterCharacter(c, shift); } io.InputQueueCharacters.resize(0); } @@ -883,8 +844,7 @@ void TextEditor::Render() { ? mState.mSelectionEnd : lineEndCoord); - if (mState.mSelectionEnd.mLine > lineNo) - ssend += mCharAdvance.x; + if (mState.mSelectionEnd.mLine > lineNo) ssend += mCharAdvance.x; if (sstart != -1 && ssend != -1 && sstart < ssend) { ImVec2 vstart(lineStartScreenPos.x + mTextStart + sstart, @@ -986,8 +946,7 @@ void TextEditor::Render() { lineStartScreenPos.y + mCharAdvance.y); drawList->AddRectFilled(cstart, cend, mPalette[(int)PaletteIndex::Cursor]); - if (elapsed > 800) - mStartTime = timeEnd; + if (elapsed > 800) mStartTime = timeEnd; } } } @@ -1045,8 +1004,7 @@ void TextEditor::Render() { i++; } else { auto l = UTF8CharLength(glyph.mChar); - while (l-- > 0) - mLineBuffer.push_back(line[i++].mChar); + while (l-- > 0) mLineBuffer.push_back(line[i++].mChar); } ++columnNo; } @@ -1110,14 +1068,12 @@ void TextEditor::Render(const char* aTitle, const ImVec2& aSize, bool aBorder) { HandleKeyboardInputs(); } - if (mHandleMouseInputs) - HandleMouseInputs(); + if (mHandleMouseInputs) HandleMouseInputs(); ColorizeInternal(); Render(); - if (!mIgnoreImGuiChild) - ImGui::EndChild(); + if (!mIgnoreImGuiChild) ImGui::EndChild(); ImGui::PopStyleVar(); ImGui::PopStyleColor(); @@ -1187,13 +1143,11 @@ void TextEditor::EnterCharacter(ImWchar aChar, bool aShift) { auto end = mState.mSelectionEnd; auto originalEnd = end; - if (start > end) - std::swap(start, end); + if (start > end) std::swap(start, end); start.mColumn = 0; // end.mColumn = end.mLine < mLines.size() ? - //mLines[end.mLine].size() : 0; - if (end.mColumn == 0 && end.mLine > 0) - --end.mLine; + // mLines[end.mLine].size() : 0; + if (end.mColumn == 0 && end.mLine > 0) --end.mLine; if (end.mLine >= (int)mLines.size()) end.mLine = mLines.empty() ? 0 : (int)mLines.size() - 1; end.mColumn = GetLineMaxColumn(end.mLine); @@ -1333,13 +1287,9 @@ void TextEditor::EnterCharacter(ImWchar aChar, bool aShift) { EnsureCursorVisible(); } -void TextEditor::SetReadOnly(bool aValue) { - mReadOnly = aValue; -} +void TextEditor::SetReadOnly(bool aValue) { mReadOnly = aValue; } -void TextEditor::SetColorizerEnable(bool aValue) { - mColorizerEnabled = aValue; -} +void TextEditor::SetColorizerEnable(bool aValue) { mColorizerEnabled = aValue; } void TextEditor::SetCursorPosition(const Coordinates& aPosition) { if (mState.mCursorPosition != aPosition) { @@ -1406,8 +1356,7 @@ void TextEditor::InsertText(const std::string& aValue) { } void TextEditor::InsertText(const char* aValue) { - if (aValue == nullptr) - return; + if (aValue == nullptr) return; auto pos = GetActualCursorCoordinates(); auto start = std::min(pos, mState.mSelectionStart); @@ -1423,8 +1372,7 @@ void TextEditor::InsertText(const char* aValue) { void TextEditor::DeleteSelection() { assert(mState.mSelectionEnd >= mState.mSelectionStart); - if (mState.mSelectionEnd == mState.mSelectionStart) - return; + if (mState.mSelectionEnd == mState.mSelectionStart) return; DeleteRange(mState.mSelectionStart, mState.mSelectionEnd); @@ -1480,13 +1428,10 @@ void TextEditor::MoveDown(int aAmount, bool aSelect) { } } -static bool IsUTFSequence(char c) { - return (c & 0xC0) == 0x80; -} +static bool IsUTFSequence(char c) { return (c & 0xC0) == 0x80; } void TextEditor::MoveLeft(int aAmount, bool aSelect, bool aWordMode) { - if (mLines.empty()) - return; + if (mLines.empty()) return; auto oldPos = mState.mCursorPosition; mState.mCursorPosition = GetActualCursorCoordinates(); @@ -1544,8 +1489,7 @@ void TextEditor::MoveLeft(int aAmount, bool aSelect, bool aWordMode) { void TextEditor::MoveRight(int aAmount, bool aSelect, bool aWordMode) { auto oldPos = mState.mCursorPosition; - if (mLines.empty() || oldPos.mLine >= mLines.size()) - return; + if (mLines.empty() || oldPos.mLine >= mLines.size()) return; auto cindex = GetCharacterIndex(mState.mCursorPosition); while (aAmount-- > 0) { @@ -1657,8 +1601,7 @@ void TextEditor::MoveEnd(bool aSelect) { void TextEditor::Delete() { assert(!mReadOnly); - if (mLines.empty()) - return; + if (mLines.empty()) return; UndoRecord u; u.mBefore = mState; @@ -1675,8 +1618,7 @@ void TextEditor::Delete() { auto& line = mLines[pos.mLine]; if (pos.mColumn == GetLineMaxColumn(pos.mLine)) { - if (pos.mLine == (int)mLines.size() - 1) - return; + if (pos.mLine == (int)mLines.size() - 1) return; u.mRemoved = '\n'; u.mRemovedStart = u.mRemovedEnd = GetActualCursorCoordinates(); @@ -1708,8 +1650,7 @@ void TextEditor::Delete() { void TextEditor::Backspace() { assert(!mReadOnly); - if (mLines.empty()) - return; + if (mLines.empty()) return; UndoRecord u; u.mBefore = mState; @@ -1725,8 +1666,7 @@ void TextEditor::Backspace() { SetCursorPosition(pos); if (mState.mCursorPosition.mColumn == 0) { - if (mState.mCursorPosition.mLine == 0) - return; + if (mState.mCursorPosition.mLine == 0) return; u.mRemoved = '\n'; u.mRemovedStart = u.mRemovedEnd = @@ -1752,8 +1692,7 @@ void TextEditor::Backspace() { auto& line = mLines[mState.mCursorPosition.mLine]; auto cindex = GetCharacterIndex(pos) - 1; auto cend = cindex + 1; - while (cindex > 0 && IsUTFSequence(line[cindex].mChar)) - --cindex; + while (cindex > 0 && IsUTFSequence(line[cindex].mChar)) --cindex; // if (cindex > 0 && UTF8CharLength(line[cindex].mChar) > 1) // --cindex; @@ -1798,8 +1737,7 @@ void TextEditor::Copy() { if (!mLines.empty()) { std::string str; auto& line = mLines[GetActualCursorCoordinates().mLine]; - for (auto& g : line) - str.push_back(g.mChar); + for (auto& g : line) str.push_back(g.mChar); ImGui::SetClipboardText(str.c_str()); } } @@ -1826,8 +1764,7 @@ void TextEditor::Cut() { } void TextEditor::Paste() { - if (IsReadOnly()) - return; + if (IsReadOnly()) return; auto clipText = ImGui::GetClipboardText(); if (clipText != nullptr && strlen(clipText) > 0) { @@ -1852,22 +1789,18 @@ void TextEditor::Paste() { } } -bool TextEditor::CanUndo() const { - return !mReadOnly && mUndoIndex > 0; -} +bool TextEditor::CanUndo() const { return !mReadOnly && mUndoIndex > 0; } bool TextEditor::CanRedo() const { return !mReadOnly && mUndoIndex < (int)mUndoBuffer.size(); } void TextEditor::Undo(int aSteps) { - while (CanUndo() && aSteps-- > 0) - mUndoBuffer[--mUndoIndex].Undo(this); + while (CanUndo() && aSteps-- > 0) mUndoBuffer[--mUndoIndex].Undo(this); } void TextEditor::Redo(int aSteps) { - while (CanRedo() && aSteps-- > 0) - mUndoBuffer[mUndoIndex++].Redo(this); + while (CanRedo() && aSteps-- > 0) mUndoBuffer[mUndoIndex++].Redo(this); } const TextEditor::Palette& TextEditor::GetDarkPalette() { @@ -1965,8 +1898,7 @@ std::vector TextEditor::GetTextLines() const { text.resize(line.size()); - for (size_t i = 0; i < line.size(); ++i) - text[i] = line[i].mChar; + for (size_t i = 0; i < line.size(); ++i) text[i] = line[i].mChar; result.emplace_back(std::move(text)); } @@ -1997,8 +1929,7 @@ void TextEditor::Colorize(int aFromLine, int aLines) { } void TextEditor::ColorizeRange(int aFromLine, int aToLine) { - if (mLines.empty() || aFromLine >= aToLine) - return; + if (mLines.empty() || aFromLine >= aToLine) return; std::string buffer; std::cmatch results; @@ -2008,8 +1939,7 @@ void TextEditor::ColorizeRange(int aFromLine, int aToLine) { for (int i = aFromLine; i < endLine; ++i) { auto& line = mLines[i]; - if (line.empty()) - continue; + if (line.empty()) continue; buffer.resize(line.size()); for (size_t j = 0; j < line.size(); ++j) { @@ -2091,8 +2021,7 @@ void TextEditor::ColorizeRange(int aFromLine, int aToLine) { } void TextEditor::ColorizeInternal() { - if (mLines.empty() || !mColorizerEnabled) - return; + if (mLines.empty() || !mColorizerEnabled) return; if (mCheckComments) { auto endLine = mLines.size(); @@ -2363,8 +2292,7 @@ static bool TokenizeCStyleString(const char* in_begin, const char* in_end, } // handle escape character for " - if (*p == '\\' && p + 1 < in_end && p[1] == '"') - p++; + if (*p == '\\' && p + 1 < in_end && p[1] == '"') p++; p++; } @@ -2383,11 +2311,9 @@ static bool TokenizeCStyleCharacterLiteral(const char* in_begin, p++; // handle escape characters - if (p < in_end && *p == '\\') - p++; + if (p < in_end && *p == '\\') p++; - if (p < in_end) - p++; + if (p < in_end) p++; // handle end of character literal if (p < in_end && *p == '\'') { @@ -2427,8 +2353,7 @@ static bool TokenizeCStyleNumber(const char* in_begin, const char* in_end, const bool startsWithNumber = *p >= '0' && *p <= '9'; - if (*p != '+' && *p != '-' && !startsWithNumber) - return false; + if (*p != '+' && *p != '-' && !startsWithNumber) return false; p++; @@ -2440,8 +2365,7 @@ static bool TokenizeCStyleNumber(const char* in_begin, const char* in_end, p++; } - if (hasNumber == false) - return false; + if (hasNumber == false) return false; bool isFloat = false; bool isHex = false; @@ -2453,8 +2377,7 @@ static bool TokenizeCStyleNumber(const char* in_begin, const char* in_end, p++; - while (p < in_end && (*p >= '0' && *p <= '9')) - p++; + while (p < in_end && (*p >= '0' && *p <= '9')) p++; } else if (*p == 'x' || *p == 'X') { // hex formatted integer of the type 0xef80 @@ -2473,8 +2396,7 @@ static bool TokenizeCStyleNumber(const char* in_begin, const char* in_end, p++; - while (p < in_end && (*p >= '0' && *p <= '1')) - p++; + while (p < in_end && (*p >= '0' && *p <= '1')) p++; } } @@ -2485,8 +2407,7 @@ static bool TokenizeCStyleNumber(const char* in_begin, const char* in_end, p++; - if (p < in_end && (*p == '+' || *p == '-')) - p++; + if (p < in_end && (*p == '+' || *p == '-')) p++; bool hasDigits = false; @@ -2496,13 +2417,11 @@ static bool TokenizeCStyleNumber(const char* in_begin, const char* in_end, p++; } - if (hasDigits == false) - return false; + if (hasDigits == false) return false; } // single precision floating point type - if (p < in_end && *p == 'f') - p++; + if (p < in_end && *p == 'f') p++; } if (isFloat == false) { @@ -2651,8 +2570,7 @@ TextEditor::LanguageDefinition::CPlusPlus() { "while", "xor", "xor_eq"}; - for (auto& k : cppKeywords) - langDef.mKeywords.insert(k); + for (auto& k : cppKeywords) langDef.mKeywords.insert(k); static const char* const identifiers[] = { "abort", "abs", "acos", "asin", "atan", @@ -2908,8 +2826,7 @@ const TextEditor::LanguageDefinition& TextEditor::LanguageDefinition::HLSL() { "half3x4", "half4x4", }; - for (auto& k : keywords) - langDef.mKeywords.insert(k); + for (auto& k : keywords) langDef.mKeywords.insert(k); static const char* const identifiers[] = { "abort", @@ -3120,8 +3037,7 @@ const TextEditor::LanguageDefinition& TextEditor::LanguageDefinition::GLSL() { "volatile", "while", "_Alignas", "_Alignof", "_Atomic", "_Bool", "_Complex", "_Generic", "_Imaginary", "_Noreturn", "_Static_assert", "_Thread_local"}; - for (auto& k : keywords) - langDef.mKeywords.insert(k); + for (auto& k : keywords) langDef.mKeywords.insert(k); static const char* const identifiers[] = { "abort", "abs", "acos", "asin", "atan", "atexit", @@ -3200,8 +3116,7 @@ const TextEditor::LanguageDefinition& TextEditor::LanguageDefinition::C() { "volatile", "while", "_Alignas", "_Alignof", "_Atomic", "_Bool", "_Complex", "_Generic", "_Imaginary", "_Noreturn", "_Static_assert", "_Thread_local"}; - for (auto& k : keywords) - langDef.mKeywords.insert(k); + for (auto& k : keywords) langDef.mKeywords.insert(k); static const char* const identifiers[] = { "abort", "abs", "acos", "asin", "atan", "atexit", @@ -3439,8 +3354,7 @@ const TextEditor::LanguageDefinition& TextEditor::LanguageDefinition::SQL() { "OVER", "WRITETEXT"}; - for (auto& k : keywords) - langDef.mKeywords.insert(k); + for (auto& k : keywords) langDef.mKeywords.insert(k); static const char* const identifiers[] = {"ABS", "ACOS", @@ -3645,8 +3559,7 @@ TextEditor::LanguageDefinition::AngelScript() { "typedef", "uint", "uint8", "uint16", "uint32", "uint64", "void", "while", "xor"}; - for (auto& k : keywords) - langDef.mKeywords.insert(k); + for (auto& k : keywords) langDef.mKeywords.insert(k); static const char* const identifiers[] = { "cos", "sin", "tab", "acos", "asin", @@ -3713,8 +3626,7 @@ const TextEditor::LanguageDefinition& TextEditor::LanguageDefinition::Lua() { "for", "function", "if", "in", "", "local", "nil", "not", "or", "repeat", "return", "then", "true", "until", "while"}; - for (auto& k : keywords) - langDef.mKeywords.insert(k); + for (auto& k : keywords) langDef.mKeywords.insert(k); static const char* const identifiers[] = {"assert", "collectgarbage", "dofile", "error", diff --git a/src/app/gui/widgets/text_editor.h b/src/app/gui/widgets/text_editor.h index 0e134aec..27f9344e 100644 --- a/src/app/gui/widgets/text_editor.h +++ b/src/app/gui/widgets/text_editor.h @@ -80,26 +80,22 @@ class TextEditor { } bool operator<(const Coordinates& o) const { - if (mLine != o.mLine) - return mLine < o.mLine; + if (mLine != o.mLine) return mLine < o.mLine; return mColumn < o.mColumn; } bool operator>(const Coordinates& o) const { - if (mLine != o.mLine) - return mLine > o.mLine; + if (mLine != o.mLine) return mLine > o.mLine; return mColumn > o.mColumn; } bool operator<=(const Coordinates& o) const { - if (mLine != o.mLine) - return mLine < o.mLine; + if (mLine != o.mLine) return mLine < o.mLine; return mColumn <= o.mColumn; } bool operator>=(const Coordinates& o) const { - if (mLine != o.mLine) - return mLine > o.mLine; + if (mLine != o.mLine) return mLine > o.mLine; return mColumn >= o.mColumn; } }; diff --git a/src/app/gui/widgets/themed_widgets.cc b/src/app/gui/widgets/themed_widgets.cc index 59b9a4e9..ced10be3 100644 --- a/src/app/gui/widgets/themed_widgets.cc +++ b/src/app/gui/widgets/themed_widgets.cc @@ -74,9 +74,7 @@ bool DangerButton(const char* label, const ImVec2& size) { // Headers & Sections // ============================================================================ -void SectionHeader(const char* label) { - LayoutHelpers::SectionHeader(label); -} +void SectionHeader(const char* label) { LayoutHelpers::SectionHeader(label); } bool ThemedCollapsingHeader(const char* label, ImGuiTreeNodeFlags flags) { const auto& theme = GetTheme(); @@ -212,17 +210,13 @@ bool BeginThemedTable(const char* str_id, int columns, ImGuiTableFlags flags, outer_size, inner_width); } -void EndThemedTable() { - LayoutHelpers::EndTable(); -} +void EndThemedTable() { LayoutHelpers::EndTable(); } // ============================================================================ // Tooltips & Help // ============================================================================ -void ThemedHelpMarker(const char* desc) { - LayoutHelpers::HelpMarker(desc); -} +void ThemedHelpMarker(const char* desc) { LayoutHelpers::HelpMarker(desc); } void BeginThemedTooltip() { const auto& theme = GetTheme(); @@ -322,8 +316,7 @@ void ColorInfoPanel(const yaze::gfx::SnesColor& color, bool show_snes_format, } void ModifiedBadge(bool is_modified, const char* text) { - if (!is_modified) - return; + if (!is_modified) return; const auto& theme = GetTheme(); ImVec4 color = ConvertColorToImVec4(theme.warning); @@ -353,9 +346,7 @@ void PushThemedWidgetColors() { ConvertColorToImVec4(theme.button_active)); } -void PopThemedWidgetColors() { - ImGui::PopStyleColor(6); -} +void PopThemedWidgetColors() { ImGui::PopStyleColor(6); } } // namespace gui } // namespace yaze diff --git a/src/app/gui/widgets/themed_widgets.h b/src/app/gui/widgets/themed_widgets.h index b2230aaf..9e1c58d1 100644 --- a/src/app/gui/widgets/themed_widgets.h +++ b/src/app/gui/widgets/themed_widgets.h @@ -12,8 +12,9 @@ namespace gui { /** * @brief Theme-aware widget library * - * All widgets in this file automatically use the current theme from ThemeManager. - * These are drop-in replacements for standard ImGui widgets with automatic theming. + * All widgets in this file automatically use the current theme from + * ThemeManager. These are drop-in replacements for standard ImGui widgets with + * automatic theming. * * Usage: * ```cpp @@ -183,7 +184,8 @@ void ThemedProgressBar(float fraction, const ImVec2& size = ImVec2(-1, 0), // Palette Editor Widgets // ============================================================================ -// NOTE: PaletteColorButton moved to color.h for consistency with other color utilities +// NOTE: PaletteColorButton moved to color.h for consistency with other color +// utilities /** * @brief Display color information with copy-to-clipboard functionality diff --git a/src/app/gui/widgets/tile_selector_widget.cc b/src/app/gui/widgets/tile_selector_widget.cc index d044cbb4..4615e150 100644 --- a/src/app/gui/widgets/tile_selector_widget.cc +++ b/src/app/gui/widgets/tile_selector_widget.cc @@ -14,9 +14,7 @@ TileSelectorWidget::TileSelectorWidget(std::string widget_id, Config config) total_tiles_(config.total_tiles), widget_id_(std::move(widget_id)) {} -void TileSelectorWidget::AttachCanvas(Canvas* canvas) { - canvas_ = canvas; -} +void TileSelectorWidget::AttachCanvas(Canvas* canvas) { canvas_ = canvas; } void TileSelectorWidget::SetTileCount(int total_tiles) { total_tiles_ = std::max(total_tiles, 0); @@ -49,12 +47,14 @@ TileSelectorWidget::RenderResult TileSelectorWidget::Render(gfx::Bitmap& atlas, config_.tiles_per_row * tile_display_size + config_.draw_offset.x * 2, num_rows * tile_display_size + config_.draw_offset.y * 2); - // Set content size for ImGui child window (must be called before DrawBackground) + // Set content size for ImGui child window (must be called before + // DrawBackground) ImGui::SetCursorPos(ImVec2(0, 0)); ImGui::Dummy(content_size); ImGui::SetCursorPos(ImVec2(0, 0)); - // Handle pending scroll (deferred from ScrollToTile call outside render context) + // Handle pending scroll (deferred from ScrollToTile call outside render + // context) if (pending_scroll_tile_id_ >= 0) { if (IsValidTileId(pending_scroll_tile_id_)) { const ImVec2 target = TileOrigin(pending_scroll_tile_id_); @@ -173,7 +173,8 @@ void TileSelectorWidget::ScrollToTile(int tile_id, bool use_imgui_scroll) { return; } - // Defer scroll until next render (when we're in the correct ImGui window context) + // Defer scroll until next render (when we're in the correct ImGui window + // context) pending_scroll_tile_id_ = tile_id; pending_scroll_use_imgui_ = use_imgui_scroll; } diff --git a/src/app/gui/widgets/tile_selector_widget.h b/src/app/gui/widgets/tile_selector_widget.h index 2dd2e240..eedc056e 100644 --- a/src/app/gui/widgets/tile_selector_widget.h +++ b/src/app/gui/widgets/tile_selector_widget.h @@ -59,7 +59,8 @@ class TileSelectorWidget { int total_tiles_ = 0; std::string widget_id_; - // Deferred scroll state (for when ScrollToTile is called outside render context) + // Deferred scroll state (for when ScrollToTile is called outside render + // context) mutable int pending_scroll_tile_id_ = -1; mutable bool pending_scroll_use_imgui_ = true; }; diff --git a/src/app/main.cc b/src/app/main.cc index 690d48fd..c12b282b 100644 --- a/src/app/main.cc +++ b/src/app/main.cc @@ -144,7 +144,8 @@ int main(int argc, char** argv) { auto controller = std::make_unique(); EXIT_IF_ERROR(controller->OnEntry(rom_filename)) - // Set startup editor and cards from flags (after OnEntry initializes editor manager) + // Set startup editor and cards from flags (after OnEntry initializes editor + // manager) if (!FLAGS_editor->Get().empty()) { controller->SetStartupEditor(FLAGS_editor->Get(), FLAGS_cards->Get()); } diff --git a/src/app/net/collaboration_service.cc b/src/app/net/collaboration_service.cc index 978cc7c4..52b286ba 100644 --- a/src/app/net/collaboration_service.cc +++ b/src/app/net/collaboration_service.cc @@ -16,14 +16,11 @@ CollaborationService::CollaborationService(Rom* rom) client_(std::make_unique()), sync_in_progress_(false) {} -CollaborationService::~CollaborationService() { - Disconnect(); -} +CollaborationService::~CollaborationService() { Disconnect(); } absl::Status CollaborationService::Initialize( const Config& config, RomVersionManager* version_mgr, ProposalApprovalManager* approval_mgr) { - config_ = config; version_mgr_ = version_mgr; approval_mgr_ = approval_mgr; @@ -82,7 +79,6 @@ void CollaborationService::Disconnect() { absl::Status CollaborationService::HostSession(const std::string& session_name, const std::string& username, bool ai_enabled) { - if (!client_->IsConnected()) { return absl::FailedPreconditionError("Not connected to server"); } @@ -118,7 +114,6 @@ absl::Status CollaborationService::HostSession(const std::string& session_name, absl::Status CollaborationService::JoinSession(const std::string& session_code, const std::string& username) { - if (!client_->IsConnected()) { return absl::FailedPreconditionError("Not connected to server"); } @@ -157,7 +152,6 @@ absl::Status CollaborationService::LeaveSession() { absl::Status CollaborationService::SubmitChangesAsProposal( const std::string& description, const std::string& username) { - if (!client_->InSession()) { return absl::FailedPreconditionError("Not in a session"); } @@ -195,7 +189,6 @@ absl::Status CollaborationService::SubmitChangesAsProposal( absl::Status CollaborationService::ApplyRomSync(const std::string& diff_data, const std::string& rom_hash, const std::string& sender) { - if (!rom_ || !rom_->is_loaded()) { return absl::FailedPreconditionError("ROM not loaded"); } @@ -239,7 +232,6 @@ absl::Status CollaborationService::ApplyRomSync(const std::string& diff_data, absl::Status CollaborationService::HandleIncomingProposal( const std::string& proposal_id, const nlohmann::json& proposal_data, const std::string& sender) { - if (!approval_mgr_) { return absl::FailedPreconditionError("Approval manager not initialized"); } @@ -252,7 +244,6 @@ absl::Status CollaborationService::HandleIncomingProposal( absl::Status CollaborationService::VoteOnProposal( const std::string& proposal_id, bool approved, const std::string& username) { - if (!client_->InSession()) { return absl::FailedPreconditionError("Not in a session"); } @@ -270,7 +261,6 @@ absl::Status CollaborationService::VoteOnProposal( absl::Status CollaborationService::ApplyApprovedProposal( const std::string& proposal_id) { - if (!approval_mgr_->IsProposalApproved(proposal_id)) { return absl::FailedPreconditionError("Proposal not approved"); } @@ -361,7 +351,6 @@ void CollaborationService::OnParticipantLeft(const nlohmann::json& payload) { std::string CollaborationService::GenerateDiff(const std::string& from_hash, const std::string& to_hash) { - // Simplified diff generation // In production, this would generate a binary diff // For now, just return placeholder diff --git a/src/app/net/collaboration_service.h b/src/app/net/collaboration_service.h index ab082f81..227c77a1 100644 --- a/src/app/net/collaboration_service.h +++ b/src/app/net/collaboration_service.h @@ -17,12 +17,12 @@ namespace net { /** * @class CollaborationService * @brief High-level service integrating version management with networking - * + * * Bridges the gap between: * - Local ROM version management * - Remote collaboration via WebSocket * - Proposal approval workflow - * + * * Features: * - Automatic ROM sync on changes * - Network-aware proposal approval diff --git a/src/app/net/rom_service_impl.cc b/src/app/net/rom_service_impl.cc index 3c654a05..1b294fd4 100644 --- a/src/app/net/rom_service_impl.cc +++ b/src/app/net/rom_service_impl.cc @@ -19,14 +19,11 @@ RomServiceImpl::RomServiceImpl(Rom* rom, RomVersionManager* version_manager, version_mgr_(version_manager), approval_mgr_(approval_manager) {} -void RomServiceImpl::SetConfig(const Config& config) { - config_ = config; -} +void RomServiceImpl::SetConfig(const Config& config) { config_ = config; } grpc::Status RomServiceImpl::ReadBytes(grpc::ServerContext* context, const rom_svc::ReadBytesRequest* request, rom_svc::ReadBytesResponse* response) { - if (!rom_ || !rom_->is_loaded()) { return grpc::Status(grpc::StatusCode::FAILED_PRECONDITION, "ROM not loaded"); @@ -53,7 +50,6 @@ grpc::Status RomServiceImpl::ReadBytes(grpc::ServerContext* context, grpc::Status RomServiceImpl::WriteBytes( grpc::ServerContext* context, const rom_svc::WriteBytesRequest* request, rom_svc::WriteBytesResponse* response) { - if (!rom_ || !rom_->is_loaded()) { return grpc::Status(grpc::StatusCode::FAILED_PRECONDITION, "ROM not loaded"); @@ -111,7 +107,6 @@ grpc::Status RomServiceImpl::WriteBytes( grpc::Status RomServiceImpl::GetRomInfo( grpc::ServerContext* context, const rom_svc::GetRomInfoRequest* request, rom_svc::GetRomInfoResponse* response) { - if (!rom_ || !rom_->is_loaded()) { return grpc::Status(grpc::StatusCode::FAILED_PRECONDITION, "ROM not loaded"); @@ -129,7 +124,6 @@ grpc::Status RomServiceImpl::GetRomInfo( grpc::Status RomServiceImpl::GetTileData( grpc::ServerContext* context, const rom_svc::GetTileDataRequest* request, rom_svc::GetTileDataResponse* response) { - return grpc::Status(grpc::StatusCode::UNIMPLEMENTED, "GetTileData not yet implemented"); } @@ -137,7 +131,6 @@ grpc::Status RomServiceImpl::GetTileData( grpc::Status RomServiceImpl::SetTileData( grpc::ServerContext* context, const rom_svc::SetTileDataRequest* request, rom_svc::SetTileDataResponse* response) { - return grpc::Status(grpc::StatusCode::UNIMPLEMENTED, "SetTileData not yet implemented"); } @@ -145,7 +138,6 @@ grpc::Status RomServiceImpl::SetTileData( grpc::Status RomServiceImpl::GetMapData( grpc::ServerContext* context, const rom_svc::GetMapDataRequest* request, rom_svc::GetMapDataResponse* response) { - return grpc::Status(grpc::StatusCode::UNIMPLEMENTED, "GetMapData not yet implemented"); } @@ -153,7 +145,6 @@ grpc::Status RomServiceImpl::GetMapData( grpc::Status RomServiceImpl::SetMapData( grpc::ServerContext* context, const rom_svc::SetMapDataRequest* request, rom_svc::SetMapDataResponse* response) { - return grpc::Status(grpc::StatusCode::UNIMPLEMENTED, "SetMapData not yet implemented"); } @@ -161,7 +152,6 @@ grpc::Status RomServiceImpl::SetMapData( grpc::Status RomServiceImpl::GetSpriteData( grpc::ServerContext* context, const rom_svc::GetSpriteDataRequest* request, rom_svc::GetSpriteDataResponse* response) { - return grpc::Status(grpc::StatusCode::UNIMPLEMENTED, "GetSpriteData not yet implemented"); } @@ -169,7 +159,6 @@ grpc::Status RomServiceImpl::GetSpriteData( grpc::Status RomServiceImpl::SetSpriteData( grpc::ServerContext* context, const rom_svc::SetSpriteDataRequest* request, rom_svc::SetSpriteDataResponse* response) { - return grpc::Status(grpc::StatusCode::UNIMPLEMENTED, "SetSpriteData not yet implemented"); } @@ -177,7 +166,6 @@ grpc::Status RomServiceImpl::SetSpriteData( grpc::Status RomServiceImpl::GetDialogue( grpc::ServerContext* context, const rom_svc::GetDialogueRequest* request, rom_svc::GetDialogueResponse* response) { - return grpc::Status(grpc::StatusCode::UNIMPLEMENTED, "GetDialogue not yet implemented"); } @@ -185,7 +173,6 @@ grpc::Status RomServiceImpl::GetDialogue( grpc::Status RomServiceImpl::SetDialogue( grpc::ServerContext* context, const rom_svc::SetDialogueRequest* request, rom_svc::SetDialogueResponse* response) { - return grpc::Status(grpc::StatusCode::UNIMPLEMENTED, "SetDialogue not yet implemented"); } diff --git a/src/app/net/rom_service_impl.h b/src/app/net/rom_service_impl.h index 95364bf8..fbee843a 100644 --- a/src/app/net/rom_service_impl.h +++ b/src/app/net/rom_service_impl.h @@ -15,6 +15,7 @@ #undef ERROR #endif // _WIN32 #include + #include "protos/rom_service.grpc.pb.h" #ifdef _WIN32 #pragma pop_macro("DWORD") @@ -34,13 +35,13 @@ namespace net { /** * @brief gRPC service implementation for remote ROM manipulation - * + * * Enables remote clients (like z3ed CLI) to: * - Read/write ROM data * - Submit proposals for collaborative editing * - Manage ROM versions and snapshots * - Query ROM structures (overworld, dungeons, sprites) - * + * * Thread-safe and designed for concurrent access. */ class RomServiceImpl final : public proto::RomService::Service { diff --git a/src/app/net/rom_version_manager.cc b/src/app/net/rom_version_manager.cc index 853333e9..662074e0 100644 --- a/src/app/net/rom_version_manager.cc +++ b/src/app/net/rom_version_manager.cc @@ -74,7 +74,6 @@ absl::Status RomVersionManager::Initialize(const Config& config) { absl::StatusOr RomVersionManager::CreateSnapshot( const std::string& description, const std::string& creator, bool is_checkpoint) { - if (!rom_ || !rom_->is_loaded()) { return absl::FailedPreconditionError("ROM not loaded"); } @@ -302,12 +301,9 @@ RomVersionManager::Stats RomVersionManager::GetStats() const { stats.total_snapshots = snapshots_.size(); for (const auto& [id, snapshot] : snapshots_) { - if (snapshot.is_safe_point) - stats.safe_points++; - if (snapshot.is_checkpoint) - stats.manual_checkpoints++; - if (!snapshot.is_checkpoint) - stats.auto_backups++; + if (snapshot.is_safe_point) stats.safe_points++; + if (snapshot.is_checkpoint) stats.manual_checkpoints++; + if (!snapshot.is_checkpoint) stats.auto_backups++; stats.total_storage_bytes += snapshot.compressed_size; if (stats.oldest_snapshot_timestamp == 0 || @@ -393,7 +389,6 @@ void ProposalApprovalManager::SetHost(const std::string& host_username) { absl::Status ProposalApprovalManager::SubmitProposal( const std::string& proposal_id, const std::string& sender, const std::string& description, const nlohmann::json& proposal_data) { - ApprovalStatus status; status.proposal_id = proposal_id; status.status = "pending"; @@ -418,7 +413,6 @@ absl::Status ProposalApprovalManager::SubmitProposal( absl::Status ProposalApprovalManager::VoteOnProposal( const std::string& proposal_id, const std::string& username, bool approved) { - auto it = proposals_.find(proposal_id); if (it == proposals_.end()) { return absl::NotFoundError("Proposal not found"); @@ -441,8 +435,7 @@ absl::Status ProposalApprovalManager::VoteOnProposal( // Check if rejection threshold reached size_t rejection_count = 0; for (const auto& [user, vote] : status.votes) { - if (!vote) - rejection_count++; + if (!vote) rejection_count++; } // If host rejected (in host-only mode), reject immediately @@ -458,7 +451,6 @@ absl::Status ProposalApprovalManager::VoteOnProposal( bool ProposalApprovalManager::CheckApprovalThreshold( const ApprovalStatus& status) const { - switch (mode_) { case ApprovalMode::kHostOnly: // Only host vote matters @@ -470,8 +462,7 @@ bool ProposalApprovalManager::CheckApprovalThreshold( case ApprovalMode::kMajorityVote: { size_t approval_count = 0; for (const auto& [user, approved] : status.votes) { - if (approved) - approval_count++; + if (approved) approval_count++; } return approval_count > participants_.size() / 2; } @@ -481,8 +472,7 @@ bool ProposalApprovalManager::CheckApprovalThreshold( return false; // Not everyone voted yet } for (const auto& [user, approved] : status.votes) { - if (!approved) - return false; + if (!approved) return false; } return true; } diff --git a/src/app/net/rom_version_manager.h b/src/app/net/rom_version_manager.h index 64909095..bb56ebaa 100644 --- a/src/app/net/rom_version_manager.h +++ b/src/app/net/rom_version_manager.h @@ -55,7 +55,7 @@ struct VersionDiff { /** * @class RomVersionManager * @brief Manages ROM versioning, snapshots, and rollback capabilities - * + * * Provides: * - Automatic periodic snapshots * - Manual checkpoints @@ -185,7 +185,7 @@ class RomVersionManager { /** * @class ProposalApprovalManager * @brief Manages proposal approval workflow for collaborative sessions - * + * * Features: * - Host approval required for all changes * - Participant voting system diff --git a/src/app/net/websocket_client.cc b/src/app/net/websocket_client.cc index 5391bd89..a9ca9649 100644 --- a/src/app/net/websocket_client.cc +++ b/src/app/net/websocket_client.cc @@ -62,8 +62,7 @@ class WebSocketClient::Impl { void Disconnect() { std::lock_guard lock(mutex_); - if (!connected_) - return; + if (!connected_) return; should_stop_ = true; connected_ = false; @@ -175,9 +174,7 @@ class WebSocketClient::Impl { WebSocketClient::WebSocketClient() : impl_(std::make_unique()), state_(ConnectionState::kDisconnected) {} -WebSocketClient::~WebSocketClient() { - Disconnect(); -} +WebSocketClient::~WebSocketClient() { Disconnect(); } absl::Status WebSocketClient::Connect(const std::string& host, int port) { auto status = impl_->Connect(host, port); @@ -200,7 +197,6 @@ void WebSocketClient::Disconnect() { absl::StatusOr WebSocketClient::HostSession( const std::string& session_name, const std::string& username, const std::string& rom_hash, bool ai_enabled) { - #ifdef YAZE_WITH_JSON if (!IsConnected()) { return absl::FailedPreconditionError("Not connected to server"); @@ -235,7 +231,6 @@ absl::StatusOr WebSocketClient::HostSession( absl::StatusOr WebSocketClient::JoinSession( const std::string& session_code, const std::string& username) { - #ifdef YAZE_WITH_JSON if (!IsConnected()) { return absl::FailedPreconditionError("Not connected to server"); @@ -279,7 +274,6 @@ absl::Status WebSocketClient::LeaveSession() { absl::Status WebSocketClient::SendChatMessage(const std::string& message, const std::string& sender) { - #ifdef YAZE_WITH_JSON nlohmann::json msg = { {"type", "chat_message"}, @@ -294,7 +288,6 @@ absl::Status WebSocketClient::SendChatMessage(const std::string& message, absl::Status WebSocketClient::SendRomSync(const std::string& diff_data, const std::string& rom_hash, const std::string& sender) { - #ifdef YAZE_WITH_JSON nlohmann::json message = { {"type", "rom_sync"}, @@ -309,7 +302,6 @@ absl::Status WebSocketClient::SendRomSync(const std::string& diff_data, absl::Status WebSocketClient::ShareProposal(const nlohmann::json& proposal_data, const std::string& sender) { - #ifdef YAZE_WITH_JSON nlohmann::json message = { {"type", "proposal_share"}, @@ -324,7 +316,6 @@ absl::Status WebSocketClient::ShareProposal(const nlohmann::json& proposal_data, absl::Status WebSocketClient::VoteOnProposal(const std::string& proposal_id, bool approved, const std::string& username) { - #ifdef YAZE_WITH_JSON nlohmann::json message = {{"type", "proposal_vote"}, {"payload", @@ -340,7 +331,6 @@ absl::Status WebSocketClient::VoteOnProposal(const std::string& proposal_id, absl::Status WebSocketClient::UpdateProposalStatus( const std::string& proposal_id, const std::string& status) { - #ifdef YAZE_WITH_JSON nlohmann::json message = { {"type", "proposal_update"}, diff --git a/src/app/net/websocket_client.h b/src/app/net/websocket_client.h index 8e1dfa92..9aa97ed6 100644 --- a/src/app/net/websocket_client.h +++ b/src/app/net/websocket_client.h @@ -48,7 +48,7 @@ struct SessionInfo { /** * @class WebSocketClient * @brief WebSocket client for connecting to yaze-server - * + * * Provides: * - Connection management with auto-reconnect * - Session hosting and joining diff --git a/src/app/platform/asset_loader.h b/src/app/platform/asset_loader.h index 9cd7e004..f365395e 100644 --- a/src/app/platform/asset_loader.h +++ b/src/app/platform/asset_loader.h @@ -12,7 +12,7 @@ namespace yaze { /** * @class AssetLoader * @brief Cross-platform asset file loading utility - * + * * Handles platform-specific paths for loading assets from: * - macOS bundle resources * - Windows relative paths @@ -23,7 +23,8 @@ class AssetLoader { public: /** * Load a text file from the assets directory - * @param relative_path Path relative to assets/ (e.g., "agent/system_prompt.txt") + * @param relative_path Path relative to assets/ (e.g., + * "agent/system_prompt.txt") * @return File contents or error */ static absl::StatusOr LoadTextFile( diff --git a/src/app/platform/file_dialog_nfd.cc b/src/app/platform/file_dialog_nfd.cc index 4a183df6..8b4fe1db 100644 --- a/src/app/platform/file_dialog_nfd.cc +++ b/src/app/platform/file_dialog_nfd.cc @@ -1,11 +1,13 @@ -// Windows and Linux implementation of FileDialogWrapper using nativefiledialog-extended -#include "util/file_util.h" - +// Windows and Linux implementation of FileDialogWrapper using +// nativefiledialog-extended #include + #include #include #include +#include "util/file_util.h" + namespace yaze { namespace util { diff --git a/src/app/platform/font_loader.cc b/src/app/platform/font_loader.cc index 93fa4ba3..b76e7507 100644 --- a/src/app/platform/font_loader.cc +++ b/src/app/platform/font_loader.cc @@ -97,7 +97,8 @@ absl::Status AddJapaneseFont(const FontConfig& /*config*/) { absl::Status LoadPackageFonts() { if (font_registry.fonts.empty()) { - // Initialize the font names and sizes with proper ImFontConfig initialization + // Initialize the font names and sizes with proper ImFontConfig + // initialization font_registry.fonts = { FontConfig{KARLA_REGULAR, FONT_SIZE_DEFAULT, {}, {}}, FontConfig{ROBOTO_MEDIUM, FONT_SIZE_DEFAULT, {}, {}}, diff --git a/src/app/platform/timing.h b/src/app/platform/timing.h index b39c89ba..08d00874 100644 --- a/src/app/platform/timing.h +++ b/src/app/platform/timing.h @@ -2,6 +2,7 @@ #define YAZE_APP_CORE_TIMING_H #include + #include namespace yaze { @@ -9,7 +10,7 @@ namespace yaze { /** * @class TimingManager * @brief Provides accurate timing for animations and frame pacing - * + * * This class solves the issue where ImGui::GetIO().DeltaTime only updates * when events are processed (mouse movement, etc). It uses SDL's performance * counter to provide accurate timing regardless of input events. @@ -67,8 +68,7 @@ class TimingManager { * @brief Get total elapsed time since first update */ float GetElapsedTime() const { - if (last_time_ == 0) - return 0.0f; + if (last_time_ == 0) return 0.0f; uint64_t current_time = SDL_GetPerformanceCounter(); return (current_time - first_time_) / static_cast(frequency_); } diff --git a/src/app/rom.cc b/src/app/rom.cc index 9619460e..d375cd3a 100644 --- a/src/app/rom.cc +++ b/src/app/rom.cc @@ -47,9 +47,7 @@ void MaybeStripSmcHeader(std::vector& rom_data, unsigned long& size) { } // namespace -RomLoadOptions RomLoadOptions::AppDefaults() { - return RomLoadOptions{}; -} +RomLoadOptions RomLoadOptions::AppDefaults() { return RomLoadOptions{}; } RomLoadOptions RomLoadOptions::CliDefaults() { RomLoadOptions options; @@ -110,8 +108,9 @@ absl::StatusOr> LoadLinkGraphics( link_graphics[i].Create(gfx::kTilesheetWidth, gfx::kTilesheetHeight, gfx::kTilesheetDepth, link_sheet_8bpp); link_graphics[i].SetPalette(rom.palette_group().armors[0]); - // Texture creation is deferred until GraphicsEditor is opened and renderer is available. - // The graphics will be queued for texturing when needed via Arena's deferred system. + // Texture creation is deferred until GraphicsEditor is opened and renderer + // is available. The graphics will be queued for texturing when needed via + // Arena's deferred system. } return link_graphics; } @@ -627,8 +626,7 @@ absl::Status Rom::SaveToFile(const SaveSettings& settings) { absl::StrCat("Error while writing to ROM file: ", filename)); } - if (non_firing_status.ok()) - dirty_ = false; + if (non_firing_status.ok()) dirty_ = false; return non_firing_status.ok() ? absl::OkStatus() : non_firing_status; } @@ -800,8 +798,7 @@ absl::Status Rom::WriteColor(uint32_t address, const gfx::SnesColor& color) { // Write the 16-bit color value to the ROM at the specified address LOG_DEBUG("Rom", "WriteColor: %#06X: %s", address, util::HexWord(bgr).data()); auto st = WriteShort(address, bgr); - if (st.ok()) - dirty_ = true; + if (st.ok()) dirty_ = true; return st; } diff --git a/src/app/rom.h b/src/app/rom.h index 11d0beee..62d1e0fb 100644 --- a/src/app/rom.h +++ b/src/app/rom.h @@ -193,8 +193,7 @@ class Rom { } uint8_t& operator[](unsigned long i) { - if (i >= size_) - throw std::out_of_range("Rom index out of range"); + if (i >= size_) throw std::out_of_range("Rom index out of range"); return rom_data_[i]; } diff --git a/src/app/service/canvas_automation_service.cc b/src/app/service/canvas_automation_service.cc index 2ce1fda3..50336095 100644 --- a/src/app/service/canvas_automation_service.cc +++ b/src/app/service/canvas_automation_service.cc @@ -3,6 +3,7 @@ #ifdef YAZE_WITH_GRPC #include + #include "app/editor/overworld/overworld_editor.h" #include "app/gui/canvas/canvas_automation_api.h" #include "protos/canvas_automation.grpc.pb.h" @@ -85,7 +86,6 @@ editor::OverworldEditor* CanvasAutomationServiceImpl::GetOverworldEditor( absl::Status CanvasAutomationServiceImpl::SetTile( const proto::SetTileRequest* request, proto::SetTileResponse* response) { - auto* canvas = GetCanvas(request->canvas_id()); if (!canvas) { response->set_success(false); @@ -107,7 +107,6 @@ absl::Status CanvasAutomationServiceImpl::SetTile( absl::Status CanvasAutomationServiceImpl::GetTile( const proto::GetTileRequest* request, proto::GetTileResponse* response) { - auto* canvas = GetCanvas(request->canvas_id()); if (!canvas) { response->set_success(false); @@ -131,7 +130,6 @@ absl::Status CanvasAutomationServiceImpl::GetTile( absl::Status CanvasAutomationServiceImpl::SetTiles( const proto::SetTilesRequest* request, proto::SetTilesResponse* response) { - auto* canvas = GetCanvas(request->canvas_id()); if (!canvas) { response->set_success(false); @@ -160,7 +158,6 @@ absl::Status CanvasAutomationServiceImpl::SetTiles( absl::Status CanvasAutomationServiceImpl::SelectTile( const proto::SelectTileRequest* request, proto::SelectTileResponse* response) { - auto* canvas = GetCanvas(request->canvas_id()); if (!canvas) { response->set_success(false); @@ -178,7 +175,6 @@ absl::Status CanvasAutomationServiceImpl::SelectTile( absl::Status CanvasAutomationServiceImpl::SelectTileRect( const proto::SelectTileRectRequest* request, proto::SelectTileRectResponse* response) { - auto* canvas = GetCanvas(request->canvas_id()); if (!canvas) { response->set_success(false); @@ -200,7 +196,6 @@ absl::Status CanvasAutomationServiceImpl::SelectTileRect( absl::Status CanvasAutomationServiceImpl::GetSelection( const proto::GetSelectionRequest* request, proto::GetSelectionResponse* response) { - auto* canvas = GetCanvas(request->canvas_id()); if (!canvas) { return absl::NotFoundError("Canvas not found: " + request->canvas_id()); @@ -231,7 +226,6 @@ absl::Status CanvasAutomationServiceImpl::GetSelection( absl::Status CanvasAutomationServiceImpl::ClearSelection( const proto::ClearSelectionRequest* request, proto::ClearSelectionResponse* response) { - auto* canvas = GetCanvas(request->canvas_id()); if (!canvas) { response->set_success(false); @@ -252,7 +246,6 @@ absl::Status CanvasAutomationServiceImpl::ClearSelection( absl::Status CanvasAutomationServiceImpl::ScrollToTile( const proto::ScrollToTileRequest* request, proto::ScrollToTileResponse* response) { - auto* canvas = GetCanvas(request->canvas_id()); if (!canvas) { response->set_success(false); @@ -269,7 +262,6 @@ absl::Status CanvasAutomationServiceImpl::ScrollToTile( absl::Status CanvasAutomationServiceImpl::CenterOn( const proto::CenterOnRequest* request, proto::CenterOnResponse* response) { - auto* canvas = GetCanvas(request->canvas_id()); if (!canvas) { response->set_success(false); @@ -286,7 +278,6 @@ absl::Status CanvasAutomationServiceImpl::CenterOn( absl::Status CanvasAutomationServiceImpl::SetZoom( const proto::SetZoomRequest* request, proto::SetZoomResponse* response) { - auto* canvas = GetCanvas(request->canvas_id()); if (!canvas) { response->set_success(false); @@ -306,7 +297,6 @@ absl::Status CanvasAutomationServiceImpl::SetZoom( absl::Status CanvasAutomationServiceImpl::GetZoom( const proto::GetZoomRequest* request, proto::GetZoomResponse* response) { - auto* canvas = GetCanvas(request->canvas_id()); if (!canvas) { return absl::NotFoundError("Canvas not found: " + request->canvas_id()); @@ -325,7 +315,6 @@ absl::Status CanvasAutomationServiceImpl::GetZoom( absl::Status CanvasAutomationServiceImpl::GetDimensions( const proto::GetDimensionsRequest* request, proto::GetDimensionsResponse* response) { - auto* canvas = GetCanvas(request->canvas_id()); if (!canvas) { return absl::NotFoundError("Canvas not found: " + request->canvas_id()); @@ -345,7 +334,6 @@ absl::Status CanvasAutomationServiceImpl::GetDimensions( absl::Status CanvasAutomationServiceImpl::GetVisibleRegion( const proto::GetVisibleRegionRequest* request, proto::GetVisibleRegionResponse* response) { - auto* canvas = GetCanvas(request->canvas_id()); if (!canvas) { return absl::NotFoundError("Canvas not found: " + request->canvas_id()); @@ -366,7 +354,6 @@ absl::Status CanvasAutomationServiceImpl::GetVisibleRegion( absl::Status CanvasAutomationServiceImpl::IsTileVisible( const proto::IsTileVisibleRequest* request, proto::IsTileVisibleResponse* response) { - auto* canvas = GetCanvas(request->canvas_id()); if (!canvas) { return absl::NotFoundError("Canvas not found: " + request->canvas_id()); @@ -384,7 +371,7 @@ absl::Status CanvasAutomationServiceImpl::IsTileVisible( /** * @brief gRPC service wrapper that forwards to CanvasAutomationServiceImpl - * + * * This adapter implements the proto-generated Service interface and * forwards all calls to our implementation, converting between gRPC * and absl::Status types. diff --git a/src/app/service/canvas_automation_service.h b/src/app/service/canvas_automation_service.h index 8d63d5ed..8650ba09 100644 --- a/src/app/service/canvas_automation_service.h +++ b/src/app/service/canvas_automation_service.h @@ -129,11 +129,11 @@ class CanvasAutomationServiceImpl { /** * @brief Factory function to create gRPC service wrapper - * + * * Creates the gRPC service wrapper for CanvasAutomationServiceImpl. * The wrapper handles the conversion between gRPC and absl::Status. * Returns as base grpc::Service to avoid incomplete type issues. - * + * * @param impl Pointer to implementation (not owned) * @return Unique pointer to gRPC service */ diff --git a/src/app/service/imgui_test_harness_service.cc b/src/app/service/imgui_test_harness_service.cc index c1ca739f..4b732984 100644 --- a/src/app/service/imgui_test_harness_service.cc +++ b/src/app/service/imgui_test_harness_service.cc @@ -1758,9 +1758,7 @@ ImGuiTestHarnessServer& ImGuiTestHarnessServer::Instance() { return *instance; } -ImGuiTestHarnessServer::~ImGuiTestHarnessServer() { - Shutdown(); -} +ImGuiTestHarnessServer::~ImGuiTestHarnessServer() { Shutdown(); } absl::Status ImGuiTestHarnessServer::Start(int port, TestManager* test_manager) { @@ -1775,7 +1773,8 @@ absl::Status ImGuiTestHarnessServer::Start(int port, // Create the service implementation with TestManager reference service_ = std::make_unique(test_manager); - // Create the gRPC service wrapper (store as member to prevent it from going out of scope) + // Create the gRPC service wrapper (store as member to prevent it from going + // out of scope) grpc_service_ = std::make_unique(service_.get()); std::string server_address = absl::StrFormat("0.0.0.0:%d", port); diff --git a/src/app/service/imgui_test_harness_service.h b/src/app/service/imgui_test_harness_service.h index dfe11867..980ba9d8 100644 --- a/src/app/service/imgui_test_harness_service.h +++ b/src/app/service/imgui_test_harness_service.h @@ -147,7 +147,8 @@ class ImGuiTestHarnessServer { private: ImGuiTestHarnessServer() = default; - ~ImGuiTestHarnessServer(); // Defined in .cc file to allow incomplete type deletion + ~ImGuiTestHarnessServer(); // Defined in .cc file to allow incomplete type + // deletion // Disable copy and move ImGuiTestHarnessServer(const ImGuiTestHarnessServer&) = delete; diff --git a/src/app/service/screenshot_utils.cc b/src/app/service/screenshot_utils.cc index fc60f967..59bf328b 100644 --- a/src/app/service/screenshot_utils.cc +++ b/src/app/service/screenshot_utils.cc @@ -152,10 +152,8 @@ absl::StatusOr CaptureHarnessScreenshotRegion( capture_height = region->height; // Clamp to renderer bounds - if (capture_x < 0) - capture_x = 0; - if (capture_y < 0) - capture_y = 0; + if (capture_x < 0) capture_x = 0; + if (capture_y < 0) capture_y = 0; if (capture_x + capture_width > full_width) { capture_width = full_width - capture_x; } diff --git a/src/app/service/screenshot_utils.h b/src/app/service/screenshot_utils.h index ec752726..4c863c7f 100644 --- a/src/app/service/screenshot_utils.h +++ b/src/app/service/screenshot_utils.h @@ -33,7 +33,8 @@ absl::StatusOr CaptureHarnessScreenshot( const std::string& preferred_path = ""); // Captures a specific region of the renderer output. -// If region is nullopt, captures the full renderer (same as CaptureHarnessScreenshot). +// If region is nullopt, captures the full renderer (same as +// CaptureHarnessScreenshot). absl::StatusOr CaptureHarnessScreenshotRegion( const std::optional& region, const std::string& preferred_path = ""); diff --git a/src/app/service/unified_grpc_server.cc b/src/app/service/unified_grpc_server.cc index 92c1998e..73fd2487 100644 --- a/src/app/service/unified_grpc_server.cc +++ b/src/app/service/unified_grpc_server.cc @@ -2,6 +2,8 @@ #ifdef YAZE_WITH_GRPC +#include + #include #include @@ -10,8 +12,6 @@ #include "app/rom.h" #include "app/service/canvas_automation_service.h" #include "app/service/imgui_test_harness_service.h" - -#include #include "protos/canvas_automation.grpc.pb.h" namespace yaze { @@ -19,16 +19,13 @@ namespace yaze { YazeGRPCServer::YazeGRPCServer() : is_running_(false) {} // Destructor defined here so CanvasAutomationServiceGrpc is a complete type -YazeGRPCServer::~YazeGRPCServer() { - Shutdown(); -} +YazeGRPCServer::~YazeGRPCServer() { Shutdown(); } absl::Status YazeGRPCServer::Initialize( int port, test::TestManager* test_manager, Rom* rom, net::RomVersionManager* version_mgr, net::ProposalApprovalManager* approval_mgr, CanvasAutomationServiceImpl* canvas_service) { - if (is_running_) { return absl::FailedPreconditionError("Server is already running"); } @@ -127,9 +124,7 @@ void YazeGRPCServer::Shutdown() { } } -bool YazeGRPCServer::IsRunning() const { - return is_running_; -} +bool YazeGRPCServer::IsRunning() const { return is_running_; } absl::Status YazeGRPCServer::BuildServer() { if (is_running_) { diff --git a/src/app/service/unified_grpc_server.h b/src/app/service/unified_grpc_server.h index 349b43e6..12c78177 100644 --- a/src/app/service/unified_grpc_server.h +++ b/src/app/service/unified_grpc_server.h @@ -34,21 +34,22 @@ class ImGuiTestHarnessServiceImpl; /** * @class YazeGRPCServer * @brief YAZE's unified gRPC server for Zelda3 editor automation - * + * * This server combines multiple automation services for the Zelda editor: - * 1. ImGuiTestHarness - GUI test automation (widget discovery, screenshots, etc.) + * 1. ImGuiTestHarness - GUI test automation (widget discovery, screenshots, + * etc.) * 2. RomService - ROM manipulation (read/write, proposals, version management) * 3. CanvasAutomation - Canvas operations (tiles, selection, zoom, pan) - * + * * All services share the same gRPC server instance and port, allowing - * clients (CLI, AI agents, remote scripts) to interact with GUI, ROM data, + * clients (CLI, AI agents, remote scripts) to interact with GUI, ROM data, * and canvas operations simultaneously. - * + * * Example usage: * ```cpp * YazeGRPCServer server; - * server.Initialize(50051, test_manager, rom, version_mgr, approval_mgr, canvas_service); - * server.Start(); + * server.Initialize(50051, test_manager, rom, version_mgr, approval_mgr, + * canvas_service); server.Start(); * // ... do work ... * server.Shutdown(); * ``` @@ -67,7 +68,8 @@ class YazeGRPCServer { }; YazeGRPCServer(); - // Destructor must be defined in .cc file to allow deletion of incomplete types + // Destructor must be defined in .cc file to allow deletion of incomplete + // types ~YazeGRPCServer(); /** diff --git a/src/app/test/e2e_test_suite.h b/src/app/test/e2e_test_suite.h index a776b334..80c3d519 100644 --- a/src/app/test/e2e_test_suite.h +++ b/src/app/test/e2e_test_suite.h @@ -15,7 +15,7 @@ namespace test { /** * @brief End-to-End test suite for comprehensive ROM testing - * + * * This test suite provides comprehensive E2E testing capabilities including: * - ROM loading/saving validation * - Data integrity testing @@ -89,10 +89,8 @@ class E2ETestSuite : public TestSuite { if (test_large_scale_editing_) { ImGui::Indent(); ImGui::InputInt("Number of edits", &num_edits_); - if (num_edits_ < 1) - num_edits_ = 1; - if (num_edits_ > 100) - num_edits_ = 100; + if (num_edits_ < 1) num_edits_ = 1; + if (num_edits_ > 100) num_edits_ = 100; ImGui::Unindent(); } } diff --git a/src/app/test/emulator_test_suite.h b/src/app/test/emulator_test_suite.h index dc5a2276..dd79b423 100644 --- a/src/app/test/emulator_test_suite.h +++ b/src/app/test/emulator_test_suite.h @@ -21,7 +21,7 @@ namespace test { /** * @brief Test suite for core emulator components. - * + * * This suite validates the contracts outlined in the emulator enhancement * and APU timing fix roadmaps. It tests the functionality of the CPU, APU, * SPC700, and debugging components to ensure they meet the requirements @@ -36,16 +36,11 @@ class EmulatorTestSuite : public TestSuite { TestCategory GetCategory() const override { return TestCategory::kUnit; } absl::Status RunTests(TestResults& results) override { - if (test_apu_handshake_) - RunApuHandshakeTest(results); - if (test_spc700_cycles_) - RunSpc700CycleAccuracyTest(results); - if (test_breakpoint_manager_) - RunBreakpointManagerTest(results); - if (test_watchpoint_manager_) - RunWatchpointManagerTest(results); - if (test_audio_backend_) - RunAudioBackendTest(results); + if (test_apu_handshake_) RunApuHandshakeTest(results); + if (test_spc700_cycles_) RunSpc700CycleAccuracyTest(results); + if (test_breakpoint_manager_) RunBreakpointManagerTest(results); + if (test_watchpoint_manager_) RunWatchpointManagerTest(results); + if (test_audio_backend_) RunAudioBackendTest(results); return absl::OkStatus(); } @@ -70,11 +65,12 @@ class EmulatorTestSuite : public TestSuite { /** * @brief Verifies the CPU-APU handshake protocol. - * + * * **Contract:** Ensures the APU correctly signals its ready state and the * CPU can initiate the audio driver transfer. This is based on the protocol - * described in `APU_Timing_Fix_Plan.md`. A failure here indicates a fundamental - * timing or communication issue preventing audio from initializing. + * described in `APU_Timing_Fix_Plan.md`. A failure here indicates a + * fundamental timing or communication issue preventing audio from + * initializing. */ void RunApuHandshakeTest(TestResults& results) { auto start_time = std::chrono::steady_clock::now(); @@ -144,12 +140,13 @@ class EmulatorTestSuite : public TestSuite { /** * @brief Validates the cycle counting for SPC700 opcodes. - * - * **Contract:** Each SPC700 instruction must consume a precise number of cycles. - * This test verifies that the `Spc700::GetLastOpcodeCycles()` method returns - * the correct base cycle count from `spc700_cycles.h`. This is a prerequisite - * for the cycle-accurate refactoring proposed in `APU_Timing_Fix_Plan.md`. - * Note: This test does not yet account for variable cycle costs (page crossing, etc.). + * + * **Contract:** Each SPC700 instruction must consume a precise number of + * cycles. This test verifies that the `Spc700::GetLastOpcodeCycles()` method + * returns the correct base cycle count from `spc700_cycles.h`. This is a + * prerequisite for the cycle-accurate refactoring proposed in + * `APU_Timing_Fix_Plan.md`. Note: This test does not yet account for variable + * cycle costs (page crossing, etc.). */ void RunSpc700CycleAccuracyTest(TestResults& results) { auto start_time = std::chrono::steady_clock::now(); @@ -162,13 +159,9 @@ class EmulatorTestSuite : public TestSuite { try { // Dummy callbacks for SPC700 instantiation emu::ApuCallbacks callbacks; - callbacks.read = [](uint16_t) { - return 0; - }; - callbacks.write = [](uint16_t, uint8_t) { - }; - callbacks.idle = [](bool) { - }; + callbacks.read = [](uint16_t) { return 0; }; + callbacks.write = [](uint16_t, uint8_t) {}; + callbacks.idle = [](bool) {}; emu::Spc700 spc(callbacks); spc.Reset(true); @@ -209,10 +202,11 @@ class EmulatorTestSuite : public TestSuite { /** * @brief Tests the core functionality of the BreakpointManager. - * - * **Contract:** The `BreakpointManager` must be able to add, remove, and correctly - * identify hit breakpoints of various types (Execute, Read, Write). This is a - * core feature of the "Advanced Debugger" goal in `E1-emulator-enhancement-roadmap.md`. + * + * **Contract:** The `BreakpointManager` must be able to add, remove, and + * correctly identify hit breakpoints of various types (Execute, Read, Write). + * This is a core feature of the "Advanced Debugger" goal in + * `E1-emulator-enhancement-roadmap.md`. */ void RunBreakpointManagerTest(TestResults& results) { auto start_time = std::chrono::steady_clock::now(); @@ -270,7 +264,7 @@ class EmulatorTestSuite : public TestSuite { /** * @brief Tests the memory WatchpointManager. - * + * * **Contract:** The `WatchpointManager` must correctly log memory accesses * and trigger breaks when configured to do so. This is a key feature for * debugging data corruption issues, as outlined in the emulator roadmap. @@ -332,7 +326,7 @@ class EmulatorTestSuite : public TestSuite { /** * @brief Tests the audio backend abstraction layer. - * + * * **Contract:** The audio backend must initialize correctly, manage its state * (playing/paused), and accept audio samples. This is critical for fixing the * audio output as described in `E1-emulator-enhancement-roadmap.md`. diff --git a/src/app/test/integrated_test_suite.h b/src/app/test/integrated_test_suite.h index 3fe1b658..c0341c7f 100644 --- a/src/app/test/integrated_test_suite.h +++ b/src/app/test/integrated_test_suite.h @@ -387,8 +387,8 @@ class PerformanceTestSuite : public TestSuite { size_t baseline_textures = arena.GetTextureCount(); size_t baseline_surfaces = arena.GetSurfaceCount(); - // Simulate some operations (this would be more comprehensive with actual workload) - // For now, just verify resource counts remain stable + // Simulate some operations (this would be more comprehensive with actual + // workload) For now, just verify resource counts remain stable size_t final_textures = arena.GetTextureCount(); size_t final_surfaces = arena.GetSurfaceCount(); diff --git a/src/app/test/test_manager.cc b/src/app/test/test_manager.cc index 92eb38b5..a9146339 100644 --- a/src/app/test/test_manager.cc +++ b/src/app/test/test_manager.cc @@ -153,8 +153,8 @@ TestManager& TestManager::Get() { } TestManager::TestManager() { - // Note: UI test engine initialization is deferred until ImGui context is ready - // Call InitializeUITesting() explicitly after ImGui::CreateContext() + // Note: UI test engine initialization is deferred until ImGui context is + // ready Call InitializeUITesting() explicitly after ImGui::CreateContext() } TestManager::~TestManager() { @@ -1289,8 +1289,8 @@ void TestManager::DrawTestDashboard(bool* show_dashboard) { // Initialize problematic tests as disabled by default static bool initialized_defaults = false; if (!initialized_defaults) { - DisableTest( - "Comprehensive_Save_Test"); // Disable crash-prone test by default + DisableTest("Comprehensive_Save_Test"); // Disable crash-prone test + // by default initialized_defaults = true; } @@ -1656,7 +1656,8 @@ absl::Status TestManager::TestRomDataIntegrity(Rom* rom) { return absl::FailedPreconditionError("No ROM loaded for testing"); } - // Use TestRomWithCopy for integrity testing (read-only but uses copy for safety) + // Use TestRomWithCopy for integrity testing (read-only but uses copy for + // safety) return TestRomWithCopy(rom, [](Rom* test_rom) -> absl::Status { LOG_INFO("TestManager", "Testing ROM data integrity on copy: %s", test_rom->title().c_str()); @@ -1894,7 +1895,8 @@ absl::Status TestManager::ReplayLastPlan() { #endif absl::Status TestManager::ShowHarnessDashboard() { - // These methods are always available, but may return unimplemented without GRPC + // These methods are always available, but may return unimplemented without + // GRPC #if defined(YAZE_WITH_GRPC) return absl::OkStatus(); #else diff --git a/src/app/test/test_manager.h b/src/app/test/test_manager.h index f6723ce8..c34b05dd 100644 --- a/src/app/test/test_manager.h +++ b/src/app/test/test_manager.h @@ -19,7 +19,6 @@ #define IMGUI_DEFINE_MATH_OPERATORS #include "imgui.h" - #include "util/log.h" // Forward declarations diff --git a/src/app/test/unit_test_suite.h b/src/app/test/unit_test_suite.h index 706e69f3..408e8554 100644 --- a/src/app/test/unit_test_suite.h +++ b/src/app/test/unit_test_suite.h @@ -11,7 +11,8 @@ #include #endif -// Note: ImGui Test Engine is handled through YAZE_ENABLE_IMGUI_TEST_ENGINE in TestManager +// Note: ImGui Test Engine is handled through YAZE_ENABLE_IMGUI_TEST_ENGINE in +// TestManager namespace yaze { namespace test { @@ -143,8 +144,7 @@ class UnitTestSuite : public TestSuite { ImGui::Checkbox("Run disabled tests", &run_disabled_tests_); ImGui::Checkbox("Shuffle tests", &shuffle_tests_); ImGui::InputInt("Repeat count", &repeat_count_); - if (repeat_count_ < 1) - repeat_count_ = 1; + if (repeat_count_ < 1) repeat_count_ = 1; ImGui::InputText("Test filter", test_filter_, sizeof(test_filter_)); ImGui::SameLine(); diff --git a/src/app/test/z3ed_test_suite.h b/src/app/test/z3ed_test_suite.h index f502694a..afd82019 100644 --- a/src/app/test/z3ed_test_suite.h +++ b/src/app/test/z3ed_test_suite.h @@ -73,7 +73,8 @@ class Z3edAIAgentTestSuite : public TestSuite { result.status = TestStatus::kSkipped; result.error_message = "GEMINI_API_KEY environment variable not set"; } else { - // Test basic connectivity (would need actual API call in real implementation) + // Test basic connectivity (would need actual API call in real + // implementation) result.status = TestStatus::kPassed; result.error_message = "Gemini API key configured"; } diff --git a/src/app/test/zscustomoverworld_test_suite.h b/src/app/test/zscustomoverworld_test_suite.h index 376eb6af..569b5ed7 100644 --- a/src/app/test/zscustomoverworld_test_suite.h +++ b/src/app/test/zscustomoverworld_test_suite.h @@ -14,7 +14,7 @@ namespace test { /** * @brief ZSCustomOverworld upgrade testing suite - * + * * This test suite validates ZSCustomOverworld version upgrades: * - Vanilla -> v2 -> v3 upgrade path testing * - Address validation for each version diff --git a/src/app/transaction.h b/src/app/transaction.h index f7975178..79e7d2da 100644 --- a/src/app/transaction.h +++ b/src/app/transaction.h @@ -24,8 +24,7 @@ class Transaction { explicit Transaction(Rom& rom) : rom_(rom) {} Transaction& WriteByte(int address, uint8_t value) { - if (!status_.ok()) - return *this; + if (!status_.ok()) return *this; auto original = rom_.ReadByte(address); if (!original.ok()) { status_ = original.status(); @@ -40,8 +39,7 @@ class Transaction { } Transaction& WriteWord(int address, uint16_t value) { - if (!status_.ok()) - return *this; + if (!status_.ok()) return *this; auto original = rom_.ReadWord(address); if (!original.ok()) { status_ = original.status(); @@ -56,8 +54,7 @@ class Transaction { } Transaction& WriteLong(int address, uint32_t value) { - if (!status_.ok()) - return *this; + if (!status_.ok()) return *this; auto original = rom_.ReadLong(address); if (!original.ok()) { status_ = original.status(); @@ -72,8 +69,7 @@ class Transaction { } Transaction& WriteVector(int address, const std::vector& data) { - if (!status_.ok()) - return *this; + if (!status_.ok()) return *this; auto original = rom_.ReadByteVector(address, static_cast(data.size())); if (!original.ok()) { @@ -88,8 +84,7 @@ class Transaction { } Transaction& WriteColor(int address, const gfx::SnesColor& color) { - if (!status_.ok()) - return *this; + if (!status_.ok()) return *this; // Store original raw 16-bit value for rollback via WriteWord. auto original_word = rom_.ReadWord(address); if (!original_word.ok()) { diff --git a/src/cli/cli.cc b/src/cli/cli.cc index 8f90c758..38ab3efb 100644 --- a/src/cli/cli.cc +++ b/src/cli/cli.cc @@ -1,4 +1,5 @@ #include "cli/cli.h" + #include "absl/strings/str_cat.h" #include "absl/strings/str_join.h" #include "cli/handlers/command_handlers.h" @@ -145,12 +146,9 @@ void ModernCLI::ShowCategoryHelp(const std::string& category) const { auto* metadata = registry.GetMetadata(cmd_name); if (metadata) { std::string requirements; - if (metadata->requires_rom) - requirements += "ROM "; - if (metadata->requires_grpc) - requirements += "gRPC "; - if (requirements.empty()) - requirements = "—"; + if (metadata->requires_rom) requirements += "ROM "; + if (metadata->requires_grpc) requirements += "gRPC "; + if (requirements.empty()) requirements = "—"; rows.push_back({cmd_name, metadata->description, requirements}); } diff --git a/src/cli/handlers/agent.cc b/src/cli/handlers/agent.cc index afd77e8b..6f78d0d1 100644 --- a/src/cli/handlers/agent.cc +++ b/src/cli/handlers/agent.cc @@ -1,6 +1,3 @@ -#include "cli/cli.h" -#include "cli/handlers/agent/todo_commands.h" - #include #include #include @@ -11,6 +8,7 @@ #include "absl/status/status.h" #include "absl/strings/str_cat.h" #include "app/rom.h" +#include "cli/cli.h" #include "cli/handlers/agent/common.h" #include "cli/handlers/agent/simple_chat_command.h" #include "cli/handlers/agent/todo_commands.h" @@ -73,8 +71,7 @@ std::string GenerateAgentHelp() { const auto& cmd = agent_commands[i]; if (auto* meta = registry.GetMetadata(cmd); meta != nullptr) { help << " " << cmd; - for (size_t pad = cmd.length(); pad < 24; ++pad) - help << " "; + for (size_t pad = cmd.length(); pad < 24; ++pad) help << " "; help << meta->description << "\n"; } } @@ -103,7 +100,7 @@ namespace handlers { /** * @brief Unified agent command handler using CommandRegistry - * + * * Routes commands in this order: * 1. Special agent commands (plan, test, learn, todo) - Not in registry * 2. Registry commands (resource-*, dungeon-*, overworld-*, emulator-*, etc.) diff --git a/src/cli/handlers/agent/common.cc b/src/cli/handlers/agent/common.cc index bd94f44e..df6d87dd 100644 --- a/src/cli/handlers/agent/common.cc +++ b/src/cli/handlers/agent/common.cc @@ -121,18 +121,12 @@ bool IsTerminalStatus(TestRunStatus status) { std::optional ParseStatusFilter(absl::string_view value) { std::string lower = std::string(absl::AsciiStrToLower(value)); - if (lower == "queued") - return TestRunStatus::kQueued; - if (lower == "running") - return TestRunStatus::kRunning; - if (lower == "passed") - return TestRunStatus::kPassed; - if (lower == "failed") - return TestRunStatus::kFailed; - if (lower == "timeout") - return TestRunStatus::kTimeout; - if (lower == "unknown") - return TestRunStatus::kUnknown; + if (lower == "queued") return TestRunStatus::kQueued; + if (lower == "running") return TestRunStatus::kRunning; + if (lower == "passed") return TestRunStatus::kPassed; + if (lower == "failed") return TestRunStatus::kFailed; + if (lower == "timeout") return TestRunStatus::kTimeout; + if (lower == "unknown") return TestRunStatus::kUnknown; return std::nullopt; } diff --git a/src/cli/handlers/agent/conversation_test.cc b/src/cli/handlers/agent/conversation_test.cc index b20b91a7..06fd8b5a 100644 --- a/src/cli/handlers/agent/conversation_test.cc +++ b/src/cli/handlers/agent/conversation_test.cc @@ -1,18 +1,17 @@ -#include "app/rom.h" -#include "cli/handlers/rom/mock_rom.h" -#include "core/project.h" - #include #include #include #include + #include "absl/flags/declare.h" #include "absl/flags/flag.h" - #include "absl/status/status.h" #include "absl/strings/str_cat.h" +#include "app/rom.h" #include "cli/handlers/agent/common.h" +#include "cli/handlers/rom/mock_rom.h" #include "cli/service/agent/conversational_agent_service.h" +#include "core/project.h" #include "nlohmann/json.hpp" ABSL_DECLARE_FLAG(std::string, rom); diff --git a/src/cli/handlers/agent/simple_chat_command.cc b/src/cli/handlers/agent/simple_chat_command.cc index 4c51ba3a..b5f54967 100644 --- a/src/cli/handlers/agent/simple_chat_command.cc +++ b/src/cli/handlers/agent/simple_chat_command.cc @@ -26,8 +26,7 @@ absl::Status SimpleChatCommandHandler::Execute( // Determine desired output format std::optional format_arg = parser.GetString("format"); - if (parser.HasFlag("json")) - format_arg = "json"; + if (parser.HasFlag("json")) format_arg = "json"; if (parser.HasFlag("markdown") || parser.HasFlag("md")) format_arg = "markdown"; if (parser.HasFlag("compact") || parser.HasFlag("raw")) @@ -36,8 +35,7 @@ absl::Status SimpleChatCommandHandler::Execute( auto select_format = [](absl::string_view value) -> std::optional { std::string normalized = absl::AsciiStrToLower(value); - if (normalized == "json") - return agent::AgentOutputFormat::kJson; + if (normalized == "json") return agent::AgentOutputFormat::kJson; if (normalized == "markdown" || normalized == "md") return agent::AgentOutputFormat::kMarkdown; if (normalized == "compact" || normalized == "raw") diff --git a/src/cli/handlers/agent/todo_commands.h b/src/cli/handlers/agent/todo_commands.h index 26542fcc..490164ca 100644 --- a/src/cli/handlers/agent/todo_commands.h +++ b/src/cli/handlers/agent/todo_commands.h @@ -12,7 +12,7 @@ namespace handlers { /** * @brief Handle z3ed agent todo commands - * + * * Commands: * agent todo create [--category=] [--priority=] * agent todo list [--status=] [--category=] diff --git a/src/cli/handlers/command_handlers.cc b/src/cli/handlers/command_handlers.cc index 905b8fb3..289a5b0e 100644 --- a/src/cli/handlers/command_handlers.cc +++ b/src/cli/handlers/command_handlers.cc @@ -5,6 +5,8 @@ #ifdef YAZE_WITH_GRPC #include "cli/handlers/tools/emulator_commands.h" #endif +#include + #include "cli/handlers/game/dialogue_commands.h" #include "cli/handlers/game/dungeon_commands.h" #include "cli/handlers/game/message_commands.h" @@ -14,8 +16,6 @@ #include "cli/handlers/graphics/palette_commands.h" #include "cli/handlers/graphics/sprite_commands.h" -#include - namespace yaze { namespace cli { namespace handlers { diff --git a/src/cli/handlers/command_handlers.h b/src/cli/handlers/command_handlers.h index b766b14f..c47305cb 100644 --- a/src/cli/handlers/command_handlers.h +++ b/src/cli/handlers/command_handlers.h @@ -5,9 +5,8 @@ #include #include -#include "cli/service/resources/command_handler.h" - #include "cli/handlers/agent/simple_chat_command.h" +#include "cli/service/resources/command_handler.h" namespace yaze { namespace cli { @@ -75,7 +74,7 @@ class EmulatorGetMetricsCommandHandler; /** * @brief Factory function to create all CLI-level command handlers - * + * * @return Vector of unique pointers to command handler instances */ std::vector> @@ -83,7 +82,7 @@ CreateCliCommandHandlers(); /** * @brief Factory function to create all agent-specific command handlers - * + * * @return Vector of unique pointers to command handler instances */ std::vector> @@ -91,7 +90,7 @@ CreateAgentCommandHandlers(); /** * @brief Factory function to create all command handlers (CLI + agent) - * + * * @return Vector of unique pointers to command handler instances */ std::vector> diff --git a/src/cli/handlers/game/message.cc b/src/cli/handlers/game/message.cc index 01f07f02..8ed51156 100644 --- a/src/cli/handlers/game/message.cc +++ b/src/cli/handlers/game/message.cc @@ -132,8 +132,7 @@ absl::Status HandleMessageListCommand(const std::vector& arg_vec, bool first = true; for (int i = start_id; i <= end_id; ++i) { const auto& msg = messages[i]; - if (!first) - std::cout << ",\n"; + if (!first) std::cout << ",\n"; std::cout << " {\n"; std::cout << absl::StrFormat(" \"id\": %d,\n", msg.ID); std::cout << absl::StrFormat(" \"address\": \"0x%06X\",\n", @@ -317,8 +316,7 @@ absl::Status HandleMessageSearchCommand(const std::vector& arg_vec, for (size_t i = 0; i < matches.size(); ++i) { const auto& msg = messages[matches[i]]; - if (i > 0) - std::cout << ",\n"; + if (i > 0) std::cout << ",\n"; std::string escaped_text = msg.ContentsParsed; size_t pos = 0; diff --git a/src/cli/handlers/game/message.h b/src/cli/handlers/game/message.h index 1d50b450..e67d4233 100644 --- a/src/cli/handlers/game/message.h +++ b/src/cli/handlers/game/message.h @@ -16,7 +16,8 @@ namespace message { /** * @brief List all messages in the ROM - * @param arg_vec Command arguments: [--format ] [--range ] + * @param arg_vec Command arguments: [--format ] [--range + * ] * @param rom_context Optional ROM context to avoid reloading */ absl::Status HandleMessageListCommand(const std::vector& arg_vec, diff --git a/src/cli/handlers/game/overworld.cc b/src/cli/handlers/game/overworld.cc index fbfb25ac..365b8a3d 100644 --- a/src/cli/handlers/game/overworld.cc +++ b/src/cli/handlers/game/overworld.cc @@ -1,6 +1,4 @@ #include "zelda3/overworld/overworld.h" -#include "cli/cli.h" -#include "cli/handlers/game/overworld_inspect.h" #include #include @@ -20,6 +18,8 @@ #include "absl/strings/str_cat.h" #include "absl/strings/str_format.h" #include "absl/strings/str_join.h" +#include "cli/cli.h" +#include "cli/handlers/game/overworld_inspect.h" ABSL_DECLARE_FLAG(std::string, rom); @@ -817,7 +817,8 @@ absl::Status HandleOverworldSetZoomLegacy( return absl::OkStatus(); } -// Legacy OverworldGetVisibleRegion class removed - using new CommandHandler system +// Legacy OverworldGetVisibleRegion class removed - using new CommandHandler +// system // TODO: Implement OverworldGetVisibleRegionCommandHandler absl::Status HandleOverworldGetVisibleRegionLegacy( const std::vector& arg_vec) { diff --git a/src/cli/handlers/game/overworld_inspect.cc b/src/cli/handlers/game/overworld_inspect.cc index 66b11237..0fb8dde7 100644 --- a/src/cli/handlers/game/overworld_inspect.cc +++ b/src/cli/handlers/game/overworld_inspect.cc @@ -463,7 +463,6 @@ absl::StatusOr GetEntranceDetails( absl::StatusOr AnalyzeTileUsage( zelda3::Overworld& overworld, uint16_t tile_id, const TileSearchOptions& options) { - // Use FindTileMatches to get all occurrences ASSIGN_OR_RETURN(auto matches, FindTileMatches(overworld, tile_id, options)); diff --git a/src/cli/handlers/graphics/hex_commands.cc b/src/cli/handlers/graphics/hex_commands.cc index 24e8c63f..0fb2ab60 100644 --- a/src/cli/handlers/graphics/hex_commands.cc +++ b/src/cli/handlers/graphics/hex_commands.cc @@ -1,6 +1,7 @@ #include "cli/handlers/graphics/hex_commands.h" #include + #include "absl/strings/str_format.h" #include "absl/strings/str_split.h" @@ -46,8 +47,7 @@ absl::Status HexReadCommandHandler::Execute( std::string hex_data; for (int i = 0; i < length; ++i) { absl::StrAppendFormat(&hex_data, "%02X", data[i]); - if (i < length - 1) - hex_data += " "; + if (i < length - 1) hex_data += " "; } formatter.AddField("hex_data", hex_data); @@ -87,8 +87,7 @@ absl::Status HexWriteCommandHandler::Execute( std::vector bytes; for (const auto& byte_str : byte_strs) { - if (byte_str.empty()) - continue; + if (byte_str.empty()) continue; try { uint8_t value = static_cast(std::stoul(byte_str, nullptr, 16)); bytes.push_back(value); @@ -114,8 +113,7 @@ absl::Status HexWriteCommandHandler::Execute( std::string hex_data; for (size_t i = 0; i < bytes.size(); ++i) { absl::StrAppendFormat(&hex_data, "%02X", bytes[i]); - if (i < bytes.size() - 1) - hex_data += " "; + if (i < bytes.size() - 1) hex_data += " "; } formatter.BeginObject("Hex Write"); @@ -150,8 +148,7 @@ absl::Status HexSearchCommandHandler::Execute( std::vector> pattern; // (value, is_wildcard) for (const auto& byte_str : byte_strs) { - if (byte_str.empty()) - continue; + if (byte_str.empty()) continue; if (byte_str == "??" || byte_str == "**") { pattern.push_back({0, true}); // Wildcard } else { diff --git a/src/cli/handlers/graphics/palette.cc b/src/cli/handlers/graphics/palette.cc index 609c4072..f02c4b4a 100644 --- a/src/cli/handlers/graphics/palette.cc +++ b/src/cli/handlers/graphics/palette.cc @@ -1,10 +1,9 @@ -#include "cli/cli.h" -#include "cli/tui/palette_editor.h" - #include "absl/flags/declare.h" #include "absl/flags/flag.h" #include "app/gfx/types/snes_palette.h" #include "app/gfx/util/scad_format.h" +#include "cli/cli.h" +#include "cli/tui/palette_editor.h" ABSL_DECLARE_FLAG(std::string, rom); diff --git a/src/cli/handlers/graphics/sprite_commands.cc b/src/cli/handlers/graphics/sprite_commands.cc index 8bd4fa91..160a5604 100644 --- a/src/cli/handlers/graphics/sprite_commands.cc +++ b/src/cli/handlers/graphics/sprite_commands.cc @@ -11,7 +11,6 @@ namespace handlers { absl::Status SpriteListCommandHandler::Execute( Rom* /*rom*/, const resources::ArgumentParser& parser, resources::OutputFormatter& formatter) { - auto limit = parser.GetInt("limit").value_or(256); auto type = parser.GetString("type").value_or("all"); @@ -38,7 +37,6 @@ absl::Status SpriteListCommandHandler::Execute( absl::Status SpritePropertiesCommandHandler::Execute( Rom* /*rom*/, const resources::ArgumentParser& parser, resources::OutputFormatter& formatter) { - auto id_str = parser.GetString("id").value(); int sprite_id; @@ -79,7 +77,6 @@ absl::Status SpritePropertiesCommandHandler::Execute( absl::Status SpritePaletteCommandHandler::Execute( Rom* /*rom*/, const resources::ArgumentParser& parser, resources::OutputFormatter& formatter) { - auto id_str = parser.GetString("id").value(); int sprite_id; diff --git a/src/cli/handlers/rom/mock_rom.cc b/src/cli/handlers/rom/mock_rom.cc index 1ea9836b..fa513e6f 100644 --- a/src/cli/handlers/rom/mock_rom.cc +++ b/src/cli/handlers/rom/mock_rom.cc @@ -76,9 +76,7 @@ absl::Status InitializeMockRom(Rom& rom) { return absl::OkStatus(); } -bool ShouldUseMockRom() { - return absl::GetFlag(FLAGS_mock_rom); -} +bool ShouldUseMockRom() { return absl::GetFlag(FLAGS_mock_rom); } } // namespace cli } // namespace yaze diff --git a/src/cli/handlers/rom/mock_rom.h b/src/cli/handlers/rom/mock_rom.h index 7c29756c..4eadcf43 100644 --- a/src/cli/handlers/rom/mock_rom.h +++ b/src/cli/handlers/rom/mock_rom.h @@ -9,14 +9,14 @@ namespace cli { /** * @brief Initialize a mock ROM for testing without requiring an actual ROM file - * + * * This creates a minimal but valid ROM structure populated with: * - All Zelda3 embedded labels (rooms, sprites, entrances, items, etc.) * - Minimal header data to satisfy ROM validation * - Empty but properly sized data sections - * + * * Purpose: Allow AI agent testing and CI/CD without committing ROM files - * + * * @param rom ROM object to initialize as mock * @return absl::OkStatus() on success, error status on failure */ diff --git a/src/cli/handlers/rom/project_commands.cc b/src/cli/handlers/rom/project_commands.cc index 0a2dcde8..45061e40 100644 --- a/src/cli/handlers/rom/project_commands.cc +++ b/src/cli/handlers/rom/project_commands.cc @@ -2,6 +2,7 @@ #include #include + #include "core/project.h" #include "util/bps.h" #include "util/file_util.h" diff --git a/src/cli/handlers/rom/rom_commands.cc b/src/cli/handlers/rom/rom_commands.cc index 5e1db6df..d463a47e 100644 --- a/src/cli/handlers/rom/rom_commands.cc +++ b/src/cli/handlers/rom/rom_commands.cc @@ -1,6 +1,7 @@ #include "cli/handlers/rom/rom_commands.h" #include + #include "absl/strings/str_format.h" #include "util/macro.h" @@ -52,8 +53,7 @@ absl::Status RomValidateCommandHandler::Execute( formatter.AddField("validation_passed", all_ok); std::string results_str; for (const auto& result : validation_results) { - if (!results_str.empty()) - results_str += "; "; + if (!results_str.empty()) results_str += "; "; results_str += result; } formatter.AddField("results", results_str); @@ -115,8 +115,7 @@ absl::Status RomDiffCommandHandler::Execute( if (!diff_details.empty()) { std::string diff_str; for (const auto& diff : diff_details) { - if (!diff_str.empty()) - diff_str += "; "; + if (!diff_str.empty()) diff_str += "; "; diff_str += diff; } formatter.AddField("differences", diff_str); diff --git a/src/cli/handlers/tools/emulator_commands.cc b/src/cli/handlers/tools/emulator_commands.cc index 5444b027..ab991d28 100644 --- a/src/cli/handlers/tools/emulator_commands.cc +++ b/src/cli/handlers/tools/emulator_commands.cc @@ -1,6 +1,7 @@ #include "cli/handlers/tools/emulator_commands.h" #include + #include "absl/status/statusor.h" #include "absl/strings/escaping.h" #include "absl/strings/str_split.h" @@ -28,7 +29,6 @@ class EmulatorClient { grpc::Status (agent::EmulatorService::Stub::*rpc_method)( grpc::ClientContext*, const TRequest&, TResponse*), const TRequest& request) { - TResponse response; grpc::ClientContext context; @@ -51,30 +51,18 @@ class EmulatorClient { // Helper to parse button from string absl::StatusOr StringToButton(absl::string_view s) { - if (s == "A") - return agent::Button::A; - if (s == "B") - return agent::Button::B; - if (s == "X") - return agent::Button::X; - if (s == "Y") - return agent::Button::Y; - if (s == "L") - return agent::Button::L; - if (s == "R") - return agent::Button::R; - if (s == "SELECT") - return agent::Button::SELECT; - if (s == "START") - return agent::Button::START; - if (s == "UP") - return agent::Button::UP; - if (s == "DOWN") - return agent::Button::DOWN; - if (s == "LEFT") - return agent::Button::LEFT; - if (s == "RIGHT") - return agent::Button::RIGHT; + if (s == "A") return agent::Button::A; + if (s == "B") return agent::Button::B; + if (s == "X") return agent::Button::X; + if (s == "Y") return agent::Button::Y; + if (s == "L") return agent::Button::L; + if (s == "R") return agent::Button::R; + if (s == "SELECT") return agent::Button::SELECT; + if (s == "START") return agent::Button::START; + if (s == "UP") return agent::Button::UP; + if (s == "DOWN") return agent::Button::DOWN; + if (s == "LEFT") return agent::Button::LEFT; + if (s == "RIGHT") return agent::Button::RIGHT; return absl::InvalidArgumentError(absl::StrCat("Unknown button: ", s)); } @@ -198,8 +186,7 @@ absl::Status EmulatorPressButtonsCommandHandler::Execute( absl::StrSplit(parser.GetString("buttons").value(), ','); for (const auto& btn_str : buttons) { auto button_or = StringToButton(btn_str); - if (!button_or.ok()) - return button_or.status(); + if (!button_or.ok()) return button_or.status(); request.add_buttons(button_or.value()); } @@ -226,8 +213,7 @@ absl::Status EmulatorReleaseButtonsCommandHandler::Execute( absl::StrSplit(parser.GetString("buttons").value(), ','); for (const auto& btn_str : buttons) { auto button_or = StringToButton(btn_str); - if (!button_or.ok()) - return button_or.status(); + if (!button_or.ok()) return button_or.status(); request.add_buttons(button_or.value()); } @@ -254,8 +240,7 @@ absl::Status EmulatorHoldButtonsCommandHandler::Execute( absl::StrSplit(parser.GetString("buttons").value(), ','); for (const auto& btn_str : buttons) { auto button_or = StringToButton(btn_str); - if (!button_or.ok()) - return button_or.status(); + if (!button_or.ok()) return button_or.status(); request.add_buttons(button_or.value()); } request.set_duration_ms(parser.GetInt("duration").value()); diff --git a/src/cli/handlers/tools/resource_commands.cc b/src/cli/handlers/tools/resource_commands.cc index 7ec961d9..1b7db948 100644 --- a/src/cli/handlers/tools/resource_commands.cc +++ b/src/cli/handlers/tools/resource_commands.cc @@ -52,8 +52,7 @@ absl::Status ResourceSearchCommandHandler::Execute( for (const auto& category : categories) { auto labels_or = builder.GetLabels(category); - if (!labels_or.ok()) - continue; + if (!labels_or.ok()) continue; auto labels = labels_or.value(); for (const auto& [key, value] : labels) { diff --git a/src/cli/service/agent/advanced_routing.cc b/src/cli/service/agent/advanced_routing.cc index 6392b647..dd2e3c85 100644 --- a/src/cli/service/agent/advanced_routing.cc +++ b/src/cli/service/agent/advanced_routing.cc @@ -3,6 +3,7 @@ #include #include #include + #include "absl/strings/str_format.h" #include "absl/strings/str_join.h" @@ -13,7 +14,6 @@ namespace agent { AdvancedRouter::RoutedResponse AdvancedRouter::RouteHexAnalysis( const std::vector& data, uint32_t address, const RouteContext& ctx) { - RoutedResponse response; // Infer data type @@ -67,7 +67,6 @@ AdvancedRouter::RoutedResponse AdvancedRouter::RouteHexAnalysis( AdvancedRouter::RoutedResponse AdvancedRouter::RouteMapEdit( const std::string& edit_intent, const RouteContext& ctx) { - RoutedResponse response; // Parse intent and generate action sequence @@ -93,7 +92,6 @@ AdvancedRouter::RoutedResponse AdvancedRouter::RouteMapEdit( AdvancedRouter::RoutedResponse AdvancedRouter::RoutePaletteAnalysis( const std::vector& colors, const RouteContext& ctx) { - RoutedResponse response; // Analyze color relationships @@ -131,7 +129,6 @@ AdvancedRouter::RoutedResponse AdvancedRouter::RoutePaletteAnalysis( AdvancedRouter::RoutedResponse AdvancedRouter::SynthesizeMultiToolResponse( const std::vector& tool_results, const RouteContext& ctx) { - RoutedResponse response; // Combine results intelligently @@ -158,14 +155,10 @@ std::string AdvancedRouter::GenerateGUIScript( } std::string AdvancedRouter::InferDataType(const std::vector& data) { - if (data.size() == 8) - return "tile16 data"; - if (data.size() % 3 == 0 && data.size() <= 48) - return "sprite data"; - if (data.size() == 32) - return "palette data (16 colors)"; - if (data.size() > 1000) - return "compressed data block"; + if (data.size() == 8) return "tile16 data"; + if (data.size() % 3 == 0 && data.size() <= 48) return "sprite data"; + if (data.size() == 32) return "palette data (16 colors)"; + if (data.size() > 1000) return "compressed data block"; return "unknown data"; } @@ -191,15 +184,11 @@ std::vector AdvancedRouter::ExtractPatterns( if (data.size() > 3) { bool ascending = true, descending = true; for (size_t i = 1; i < data.size(); ++i) { - if (data[i] != data[i - 1] + 1) - ascending = false; - if (data[i] != data[i - 1] - 1) - descending = false; + if (data[i] != data[i - 1] + 1) ascending = false; + if (data[i] != data[i - 1] - 1) descending = false; } - if (ascending) - patterns.push_back("Ascending sequence"); - if (descending) - patterns.push_back("Descending sequence"); + if (ascending) patterns.push_back("Ascending sequence"); + if (descending) patterns.push_back("Descending sequence"); } return patterns; diff --git a/src/cli/service/agent/advanced_routing.h b/src/cli/service/agent/advanced_routing.h index 0746468e..4097c6e4 100644 --- a/src/cli/service/agent/advanced_routing.h +++ b/src/cli/service/agent/advanced_routing.h @@ -4,6 +4,7 @@ #include #include #include + #include "absl/status/statusor.h" namespace yaze { @@ -14,7 +15,7 @@ namespace agent { /** * @brief Advanced routing system for agent tool responses - * + * * Optimizes information flow back to agent for: * - Map editing with GUI automation * - Hex data analysis and pattern recognition diff --git a/src/cli/service/agent/agent_control_server.cc b/src/cli/service/agent/agent_control_server.cc index 4e9467dd..8a289e1c 100644 --- a/src/cli/service/agent/agent_control_server.cc +++ b/src/cli/service/agent/agent_control_server.cc @@ -1,7 +1,10 @@ #include "cli/service/agent/agent_control_server.h" + #include #include + #include + #include "cli/service/agent/emulator_service_impl.h" namespace yaze::agent { @@ -9,9 +12,7 @@ namespace yaze::agent { AgentControlServer::AgentControlServer(yaze::emu::Emulator* emulator) : emulator_(emulator) {} -AgentControlServer::~AgentControlServer() { - Stop(); -} +AgentControlServer::~AgentControlServer() { Stop(); } void AgentControlServer::Start() { server_thread_ = std::thread(&AgentControlServer::Run, this); diff --git a/src/cli/service/agent/agent_pretraining.cc b/src/cli/service/agent/agent_pretraining.cc index de463b36..397c27a9 100644 --- a/src/cli/service/agent/agent_pretraining.cc +++ b/src/cli/service/agent/agent_pretraining.cc @@ -175,7 +175,8 @@ std::string AgentPretraining::GeneratePretrainingPrompt(Rom* rom) { if (rom && rom->is_loaded()) { prompt += absl::StrFormat("## Current ROM: %s\n", rom->title()); prompt += absl::StrFormat("Size: %zu bytes\n", rom->size()); - // prompt += absl::StrFormat("Type: %s\n\n", rom->is_expanded() ? "Expanded" : "Vanilla"); + // prompt += absl::StrFormat("Type: %s\n\n", rom->is_expanded() ? "Expanded" + // : "Vanilla"); } for (const auto& module : GetModules()) { diff --git a/src/cli/service/agent/agent_pretraining.h b/src/cli/service/agent/agent_pretraining.h index 71ab09c2..8be03757 100644 --- a/src/cli/service/agent/agent_pretraining.h +++ b/src/cli/service/agent/agent_pretraining.h @@ -3,6 +3,7 @@ #include #include + #include "absl/status/status.h" namespace yaze { @@ -13,7 +14,7 @@ namespace agent { /** * @brief Pre-training system for AI agents - * + * * Provides structured knowledge injection before interactive use. * Teaches agent about ROM structure, common patterns, and tool usage. */ diff --git a/src/cli/service/agent/conversational_agent_service.cc b/src/cli/service/agent/conversational_agent_service.cc index 2e2a39c0..ec1644c6 100644 --- a/src/cli/service/agent/conversational_agent_service.cc +++ b/src/cli/service/agent/conversational_agent_service.cc @@ -348,7 +348,8 @@ absl::StatusOr ConversationalAgentService::SendMessage( } if (!agent_response.tool_calls.empty()) { - // Check if we were waiting for a text response but got more tool calls instead + // Check if we were waiting for a text response but got more tool calls + // instead if (waiting_for_text_response) { util::PrintWarning( absl::StrCat("LLM called tools again instead of providing final " @@ -386,8 +387,7 @@ absl::StatusOr ConversationalAgentService::SendMessage( << std::endl; std::string preview = tool_output.substr( 0, std::min(size_t(200), tool_output.size())); - if (tool_output.size() > 200) - preview += "..."; + if (tool_output.size() > 200) preview += "..."; std::cout << util::colors::kDim << preview << util::colors::kReset << std::endl; } diff --git a/src/cli/service/agent/conversational_agent_service.h b/src/cli/service/agent/conversational_agent_service.h index 88408bce..d7aacdd6 100644 --- a/src/cli/service/agent/conversational_agent_service.h +++ b/src/cli/service/agent/conversational_agent_service.h @@ -51,8 +51,8 @@ struct ChatMessage { absl::Time timestamp; std::optional json_pretty; std::optional table_data; - bool is_internal = - false; // True for tool results and other messages not meant for user display + bool is_internal = false; // True for tool results and other messages not + // meant for user display std::vector warnings; struct ModelMetadata { std::string provider; diff --git a/src/cli/service/agent/emulator_service_impl.cc b/src/cli/service/agent/emulator_service_impl.cc index 32cb4384..82576012 100644 --- a/src/cli/service/agent/emulator_service_impl.cc +++ b/src/cli/service/agent/emulator_service_impl.cc @@ -1,6 +1,8 @@ #include "cli/service/agent/emulator_service_impl.h" + #include #include + #include "absl/strings/escaping.h" #include "absl/strings/str_format.h" #include "app/emu/debug/breakpoint_manager.h" @@ -471,7 +473,8 @@ grpc::Status EmulatorServiceImpl::RunToBreakpoint( "SNES is not initialized."); } - // Run emulator until breakpoint is hit (max 1 million instructions to prevent hangs) + // Run emulator until breakpoint is hit (max 1 million instructions to prevent + // hangs) const int kMaxInstructions = 1000000; int instruction_count = 0; @@ -571,7 +574,8 @@ grpc::Status EmulatorServiceImpl::GetDisassembly( // Read opcode and disassemble uint8_t opcode = memory.ReadByte(current_address); - // Basic disassembly (simplified - real implementation would use CPU's disassembler) + // Basic disassembly (simplified - real implementation would use CPU's + // disassembler) auto* line = response->add_lines(); line->set_address(current_address); line->set_opcode(opcode); @@ -659,8 +663,7 @@ grpc::Status EmulatorServiceImpl::GetDebugStatus( auto breakpoints = emulator_->breakpoint_manager().GetAllBreakpoints(); uint32_t active_bp_count = 0; for (const auto& bp : breakpoints) { - if (bp.enabled) - active_bp_count++; + if (bp.enabled) active_bp_count++; } response->set_active_breakpoints(active_bp_count); response->set_active_watchpoints( diff --git a/src/cli/service/agent/emulator_service_impl.h b/src/cli/service/agent/emulator_service_impl.h index b90c7f81..863cdcb6 100644 --- a/src/cli/service/agent/emulator_service_impl.h +++ b/src/cli/service/agent/emulator_service_impl.h @@ -1,6 +1,7 @@ #pragma once #include + #include "protos/emulator_service.grpc.pb.h" // Forward declaration to avoid circular dependencies diff --git a/src/cli/service/agent/enhanced_tui.cc b/src/cli/service/agent/enhanced_tui.cc index fa6e5417..be355e34 100644 --- a/src/cli/service/agent/enhanced_tui.cc +++ b/src/cli/service/agent/enhanced_tui.cc @@ -116,9 +116,7 @@ int ReadChar() { } // Check if a key is a special key -bool IsSpecialKey(int key) { - return key >= 1000; -} +bool IsSpecialKey(int key) { return key >= 1000; } } // namespace @@ -144,9 +142,7 @@ EnhancedTUI::EnhancedTUI(const TUIConfig& config) : config_(config) { LoadTheme(config_.theme); } -EnhancedTUI::~EnhancedTUI() { - Shutdown(); -} +EnhancedTUI::~EnhancedTUI() { Shutdown(); } absl::Status EnhancedTUI::Initialize() { if (terminal_initialized_) { @@ -175,9 +171,7 @@ void EnhancedTUI::Shutdown() { terminal_initialized_ = false; } -void EnhancedTUI::SetRomContext(Rom* rom) { - rom_context_ = rom; -} +void EnhancedTUI::SetRomContext(Rom* rom) { rom_context_ = rom; } absl::Status EnhancedTUI::Run() { RETURN_IF_ERROR(Initialize()); diff --git a/src/cli/service/agent/enhanced_tui.h b/src/cli/service/agent/enhanced_tui.h index c75b7a71..538dff08 100644 --- a/src/cli/service/agent/enhanced_tui.h +++ b/src/cli/service/agent/enhanced_tui.h @@ -82,7 +82,7 @@ struct TUIConfig { /** * @class EnhancedTUI * @brief Enhanced Terminal User Interface for z3ed CLI - * + * * Provides a modern, feature-rich TUI with: * - Multi-panel layout with resizable components * - Syntax highlighting for code and JSON @@ -227,7 +227,7 @@ class EnhancedTUI { /** * @class TUICommandHandler * @brief Base class for TUI-integrated command handlers - * + * * Extends CommandHandler with TUI-specific features: * - Rich output formatting * - Progress indicators diff --git a/src/cli/service/agent/learned_knowledge_service.cc b/src/cli/service/agent/learned_knowledge_service.cc index 662d1f94..25755aad 100644 --- a/src/cli/service/agent/learned_knowledge_service.cc +++ b/src/cli/service/agent/learned_knowledge_service.cc @@ -10,9 +10,8 @@ #include "absl/strings/str_format.h" #include "absl/time/clock.h" #include "absl/time/time.h" -#include "util/platform_paths.h" - #include "nlohmann/json.hpp" +#include "util/platform_paths.h" namespace yaze { namespace cli { @@ -20,9 +19,7 @@ namespace agent { namespace { -int64_t CurrentTimestamp() { - return absl::ToUnixMillis(absl::Now()); -} +int64_t CurrentTimestamp() { return absl::ToUnixMillis(absl::Now()); } std::string GenerateRandomID() { static int counter = 0; @@ -83,20 +80,16 @@ absl::Status LearnedKnowledgeService::Initialize() { absl::Status LearnedKnowledgeService::SaveAll() { auto status = SavePreferences(); - if (!status.ok()) - return status; + if (!status.ok()) return status; status = SavePatterns(); - if (!status.ok()) - return status; + if (!status.ok()) return status; status = SaveProjects(); - if (!status.ok()) - return status; + if (!status.ok()) return status; status = SaveMemories(); - if (!status.ok()) - return status; + if (!status.ok()) return status; return absl::OkStatus(); } diff --git a/src/cli/service/agent/learned_knowledge_service.h b/src/cli/service/agent/learned_knowledge_service.h index 77e86da4..99246f73 100644 --- a/src/cli/service/agent/learned_knowledge_service.h +++ b/src/cli/service/agent/learned_knowledge_service.h @@ -20,7 +20,7 @@ namespace agent { /** * @class LearnedKnowledgeService * @brief Manages persistent learned information across agent sessions - * + * * Stores: * - User preferences (default palettes, favorite tools, etc.) * - ROM patterns (frequently accessed rooms, sprite placements, etc.) @@ -77,7 +77,8 @@ class LearnedKnowledgeService { /** * Learn a pattern from the current ROM - * @param type Pattern type (e.g., "sprite_distribution", "room_access_frequency") + * @param type Pattern type (e.g., "sprite_distribution", + * "room_access_frequency") * @param rom_hash SHA256 hash of the ROM * @param data Pattern-specific data (JSON) */ diff --git a/src/cli/service/agent/prompt_manager.cc b/src/cli/service/agent/prompt_manager.cc index 6b4d571f..b73b4ee9 100644 --- a/src/cli/service/agent/prompt_manager.cc +++ b/src/cli/service/agent/prompt_manager.cc @@ -1,6 +1,8 @@ #include "cli/service/agent/prompt_manager.h" + #include #include + #include "util/file_util.h" namespace yaze { @@ -10,8 +12,7 @@ namespace agent { std::string PromptManager::LoadPrompt(PromptMode mode) { std::string path = GetPromptPath(mode); std::ifstream file(path); - if (!file) - return ""; + if (!file) return ""; std::ostringstream ss; ss << file.rdbuf(); diff --git a/src/cli/service/agent/simple_chat_session.cc b/src/cli/service/agent/simple_chat_session.cc index 48a526d7..f3176019 100644 --- a/src/cli/service/agent/simple_chat_session.cc +++ b/src/cli/service/agent/simple_chat_session.cc @@ -202,8 +202,7 @@ std::string SessionMetricsToJson(const ChatMessage::SessionMetrics& metrics) { } // namespace void SimpleChatSession::PrintTable(const ChatMessage::TableData& table) { - if (table.headers.empty()) - return; + if (table.headers.empty()) return; // Calculate column widths std::vector col_widths(table.headers.size(), 0); @@ -369,10 +368,8 @@ absl::Status SimpleChatSession::RunInteractive() { } } - if (input.empty()) - continue; - if (input == "quit" || input == "exit") - break; + if (input.empty()) continue; + if (input == "quit" || input == "exit") break; if (input == "reset") { Reset(); @@ -460,8 +457,7 @@ absl::Status SimpleChatSession::RunBatch(const std::string& input_file) { ++line_num; // Skip empty lines and comments - if (line.empty() || line[0] == '#') - continue; + if (line.empty() || line[0] == '#') continue; if (config_.output_format == AgentOutputFormat::kFriendly) { std::cout << "Input [" << line_num << "]: " << line << "\n"; diff --git a/src/cli/service/agent/simple_chat_session.h b/src/cli/service/agent/simple_chat_session.h index c22080e9..762e9c4c 100644 --- a/src/cli/service/agent/simple_chat_session.h +++ b/src/cli/service/agent/simple_chat_session.h @@ -19,10 +19,10 @@ namespace agent { /** * @class SimpleChatSession * @brief Simple text-based chat session for AI agent interaction - * + * * Provides a basic REPL-style interface without FTXUI dependencies, * suitable for automated testing and AI agent interactions. - * + * * Supports multiple input modes: * - Interactive REPL (default when stdin is a TTY) * - Piped input (reads lines from stdin) diff --git a/src/cli/service/agent/todo_manager.cc b/src/cli/service/agent/todo_manager.cc index 634e16b2..0c8056d1 100644 --- a/src/cli/service/agent/todo_manager.cc +++ b/src/cli/service/agent/todo_manager.cc @@ -48,16 +48,11 @@ std::string TodoItem::StatusToString() const { } TodoItem::Status TodoItem::StringToStatus(const std::string& str) { - if (str == "pending") - return Status::PENDING; - if (str == "in_progress") - return Status::IN_PROGRESS; - if (str == "completed") - return Status::COMPLETED; - if (str == "blocked") - return Status::BLOCKED; - if (str == "cancelled") - return Status::CANCELLED; + if (str == "pending") return Status::PENDING; + if (str == "in_progress") return Status::IN_PROGRESS; + if (str == "completed") return Status::COMPLETED; + if (str == "blocked") return Status::BLOCKED; + if (str == "cancelled") return Status::CANCELLED; return Status::PENDING; } @@ -93,9 +88,7 @@ std::string TodoManager::GenerateId() { return absl::StrFormat("todo_%d", next_id_++); } -std::string TodoManager::GetTimestamp() const { - return CurrentTimestamp(); -} +std::string TodoManager::GetTimestamp() const { return CurrentTimestamp(); } absl::StatusOr TodoManager::CreateTodo(const std::string& description, const std::string& category, @@ -166,9 +159,7 @@ absl::StatusOr TodoManager::GetTodo(const std::string& id) const { return *it; } -std::vector TodoManager::GetAllTodos() const { - return todos_; -} +std::vector TodoManager::GetAllTodos() const { return todos_; } std::vector TodoManager::GetTodosByStatus( TodoItem::Status status) const { diff --git a/src/cli/service/agent/todo_manager.h b/src/cli/service/agent/todo_manager.h index 48376c69..d99dc05a 100644 --- a/src/cli/service/agent/todo_manager.h +++ b/src/cli/service/agent/todo_manager.h @@ -43,7 +43,7 @@ struct TodoItem { /** * @class TodoManager * @brief Manages TODO lists for z3ed agent task execution - * + * * Enables the AI agent to: * - Create and track TODO lists for complex tasks * - Break down goals into executable steps diff --git a/src/cli/service/agent/tool_dispatcher.cc b/src/cli/service/agent/tool_dispatcher.cc index d0945b71..bb53f9b9 100644 --- a/src/cli/service/agent/tool_dispatcher.cc +++ b/src/cli/service/agent/tool_dispatcher.cc @@ -30,10 +30,8 @@ namespace { // Map tool name to handler type ToolCallType GetToolCallType(const std::string& tool_name) { // Resource commands - if (tool_name == "resource-list") - return ToolCallType::kResourceList; - if (tool_name == "resource-search") - return ToolCallType::kResourceSearch; + if (tool_name == "resource-list") return ToolCallType::kResourceList; + if (tool_name == "resource-search") return ToolCallType::kResourceSearch; // Dungeon commands if (tool_name == "dungeon-list-sprites") @@ -64,56 +62,35 @@ ToolCallType GetToolCallType(const std::string& tool_name) { return ToolCallType::kOverworldTileStats; // Message & Dialogue commands - if (tool_name == "message-list") - return ToolCallType::kMessageList; - if (tool_name == "message-read") - return ToolCallType::kMessageRead; - if (tool_name == "message-search") - return ToolCallType::kMessageSearch; - if (tool_name == "dialogue-list") - return ToolCallType::kDialogueList; - if (tool_name == "dialogue-read") - return ToolCallType::kDialogueRead; - if (tool_name == "dialogue-search") - return ToolCallType::kDialogueSearch; + if (tool_name == "message-list") return ToolCallType::kMessageList; + if (tool_name == "message-read") return ToolCallType::kMessageRead; + if (tool_name == "message-search") return ToolCallType::kMessageSearch; + if (tool_name == "dialogue-list") return ToolCallType::kDialogueList; + if (tool_name == "dialogue-read") return ToolCallType::kDialogueRead; + if (tool_name == "dialogue-search") return ToolCallType::kDialogueSearch; // GUI Automation commands - if (tool_name == "gui-place-tile") - return ToolCallType::kGuiPlaceTile; - if (tool_name == "gui-click") - return ToolCallType::kGuiClick; - if (tool_name == "gui-discover-tool") - return ToolCallType::kGuiDiscover; - if (tool_name == "gui-screenshot") - return ToolCallType::kGuiScreenshot; + if (tool_name == "gui-place-tile") return ToolCallType::kGuiPlaceTile; + if (tool_name == "gui-click") return ToolCallType::kGuiClick; + if (tool_name == "gui-discover-tool") return ToolCallType::kGuiDiscover; + if (tool_name == "gui-screenshot") return ToolCallType::kGuiScreenshot; // Music commands - if (tool_name == "music-list") - return ToolCallType::kMusicList; - if (tool_name == "music-info") - return ToolCallType::kMusicInfo; - if (tool_name == "music-tracks") - return ToolCallType::kMusicTracks; + if (tool_name == "music-list") return ToolCallType::kMusicList; + if (tool_name == "music-info") return ToolCallType::kMusicInfo; + if (tool_name == "music-tracks") return ToolCallType::kMusicTracks; // Sprite commands - if (tool_name == "sprite-list") - return ToolCallType::kSpriteList; - if (tool_name == "sprite-properties") - return ToolCallType::kSpriteProperties; - if (tool_name == "sprite-palette") - return ToolCallType::kSpritePalette; + if (tool_name == "sprite-list") return ToolCallType::kSpriteList; + if (tool_name == "sprite-properties") return ToolCallType::kSpriteProperties; + if (tool_name == "sprite-palette") return ToolCallType::kSpritePalette; // Emulator & Debugger commands - if (tool_name == "emulator-step") - return ToolCallType::kEmulatorStep; - if (tool_name == "emulator-run") - return ToolCallType::kEmulatorRun; - if (tool_name == "emulator-pause") - return ToolCallType::kEmulatorPause; - if (tool_name == "emulator-reset") - return ToolCallType::kEmulatorReset; - if (tool_name == "emulator-get-state") - return ToolCallType::kEmulatorGetState; + if (tool_name == "emulator-step") return ToolCallType::kEmulatorStep; + if (tool_name == "emulator-run") return ToolCallType::kEmulatorRun; + if (tool_name == "emulator-pause") return ToolCallType::kEmulatorPause; + if (tool_name == "emulator-reset") return ToolCallType::kEmulatorReset; + if (tool_name == "emulator-get-state") return ToolCallType::kEmulatorGetState; if (tool_name == "emulator-set-breakpoint") return ToolCallType::kEmulatorSetBreakpoint; if (tool_name == "emulator-clear-breakpoint") diff --git a/src/cli/service/agent/tool_dispatcher.h b/src/cli/service/agent/tool_dispatcher.h index 3d8c50fd..4aa9aac9 100644 --- a/src/cli/service/agent/tool_dispatcher.h +++ b/src/cli/service/agent/tool_dispatcher.h @@ -2,6 +2,7 @@ #define YAZE_SRC_CLI_SERVICE_AGENT_TOOL_DISPATCHER_H_ #include + #include "absl/status/statusor.h" #include "cli/service/ai/common.h" diff --git a/src/cli/service/agent/vim_mode.cc b/src/cli/service/agent/vim_mode.cc index d7476ace..29f4829e 100644 --- a/src/cli/service/agent/vim_mode.cc +++ b/src/cli/service/agent/vim_mode.cc @@ -290,8 +290,7 @@ void VimMode::MoveWordForward() { } void VimMode::MoveWordBackward() { - if (cursor_pos_ > 0) - cursor_pos_--; + if (cursor_pos_ > 0) cursor_pos_--; while (cursor_pos_ > 0 && std::isspace(current_line_[cursor_pos_])) { cursor_pos_--; } @@ -300,13 +299,9 @@ void VimMode::MoveWordBackward() { } } -void VimMode::MoveToLineStart() { - cursor_pos_ = 0; -} +void VimMode::MoveToLineStart() { cursor_pos_ = 0; } -void VimMode::MoveToLineEnd() { - cursor_pos_ = current_line_.length(); -} +void VimMode::MoveToLineEnd() { cursor_pos_ = current_line_.length(); } // Editing implementations void VimMode::DeleteChar() { @@ -323,9 +318,7 @@ void VimMode::DeleteLine() { cursor_pos_ = 0; } -void VimMode::YankLine() { - yank_buffer_ = current_line_; -} +void VimMode::YankLine() { yank_buffer_ = current_line_; } void VimMode::PasteBefore() { if (!yank_buffer_.empty()) { @@ -379,9 +372,7 @@ void VimMode::Backspace() { } } -void VimMode::Delete() { - DeleteChar(); -} +void VimMode::Delete() { DeleteChar(); } void VimMode::Complete() { if (autocomplete_callback_) { @@ -398,8 +389,7 @@ void VimMode::Complete() { // History navigation void VimMode::HistoryPrev() { - if (history_.empty()) - return; + if (history_.empty()) return; if (history_index_ == -1) { history_index_ = history_.size() - 1; @@ -412,8 +402,7 @@ void VimMode::HistoryPrev() { } void VimMode::HistoryNext() { - if (history_.empty() || history_index_ == -1) - return; + if (history_.empty() || history_index_ == -1) return; if (history_index_ < static_cast(history_.size()) - 1) { history_index_++; diff --git a/src/cli/service/agent/vim_mode.h b/src/cli/service/agent/vim_mode.h index 2a1da285..4ab69196 100644 --- a/src/cli/service/agent/vim_mode.h +++ b/src/cli/service/agent/vim_mode.h @@ -23,7 +23,7 @@ enum class VimModeType { /** * @class VimMode * @brief Vim-style line editing for z3ed CLI chat - * + * * Provides vim keybindings for enhanced terminal UX: * - Normal mode: hjkl navigation, dd, yy, p, u * - Insert mode: Regular text input diff --git a/src/cli/service/ai/ai_action_parser.h b/src/cli/service/ai/ai_action_parser.h index ef3f89a4..ec3cc826 100644 --- a/src/cli/service/ai/ai_action_parser.h +++ b/src/cli/service/ai/ai_action_parser.h @@ -44,7 +44,7 @@ struct AIAction { /** * @class AIActionParser * @brief Parses natural language commands into structured GUI actions - * + * * Understands commands like: * - "Place tile 0x42 at overworld position (5, 7)" * - "Open the overworld editor" diff --git a/src/cli/service/ai/ai_gui_controller.cc b/src/cli/service/ai/ai_gui_controller.cc index 488fa865..f4924bfa 100644 --- a/src/cli/service/ai/ai_gui_controller.cc +++ b/src/cli/service/ai/ai_gui_controller.cc @@ -23,7 +23,6 @@ AIGUIController::AIGUIController(GeminiAIService* gemini_service, : gemini_service_(gemini_service), gui_client_(gui_client), vision_refiner_(std::make_unique(gemini_service)) { - if (!gemini_service_) { throw std::invalid_argument("Gemini service cannot be null"); } @@ -44,7 +43,6 @@ absl::Status AIGUIController::Initialize(const ControlLoopConfig& config) { absl::StatusOr AIGUIController::ExecuteCommand( const std::string& command) { - // Parse natural language command into actions auto actions_result = AIActionParser::ParseCommand(command); if (!actions_result.ok()) { @@ -56,7 +54,6 @@ absl::StatusOr AIGUIController::ExecuteCommand( absl::StatusOr AIGUIController::ExecuteActions( const std::vector& actions) { - ControlResult result; result.success = false; @@ -147,7 +144,6 @@ absl::StatusOr AIGUIController::ExecuteActions( absl::StatusOr AIGUIController::ExecuteSingleAction( const AIAction& action, bool verify_with_vision) { - VisionAnalysisResult result; // Capture before screenshot @@ -197,7 +193,6 @@ absl::StatusOr AIGUIController::ExecuteSingleAction( absl::StatusOr AIGUIController::AnalyzeCurrentGUIState( const std::string& context) { - auto screenshot = CaptureCurrentState("analysis"); if (!screenshot.ok()) { return screenshot.status(); @@ -210,7 +205,6 @@ absl::StatusOr AIGUIController::AnalyzeCurrentGUIState( absl::StatusOr AIGUIController::CaptureCurrentState( const std::string& description) { - #ifdef YAZE_WITH_GRPC std::filesystem::path path = GenerateScreenshotPath(description); @@ -272,7 +266,8 @@ absl::Status AIGUIController::ExecuteGRPCAction(const AIAction& action) { return absl::OkStatus(); } else if (action.type == AIActionType::kSelectTile) { - // Extract target and text from parameters (treating select as a type-like action) + // Extract target and text from parameters (treating select as a type-like + // action) std::string target = "input:Unknown"; std::string text = ""; bool clear_first = true; @@ -401,14 +396,12 @@ absl::Status AIGUIController::ExecuteGRPCAction(const AIAction& action) { absl::StatusOr AIGUIController::VerifyActionSuccess( const AIAction& action, const std::filesystem::path& before_screenshot, const std::filesystem::path& after_screenshot) { - return vision_refiner_->VerifyAction(action, before_screenshot, after_screenshot); } absl::StatusOr AIGUIController::RefineActionWithVision( const AIAction& original_action, const VisionAnalysisResult& analysis) { - auto refinement = vision_refiner_->RefineAction(original_action, analysis); if (!refinement.ok()) { return refinement.status(); @@ -436,7 +429,6 @@ void AIGUIController::EnsureScreenshotsDirectory() { std::filesystem::path AIGUIController::GenerateScreenshotPath( const std::string& suffix) { - int64_t timestamp = absl::ToUnixMillis(absl::Now()); std::string filename = absl::StrFormat("ai_gui_%s_%lld.png", suffix, diff --git a/src/cli/service/ai/ai_gui_controller.h b/src/cli/service/ai/ai_gui_controller.h index 3a017e7c..272eacbd 100644 --- a/src/cli/service/ai/ai_gui_controller.h +++ b/src/cli/service/ai/ai_gui_controller.h @@ -50,10 +50,11 @@ struct ControlResult { /** * @class AIGUIController - * @brief High-level controller for AI-driven GUI automation with vision feedback - * + * @brief High-level controller for AI-driven GUI automation with vision + * feedback + * * This class implements the complete vision-guided control loop: - * + * * 1. **Parse Command** → Natural language → AIActions * 2. **Take Screenshot** → Capture current GUI state * 3. **Analyze Vision** → Gemini analyzes screenshot @@ -61,18 +62,18 @@ struct ControlResult { * 5. **Verify Success** → Compare before/after screenshots * 6. **Refine & Retry** → Adjust parameters if action failed * 7. **Repeat** → Until goal achieved or max iterations reached - * + * * Example usage: * ```cpp * AIGUIController controller(gemini_service, gui_client); * controller.Initialize(config); - * + * * auto result = controller.ExecuteCommand( * "Place tile 0x42 at overworld position (5, 7)" * ); - * + * * if (result->success) { - * std::cout << "Success! Took " << result->iterations_performed + * std::cout << "Success! Took " << result->iterations_performed * << " iterations\n"; * } * ``` diff --git a/src/cli/service/ai/ai_service.cc b/src/cli/service/ai/ai_service.cc index 91068bd6..d40212c4 100644 --- a/src/cli/service/ai/ai_service.cc +++ b/src/cli/service/ai/ai_service.cc @@ -1,5 +1,4 @@ #include "cli/service/ai/ai_service.h" -#include "cli/service/agent/conversational_agent_service.h" #include #include @@ -9,6 +8,7 @@ #include "absl/strings/match.h" #include "absl/strings/numbers.h" #include "absl/strings/str_format.h" +#include "cli/service/agent/conversational_agent_service.h" namespace yaze { namespace cli { diff --git a/src/cli/service/ai/gemini_ai_service.cc b/src/cli/service/ai/gemini_ai_service.cc index 85058cce..14a383e3 100644 --- a/src/cli/service/ai/gemini_ai_service.cc +++ b/src/cli/service/ai/gemini_ai_service.cc @@ -1,5 +1,4 @@ #include "cli/service/ai/gemini_ai_service.h" -#include "cli/service/agent/conversational_agent_service.h" #include #include @@ -13,11 +12,13 @@ #include "absl/strings/strip.h" #include "absl/time/clock.h" #include "absl/time/time.h" +#include "cli/service/agent/conversational_agent_service.h" #include "util/platform_paths.h" #ifdef YAZE_WITH_JSON #include #include + #include "httplib.h" #include "nlohmann/json.hpp" @@ -142,7 +143,8 @@ std::string GeminiAIService::BuildFunctionCallSchemas() { #ifndef YAZE_WITH_JSON return "{}"; // Empty object if JSON not available #else - // Use the prompt builder's schema generation which reads from prompt_catalogue.yaml + // Use the prompt builder's schema generation which reads from + // prompt_catalogue.yaml std::string schemas = prompt_builder_.BuildFunctionCallSchemas(); if (!schemas.empty() && schemas != "[]") { return schemas; @@ -186,9 +188,7 @@ std::string GeminiAIService::BuildSystemInstruction() { return prompt_builder_.BuildSystemInstruction(); } -void GeminiAIService::SetRomContext(Rom* rom) { - prompt_builder_.SetRom(rom); -} +void GeminiAIService::SetRomContext(Rom* rom) { prompt_builder_.SetRom(rom); } absl::StatusOr> GeminiAIService::ListAvailableModels() { #ifndef YAZE_WITH_JSON @@ -480,7 +480,8 @@ absl::StatusOr GeminiAIService::GenerateResponse( nlohmann::json schemas = nlohmann::json::parse(schemas_str); - // Build tools array - schemas might be an array of tools or a function_declarations object + // Build tools array - schemas might be an array of tools or a + // function_declarations object if (schemas.is_array()) { // If it's already an array of tools, use it directly request_body["tools"] = {{{"function_declarations", schemas}}}; @@ -702,7 +703,8 @@ absl::StatusOr GeminiAIService::ParseGeminiResponse( } } } else { - // If parsing the full object fails, fallback to extracting commands from text + // If parsing the full object fails, fallback to extracting commands + // from text std::vector lines = absl::StrSplit(text_content, '\n'); for (const auto& line : lines) { std::string trimmed = std::string(absl::StripAsciiWhitespace(line)); @@ -797,15 +799,13 @@ absl::StatusOr GeminiAIService::EncodeImageToBase64( ((char_array_3[1] & 0x0f) << 2) + ((char_array_3[2] & 0xc0) >> 6); char_array_4[3] = char_array_3[2] & 0x3f; - for (i = 0; i < 4; i++) - encoded += base64_chars[char_array_4[i]]; + for (i = 0; i < 4; i++) encoded += base64_chars[char_array_4[i]]; i = 0; } } if (i) { - for (j = i; j < 3; j++) - char_array_3[j] = '\0'; + for (j = i; j < 3; j++) char_array_3[j] = '\0'; char_array_4[0] = (char_array_3[0] & 0xfc) >> 2; char_array_4[1] = @@ -813,11 +813,9 @@ absl::StatusOr GeminiAIService::EncodeImageToBase64( char_array_4[2] = ((char_array_3[1] & 0x0f) << 2) + ((char_array_3[2] & 0xc0) >> 6); - for (j = 0; j < i + 1; j++) - encoded += base64_chars[char_array_4[j]]; + for (j = 0; j < i + 1; j++) encoded += base64_chars[char_array_4[j]]; - while (i++ < 3) - encoded += '='; + while (i++ < 3) encoded += '='; } return encoded; diff --git a/src/cli/service/ai/ollama_ai_service.cc b/src/cli/service/ai/ollama_ai_service.cc index 318a3c69..9bbdd42c 100644 --- a/src/cli/service/ai/ollama_ai_service.cc +++ b/src/cli/service/ai/ollama_ai_service.cc @@ -41,9 +41,7 @@ std::string OllamaAIService::BuildSystemPrompt() { return prompt_builder_.BuildSystemInstruction(); } -void OllamaAIService::SetRomContext(Rom* rom) { - prompt_builder_.SetRom(rom); -} +void OllamaAIService::SetRomContext(Rom* rom) { prompt_builder_.SetRom(rom); } absl::Status OllamaAIService::CheckAvailability() { #ifndef YAZE_WITH_JSON @@ -151,12 +149,9 @@ absl::StatusOr> OllamaAIService::ListAvailableModels() { // Build description std::string desc; - if (!info.family.empty()) - desc += info.family + " "; - if (!info.parameter_size.empty()) - desc += info.parameter_size + " "; - if (!info.quantization.empty()) - desc += "(" + info.quantization + ")"; + if (!info.family.empty()) desc += info.family + " "; + if (!info.parameter_size.empty()) desc += info.parameter_size + " "; + if (!info.quantization.empty()) desc += "(" + info.quantization + ")"; info.description = desc; } models.push_back(std::move(info)); diff --git a/src/cli/service/ai/prompt_builder.cc b/src/cli/service/ai/prompt_builder.cc index fdef488c..b84719f3 100644 --- a/src/cli/service/ai/prompt_builder.cc +++ b/src/cli/service/ai/prompt_builder.cc @@ -1,5 +1,4 @@ #include "cli/service/ai/prompt_builder.h" -#include "cli/service/agent/conversational_agent_service.h" #include #include @@ -10,6 +9,7 @@ #include "absl/strings/ascii.h" #include "absl/strings/str_cat.h" #include "absl/strings/str_join.h" +#include "cli/service/agent/conversational_agent_service.h" #include "nlohmann/json.hpp" #include "util/platform_paths.h" #include "yaml-cpp/yaml.h" diff --git a/src/cli/service/ai/service_factory.cc b/src/cli/service/ai/service_factory.cc index 73d6bf85..e3b65d01 100644 --- a/src/cli/service/ai/service_factory.cc +++ b/src/cli/service/ai/service_factory.cc @@ -36,13 +36,11 @@ std::unique_ptr CreateAIService() { // Fall back to environment variables if flags not set if (config.gemini_api_key.empty()) { const char* env_key = std::getenv("GEMINI_API_KEY"); - if (env_key) - config.gemini_api_key = env_key; + if (env_key) config.gemini_api_key = env_key; } if (config.model.empty()) { const char* env_model = std::getenv("OLLAMA_MODEL"); - if (env_model) - config.model = env_model; + if (env_model) config.model = env_model; } return CreateAIService(config); diff --git a/src/cli/service/ai/service_factory_stub.cc b/src/cli/service/ai/service_factory_stub.cc index e478e947..c228427e 100644 --- a/src/cli/service/ai/service_factory_stub.cc +++ b/src/cli/service/ai/service_factory_stub.cc @@ -1,9 +1,8 @@ #ifndef YAZE_AI_RUNTIME_AVAILABLE -#include "cli/service/ai/service_factory.h" - #include "absl/status/status.h" #include "absl/status/statusor.h" +#include "cli/service/ai/service_factory.h" namespace yaze::cli { diff --git a/src/cli/service/ai/vision_action_refiner.cc b/src/cli/service/ai/vision_action_refiner.cc index cc5d1e97..aec16b53 100644 --- a/src/cli/service/ai/vision_action_refiner.cc +++ b/src/cli/service/ai/vision_action_refiner.cc @@ -21,7 +21,6 @@ VisionActionRefiner::VisionActionRefiner(GeminiAIService* gemini_service) absl::StatusOr VisionActionRefiner::AnalyzeScreenshot( const std::filesystem::path& screenshot_path, const std::string& context) { - if (!std::filesystem::exists(screenshot_path)) { return absl::NotFoundError( absl::StrCat("Screenshot not found: ", screenshot_path.string())); @@ -42,7 +41,6 @@ absl::StatusOr VisionActionRefiner::AnalyzeScreenshot( absl::StatusOr VisionActionRefiner::VerifyAction( const AIAction& action, const std::filesystem::path& before_screenshot, const std::filesystem::path& after_screenshot) { - if (!std::filesystem::exists(before_screenshot)) { return absl::NotFoundError("Before screenshot not found"); } @@ -66,7 +64,6 @@ absl::StatusOr VisionActionRefiner::VerifyAction( absl::StatusOr VisionActionRefiner::RefineAction( const AIAction& original_action, const VisionAnalysisResult& analysis) { - ActionRefinement refinement; // If action was successful, no refinement needed @@ -124,7 +121,6 @@ absl::StatusOr> VisionActionRefiner::LocateUIElement( const std::filesystem::path& screenshot_path, const std::string& element_name) { - std::string prompt = BuildElementLocationPrompt(element_name); auto response = gemini_service_->GenerateMultimodalResponse( @@ -171,7 +167,6 @@ VisionActionRefiner::LocateUIElement( absl::StatusOr> VisionActionRefiner::ExtractVisibleWidgets( const std::filesystem::path& screenshot_path) { - std::string prompt = BuildWidgetExtractionPrompt(); auto response = gemini_service_->GenerateMultimodalResponse( @@ -266,7 +261,6 @@ std::string VisionActionRefiner::BuildWidgetExtractionPrompt() { VisionAnalysisResult VisionActionRefiner::ParseAnalysisResponse( const std::string& response) { - VisionAnalysisResult result; result.description = response; @@ -302,7 +296,6 @@ VisionAnalysisResult VisionActionRefiner::ParseAnalysisResponse( VisionAnalysisResult VisionActionRefiner::ParseVerificationResponse( const std::string& response, const AIAction& action) { - VisionAnalysisResult result; result.description = response; diff --git a/src/cli/service/ai/vision_action_refiner.h b/src/cli/service/ai/vision_action_refiner.h index 258bc6c7..b98ec42b 100644 --- a/src/cli/service/ai/vision_action_refiner.h +++ b/src/cli/service/ai/vision_action_refiner.h @@ -42,30 +42,30 @@ struct ActionRefinement { /** * @class VisionActionRefiner * @brief Uses Gemini Vision to analyze GUI screenshots and refine AI actions - * + * * This class implements the vision-guided action loop: * 1. Take screenshot of current GUI state * 2. Send to Gemini Vision with contextual prompt * 3. Analyze response to determine next action * 4. Verify action success by comparing screenshots - * + * * Example usage: * ```cpp * VisionActionRefiner refiner(gemini_service); - * + * * // Analyze current state * auto analysis = refiner.AnalyzeCurrentState( * "overworld_editor", * "Looking for tile selector" * ); - * + * * // Verify action was successful * auto verification = refiner.VerifyAction( * AIAction(kPlaceTile, {{"x", "5"}, {"y", "7"}}), * before_screenshot, * after_screenshot * ); - * + * * // Refine failed action * if (!verification->action_successful) { * auto refinement = refiner.RefineAction( @@ -94,7 +94,8 @@ class VisionActionRefiner { const std::string& context = ""); /** - * @brief Verify an action was successful by comparing before/after screenshots + * @brief Verify an action was successful by comparing before/after + * screenshots * @param action The action that was performed * @param before_screenshot Screenshot before action * @param after_screenshot Screenshot after action diff --git a/src/cli/service/api/http_server.cc b/src/cli/service/api/http_server.cc index 0de086c7..226ec53b 100644 --- a/src/cli/service/api/http_server.cc +++ b/src/cli/service/api/http_server.cc @@ -3,10 +3,10 @@ #include "cli/service/api/api_handlers.h" #include "util/log.h" -// Include httplib implementation in one file or just use the header if header-only -// usually cpp-httplib is header only, so just including is enough. -// However, we need to be careful about multiple definitions if we include it in multiple .cc files without precautions? -// cpp-httplib is header only. +// Include httplib implementation in one file or just use the header if +// header-only usually cpp-httplib is header only, so just including is enough. +// However, we need to be careful about multiple definitions if we include it in +// multiple .cc files without precautions? cpp-httplib is header only. #include "httplib.h" namespace yaze { @@ -15,9 +15,7 @@ namespace api { HttpServer::HttpServer() : server_(std::make_unique()) {} -HttpServer::~HttpServer() { - Stop(); -} +HttpServer::~HttpServer() { Stop(); } absl::Status HttpServer::Start(int port) { if (is_running_) { @@ -33,7 +31,8 @@ absl::Status HttpServer::Start(int port) { // Start server in a separate thread is_running_ = true; - // Capture server pointer to avoid race conditions if 'this' is destroyed (though HttpServer shouldn't be) + // Capture server pointer to avoid race conditions if 'this' is destroyed + // (though HttpServer shouldn't be) server_thread_ = std::make_unique([this, port]() { LOG_INFO("HttpServer", "Starting API server on port %d", port); bool ret = server_->listen("0.0.0.0", port); @@ -59,16 +58,15 @@ void HttpServer::Stop() { } } -bool HttpServer::IsRunning() const { - return is_running_; -} +bool HttpServer::IsRunning() const { return is_running_; } void HttpServer::RegisterRoutes() { server_->Get("/api/v1/health", HandleHealth); server_->Get("/api/v1/models", HandleListModels); // Handle CORS options for all routes? - // For now, we set CORS headers in individual handlers or via a middleware if httplib supported it easily. + // For now, we set CORS headers in individual handlers or via a middleware if + // httplib supported it easily. } } // namespace api diff --git a/src/cli/service/command_registry.h b/src/cli/service/command_registry.h index 5a375090..17eceb79 100644 --- a/src/cli/service/command_registry.h +++ b/src/cli/service/command_registry.h @@ -15,14 +15,14 @@ namespace cli { /** * @class CommandRegistry * @brief Single source of truth for all z3ed commands - * + * * Serves as the central registry for: * - CLI command routing * - Agent tool calling * - Help text generation * - TUI menu generation * - Function schema export (for AI) - * + * * Ensures consistency: if a command exists, it's available to both * human users (CLI) and AI agents (tool calling). */ diff --git a/src/cli/service/gui/gui_action_generator.cc b/src/cli/service/gui/gui_action_generator.cc index df1d3a05..fd8a0bc9 100644 --- a/src/cli/service/gui/gui_action_generator.cc +++ b/src/cli/service/gui/gui_action_generator.cc @@ -57,7 +57,8 @@ nlohmann::json GuiActionGenerator::ActionToJSON(const ai::AIAction& action) { auto it = action.parameters.find("tile_id"); if (it != action.parameters.end()) { int tile_id = std::stoi(it->second); - // Calculate position in tile selector (8 tiles per row, 16x16 pixels each) + // Calculate position in tile selector (8 tiles per row, 16x16 pixels + // each) int tile_x = (tile_id % 8) * 16 + 8; // Center of tile int tile_y = (tile_id / 8) * 16 + 8; diff --git a/src/cli/service/gui/gui_action_generator.h b/src/cli/service/gui/gui_action_generator.h index 50c19bf1..5188d97a 100644 --- a/src/cli/service/gui/gui_action_generator.h +++ b/src/cli/service/gui/gui_action_generator.h @@ -16,9 +16,9 @@ namespace cli { namespace gui { /** - * @class GuiActionGenerator + * @class GuiActionGenerator * @brief Converts high-level AI actions into executable GUI test scripts - * + * * Takes parsed AI actions and generates gRPC test harness commands or * JSON test scripts that can be executed to control the GUI. */ diff --git a/src/cli/service/gui/gui_automation_client.cc b/src/cli/service/gui/gui_automation_client.cc index 2562c715..37ed1f1e 100644 --- a/src/cli/service/gui/gui_automation_client.cc +++ b/src/cli/service/gui/gui_automation_client.cc @@ -3,12 +3,12 @@ #include "cli/service/gui/gui_automation_client.h" +#include + #include "absl/strings/str_cat.h" #include "absl/strings/str_format.h" #include "absl/time/time.h" -#include - namespace yaze { namespace cli { diff --git a/src/cli/service/gui/gui_automation_client.h b/src/cli/service/gui/gui_automation_client.h index 0596c689..17ef9842 100644 --- a/src/cli/service/gui/gui_automation_client.h +++ b/src/cli/service/gui/gui_automation_client.h @@ -4,10 +4,6 @@ #ifndef YAZE_CLI_SERVICE_GUI_AUTOMATION_CLIENT_H #define YAZE_CLI_SERVICE_GUI_AUTOMATION_CLIENT_H -#include "absl/status/status.h" -#include "absl/status/statusor.h" -#include "absl/time/time.h" - #include #include #include @@ -16,6 +12,10 @@ #include #include +#include "absl/status/status.h" +#include "absl/status/statusor.h" +#include "absl/time/time.h" + #ifdef YAZE_WITH_GRPC // Undefine Windows macros that conflict with protobuf generated code #ifdef _WIN32 @@ -26,6 +26,7 @@ #endif // _WIN32 #include + #include "protos/imgui_test_harness.grpc.pb.h" // Restore Windows macros @@ -217,18 +218,18 @@ struct DiscoverWidgetsResult { /** * @brief Client for automating YAZE GUI through gRPC - * + * * This client wraps the ImGuiTestHarness gRPC service and provides * a C++ API for CLI commands to drive the YAZE GUI remotely. - * + * * Example usage: * @code * GuiAutomationClient client("localhost:50052"); * RETURN_IF_ERROR(client.Connect()); - * + * * auto result = client.Click("button:Overworld", ClickType::kLeft); * if (!result.ok()) return result.status(); - * + * * if (!result->success) { * return absl::InternalError(result->message); * } @@ -238,7 +239,8 @@ class GuiAutomationClient { public: /** * @brief Construct a new GUI automation client - * @param server_address Address of the test harness server (e.g., "localhost:50052") + * @param server_address Address of the test harness server (e.g., + * "localhost:50052") */ explicit GuiAutomationClient(const std::string& server_address); diff --git a/src/cli/service/net/z3ed_network_client.cc b/src/cli/service/net/z3ed_network_client.cc index 52caab3b..fd145fb9 100644 --- a/src/cli/service/net/z3ed_network_client.cc +++ b/src/cli/service/net/z3ed_network_client.cc @@ -357,13 +357,9 @@ absl::StatusOr Z3edNetworkClient::QueryAI( return impl_->QueryAI(query, username); } -void Z3edNetworkClient::Disconnect() { - impl_->Disconnect(); -} +void Z3edNetworkClient::Disconnect() { impl_->Disconnect(); } -bool Z3edNetworkClient::IsConnected() const { - return impl_->IsConnected(); -} +bool Z3edNetworkClient::IsConnected() const { return impl_->IsConnected(); } } // namespace net } // namespace cli diff --git a/src/cli/service/net/z3ed_network_client.h b/src/cli/service/net/z3ed_network_client.h index 8a9d2197..4f69ed40 100644 --- a/src/cli/service/net/z3ed_network_client.h +++ b/src/cli/service/net/z3ed_network_client.h @@ -18,7 +18,7 @@ namespace net { /** * @class Z3edNetworkClient * @brief Simplified WebSocket client for z3ed CLI - * + * * Provides command-line friendly interface for: * - Connecting to yaze-server * - Submitting proposals from CLI diff --git a/src/cli/service/planning/policy_evaluator.cc b/src/cli/service/planning/policy_evaluator.cc index 2c0f52aa..a6a8ac7c 100644 --- a/src/cli/service/planning/policy_evaluator.cc +++ b/src/cli/service/planning/policy_evaluator.cc @@ -134,8 +134,7 @@ absl::Status PolicyEvaluator::ParsePolicyFile(absl::string_view yaml_content) { std::string trimmed = std::string(absl::StripAsciiWhitespace(line)); // Skip comments and empty lines - if (trimmed.empty() || trimmed[0] == '#') - continue; + if (trimmed.empty() || trimmed[0] == '#') continue; // Check for main keys if (absl::StartsWith(trimmed, "version:")) { @@ -232,8 +231,7 @@ void PolicyEvaluator::EvaluateTestRequirements(absl::string_view proposal_id, // For now, all test requirements pass (no test framework yet) std::string proposal_id_str(proposal_id); for (const auto& policy : config_->test_requirements) { - if (!policy.enabled) - continue; + if (!policy.enabled) continue; // Placeholder: would check actual test results here // For now, we skip test validation @@ -252,8 +250,7 @@ void PolicyEvaluator::EvaluateChangeConstraints(absl::string_view proposal_id, const auto& proposal = proposal_result.value(); for (const auto& policy : config_->change_constraints) { - if (!policy.enabled) - continue; + if (!policy.enabled) continue; // Check max bytes changed if (policy.max_bytes_changed > 0 && @@ -291,8 +288,7 @@ void PolicyEvaluator::EvaluateForbiddenRanges(absl::string_view proposal_id, // Would need to parse diff or track ROM modifications // For now, we assume no forbidden range violations for (const auto& policy : config_->forbidden_ranges) { - if (!policy.enabled) - continue; + if (!policy.enabled) continue; // Placeholder: would check ROM modification ranges here } @@ -310,8 +306,7 @@ void PolicyEvaluator::EvaluateReviewRequirements(absl::string_view proposal_id, const auto& proposal = proposal_result.value(); for (const auto& policy : config_->review_requirements) { - if (!policy.enabled) - continue; + if (!policy.enabled) continue; // Evaluate conditions for (const auto& condition : policy.conditions) { diff --git a/src/cli/service/planning/proposal_registry.cc b/src/cli/service/planning/proposal_registry.cc index d41be0b8..4bc864c7 100644 --- a/src/cli/service/planning/proposal_registry.cc +++ b/src/cli/service/planning/proposal_registry.cc @@ -13,7 +13,6 @@ #include "absl/strings/str_cat.h" #include "absl/strings/str_format.h" #include "absl/time/time.h" - #include "nlohmann/json.hpp" #include "util/macro.h" @@ -57,9 +56,7 @@ ProposalRegistry::ProposalStatus ParseStatus(absl::string_view value) { return ProposalRegistry::ProposalStatus::kPending; } -int64_t TimeToMillis(absl::Time time) { - return absl::ToUnixMillis(time); -} +int64_t TimeToMillis(absl::Time time) { return absl::ToUnixMillis(time); } std::optional OptionalTimeFromMillis(int64_t millis) { if (millis <= 0) { diff --git a/src/cli/service/planning/tile16_proposal_generator.cc b/src/cli/service/planning/tile16_proposal_generator.cc index 950730ce..c4096016 100644 --- a/src/cli/service/planning/tile16_proposal_generator.cc +++ b/src/cli/service/planning/tile16_proposal_generator.cc @@ -57,8 +57,7 @@ std::string Tile16Proposal::ToJson() const { << "\",\n"; json << " \"new_tile\": \"0x" << std::hex << change.new_tile << "\"\n"; json << " }"; - if (i < changes.size() - 1) - json << ","; + if (i < changes.size() - 1) json << ","; json << "\n"; } json << " ]\n"; @@ -249,7 +248,6 @@ std::string Tile16ProposalGenerator::GenerateProposalId() const { absl::StatusOr Tile16ProposalGenerator::ParseSetTileCommand( const std::string& command, Rom* rom) { - // Expected format: "overworld set-tile --map 0 --x 10 --y 20 --tile 0x02E" std::vector parts = absl::StrSplit(command, ' '); @@ -267,8 +265,7 @@ absl::StatusOr Tile16ProposalGenerator::ParseSetTileCommand( // Parse arguments for (size_t i = 2; i < parts.size(); i += 2) { - if (i + 1 >= parts.size()) - break; + if (i + 1 >= parts.size()) break; const std::string& flag = parts[i]; const std::string& value = parts[i + 1]; @@ -313,8 +310,8 @@ absl::StatusOr Tile16ProposalGenerator::ParseSetTileCommand( absl::StatusOr> Tile16ProposalGenerator::ParseSetAreaCommand(const std::string& command, Rom* rom) { - - // Expected format: "overworld set-area --map 0 --x 10 --y 20 --width 5 --height 3 --tile 0x02E" + // Expected format: "overworld set-area --map 0 --x 10 --y 20 --width 5 + // --height 3 --tile 0x02E" std::vector parts = absl::StrSplit(command, ' '); if (parts.size() < 12) { @@ -332,8 +329,7 @@ Tile16ProposalGenerator::ParseSetAreaCommand(const std::string& command, // Parse arguments for (size_t i = 2; i < parts.size(); i += 2) { - if (i + 1 >= parts.size()) - break; + if (i + 1 >= parts.size()) break; const std::string& flag = parts[i]; const std::string& value = parts[i + 1]; @@ -404,9 +400,9 @@ Tile16ProposalGenerator::ParseSetAreaCommand(const std::string& command, absl::StatusOr> Tile16ProposalGenerator::ParseReplaceTileCommand(const std::string& command, Rom* rom) { - - // Expected format: "overworld replace-tile --map 0 --old-tile 0x02E --new-tile 0x030" - // Optional bounds: --x-min 0 --y-min 0 --x-max 31 --y-max 31 + // Expected format: "overworld replace-tile --map 0 --old-tile 0x02E + // --new-tile 0x030" Optional bounds: --x-min 0 --y-min 0 --x-max 31 --y-max + // 31 std::vector parts = absl::StrSplit(command, ' '); if (parts.size() < 8) { @@ -425,8 +421,7 @@ Tile16ProposalGenerator::ParseReplaceTileCommand(const std::string& command, // Parse arguments for (size_t i = 2; i < parts.size(); i += 2) { - if (i + 1 >= parts.size()) - break; + if (i + 1 >= parts.size()) break; const std::string& flag = parts[i]; const std::string& value = parts[i + 1]; @@ -498,7 +493,6 @@ Tile16ProposalGenerator::ParseReplaceTileCommand(const std::string& command, absl::StatusOr Tile16ProposalGenerator::GenerateFromCommands( const std::string& prompt, const std::vector& commands, const std::string& ai_service, Rom* rom) { - Tile16Proposal proposal; proposal.id = GenerateProposalId(); proposal.prompt = prompt; @@ -555,7 +549,6 @@ absl::StatusOr Tile16ProposalGenerator::GenerateFromCommands( absl::Status Tile16ProposalGenerator::ApplyProposal( const Tile16Proposal& proposal, Rom* rom) { - if (!rom || !rom->is_loaded()) { return absl::FailedPreconditionError("ROM not loaded"); } @@ -589,7 +582,6 @@ absl::Status Tile16ProposalGenerator::ApplyProposal( absl::StatusOr Tile16ProposalGenerator::GenerateDiff( const Tile16Proposal& proposal, Rom* before_rom, Rom* after_rom) { - if (!before_rom || !before_rom->is_loaded()) { return absl::FailedPreconditionError("Before ROM not loaded"); } @@ -608,14 +600,10 @@ absl::StatusOr Tile16ProposalGenerator::GenerateDiff( int map_id = proposal.changes[0].map_id; for (const auto& change : proposal.changes) { - if (change.x < min_x) - min_x = change.x; - if (change.y < min_y) - min_y = change.y; - if (change.x > max_x) - max_x = change.x; - if (change.y > max_y) - max_y = change.y; + if (change.x < min_x) min_x = change.x; + if (change.y < min_y) min_y = change.y; + if (change.x > max_x) max_x = change.x; + if (change.y > max_y) max_y = change.y; } // Add some padding around the changes @@ -710,7 +698,6 @@ absl::StatusOr Tile16ProposalGenerator::GenerateDiff( absl::Status Tile16ProposalGenerator::SaveProposal( const Tile16Proposal& proposal, const std::string& path) { - std::ofstream file(path); if (!file.is_open()) { return absl::InvalidArgumentError( @@ -725,7 +712,6 @@ absl::Status Tile16ProposalGenerator::SaveProposal( absl::StatusOr Tile16ProposalGenerator::LoadProposal( const std::string& path) { - std::ifstream file(path); if (!file.is_open()) { return absl::InvalidArgumentError( diff --git a/src/cli/service/planning/tile16_proposal_generator.h b/src/cli/service/planning/tile16_proposal_generator.h index 332cfdb5..db02f07e 100644 --- a/src/cli/service/planning/tile16_proposal_generator.h +++ b/src/cli/service/planning/tile16_proposal_generator.h @@ -28,7 +28,7 @@ struct Tile16Change { /** * @brief Represents a proposal for tile16 edits on the overworld. - * + * * This is the core data structure for the accept/reject workflow. * AI generates proposals, which are then applied to a sandbox ROM * for preview before being committed to the main ROM. @@ -56,7 +56,7 @@ struct Tile16Proposal { /** * @brief Generates and manages tile16 editing proposals. - * + * * This class bridges the AI service with the overworld editing system, * providing a safe sandbox workflow for reviewing and applying changes. */ @@ -69,7 +69,7 @@ class Tile16ProposalGenerator { /** * @brief Generate a tile16 proposal from an AI-generated command list. - * + * * @param prompt The original user prompt * @param commands List of commands from AI (e.g., "overworld set-tile ...") * @param ai_service Name of the AI service used @@ -82,10 +82,10 @@ class Tile16ProposalGenerator { /** * @brief Apply a proposal to a ROM (typically a sandbox). - * + * * This modifies the ROM in memory but doesn't save to disk. * Used for preview and testing. - * + * * @param proposal The proposal to apply * @param rom The ROM to modify * @return Status indicating success or failure @@ -94,9 +94,9 @@ class Tile16ProposalGenerator { /** * @brief Generate a visual diff bitmap for a proposal. - * + * * Creates a side-by-side or overlay comparison of before/after state. - * + * * @param proposal The proposal to visualize * @param before_rom ROM in original state * @param after_rom ROM with proposal applied @@ -107,7 +107,7 @@ class Tile16ProposalGenerator { /** * @brief Save a proposal to a JSON file for later review. - * + * * @param proposal The proposal to save * @param path File path to save to * @return Status indicating success or failure @@ -117,7 +117,7 @@ class Tile16ProposalGenerator { /** * @brief Load a proposal from a JSON file. - * + * * @param path File path to load from * @return The loaded proposal or error */ @@ -126,7 +126,7 @@ class Tile16ProposalGenerator { private: /** * @brief Parse a single "overworld set-tile" command into a Tile16Change. - * + * * Expected format: "overworld set-tile --map 0 --x 10 --y 20 --tile 0x02E" */ absl::StatusOr ParseSetTileCommand(const std::string& command, @@ -134,17 +134,20 @@ class Tile16ProposalGenerator { /** * @brief Parse a "overworld set-area" command into multiple Tile16Changes. - * - * Expected format: "overworld set-area --map 0 --x 10 --y 20 --width 5 --height 3 --tile 0x02E" + * + * Expected format: "overworld set-area --map 0 --x 10 --y 20 --width 5 + * --height 3 --tile 0x02E" */ absl::StatusOr> ParseSetAreaCommand( const std::string& command, Rom* rom); /** - * @brief Parse a "overworld replace-tile" command into multiple Tile16Changes. - * - * Expected format: "overworld replace-tile --map 0 --old-tile 0x02E --new-tile 0x030" - * Can also specify optional bounds: --x-min 0 --y-min 0 --x-max 31 --y-max 31 + * @brief Parse a "overworld replace-tile" command into multiple + * Tile16Changes. + * + * Expected format: "overworld replace-tile --map 0 --old-tile 0x02E + * --new-tile 0x030" Can also specify optional bounds: --x-min 0 --y-min 0 + * --x-max 31 --y-max 31 */ absl::StatusOr> ParseReplaceTileCommand( const std::string& command, Rom* rom); diff --git a/src/cli/service/resources/command_context.cc b/src/cli/service/resources/command_context.cc index fcbea6ff..97b03560 100644 --- a/src/cli/service/resources/command_context.cc +++ b/src/cli/service/resources/command_context.cc @@ -386,9 +386,7 @@ void OutputFormatter::AddArrayItem(const std::string& item) { array_item_count_++; } -std::string OutputFormatter::GetOutput() const { - return buffer_; -} +std::string OutputFormatter::GetOutput() const { return buffer_; } void OutputFormatter::Print() const { std::cout << buffer_; diff --git a/src/cli/service/resources/command_context.h b/src/cli/service/resources/command_context.h index 4115a39b..90cde5fd 100644 --- a/src/cli/service/resources/command_context.h +++ b/src/cli/service/resources/command_context.h @@ -16,7 +16,7 @@ namespace resources { /** * @class CommandContext * @brief Encapsulates common context for CLI command execution - * + * * Provides unified ROM loading, argument parsing, and common options * management to reduce duplication across command handlers. */ diff --git a/src/cli/service/resources/command_handler.cc b/src/cli/service/resources/command_handler.cc index 0b6c8090..93e54c6c 100644 --- a/src/cli/service/resources/command_handler.cc +++ b/src/cli/service/resources/command_handler.cc @@ -16,11 +16,10 @@ CommandHandler::Descriptor CommandHandler::Describe() const { } // namespace cli } // namespace yaze -#include "cli/service/resources/command_handler.h" - #include #include "absl/strings/str_format.h" +#include "cli/service/resources/command_handler.h" #include "util/macro.h" namespace yaze { diff --git a/src/cli/service/resources/command_handler.h b/src/cli/service/resources/command_handler.h index a0c57d56..51e0dee2 100644 --- a/src/cli/service/resources/command_handler.h +++ b/src/cli/service/resources/command_handler.h @@ -15,13 +15,13 @@ namespace resources { /** * @class CommandHandler * @brief Base class for CLI command handlers - * + * * Provides a consistent structure for implementing CLI commands with: * - Automatic argument parsing * - ROM context management * - Output formatting * - Error handling - * + * * Example usage: * ```cpp * class MyCommandHandler : public CommandHandler { @@ -29,8 +29,8 @@ namespace resources { * absl::Status ValidateArgs(const ArgumentParser& parser) override { * return parser.RequireArgs({"required_arg"}); * } - * - * absl::Status Execute(Rom* rom, const ArgumentParser& parser, + * + * absl::Status Execute(Rom* rom, const ArgumentParser& parser, * OutputFormatter& formatter) override { * auto value = parser.GetString("required_arg").value(); * // ... business logic ... @@ -59,7 +59,7 @@ class CommandHandler { /** * @brief Execute the command - * + * * This is the main entry point that orchestrates: * 1. Argument parsing * 2. Validation @@ -71,7 +71,7 @@ class CommandHandler { /** * @brief Get the command name - * + * * Override this to provide a unique identifier for the command. * This is used for command registration and lookup. */ @@ -90,7 +90,7 @@ class CommandHandler { protected: /** * @brief Validate command arguments - * + * * Override this to check required arguments and perform custom validation. * Called before Execute(). */ @@ -98,7 +98,7 @@ class CommandHandler { /** * @brief Execute the command business logic - * + * * Override this to implement command-specific functionality. * The ROM is guaranteed to be loaded and labels initialized. */ @@ -107,7 +107,7 @@ class CommandHandler { /** * @brief Check if the command requires ROM labels - * + * * Override to return false if labels are not needed. */ virtual bool RequiresLabels() const { return false; } @@ -125,7 +125,7 @@ class CommandHandler { /** * @brief Helper macro for creating simple command handlers - * + * * Usage: * ```cpp * DEFINE_COMMAND_HANDLER(ResourceList, @@ -146,9 +146,7 @@ class CommandHandler { #define DEFINE_COMMAND_HANDLER(name, usage_str, validate_body, execute_body) \ class name##CommandHandler : public CommandHandler { \ protected: \ - std::string GetUsage() const override { \ - return usage_str; \ - } \ + std::string GetUsage() const override { return usage_str; } \ absl::Status ValidateArgs(const ArgumentParser& parser) override \ validate_body absl::Status \ Execute(Rom* rom, const ArgumentParser& parser, \ diff --git a/src/cli/service/resources/resource_catalog.h b/src/cli/service/resources/resource_catalog.h index 86117a52..8a773650 100644 --- a/src/cli/service/resources/resource_catalog.h +++ b/src/cli/service/resources/resource_catalog.h @@ -38,8 +38,8 @@ struct ResourceSchema { std::vector actions; }; -// ResourceCatalog exposes a machine-readable description of CLI resources so that -// both humans and AI agents can introspect capabilities at runtime. +// ResourceCatalog exposes a machine-readable description of CLI resources so +// that both humans and AI agents can introspect capabilities at runtime. class ResourceCatalog { public: static const ResourceCatalog& Instance(); diff --git a/src/cli/service/resources/resource_context_builder.cc b/src/cli/service/resources/resource_context_builder.cc index 3850544c..b9c2b41f 100644 --- a/src/cli/service/resources/resource_context_builder.cc +++ b/src/cli/service/resources/resource_context_builder.cc @@ -240,16 +240,14 @@ absl::StatusOr ResourceContextBuilder::ExportToJson() { bool first_category = true; for (const auto& [category, labels] : label_mgr->labels_) { - if (!first_category) - json << ",\n"; + if (!first_category) json << ",\n"; first_category = false; json << " \"" << category << "\": {\n"; bool first_label = true; for (const auto& [key, value] : labels) { - if (!first_label) - json << ",\n"; + if (!first_label) json << ",\n"; first_label = false; json << " \"" << key << "\": \"" << value << "\""; diff --git a/src/cli/service/resources/resource_context_builder.h b/src/cli/service/resources/resource_context_builder.h index 66c80f10..58242899 100644 --- a/src/cli/service/resources/resource_context_builder.h +++ b/src/cli/service/resources/resource_context_builder.h @@ -12,12 +12,12 @@ namespace cli { /** * @brief Builds contextual information from ROM resources for AI prompts. - * + * * This class extracts user-defined labels from the ROM's ResourceLabelManager * and formats them into human-readable context that can be injected into * AI prompts. This enables AI to use meaningful names like "eastern_palace" * instead of opaque IDs like "0x02". - * + * * Example usage: * ResourceContextBuilder builder(rom); * std::string context = builder.BuildResourceContext().value(); @@ -29,35 +29,35 @@ class ResourceContextBuilder { /** * @brief Build a complete resource context string for AI prompts. - * + * * Extracts all ResourceLabels from the ROM and formats them into * a structured text format suitable for AI consumption. - * + * * Example output: * ``` * === AVAILABLE RESOURCES === - * + * * Overworld Maps: * - 0: "Light World" (user: "hyrule_overworld") * - 1: "Dark World" (user: "dark_world") - * + * * Dungeons: * - 0x00: "Hyrule Castle" (user: "castle") * - 0x02: "Eastern Palace" (user: "east_palace") - * + * * Common Tile16s: * - 0x020: Grass * - 0x02E: Tree * - 0x14C: Water (top) * ``` - * + * * @return Formatted resource context string */ absl::StatusOr BuildResourceContext(); /** * @brief Get labels for a specific resource category. - * + * * @param category Resource type ("overworld", "dungeon", "entrance", etc.) * @return Map of ID -> label for that category */ @@ -66,10 +66,10 @@ class ResourceContextBuilder { /** * @brief Export all labels to JSON format. - * + * * Creates a structured JSON representation of all resources * for potential use by AI services. - * + * * @return JSON string with all resource labels */ absl::StatusOr ExportToJson(); @@ -79,7 +79,7 @@ class ResourceContextBuilder { /** * @brief Extract overworld map labels. - * + * * Returns formatted string like: * ``` * Overworld Maps: @@ -91,7 +91,7 @@ class ResourceContextBuilder { /** * @brief Extract dungeon labels. - * + * * Returns formatted string like: * ``` * Dungeons: @@ -103,7 +103,7 @@ class ResourceContextBuilder { /** * @brief Extract entrance labels. - * + * * Returns formatted string like: * ``` * Entrances: @@ -115,7 +115,7 @@ class ResourceContextBuilder { /** * @brief Extract room labels. - * + * * Returns formatted string like: * ``` * Rooms: @@ -127,7 +127,7 @@ class ResourceContextBuilder { /** * @brief Extract sprite labels. - * + * * Returns formatted string like: * ``` * Sprites: @@ -139,10 +139,10 @@ class ResourceContextBuilder { /** * @brief Add common tile16 reference for AI. - * + * * Provides a quick reference of common tile16 IDs that AI * can use without needing to search through the entire tileset. - * + * * Returns formatted string like: * ``` * Common Tile16s: diff --git a/src/cli/service/rom/rom_sandbox_manager.cc b/src/cli/service/rom/rom_sandbox_manager.cc index d90031e2..0afce8f5 100644 --- a/src/cli/service/rom/rom_sandbox_manager.cc +++ b/src/cli/service/rom/rom_sandbox_manager.cc @@ -8,7 +8,6 @@ #include "absl/strings/str_cat.h" #include "absl/strings/str_format.h" #include "absl/time/time.h" - #include "util/macro.h" namespace yaze { diff --git a/src/cli/service/rom/rom_sandbox_manager.h b/src/cli/service/rom/rom_sandbox_manager.h index d31d5f5c..e57d898b 100644 --- a/src/cli/service/rom/rom_sandbox_manager.h +++ b/src/cli/service/rom/rom_sandbox_manager.h @@ -13,7 +13,6 @@ #include "absl/status/statusor.h" #include "absl/strings/string_view.h" #include "absl/time/time.h" - #include "app/rom.h" namespace yaze { diff --git a/src/cli/service/testing/test_suite_writer.cc b/src/cli/service/testing/test_suite_writer.cc index 5d84430c..7a37bd3d 100644 --- a/src/cli/service/testing/test_suite_writer.cc +++ b/src/cli/service/testing/test_suite_writer.cc @@ -14,9 +14,7 @@ namespace yaze { namespace cli { namespace { -std::string Indent(int count) { - return std::string(count, ' '); -} +std::string Indent(int count) { return std::string(count, ' '); } std::string QuoteYaml(absl::string_view value) { std::string escaped(value); @@ -56,9 +54,7 @@ std::string FormatDuration(int seconds) { return absl::StrCat(seconds, "s"); } -std::string FormatBool(bool value) { - return value ? "true" : "false"; -} +std::string FormatBool(bool value) { return value ? "true" : "false"; } std::string JoinQuotedList(const std::vector& values) { if (values.empty()) { diff --git a/src/cli/service/testing/test_workflow_generator.cc b/src/cli/service/testing/test_workflow_generator.cc index 31835aae..12bc70e6 100644 --- a/src/cli/service/testing/test_workflow_generator.cc +++ b/src/cli/service/testing/test_workflow_generator.cc @@ -3,14 +3,14 @@ #include "cli/service/testing/test_workflow_generator.h" +#include + #include "absl/strings/ascii.h" #include "absl/strings/match.h" #include "absl/strings/str_cat.h" #include "absl/strings/str_format.h" #include "absl/strings/str_replace.h" -#include - namespace yaze { namespace cli { diff --git a/src/cli/service/testing/test_workflow_generator.h b/src/cli/service/testing/test_workflow_generator.h index b5dfd359..aaebf9d2 100644 --- a/src/cli/service/testing/test_workflow_generator.h +++ b/src/cli/service/testing/test_workflow_generator.h @@ -4,11 +4,11 @@ #ifndef YAZE_CLI_SERVICE_TEST_WORKFLOW_GENERATOR_H #define YAZE_CLI_SERVICE_TEST_WORKFLOW_GENERATOR_H -#include "absl/status/statusor.h" - #include #include +#include "absl/status/statusor.h" + namespace yaze { namespace cli { @@ -49,21 +49,21 @@ struct TestWorkflow { /** * @brief Generates GUI test workflows from natural language prompts - * + * * This class uses pattern matching to convert user prompts into * structured test workflows that can be executed by GuiAutomationClient. - * + * * Example prompts: * - "Open Overworld editor" → Click button, Wait for window * - "Open Dungeon editor and verify it loads" → Click, Wait, Assert * - "Type 'zelda3.sfc' in filename input" → Click input, Type text - * + * * Usage: * @code * TestWorkflowGenerator generator; * auto workflow = generator.GenerateWorkflow("Open Overworld editor"); * if (!workflow.ok()) return workflow.status(); - * + * * for (const auto& step : workflow->steps) { * std::cout << step.ToString() << "\n"; * } diff --git a/src/cli/tui/asar_patch.cc b/src/cli/tui/asar_patch.cc index 83943f3a..3733af9f 100644 --- a/src/cli/tui/asar_patch.cc +++ b/src/cli/tui/asar_patch.cc @@ -29,13 +29,13 @@ ftxui::Component AsarPatchComponent::Render() { auto apply_button = Button("Apply Asar Patch", [state] { if (state->patch_file.empty()) { app_context.error_message = "Please specify an assembly patch file"; - //SwitchComponents(screen, LayoutID::kError); + // SwitchComponents(screen, LayoutID::kError); return; } if (!app_context.rom.is_loaded()) { app_context.error_message = "No ROM loaded. Please load a ROM first."; - //SwitchComponents(screen, LayoutID::kError); + // SwitchComponents(screen, LayoutID::kError); return; } @@ -45,7 +45,7 @@ ftxui::Component AsarPatchComponent::Render() { if (!init_status.ok()) { app_context.error_message = absl::StrCat("Failed to initialize Asar: ", init_status.message()); - //SwitchComponents(screen, LayoutID::kError); + // SwitchComponents(screen, LayoutID::kError); return; } @@ -55,7 +55,7 @@ ftxui::Component AsarPatchComponent::Render() { if (!patch_result.ok()) { app_context.error_message = absl::StrCat("Patch failed: ", patch_result.status().message()); - //SwitchComponents(screen, LayoutID::kError); + // SwitchComponents(screen, LayoutID::kError); return; } @@ -63,7 +63,7 @@ ftxui::Component AsarPatchComponent::Render() { if (!result.success) { app_context.error_message = absl::StrCat("Patch failed: ", absl::StrJoin(result.errors, "; ")); - //SwitchComponents(screen, LayoutID::kError); + // SwitchComponents(screen, LayoutID::kError); return; } @@ -82,7 +82,7 @@ ftxui::Component AsarPatchComponent::Render() { } catch (const std::exception& e) { app_context.error_message = "Exception: " + std::string(e.what()); - //SwitchComponents(screen, LayoutID::kError); + // SwitchComponents(screen, LayoutID::kError); } }); @@ -93,7 +93,7 @@ ftxui::Component AsarPatchComponent::Render() { state->output_message.clear(); state->symbols_list.clear(); state->show_symbols = false; - //SwitchComponents(screen, LayoutID::kMainMenu); + // SwitchComponents(screen, LayoutID::kMainMenu); }); auto container = Container::Vertical({ diff --git a/src/cli/tui/autocomplete_ui.cc b/src/cli/tui/autocomplete_ui.cc index 1ffb2371..e9a37ab8 100644 --- a/src/cli/tui/autocomplete_ui.cc +++ b/src/cli/tui/autocomplete_ui.cc @@ -1,6 +1,7 @@ #include #include #include + #include "cli/util/autocomplete.h" namespace yaze { @@ -43,8 +44,8 @@ Component CreateAutocompleteInput(std::string* input_str, } Component CreateQuickActionMenu(ScreenInteractive& screen) { - // Note: This function is a placeholder for future quick action menu integration. - // Currently not used in the TUI, but kept for API compatibility. + // Note: This function is a placeholder for future quick action menu + // integration. Currently not used in the TUI, but kept for API compatibility. struct MenuState { int selected = 0; std::vector actions = { diff --git a/src/cli/tui/autocomplete_ui.h b/src/cli/tui/autocomplete_ui.h index 8049ead0..3eb5b892 100644 --- a/src/cli/tui/autocomplete_ui.h +++ b/src/cli/tui/autocomplete_ui.h @@ -3,6 +3,7 @@ #include #include + #include "cli/util/autocomplete.h" namespace yaze { @@ -10,7 +11,7 @@ namespace cli { /** * @brief Create an input component with autocomplete suggestions - * + * * @param input_str Pointer to the input string * @param engine Pointer to the autocomplete engine * @return ftxui::Component Input component with autocomplete dropdown @@ -20,7 +21,7 @@ ftxui::Component CreateAutocompleteInput(std::string* input_str, /** * @brief Create a quick action menu for common ROM operations - * + * * @param screen The screen interactive reference * @return ftxui::Component Menu component with quick actions */ diff --git a/src/cli/tui/chat_tui.cc b/src/cli/tui/chat_tui.cc index 6c4b3bda..b1623e9a 100644 --- a/src/cli/tui/chat_tui.cc +++ b/src/cli/tui/chat_tui.cc @@ -81,9 +81,7 @@ ChatTUI::ChatTUI(Rom* rom_context) : rom_context_(rom_context) { "Show ROM info"}; } -ChatTUI::~ChatTUI() { - CleanupWorkers(); -} +ChatTUI::~ChatTUI() { CleanupWorkers(); } void ChatTUI::SetRomContext(Rom* rom_context) { rom_context_ = rom_context; @@ -119,20 +117,15 @@ void ChatTUI::Run() { auto input_component = CreateAutocompleteInput(input_message.get(), &autocomplete_engine_); - auto todo_popup_toggle = [this] { - ToggleTodoPopup(); - }; - auto shortcut_palette_toggle = [this] { - ToggleShortcutPalette(); - }; + auto todo_popup_toggle = [this] { ToggleTodoPopup(); }; + auto shortcut_palette_toggle = [this] { ToggleShortcutPalette(); }; // Handle Enter key BEFORE adding to container input_component = CatchEvent(input_component, [this, input_message, todo_popup_toggle, shortcut_palette_toggle](const Event& event) { if (event == Event::Return) { - if (input_message->empty()) - return true; + if (input_message->empty()) return true; OnSubmit(*input_message); input_message->clear(); return true; @@ -149,8 +142,7 @@ void ChatTUI::Run() { }); auto send_button = Button("Send", [this, input_message] { - if (input_message->empty()) - return; + if (input_message->empty()) return; OnSubmit(*input_message); input_message->clear(); }); diff --git a/src/cli/tui/chat_tui.h b/src/cli/tui/chat_tui.h index c39cd66e..19cc94fe 100644 --- a/src/cli/tui/chat_tui.h +++ b/src/cli/tui/chat_tui.h @@ -11,11 +11,10 @@ #include "cli/service/agent/conversational_agent_service.h" #include "cli/service/agent/todo_manager.h" +#include "cli/util/autocomplete.h" #include "ftxui/component/component.hpp" #include "ftxui/component/screen_interactive.hpp" -#include "cli/util/autocomplete.h" - namespace yaze { class Rom; diff --git a/src/cli/tui/command_palette.cc b/src/cli/tui/command_palette.cc index 5a170e2a..b6ad6504 100644 --- a/src/cli/tui/command_palette.cc +++ b/src/cli/tui/command_palette.cc @@ -17,10 +17,8 @@ using namespace ftxui; namespace { // A simple fuzzy search implementation int fuzzy_match(const std::string& query, const std::string& target) { - if (query.empty()) - return 1; - if (target.empty()) - return 0; + if (query.empty()) return 1; + if (target.empty()) return 0; int score = 0; int query_idx = 0; @@ -63,39 +61,23 @@ Component CommandPaletteComponent::Render() { static std::vector cmds = { {"hex-read", "🔢 Hex", "Read ROM bytes", "--address=0x1C800 --length=16 --format=both", - []() { - return absl::OkStatus(); - }}, + []() { return absl::OkStatus(); }}, {"hex-write", "🔢 Hex", "Write ROM bytes", - "--address=0x1C800 --data=\"FF 00\"", - []() { - return absl::OkStatus(); - }}, + "--address=0x1C800 --data=\"FF 00\"", []() { return absl::OkStatus(); }}, {"hex-search", "🔢 Hex", "Search byte pattern", - "--pattern=\"FF 00 ?? 12\"", - []() { - return absl::OkStatus(); - }}, + "--pattern=\"FF 00 ?? 12\"", []() { return absl::OkStatus(); }}, {"palette-get", "🎨 Palette", "Get palette colors", - "--group=0 --palette=0 --format=hex", - []() { - return absl::OkStatus(); - }}, + "--group=0 --palette=0 --format=hex", []() { return absl::OkStatus(); }}, {"palette-set", "🎨 Palette", "Set palette color", "--group=0 --palette=0 --index=5 --color=FF0000", - []() { - return absl::OkStatus(); - }}, + []() { return absl::OkStatus(); }}, {"palette-analyze", "🎨 Palette", "Analyze palette", - "--type=palette --id=0/0", - []() { - return absl::OkStatus(); - }}, + "--type=palette --id=0/0", []() { return absl::OkStatus(); }}, }; auto search_input = Input(&state->query, "Search commands..."); @@ -230,8 +212,7 @@ Component CommandPaletteComponent::Render() { return true; } if (e == Event::ArrowUp) { - if (state->selected > 0) - state->selected--; + if (state->selected > 0) state->selected--; return true; } if (e == Event::ArrowDown) { diff --git a/src/cli/tui/enhanced_chat_component.cc b/src/cli/tui/enhanced_chat_component.cc index 7292c421..02907072 100644 --- a/src/cli/tui/enhanced_chat_component.cc +++ b/src/cli/tui/enhanced_chat_component.cc @@ -41,9 +41,7 @@ EnhancedChatComponent::EnhancedChatComponent(Rom* rom_context) }; } -Component EnhancedChatComponent::GetComponent() { - return chat_container_; -} +Component EnhancedChatComponent::GetComponent() { return chat_container_; } void EnhancedChatComponent::SetRomContext(Rom* rom_context) { rom_context_ = rom_context; @@ -53,8 +51,7 @@ void EnhancedChatComponent::SetRomContext(Rom* rom_context) { } void EnhancedChatComponent::SendMessage(const std::string& message) { - if (message.empty()) - return; + if (message.empty()) return; ProcessMessage(message); input_message_.clear(); @@ -102,8 +99,7 @@ Component EnhancedChatComponent::CreateChatContainer() { bool EnhancedChatComponent::HandleInputEvents(const Event& event) { if (event == Event::Return) { - if (input_message_.empty()) - return true; + if (input_message_.empty()) return true; SendMessage(input_message_); return true; diff --git a/src/cli/tui/enhanced_status_panel.cc b/src/cli/tui/enhanced_status_panel.cc index caeb6f80..baf4fe50 100644 --- a/src/cli/tui/enhanced_status_panel.cc +++ b/src/cli/tui/enhanced_status_panel.cc @@ -33,34 +33,24 @@ EnhancedStatusPanel::EnhancedStatusPanel(Rom* rom_context) }; } -Component EnhancedStatusPanel::GetComponent() { - return status_container_; -} +Component EnhancedStatusPanel::GetComponent() { return status_container_; } void EnhancedStatusPanel::SetRomContext(Rom* rom_context) { rom_context_ = rom_context; UpdateRomInfo(); } -void EnhancedStatusPanel::UpdateRomInfo() { - CollectRomInfo(); -} +void EnhancedStatusPanel::UpdateRomInfo() { CollectRomInfo(); } -void EnhancedStatusPanel::UpdateSystemInfo() { - CollectSystemInfo(); -} +void EnhancedStatusPanel::UpdateSystemInfo() { CollectSystemInfo(); } -void EnhancedStatusPanel::UpdateLayoutInfo() { - CollectLayoutInfo(); -} +void EnhancedStatusPanel::UpdateLayoutInfo() { CollectLayoutInfo(); } void EnhancedStatusPanel::SetError(const std::string& error) { current_error_ = error; } -void EnhancedStatusPanel::ClearError() { - current_error_.clear(); -} +void EnhancedStatusPanel::ClearError() { current_error_.clear(); } Component EnhancedStatusPanel::CreateStatusContainer() { auto container = Container::Vertical({rom_info_section_, system_info_section_, @@ -225,7 +215,8 @@ void EnhancedStatusPanel::CollectSystemInfo() { } void EnhancedStatusPanel::CollectLayoutInfo() { - // Placeholder layout info (in a real implementation, you'd get this from the layout manager) + // Placeholder layout info (in a real implementation, you'd get this from the + // layout manager) layout_info_.active_panel = "Main Menu"; layout_info_.panel_count = "4"; layout_info_.layout_mode = "Unified"; diff --git a/src/cli/tui/hex_viewer.cc b/src/cli/tui/hex_viewer.cc index fe7c6148..5105f9b1 100644 --- a/src/cli/tui/hex_viewer.cc +++ b/src/cli/tui/hex_viewer.cc @@ -2,6 +2,7 @@ #include #include + #include "absl/strings/str_format.h" namespace yaze { @@ -69,8 +70,7 @@ ftxui::Component HexViewerComponent::Render() { }); component_ = CatchEvent(renderer, [this](const Event& event) { - if (!rom_ || !rom_->is_loaded()) - return false; + if (!rom_ || !rom_->is_loaded()) return false; bool handled = false; if (event == Event::ArrowUp) { @@ -88,8 +88,7 @@ ftxui::Component HexViewerComponent::Render() { offset_ + (lines_to_show_ * 16)); handled = true; } else if (event == Event::Escape || event == Event::Character('b')) { - if (on_back_) - on_back_(); + if (on_back_) on_back_(); handled = true; } diff --git a/src/cli/tui/hex_viewer.h b/src/cli/tui/hex_viewer.h index 10e6a0fa..ccbbae3e 100644 --- a/src/cli/tui/hex_viewer.h +++ b/src/cli/tui/hex_viewer.h @@ -2,6 +2,7 @@ #define YAZE_SRC_CLI_TUI_HEX_VIEWER_H_ #include + #include "app/rom.h" #include "cli/tui/tui_component.h" diff --git a/src/cli/tui/palette_editor.cc b/src/cli/tui/palette_editor.cc index 96b2f5c0..d624cf46 100644 --- a/src/cli/tui/palette_editor.cc +++ b/src/cli/tui/palette_editor.cc @@ -4,6 +4,7 @@ #include #include #include + #include "absl/strings/str_format.h" #include "app/gfx/snes_palette.h" #include "cli/tui/tui.h" @@ -46,7 +47,8 @@ ftxui::Component PaletteEditorComponent::Render() { auto palette_group_menu = Menu(&palette_group_names, &selected_palette_group); // auto save_button = Button("Save", [&] { - // auto& color = ftx_palettes[selected_palette_group][selected_palette][selected_color]; + // auto& color = + // ftx_palettes[selected_palette_group][selected_palette][selected_color]; // color.set_r(std::stoi(r_str)); // color.set_g(std::stoi(g_str)); // color.set_b(std::stoi(b_str)); @@ -75,8 +77,8 @@ ftxui::Component PaletteEditorComponent::Render() { // std::vector color_boxes; // for (int i = 0; i < current_palette.size(); ++i) { // auto& color = current_palette[i]; - // Element element = text(" ") | bgcolor(Color::RGB(color.rgb().x, color.rgb().y, color.rgb().z)); - // if (i == selected_color) { + // Element element = text(" ") | bgcolor(Color::RGB(color.rgb().x, + // color.rgb().y, color.rgb().z)); if (i == selected_color) { // element = element | border; // } // color_boxes.push_back(element); diff --git a/src/cli/tui/tui.cc b/src/cli/tui/tui.cc index 633d1fc5..82c6feaf 100644 --- a/src/cli/tui/tui.cc +++ b/src/cli/tui/tui.cc @@ -1,7 +1,6 @@ #include "tui.h" #include - #include #include #include @@ -38,8 +37,7 @@ bool HandleInput(ftxui::ScreenInteractive& screen, ftxui::Event& event, return true; } if (event == Event::ArrowUp || event == Event::Character('k')) { - if (selected != 0) - selected--; + if (selected != 0) selected--; return true; } if (event == Event::Character('q')) { diff --git a/src/cli/tui/unified_layout.cc b/src/cli/tui/unified_layout.cc index 6db4c78f..57328f43 100644 --- a/src/cli/tui/unified_layout.cc +++ b/src/cli/tui/unified_layout.cc @@ -283,8 +283,7 @@ Component UnifiedLayout::CreateChatPanel() { auto input_component = Input(input_message.get(), "Type your message..."); auto send_button = Button("Send", [this, input_message] { - if (input_message->empty()) - return; + if (input_message->empty()) return; // Handle chat commands if (*input_message == "/exit") { @@ -299,8 +298,7 @@ Component UnifiedLayout::CreateChatPanel() { input_component = CatchEvent(input_component, [this, input_message](const Event& event) { if (event == Event::Return) { - if (input_message->empty()) - return true; + if (input_message->empty()) return true; if (*input_message == "/exit") { screen_.Exit(); diff --git a/src/cli/util/autocomplete.cc b/src/cli/util/autocomplete.cc index 94e500b2..845acfc9 100644 --- a/src/cli/util/autocomplete.cc +++ b/src/cli/util/autocomplete.cc @@ -24,19 +24,15 @@ void AutocompleteEngine::RegisterParameter( int AutocompleteEngine::FuzzyScore(const std::string& text, const std::string& query) { - if (query.empty()) - return 0; + if (query.empty()) return 0; std::string t = text, q = query; std::transform(t.begin(), t.end(), t.begin(), ::tolower); std::transform(q.begin(), q.end(), q.begin(), ::tolower); - if (t == q) - return 1000; - if (t.find(q) == 0) - return 500; - if (t.find(q) != std::string::npos) - return 250; + if (t == q) return 1000; + if (t.find(q) == 0) return 500; + if (t.find(q) != std::string::npos) return 250; // Fuzzy char matching size_t ti = 0, qi = 0; diff --git a/src/cli/util/terminal_colors.h b/src/cli/util/terminal_colors.h index 4978fd07..751b1bd9 100644 --- a/src/cli/util/terminal_colors.h +++ b/src/cli/util/terminal_colors.h @@ -69,8 +69,7 @@ class LoadingIndicator { ~LoadingIndicator() { Stop(); } void Start() { - if (!show_ || running_) - return; + if (!show_ || running_) return; running_ = true; thread_ = std::thread([this]() { diff --git a/src/core/asar_wrapper.cc b/src/core/asar_wrapper.cc index 2d612ba2..c523c8e7 100644 --- a/src/core/asar_wrapper.cc +++ b/src/core/asar_wrapper.cc @@ -17,17 +17,11 @@ absl::Status AsarWrapper::Initialize() { "ASAR library not available - build needs fixing"); } -void AsarWrapper::Shutdown() { - initialized_ = false; -} +void AsarWrapper::Shutdown() { initialized_ = false; } -std::string AsarWrapper::GetVersion() const { - return "ASAR disabled"; -} +std::string AsarWrapper::GetVersion() const { return "ASAR disabled"; } -int AsarWrapper::GetApiVersion() const { - return 0; -} +int AsarWrapper::GetApiVersion() const { return 0; } void AsarWrapper::Reset() { symbol_table_.clear(); diff --git a/src/core/asar_wrapper_stub.cc b/src/core/asar_wrapper_stub.cc index 383e6368..060e182f 100644 --- a/src/core/asar_wrapper_stub.cc +++ b/src/core/asar_wrapper_stub.cc @@ -1,6 +1,5 @@ -#include "core/asar_wrapper.h" - #include "absl/strings/str_format.h" +#include "core/asar_wrapper.h" // Temporary stub implementation until ASAR library build is fixed // All methods return UnimplementedError @@ -17,21 +16,13 @@ absl::Status AsarWrapper::Initialize() { "ASAR library not available - build needs fixing"); } -void AsarWrapper::Shutdown() { - initialized_ = false; -} +void AsarWrapper::Shutdown() { initialized_ = false; } -std::string AsarWrapper::GetVersion() const { - return "ASAR disabled"; -} +std::string AsarWrapper::GetVersion() const { return "ASAR disabled"; } -int AsarWrapper::GetApiVersion() const { - return 0; -} +int AsarWrapper::GetApiVersion() const { return 0; } -void AsarWrapper::Reset() { - patches_applied_.clear(); -} +void AsarWrapper::Reset() { patches_applied_.clear(); } absl::Status AsarWrapper::ApplyPatch( const std::string& patch_content, std::vector& rom_data, diff --git a/src/core/features.h b/src/core/features.h index e79fe451..1c5a3001 100644 --- a/src/core/features.h +++ b/src/core/features.h @@ -14,8 +14,8 @@ class FeatureFlags { public: struct Flags { // REMOVED: kLogInstructions - DisassemblyViewer is now always enabled - // It uses sparse address-map recording (Mesen-style) with zero performance impact - // Recording can be disabled per-viewer via UI if needed + // It uses sparse address-map recording (Mesen-style) with zero performance + // impact Recording can be disabled per-viewer via UI if needed // Flag to enable the saving of all palettes to the Rom. bool kSaveAllPalettes = false; @@ -43,7 +43,8 @@ class FeatureFlags { // Enable the new tiered graphics architecture. bool kEnableTieredGfxArchitecture = true; - // Use NFD (Native File Dialog) instead of bespoke file dialog implementation. + // Use NFD (Native File Dialog) instead of bespoke file dialog + // implementation. #if defined(YAZE_ENABLE_NFD) && YAZE_ENABLE_NFD bool kUseNativeFileDialog = true; #else @@ -70,8 +71,9 @@ class FeatureFlags { // Save overworld properties to the Rom. bool kSaveOverworldProperties = true; - // Enable custom overworld features for vanilla ROMs or override detection. - // If ZSCustomOverworld ASM is already applied, features are auto-enabled. + // Enable custom overworld features for vanilla ROMs or override + // detection. If ZSCustomOverworld ASM is already applied, features are + // auto-enabled. bool kLoadCustomOverworld = false; // Apply ZSCustomOverworld ASM patches when upgrading ROM versions. diff --git a/src/core/project.cc b/src/core/project.cc index bd0145d5..9d8bb3a9 100644 --- a/src/core/project.cc +++ b/src/core/project.cc @@ -29,8 +29,7 @@ namespace { // Helper functions for parsing key-value pairs std::pair ParseKeyValue(const std::string& line) { size_t eq_pos = line.find('='); - if (eq_pos == std::string::npos) - return {"", ""}; + if (eq_pos == std::string::npos) return {"", ""}; std::string key = line.substr(0, eq_pos); std::string value = line.substr(eq_pos + 1); @@ -58,8 +57,7 @@ float ParseFloat(const std::string& value) { std::vector ParseStringList(const std::string& value) { std::vector result; - if (value.empty()) - return result; + if (value.empty()) return result; std::vector parts = absl::StrSplit(value, ','); for (const auto& part : parts) { @@ -150,9 +148,7 @@ absl::Status YazeProject::Open(const std::string& project_path) { return absl::InvalidArgumentError("Unsupported project file format"); } -absl::Status YazeProject::Save() { - return SaveToYazeFormat(); -} +absl::Status YazeProject::Save() { return SaveToYazeFormat(); } absl::Status YazeProject::SaveAs(const std::string& new_path) { std::string old_filepath = filepath; @@ -178,8 +174,7 @@ absl::Status YazeProject::LoadFromYazeFormat(const std::string& project_path) { while (std::getline(file, line)) { // Skip empty lines and comments - if (line.empty() || line[0] == '#') - continue; + if (line.empty() || line[0] == '#') continue; // Check for section headers [section_name] if (line[0] == '[' && line.back() == ']') { @@ -188,8 +183,7 @@ absl::Status YazeProject::LoadFromYazeFormat(const std::string& project_path) { } auto [key, value] = ParseKeyValue(line); - if (key.empty()) - continue; + if (key.empty()) continue; // Parse based on current section if (current_section == "project") { @@ -239,7 +233,8 @@ absl::Status YazeProject::LoadFromYazeFormat(const std::string& project_path) { feature_flags.kSaveDungeonMaps = ParseBool(value); else if (key == "save_graphics_sheet") feature_flags.kSaveGraphicsSheet = ParseBool(value); - // REMOVED: log_instructions (deprecated - DisassemblyViewer always active) + // REMOVED: log_instructions (deprecated - DisassemblyViewer always + // active) } else if (current_section == "workspace") { if (key == "font_global_scale") workspace_settings.font_global_scale = ParseFloat(value); @@ -596,12 +591,9 @@ absl::Status YazeProject::ResetToDefaults() { absl::Status YazeProject::Validate() const { std::vector errors; - if (name.empty()) - errors.push_back("Project name is required"); - if (filepath.empty()) - errors.push_back("Project file path is required"); - if (rom_filename.empty()) - errors.push_back("ROM file is required"); + if (name.empty()) errors.push_back("Project name is required"); + if (filepath.empty()) errors.push_back("Project file path is required"); + if (rom_filename.empty()) errors.push_back("ROM file is required"); // Check if files exist if (!rom_filename.empty() && @@ -683,8 +675,7 @@ std::string YazeProject::GetDisplayName() const { std::string YazeProject::GetRelativePath( const std::string& absolute_path) const { - if (absolute_path.empty() || filepath.empty()) - return absolute_path; + if (absolute_path.empty() || filepath.empty()) return absolute_path; std::filesystem::path project_dir = std::filesystem::path(filepath).parent_path(); @@ -701,8 +692,7 @@ std::string YazeProject::GetRelativePath( std::string YazeProject::GetAbsolutePath( const std::string& relative_path) const { - if (relative_path.empty() || filepath.empty()) - return relative_path; + if (relative_path.empty() || filepath.empty()) return relative_path; std::filesystem::path project_dir = std::filesystem::path(filepath).parent_path(); @@ -717,8 +707,8 @@ bool YazeProject::IsEmpty() const { absl::Status YazeProject::ImportFromZScreamFormat( const std::string& project_path) { - // TODO: Implement ZScream format parsing when format specification is available - // For now, create a basic project that can be manually configured + // TODO: Implement ZScream format parsing when format specification is + // available For now, create a basic project that can be manually configured std::filesystem::path zs_path(project_path); name = zs_path.stem().string() + "_imported"; @@ -798,7 +788,6 @@ ProjectManager::GetProjectTemplates() { absl::StatusOr ProjectManager::CreateFromTemplate( const std::string& template_name, const std::string& project_name, const std::string& base_path) { - YazeProject project; auto status = project.Create(project_name, base_path); if (!status.ok()) { @@ -938,8 +927,7 @@ bool ResourceLabelManager::LoadLabels(const std::string& filename) { std::string current_type = ""; while (std::getline(file, line)) { - if (line.empty() || line[0] == '#') - continue; + if (line.empty() || line[0] == '#') continue; // Check for type headers [type_name] if (line[0] == '[' && line.back() == ']') { @@ -962,12 +950,10 @@ bool ResourceLabelManager::LoadLabels(const std::string& filename) { } bool ResourceLabelManager::SaveLabels() { - if (filename_.empty()) - return false; + if (filename_.empty()) return false; std::ofstream file(filename_); - if (!file.is_open()) - return false; + if (!file.is_open()) return false; file << "# yaze Resource Labels\n"; file << "# Format: [type] followed by key=value pairs\n\n"; @@ -987,8 +973,7 @@ bool ResourceLabelManager::SaveLabels() { } void ResourceLabelManager::DisplayLabels(bool* p_open) { - if (!p_open || !*p_open) - return; + if (!p_open || !*p_open) return; // Basic implementation - can be enhanced later if (ImGui::Begin("Resource Labels", p_open)) { @@ -1030,12 +1015,10 @@ void ResourceLabelManager::SelectableLabelWithNameEdit( std::string ResourceLabelManager::GetLabel(const std::string& type, const std::string& key) { auto type_it = labels_.find(type); - if (type_it == labels_.end()) - return ""; + if (type_it == labels_.end()) return ""; auto label_it = type_it->second.find(key); - if (label_it == type_it->second.end()) - return ""; + if (label_it == type_it->second.end()) return ""; return label_it->second; } @@ -1044,8 +1027,7 @@ std::string ResourceLabelManager::CreateOrGetLabel( const std::string& type, const std::string& key, const std::string& defaultValue) { auto existing = GetLabel(type, key); - if (!existing.empty()) - return existing; + if (!existing.empty()) return existing; labels_[type][key] = defaultValue; return defaultValue; @@ -1132,8 +1114,7 @@ absl::Status YazeProject::LoadFromJsonFormat(const std::string& project_path) { if (j.contains("yaze_project")) { auto& proj = j["yaze_project"]; - if (proj.contains("name")) - name = proj["name"].get(); + if (proj.contains("name")) name = proj["name"].get(); if (proj.contains("description")) metadata.description = proj["description"].get(); if (proj.contains("author")) @@ -1167,7 +1148,8 @@ absl::Status YazeProject::LoadFromJsonFormat(const std::string& project_path) { // Feature flags if (proj.contains("feature_flags")) { auto& flags = proj["feature_flags"]; - // REMOVED: kLogInstructions (deprecated - DisassemblyViewer always active) + // REMOVED: kLogInstructions (deprecated - DisassemblyViewer always + // active) if (flags.contains("kSaveDungeonMaps")) feature_flags.kSaveDungeonMaps = flags["kSaveDungeonMaps"].get(); diff --git a/src/core/project.h b/src/core/project.h index 94001408..2a40a910 100644 --- a/src/core/project.h +++ b/src/core/project.h @@ -100,7 +100,8 @@ struct YazeProject { std::unordered_map> resource_labels; - // Embedded labels flag - when true, resource_labels contains all default Zelda3 labels + // Embedded labels flag - when true, resource_labels contains all default + // Zelda3 labels bool use_embedded_labels = true; // Build and deployment diff --git a/src/lib/imgui_memory_editor.h b/src/lib/imgui_memory_editor.h index 9d2596be..53cac8f9 100644 --- a/src/lib/imgui_memory_editor.h +++ b/src/lib/imgui_memory_editor.h @@ -4,7 +4,8 @@ // Right-click anywhere to access the Options menu! // You can adjust the keyboard repeat delay/rate in ImGuiIO. // The code assume a mono-space font for simplicity! -// If you don't use the default font, use ImGui::PushFont()/PopFont() to switch to a mono-space font before calling this. +// If you don't use the default font, use ImGui::PushFont()/PopFont() to switch +// to a mono-space font before calling this. // // Usage: // // Create a window and draw memory editor inside it: @@ -22,29 +23,49 @@ // // Changelog: // - v0.10: initial version -// - v0.23 (2017/08/17): added to github. fixed right-arrow triggering a byte write. -// - v0.24 (2018/06/02): changed DragInt("Rows" to use a %d data format (which is desirable since imgui 1.61). -// - v0.25 (2018/07/11): fixed wording: all occurrences of "Rows" renamed to "Columns". +// - v0.23 (2017/08/17): added to github. fixed right-arrow triggering a byte +// write. +// - v0.24 (2018/06/02): changed DragInt("Rows" to use a %d data format (which +// is desirable since imgui 1.61). +// - v0.25 (2018/07/11): fixed wording: all occurrences of "Rows" renamed to +// "Columns". // - v0.26 (2018/08/02): fixed clicking on hex region // - v0.30 (2018/08/02): added data preview for common data types -// - v0.31 (2018/10/10): added OptUpperCaseHex option to select lower/upper casing display [@samhocevar] -// - v0.32 (2018/10/10): changed signatures to use void* instead of unsigned char* -// - v0.33 (2018/10/10): added OptShowOptions option to hide all the interactive option setting. -// - v0.34 (2019/05/07): binary preview now applies endianness setting [@nicolasnoble] +// - v0.31 (2018/10/10): added OptUpperCaseHex option to select lower/upper +// casing display [@samhocevar] +// - v0.32 (2018/10/10): changed signatures to use void* instead of unsigned +// char* +// - v0.33 (2018/10/10): added OptShowOptions option to hide all the interactive +// option setting. +// - v0.34 (2019/05/07): binary preview now applies endianness setting +// [@nicolasnoble] // - v0.35 (2020/01/29): using ImGuiDataType available since Dear ImGui 1.69. // - v0.36 (2020/05/05): minor tweaks, minor refactor. -// - v0.40 (2020/10/04): fix misuse of ImGuiListClipper API, broke with Dear ImGui 1.79. made cursor position appears on left-side of edit box. option popup appears on mouse release. fix MSVC warnings where _CRT_SECURE_NO_WARNINGS wasn't working in recent versions. -// - v0.41 (2020/10/05): fix when using with keyboard/gamepad navigation enabled. -// - v0.42 (2020/10/14): fix for . character in ASCII view always being greyed out. -// - v0.43 (2021/03/12): added OptFooterExtraHeight to allow for custom drawing at the bottom of the editor [@leiradel] -// - v0.44 (2021/03/12): use ImGuiInputTextFlags_AlwaysOverwrite in 1.82 + fix hardcoded width. -// - v0.50 (2021/11/12): various fixes for recent dear imgui versions (fixed misuse of clipper, relying on SetKeyboardFocusHere() handling scrolling from 1.85). added default size. +// - v0.40 (2020/10/04): fix misuse of ImGuiListClipper API, broke with Dear +// ImGui 1.79. made cursor position appears on left-side of edit box. option +// popup appears on mouse release. fix MSVC warnings where +// _CRT_SECURE_NO_WARNINGS wasn't working in recent versions. +// - v0.41 (2020/10/05): fix when using with keyboard/gamepad navigation +// enabled. +// - v0.42 (2020/10/14): fix for . character in ASCII view always being greyed +// out. +// - v0.43 (2021/03/12): added OptFooterExtraHeight to allow for custom drawing +// at the bottom of the editor [@leiradel] +// - v0.44 (2021/03/12): use ImGuiInputTextFlags_AlwaysOverwrite in 1.82 + fix +// hardcoded width. +// - v0.50 (2021/11/12): various fixes for recent dear imgui versions (fixed +// misuse of clipper, relying on SetKeyboardFocusHere() handling scrolling +// from 1.85). added default size. // // Todo/Bugs: -// - This is generally old/crappy code, it should work but isn't very good.. to be rewritten some day. -// - PageUp/PageDown are supported because we use _NoNav. This is a good test scenario for working out idioms of how to mix natural nav and our own... -// - Arrows are being sent to the InputText() about to disappear which for LeftArrow makes the text cursor appear at position 1 for one frame. -// - Using InputText() is awkward and maybe overkill here, consider implementing something custom. +// - This is generally old/crappy code, it should work but isn't very good.. to +// be rewritten some day. +// - PageUp/PageDown are supported because we use _NoNav. This is a good test +// scenario for working out idioms of how to mix natural nav and our own... +// - Arrows are being sent to the InputText() about to disappear which for +// LeftArrow makes the text cursor appear at position 1 for one frame. +// - Using InputText() is awkward and maybe overkill here, consider implementing +// something custom. #pragma once @@ -61,8 +82,8 @@ #ifdef _MSC_VER #pragma warning(push) -#pragma warning( \ - disable : 4996) // warning C4996: 'sprintf': This function or variable may be unsafe. +#pragma warning(disable : 4996) // warning C4996: 'sprintf': This function or + // variable may be unsafe. #endif struct MemoryEditor { @@ -74,26 +95,32 @@ struct MemoryEditor { }; // Settings - bool - Open; // = true // set to false when DrawWindow() was closed. ignore if not using DrawWindow(). - bool ReadOnly; // = false // disable any editing. - int Cols; // = 16 // number of columns to display. - bool - OptShowOptions; // = true // display options button/context menu. when disabled, options will be locked unless you provide your own UI for them. - bool - OptShowDataPreview; // = false // display a footer previewing the decimal/binary/hex/float representation of the currently selected bytes. - bool - OptShowHexII; // = false // display values in HexII representation instead of regular hexadecimal: hide null/zero bytes, ascii values as ".X". - bool - OptShowAscii; // = true // display ASCII representation on the right side. - bool - OptGreyOutZeroes; // = true // display null/zero bytes using the TextDisabled color. - bool - OptUpperCaseHex; // = true // display hexadecimal values as "FF" instead of "ff". - int OptMidColsCount; // = 8 // set to 0 to disable extra spacing between every mid-cols. - int OptAddrDigitsCount; // = 0 // number of addr digits to display (default calculated based on maximum displayed addr). - float - OptFooterExtraHeight; // = 0 // space to reserve at the bottom of the widget to add custom widgets + bool Open; // = true // set to false when DrawWindow() was closed. ignore + // if not using DrawWindow(). + bool ReadOnly; // = false // disable any editing. + int Cols; // = 16 // number of columns to display. + bool OptShowOptions; // = true // display options button/context menu. when + // disabled, options will be locked unless you provide + // your own UI for them. + bool OptShowDataPreview; // = false // display a footer previewing the + // decimal/binary/hex/float representation of the + // currently selected bytes. + bool OptShowHexII; // = false // display values in HexII representation + // instead of regular hexadecimal: hide null/zero bytes, + // ascii values as ".X". + bool OptShowAscii; // = true // display ASCII representation on the right + // side. + bool OptGreyOutZeroes; // = true // display null/zero bytes using the + // TextDisabled color. + bool OptUpperCaseHex; // = true // display hexadecimal values as "FF" + // instead of "ff". + int OptMidColsCount; // = 8 // set to 0 to disable extra spacing between + // every mid-cols. + int OptAddrDigitsCount; // = 0 // number of addr digits to display + // (default calculated based on maximum displayed + // addr). + float OptFooterExtraHeight; // = 0 // space to reserve at the bottom of + // the widget to add custom widgets ImU32 HighlightColor; // // background color of highlighted bytes. ImU8 (*ReadFn)(const ImU8* data, size_t off); // = 0 // optional handler to read bytes. @@ -101,8 +128,8 @@ struct MemoryEditor { ImU8 d); // = 0 // optional handler to write bytes. bool (*HighlightFn)( const ImU8* data, - size_t - off); //= 0 // optional handler to return Highlight property (to support non-contiguous highlighting). + size_t off); //= 0 // optional handler to return Highlight property + //(to support non-contiguous highlighting). // [Internal State] bool ContentsWidthChanged; @@ -184,10 +211,11 @@ struct MemoryEditor { ImGui::CalcTextSize("F").x + 1; // We assume the font is mono-space s.HexCellWidth = (float)(int)(s.GlyphWidth * - 2.5f); // "FF " we include trailing space in the width to easily catch clicks everywhere + 2.5f); // "FF " we include trailing space in the width to + // easily catch clicks everywhere s.SpacingBetweenMidCols = - (float)(int)(s.HexCellWidth * - 0.25f); // Every OptMidColsCount columns we add a bit of extra spacing + (float)(int)(s.HexCellWidth * 0.25f); // Every OptMidColsCount columns + // we add a bit of extra spacing s.PosHexStart = (s.AddrDigitsCount + 2) * s.GlyphWidth; s.PosHexEnd = s.PosHexStart + (s.HexCellWidth * Cols); s.PosAsciiStart = s.PosAsciiEnd = s.PosHexEnd; @@ -230,16 +258,17 @@ struct MemoryEditor { // Memory Editor contents only void DrawContents(void* mem_data_void, size_t mem_size, size_t base_display_addr = 0x0000) { - if (Cols < 1) - Cols = 1; + if (Cols < 1) Cols = 1; ImU8* mem_data = (ImU8*)mem_data_void; Sizes s; CalcSizes(s, mem_size, base_display_addr); ImGuiStyle& style = ImGui::GetStyle(); - // We begin into our scrolling region with the 'ImGuiWindowFlags_NoMove' in order to prevent click from moving the window. - // This is used as a facility since our main click detection code doesn't assign an ActiveId so the click would normally be caught as a window-move. + // We begin into our scrolling region with the 'ImGuiWindowFlags_NoMove' in + // order to prevent click from moving the window. This is used as a facility + // since our main click detection code doesn't assign an ActiveId so the + // click would normally be caught as a window-move. const float height_separator = style.ItemSpacing.y; float footer_height = OptFooterExtraHeight; if (OptShowOptions) @@ -256,17 +285,16 @@ struct MemoryEditor { ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(0, 0)); ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(0, 0)); - // We are not really using the clipper API correctly here, because we rely on visible_start_addr/visible_end_addr for our scrolling function. + // We are not really using the clipper API correctly here, because we rely + // on visible_start_addr/visible_end_addr for our scrolling function. const int line_total_count = (int)((mem_size + Cols - 1) / Cols); ImGuiListClipper clipper; clipper.Begin(line_total_count, s.LineHeight); bool data_next = false; - if (ReadOnly || DataEditingAddr >= mem_size) - DataEditingAddr = (size_t)-1; - if (DataPreviewAddr >= mem_size) - DataPreviewAddr = (size_t)-1; + if (ReadOnly || DataEditingAddr >= mem_size) DataEditingAddr = (size_t)-1; + if (DataPreviewAddr >= mem_size) DataPreviewAddr = (size_t)-1; size_t preview_data_type_size = OptShowDataPreview ? DataTypeGetSize(PreviewDataType) : 0; @@ -390,15 +418,20 @@ struct MemoryEditor { ReadFn ? ReadFn(mem_data, addr) : mem_data[addr]); } struct UserData { - // FIXME: We should have a way to retrieve the text edit cursor position more easily in the API, this is rather tedious. This is such a ugly mess we may be better off not using InputText() at all here. + // FIXME: We should have a way to retrieve the text edit cursor + // position more easily in the API, this is rather tedious. This + // is such a ugly mess we may be better off not using InputText() + // at all here. static int Callback(ImGuiInputTextCallbackData* data) { UserData* user_data = (UserData*)data->UserData; if (!data->HasSelection()) user_data->CursorPos = data->CursorPos; if (data->SelectionStart == 0 && data->SelectionEnd == data->BufTextLen) { - // When not editing a byte, always refresh its InputText content pulled from underlying memory data - // (this is a bit tricky, since InputText technically "owns" the master copy of the buffer we edit it in there) + // When not editing a byte, always refresh its InputText + // content pulled from underlying memory data (this is a bit + // tricky, since InputText technically "owns" the master copy + // of the buffer we edit it in there) data->DeleteChars(0, data->BufTextLen); data->InsertChars(0, user_data->CurrentBufOverwrite); data->SelectionStart = 0; @@ -432,8 +465,7 @@ struct MemoryEditor { else if (!DataEditingTakeFocus && !ImGui::IsItemActive()) DataEditingAddr = data_editing_addr_next = (size_t)-1; DataEditingTakeFocus = false; - if (user_data.CursorPos >= 2) - data_write = data_next = true; + if (user_data.CursorPos >= 2) data_write = data_next = true; if (data_editing_addr_next != (size_t)-1) data_write = data_next = false; unsigned int data_input_value = 0; @@ -446,7 +478,8 @@ struct MemoryEditor { } ImGui::PopID(); } else { - // NB: The trailing space is not visible but ensure there's no gap that the mouse cannot click on. + // NB: The trailing space is not visible but ensure there's no gap + // that the mouse cannot click on. ImU8 b = ReadFn ? ReadFn(mem_data, addr) : mem_data[addr]; if (OptShowHexII) { @@ -508,7 +541,8 @@ struct MemoryEditor { ImGui::PopStyleVar(2); ImGui::EndChild(); - // Notify the main window of our ideal child content size (FIXME: we are missing an API to get the contents size from the child) + // Notify the main window of our ideal child content size (FIXME: we are + // missing an API to get the contents size from the child) ImGui::SetCursorPosX(s.WindowWidth); if (data_next && DataEditingAddr + 1 < mem_size) { @@ -540,14 +574,12 @@ struct MemoryEditor { : "Range %0*" _PRISizeT "x..%0*" _PRISizeT "x"; // Options menu - if (ImGui::Button("Options")) - ImGui::OpenPopup("context"); + if (ImGui::Button("Options")) ImGui::OpenPopup("context"); if (ImGui::BeginPopup("context")) { ImGui::SetNextItemWidth(s.GlyphWidth * 7 + style.FramePadding.x * 2.0f); if (ImGui::DragInt("##cols", &Cols, 0.2f, 4, 32, "%d cols")) { ContentsWidthChanged = true; - if (Cols < 1) - Cols = 1; + if (Cols < 1) Cols = 1; } ImGui::Checkbox("Show Data Preview", &OptShowDataPreview); ImGui::Checkbox("Show HexII", &OptShowHexII); @@ -672,8 +704,7 @@ struct MemoryEditor { if (is_little_endian) { uint8_t* dst = (uint8_t*)_dst; uint8_t* src = (uint8_t*)_src + s - 1; - for (int i = 0, n = (int)s; i < n; ++i) - memcpy(dst++, src--, 1); + for (int i = 0, n = (int)s; i < n; ++i) memcpy(dst++, src--, 1); return _dst; } else { return memcpy(_dst, _src, s); @@ -687,8 +718,7 @@ struct MemoryEditor { } else { uint8_t* dst = (uint8_t*)_dst; uint8_t* src = (uint8_t*)_src + s - 1; - for (int i = 0, n = (int)s; i < n; ++i) - memcpy(dst++, src--, 1); + for (int i = 0, n = (int)s; i < n; ++i) memcpy(dst++, src--, 1); return _dst; } } diff --git a/src/util/bps.cc b/src/util/bps.cc index b49a4f38..833139b2 100644 --- a/src/util/bps.cc +++ b/src/util/bps.cc @@ -66,8 +66,7 @@ uint64_t decode(const std::vector& data, size_t& offset) { while (offset < data.size()) { uint8_t x = data[offset++]; result |= (uint64_t)(x & 0x7f) << shift; - if (x & 0x80) - break; + if (x & 0x80) break; shift += 7; } return result; diff --git a/src/util/file_util.cc b/src/util/file_util.cc index 451f957d..56fb35b2 100644 --- a/src/util/file_util.cc +++ b/src/util/file_util.cc @@ -76,12 +76,14 @@ std::string GetResourcePath(const std::string& resource_path) { return GetBundleResourcePath() + "Contents/Resources/" + resource_path; #endif #else - return resource_path; // On Linux/Windows, resources are relative to executable + return resource_path; // On Linux/Windows, resources are relative to + // executable #endif } -// Note: FileDialogWrapper implementations are in src/app/platform/file_dialog.mm -// (platform-specific implementations to avoid duplicate symbols) +// Note: FileDialogWrapper implementations are in +// src/app/platform/file_dialog.mm (platform-specific implementations to avoid +// duplicate symbols) } // namespace util } // namespace yaze \ No newline at end of file diff --git a/src/util/file_util.h b/src/util/file_util.h index c826ba7e..54eb1552 100644 --- a/src/util/file_util.h +++ b/src/util/file_util.h @@ -56,7 +56,7 @@ enum class Platform { kUnknown, kMacOS, kiOS, kWindows, kLinux }; /** * @brief Gets the file extension from a filename. - * + * * Uses std::filesystem for cross-platform consistency. * * @param filename The name of the file. @@ -66,7 +66,7 @@ std::string GetFileExtension(const std::string& filename); /** * @brief Gets the filename from a full path. - * + * * Uses std::filesystem for cross-platform consistency. * * @param filename The full path to the file. @@ -77,21 +77,21 @@ std::string GetResourcePath(const std::string& resource_path); void SaveFile(const std::string& filename, const std::string& data); /** - * @brief Loads the entire contents of a file into a string. - * - * Throws a std::runtime_error if the file cannot be opened. - * - * @param filename The full, absolute path to the file. - * @return The contents of the file as a string. - */ + * @brief Loads the entire contents of a file into a string. + * + * Throws a std::runtime_error if the file cannot be opened. + * + * @param filename The full, absolute path to the file. + * @return The contents of the file as a string. + */ std::string LoadFile(const std::string& filename); /** - * @brief Loads a file from the user's config directory. - * - * @param filename The name of the file inside the config directory. - * @return The contents of the file, or an empty string if not found. - */ + * @brief Loads a file from the user's config directory. + * + * @param filename The name of the file inside the config directory. + * @return The contents of the file, or an empty string if not found. + */ std::string LoadFileFromConfigDir(const std::string& filename); } // namespace util diff --git a/src/util/hyrule_magic.cc b/src/util/hyrule_magic.cc index a029dd2d..41df07c8 100644 --- a/src/util/hyrule_magic.cc +++ b/src/util/hyrule_magic.cc @@ -35,24 +35,16 @@ void stle3(uint8_t* const p_arr, unsigned const p_val) { } // Helper function to get the first byte in a little endian number -uint32_t ldle0(uint8_t const* const p_arr) { - return ldle(p_arr, 0); -} +uint32_t ldle0(uint8_t const* const p_arr) { return ldle(p_arr, 0); } // Helper function to get the second byte in a little endian number -uint32_t ldle1(uint8_t const* const p_arr) { - return ldle(p_arr, 1); -} +uint32_t ldle1(uint8_t const* const p_arr) { return ldle(p_arr, 1); } // Helper function to get the third byte in a little endian number -uint32_t ldle2(uint8_t const* const p_arr) { - return ldle(p_arr, 2); -} +uint32_t ldle2(uint8_t const* const p_arr) { return ldle(p_arr, 2); } // Helper function to get the third byte in a little endian number -uint32_t ldle3(uint8_t const* const p_arr) { - return ldle(p_arr, 3); -} +uint32_t ldle3(uint8_t const* const p_arr) { return ldle(p_arr, 3); } } // namespace diff --git a/src/util/log.cc b/src/util/log.cc index bed17941..5520185f 100644 --- a/src/util/log.cc +++ b/src/util/log.cc @@ -54,15 +54,15 @@ void LogManager::configure(LogLevel level, const std::string& file_path, // Log which categories are enabled for debugging std::string category_list; for (const auto& cat : categories) { - if (!category_list.empty()) - category_list += ", "; + if (!category_list.empty()) category_list += ", "; category_list += cat; } std::cerr << "Log categories filter enabled: [" << category_list << "]" << std::endl; } - // If a file path is provided, close any existing stream and open the new file. + // If a file path is provided, close any existing stream and open the new + // file. if (!file_path.empty() && file_path != log_file_path_) { if (log_stream_.is_open()) { log_stream_.close(); diff --git a/src/util/macro.h b/src/util/macro.h index 256ac07d..30a3c401 100644 --- a/src/util/macro.h +++ b/src/util/macro.h @@ -21,9 +21,8 @@ using uint = unsigned int; ImGui::EndTable(); \ } -#define HOVER_HINT(string) \ - if (ImGui::IsItemHovered()) \ - ImGui::SetTooltip(string) +#define HOVER_HINT(string) \ + if (ImGui::IsItemHovered()) ImGui::SetTooltip(string) #define PRINT_IF_ERROR(expression) \ { \ diff --git a/src/util/platform_paths.cc b/src/util/platform_paths.cc index 2d3ac980..156a7b8d 100644 --- a/src/util/platform_paths.cc +++ b/src/util/platform_paths.cc @@ -11,6 +11,7 @@ #else #include #include + #include // For PATH_MAX #ifdef __APPLE__ #include // For _NSGetExecutablePath diff --git a/src/util/platform_paths.h b/src/util/platform_paths.h index 7a117dcd..588c09d3 100644 --- a/src/util/platform_paths.h +++ b/src/util/platform_paths.h @@ -11,7 +11,7 @@ namespace util { /** * @brief Cross-platform utilities for file system paths - * + * * Provides consistent, platform-independent file and directory operations * that work correctly on Windows (MSVC), macOS, and Linux. */ @@ -19,11 +19,11 @@ class PlatformPaths { public: /** * @brief Get the user's home directory in a cross-platform way - * + * * - Windows: Uses USERPROFILE environment variable * - Unix/macOS: Uses HOME environment variable * - Fallback: Returns current directory - * + * * @return Path to user's home directory, or "." if not available */ static std::filesystem::path GetHomeDirectory(); @@ -56,9 +56,9 @@ class PlatformPaths { /** * @brief Get a subdirectory within the app data folder - * + * * Creates the directory if it doesn't exist. - * + * * @param subdir Subdirectory name (e.g., "agent", "cache", "logs") * @return StatusOr with path to subdirectory */ @@ -67,9 +67,9 @@ class PlatformPaths { /** * @brief Ensure a directory exists, creating it if necessary - * + * * Uses std::filesystem::create_directories which works cross-platform. - * + * * @param path Directory path to create * @return OK if directory exists or was created successfully */ @@ -77,7 +77,7 @@ class PlatformPaths { /** * @brief Check if a file or directory exists - * + * * @param path Path to check * @return true if exists, false otherwise */ @@ -85,20 +85,20 @@ class PlatformPaths { /** * @brief Get a temporary directory for the application - * + * * - Windows: %TEMP%\yaze * - Unix: /tmp/yaze or $TMPDIR/yaze - * + * * @return StatusOr with path to temp directory */ static absl::StatusOr GetTempDirectory(); /** * @brief Normalize path separators for display - * + * * Converts all path separators to forward slashes for consistent * output in logs and UI (forward slashes work on all platforms). - * + * * @param path Path to normalize * @return Normalized path string */ @@ -106,9 +106,9 @@ class PlatformPaths { /** * @brief Convert path to native format - * + * * Ensures path uses the correct separator for the current platform. - * + * * @param path Path to convert * @return Native path string */ @@ -116,16 +116,17 @@ class PlatformPaths { /** * @brief Find an asset file in multiple standard locations - * + * * Searches for an asset file in the following order: * 1. YAZE_ASSETS_PATH (if defined at compile time) + relative_path - * 2. Current working directory + assets/ + relative_path + * 2. Current working directory + assets/ + relative_path * 3. Executable directory + assets/ + relative_path * 4. Parent directory + assets/ + relative_path * 5. ~/.yaze/assets/ + relative_path (user-installed assets) * 6. /usr/local/share/yaze/assets/ + relative_path (system-wide on Unix) - * - * @param relative_path Path relative to assets directory (e.g., "agent/prompt_catalogue.yaml") + * + * @param relative_path Path relative to assets directory (e.g., + * "agent/prompt_catalogue.yaml") * @return StatusOr with absolute path to found asset file */ static absl::StatusOr FindAsset( diff --git a/src/yaze.cc b/src/yaze.cc index 437ca459..0381f5d1 100644 --- a/src/yaze.cc +++ b/src/yaze.cc @@ -60,13 +60,9 @@ const char* yaze_status_to_string(yaze_status status) { } } -const char* yaze_get_version_string() { - return YAZE_VERSION_STRING; -} +const char* yaze_get_version_string() { return YAZE_VERSION_STRING; } -int yaze_get_version_number() { - return YAZE_VERSION_NUMBER; -} +int yaze_get_version_number() { return YAZE_VERSION_NUMBER; } bool yaze_check_version_compatibility(const char* expected_version) { if (expected_version == nullptr) { @@ -314,12 +310,9 @@ snes_color yaze_rgb_to_snes_color(uint8_t r, uint8_t g, uint8_t b) { void yaze_snes_color_to_rgb(snes_color color, uint8_t* r, uint8_t* g, uint8_t* b) { - if (r != nullptr) - *r = static_cast(color.red); - if (g != nullptr) - *g = static_cast(color.green); - if (b != nullptr) - *b = static_cast(color.blue); + if (r != nullptr) *r = static_cast(color.red); + if (g != nullptr) *g = static_cast(color.green); + if (b != nullptr) *b = static_cast(color.blue); } // Version detection functions diff --git a/src/zelda3/common.h b/src/zelda3/common.h index 7c4f9fc5..25bc0b72 100644 --- a/src/zelda3/common.h +++ b/src/zelda3/common.h @@ -13,17 +13,19 @@ namespace yaze::zelda3 { /** * @class GameEntity * @brief Base class for all overworld and dungeon entities. - * + * * Coordinate System (matches ZScream naming conventions): * - x_, y_: World coordinates in pixels (0-4095 for overworld) - * ZScream equivalent: PlayerX/PlayerY (ExitOW.cs), GlobalX/GlobalY (EntranceOW.cs) - * - * - game_x_, game_y_: Map-local tile coordinates (0-63 for normal, 0-31 for small areas) - * ZScream equivalent: AreaX/AreaY (ExitOW.cs), GameX/GameY (items/sprites) - * + * ZScream equivalent: PlayerX/PlayerY (ExitOW.cs), GlobalX/GlobalY + * (EntranceOW.cs) + * + * - game_x_, game_y_: Map-local tile coordinates (0-63 for normal, 0-31 for + * small areas) ZScream equivalent: AreaX/AreaY (ExitOW.cs), GameX/GameY + * (items/sprites) + * * - map_id_: Parent map ID accounting for large/wide/tall multi-area maps * ZScream equivalent: MapID property - * + * * - entity_id_: Index in entity array (for display/debugging) */ class GameEntity { @@ -66,10 +68,11 @@ class GameEntity { /** * @brief Update entity properties based on map position * @param map_id Parent map ID to update to - * @param context Optional context (typically const Overworld* for coordinate calculations) - * + * @param context Optional context (typically const Overworld* for coordinate + * calculations) + * * ZScream equivalent: UpdateMapStuff() / UpdateMapProperties() - * + * * This method recalculates derived properties like: * - game_x_/game_y_ from world x_/y_ coordinates * - Scroll/camera values for exits (if is_automatic_ = true) diff --git a/src/zelda3/dungeon/dungeon_editor_system.cc b/src/zelda3/dungeon/dungeon_editor_system.cc index e642b2c4..81cb9388 100644 --- a/src/zelda3/dungeon/dungeon_editor_system.cc +++ b/src/zelda3/dungeon/dungeon_editor_system.cc @@ -762,13 +762,9 @@ absl::Status DungeonEditorSystem::Redo() { return absl::OkStatus(); } -bool DungeonEditorSystem::CanUndo() const { - return !undo_history_.empty(); -} +bool DungeonEditorSystem::CanUndo() const { return !undo_history_.empty(); } -bool DungeonEditorSystem::CanRedo() const { - return !redo_history_.empty(); -} +bool DungeonEditorSystem::CanRedo() const { return !redo_history_.empty(); } void DungeonEditorSystem::ClearHistory() { undo_history_.clear(); @@ -812,33 +808,19 @@ void DungeonEditorSystem::SetValidationCallback(ValidationCallback callback) { } // Helper methods -int DungeonEditorSystem::GenerateSpriteId() { - return next_sprite_id_++; -} +int DungeonEditorSystem::GenerateSpriteId() { return next_sprite_id_++; } -int DungeonEditorSystem::GenerateItemId() { - return next_item_id_++; -} +int DungeonEditorSystem::GenerateItemId() { return next_item_id_++; } -int DungeonEditorSystem::GenerateEntranceId() { - return next_entrance_id_++; -} +int DungeonEditorSystem::GenerateEntranceId() { return next_entrance_id_++; } -int DungeonEditorSystem::GenerateDoorId() { - return next_door_id_++; -} +int DungeonEditorSystem::GenerateDoorId() { return next_door_id_++; } -int DungeonEditorSystem::GenerateChestId() { - return next_chest_id_++; -} +int DungeonEditorSystem::GenerateChestId() { return next_chest_id_++; } -Rom* DungeonEditorSystem::GetROM() const { - return rom_; -} +Rom* DungeonEditorSystem::GetROM() const { return rom_; } -bool DungeonEditorSystem::IsDirty() const { - return editor_state_.is_dirty; -} +bool DungeonEditorSystem::IsDirty() const { return editor_state_.is_dirty; } void DungeonEditorSystem::SetROM(Rom* rom) { rom_ = rom; diff --git a/src/zelda3/dungeon/dungeon_editor_system.h b/src/zelda3/dungeon/dungeon_editor_system.h index 48cfc450..7e044641 100644 --- a/src/zelda3/dungeon/dungeon_editor_system.h +++ b/src/zelda3/dungeon/dungeon_editor_system.h @@ -23,7 +23,7 @@ namespace zelda3 { /** * @brief Comprehensive dungeon editing system - * + * * This class provides a complete dungeon editing solution including: * - Object editing (walls, floors, decorations) * - Sprite management (enemies, NPCs, interactive elements) diff --git a/src/zelda3/dungeon/dungeon_object_editor.cc b/src/zelda3/dungeon/dungeon_object_editor.cc index 09a17c67..b74757f0 100644 --- a/src/zelda3/dungeon/dungeon_object_editor.cc +++ b/src/zelda3/dungeon/dungeon_object_editor.cc @@ -381,7 +381,6 @@ absl::Status DungeonObjectEditor::HandleScrollWheel(int delta, int x, int y, if (editing_state_.current_mode == Mode::kInsert || (editing_state_.current_mode == Mode::kEdit && !selection_state_.selected_objects.empty())) { - return HandleSizeEdit(delta, room_x, room_y); } @@ -874,13 +873,9 @@ absl::Status DungeonObjectEditor::ApplyUndoPoint(const UndoPoint& undo_point) { return absl::OkStatus(); } -bool DungeonObjectEditor::CanUndo() const { - return !undo_history_.empty(); -} +bool DungeonObjectEditor::CanUndo() const { return !undo_history_.empty(); } -bool DungeonObjectEditor::CanRedo() const { - return !redo_history_.empty(); -} +bool DungeonObjectEditor::CanRedo() const { return !redo_history_.empty(); } void DungeonObjectEditor::ClearHistory() { undo_history_.clear(); @@ -894,8 +889,7 @@ void DungeonObjectEditor::ClearHistory() { // Helper for color blending static uint32_t BlendColors(uint32_t base, uint32_t tint) { uint8_t a_tint = (tint >> 24) & 0xFF; - if (a_tint == 0) - return base; + if (a_tint == 0) return base; uint8_t r_base = (base >> 16) & 0xFF; uint8_t g_base = (base >> 8) & 0xFF; @@ -921,8 +915,7 @@ void DungeonObjectEditor::RenderSelectionHighlight(gfx::Bitmap& canvas) { // Draw highlight rectangles around selected objects for (size_t obj_idx : selection_state_.selected_objects) { - if (obj_idx >= current_room_->GetTileObjectCount()) - continue; + if (obj_idx >= current_room_->GetTileObjectCount()) continue; const auto& obj = current_room_->GetTileObject(obj_idx); int x = obj.x() * 16; @@ -952,7 +945,8 @@ void DungeonObjectEditor::RenderLayerVisualization(gfx::Bitmap& canvas) { return; } - // Apply subtle color tints based on layer (simplified - just mark with colored border) + // Apply subtle color tints based on layer (simplified - just mark with + // colored border) for (const auto& obj : current_room_->GetTileObjects()) { int x = obj.x() * 16; int y = obj.y() * 16; @@ -1168,8 +1162,7 @@ absl::Status DungeonObjectEditor::HandleDragOperation(int current_x, // Move all selected objects for (size_t obj_idx : selection_state_.selected_objects) { - if (obj_idx >= current_room_->GetTileObjectCount()) - continue; + if (obj_idx >= current_room_->GetTileObjectCount()) continue; auto& obj = current_room_->GetTileObject(obj_idx); int new_x = obj.x() + grid_dx; diff --git a/src/zelda3/dungeon/object_drawer.cc b/src/zelda3/dungeon/object_drawer.cc index 2cb8ec41..8a914bda 100644 --- a/src/zelda3/dungeon/object_drawer.cc +++ b/src/zelda3/dungeon/object_drawer.cc @@ -71,13 +71,13 @@ absl::Status ObjectDrawer::DrawObject(const RoomObject& object, absl::Status ObjectDrawer::DrawObjectList( const std::vector& objects, gfx::BackgroundBuffer& bg1, gfx::BackgroundBuffer& bg2, const gfx::PaletteGroup& palette_group) { - for (const auto& object : objects) { DrawObject(object, bg1, bg2, palette_group); } // CRITICAL: Sync bitmap data to SDL surfaces after all objects are drawn - // ObjectDrawer writes directly to bitmap.mutable_data(), but textures are created from SDL surfaces + // ObjectDrawer writes directly to bitmap.mutable_data(), but textures are + // created from SDL surfaces auto& bg1_bmp = bg1.bitmap(); auto& bg2_bmp = bg2.bitmap(); @@ -110,8 +110,9 @@ absl::Status ObjectDrawer::DrawObjectList( void ObjectDrawer::InitializeDrawRoutines() { // This function maps object IDs to their corresponding draw routines. - // The mapping is based on ZScream's DungeonObjectData.cs and the game's assembly code. - // The order of functions in draw_routines_ MUST match the indices used here. + // The mapping is based on ZScream's DungeonObjectData.cs and the game's + // assembly code. The order of functions in draw_routines_ MUST match the + // indices used here. object_to_routine_map_.clear(); draw_routines_.clear(); @@ -294,8 +295,7 @@ void ObjectDrawer::DrawRightwards2x2_1to15or32( // Pattern: Draws 2x2 tiles rightward (object 0x00) // Size byte determines how many times to repeat (1-15 or 32) int size = obj.size_; - if (size == 0) - size = 32; // Special case for object 0x00 + if (size == 0) size = 32; // Special case for object 0x00 for (int s = 0; s < size; s++) { if (tiles.size() >= 4) { @@ -314,8 +314,7 @@ void ObjectDrawer::DrawRightwards2x4_1to15or26( std::span tiles) { // Pattern: Draws 2x4 tiles rightward (objects 0x01-0x02) int size = obj.size_; - if (size == 0) - size = 26; // Special case + if (size == 0) size = 26; // Special case for (int s = 0; s < size; s++) { if (tiles.size() >= 4) { @@ -681,8 +680,7 @@ void ObjectDrawer::DrawDownwards2x2_1to15or32( // Pattern: Draws 2x2 tiles downward (object 0x60) // Size byte determines how many times to repeat (1-15 or 32) int size = obj.size_; - if (size == 0) - size = 32; // Special case for object 0x60 + if (size == 0) size = 32; // Special case for object 0x60 for (int s = 0; s < size; s++) { if (tiles.size() >= 4) { @@ -701,8 +699,7 @@ void ObjectDrawer::DrawDownwards4x2_1to15or26( std::span tiles) { // Pattern: Draws 4x2 tiles downward (objects 0x61-0x62) int size = obj.size_; - if (size == 0) - size = 26; // Special case + if (size == 0) size = 26; // Special case LOG_DEBUG("ObjectDrawer", "DrawDownwards4x2_1to15or26: obj=%04X tiles=%zu size=%d", obj.id_, @@ -858,7 +855,8 @@ void ObjectDrawer::WriteTile8(gfx::BackgroundBuffer& bg, int tile_x, int tile_y, } // The room-specific graphics buffer (current_gfx16_) contains the assembled - // tile graphics for the current room. Object tile IDs are relative to this buffer. + // tile graphics for the current room. Object tile IDs are relative to this + // buffer. const uint8_t* gfx_data = room_gfx_buffer_; if (!gfx_data) { @@ -879,8 +877,7 @@ void ObjectDrawer::DrawTileToBitmap(gfx::Bitmap& bitmap, const gfx::TileInfo& tile_info, int pixel_x, int pixel_y, const uint8_t* tiledata) { // Draw an 8x8 tile directly to bitmap at pixel coordinates - if (!tiledata) - return; + if (!tiledata) return; // DEBUG: Check if bitmap is valid if (!bitmap.is_active() || bitmap.width() == 0 || bitmap.height() == 0) { @@ -889,7 +886,8 @@ void ObjectDrawer::DrawTileToBitmap(gfx::Bitmap& bitmap, return; } - // Calculate tile position in graphics sheet (128 pixels wide, 16 tiles per row) + // Calculate tile position in graphics sheet (128 pixels wide, 16 tiles per + // row) int tile_sheet_x = (tile_info.id_ % 16) * 8; // 16 tiles per row int tile_sheet_y = (tile_info.id_ / 16) * 8; // Each row is 16 tiles diff --git a/src/zelda3/dungeon/object_drawer.h b/src/zelda3/dungeon/object_drawer.h index 4dc3e996..5d8285c6 100644 --- a/src/zelda3/dungeon/object_drawer.h +++ b/src/zelda3/dungeon/object_drawer.h @@ -17,11 +17,11 @@ namespace zelda3 { /** * @brief Draws dungeon objects to background buffers using game patterns - * + * * This class interprets object IDs and draws them to BG1/BG2 buffers * using the patterns extracted from the game's drawing routines. * Based on ZScream's DungeonObjectData.cs and Subtype1_Draw.cs patterns. - * + * * Architecture: * 1. Load tile data from ROM for the object * 2. Look up draw routine ID from object ID mapping diff --git a/src/zelda3/dungeon/object_parser.cc b/src/zelda3/dungeon/object_parser.cc index ec895e7e..dd344627 100644 --- a/src/zelda3/dungeon/object_parser.cc +++ b/src/zelda3/dungeon/object_parser.cc @@ -181,7 +181,8 @@ absl::StatusOr> ObjectParser::ParseSubtype3( absl::StatusOr> ObjectParser::ReadTileData( int address, int tile_count) { // Each tile is stored as a 16-bit word (2 bytes), not 8 bytes! - // ZScream: tiles.Add(new Tile(ROM.DATA[pos + ((i * 2))], ROM.DATA[pos + ((i * 2)) + 1])); + // ZScream: tiles.Add(new Tile(ROM.DATA[pos + ((i * 2))], ROM.DATA[pos + ((i * + // 2)) + 1])); if (address < 0 || address + (tile_count * 2) >= (int)rom_->size()) { return absl::OutOfRangeError( absl::StrFormat("Tile data address out of range: %#06x", address)); diff --git a/src/zelda3/dungeon/room.cc b/src/zelda3/dungeon/room.cc index 4f13f0d3..11ba4e88 100644 --- a/src/zelda3/dungeon/room.cc +++ b/src/zelda3/dungeon/room.cc @@ -277,8 +277,7 @@ void Room::CopyRoomGraphicsToBuffer() { if (gfx_index >= 0 && gfx_index < static_cast(sizeof(current_gfx16_))) { current_gfx16_[gfx_index] = map_byte; - if (map_byte != 0) - bytes_copied++; + if (map_byte != 0) bytes_copied++; } } data++; @@ -360,7 +359,8 @@ void Room::RenderRoomGraphics() { // LoadGraphicsSheetsIntoArena() removed - using per-room graphics instead // Arena sheets are optional and not needed for room rendering - // STEP 2: Draw floor tiles to bitmaps (base layer) - if graphics changed OR bitmaps not created yet + // STEP 2: Draw floor tiles to bitmaps (base layer) - if graphics changed OR + // bitmaps not created yet bool need_floor_draw = graphics_dirty_; auto& bg1_bmp = bg1_buffer_.bitmap(); auto& bg2_bmp = bg2_buffer_.bitmap(); @@ -380,18 +380,21 @@ void Room::RenderRoomGraphics() { floor2_graphics_); } - // STEP 3: Draw background tiles (walls/structure) to buffers - if graphics changed OR bitmaps just created + // STEP 3: Draw background tiles (walls/structure) to buffers - if graphics + // changed OR bitmaps just created bool need_bg_draw = graphics_dirty_ || need_floor_draw; if (need_bg_draw) { bg1_buffer_.DrawBackground(std::span(current_gfx16_)); bg2_buffer_.DrawBackground(std::span(current_gfx16_)); } - // Get and apply palette BEFORE rendering objects (so objects use correct colors) + // Get and apply palette BEFORE rendering objects (so objects use correct + // colors) auto& dungeon_pal_group = rom()->mutable_palette_group()->dungeon_main; int num_palettes = dungeon_pal_group.size(); - // Use palette indirection table lookup (same as dungeon_canvas_viewer.cc line 854) + // Use palette indirection table lookup (same as dungeon_canvas_viewer.cc line + // 854) int palette_id = palette; // Default fallback if (palette < rom()->paletteset_ids.size() && !rom()->paletteset_ids[palette].empty()) { @@ -420,12 +423,14 @@ void Room::RenderRoomGraphics() { } // Render objects ON TOP of background tiles (AFTER palette is set) - // ObjectDrawer will write indexed pixel data that uses the palette we just set + // ObjectDrawer will write indexed pixel data that uses the palette we just + // set RenderObjectsToBackground(); - // PERFORMANCE OPTIMIZATION: Queue texture commands but DON'T process immediately - // This allows multiple rooms to batch their texture updates together - // The dungeon_canvas_viewer.cc:552 will process all queued textures once per frame + // PERFORMANCE OPTIMIZATION: Queue texture commands but DON'T process + // immediately This allows multiple rooms to batch their texture updates + // together The dungeon_canvas_viewer.cc:552 will process all queued textures + // once per frame if (bg1_bmp.texture()) { // Texture exists - UPDATE it with new object data LOG_DEBUG("[RenderRoomGraphics]", @@ -509,8 +514,9 @@ void Room::RenderObjectsToBackground() { return; } - // PERFORMANCE OPTIMIZATION: Only render objects if they have changed or if graphics changed - // Also render if bitmaps were just created (need_floor_draw was true in RenderRoomGraphics) + // PERFORMANCE OPTIMIZATION: Only render objects if they have changed or if + // graphics changed Also render if bitmaps were just created (need_floor_draw + // was true in RenderRoomGraphics) auto& bg1_bmp = bg1_buffer_.bitmap(); auto& bg2_bmp = bg2_buffer_.bitmap(); bool bitmaps_exist = bg1_bmp.is_active() && bg1_bmp.width() > 0 && @@ -522,7 +528,8 @@ void Room::RenderObjectsToBackground() { return; } - // Get palette group for object rendering (use SAME lookup as RenderRoomGraphics) + // Get palette group for object rendering (use SAME lookup as + // RenderRoomGraphics) auto& dungeon_pal_group = rom()->mutable_palette_group()->dungeon_main; int num_palettes = dungeon_pal_group.size(); @@ -542,7 +549,8 @@ void Room::RenderObjectsToBackground() { } auto room_palette = dungeon_pal_group[palette_id]; - // Dungeon palettes are 16-color sub-palettes. Split the 90-color palette into 16-color groups. + // Dungeon palettes are 16-color sub-palettes. Split the 90-color palette into + // 16-color groups. auto palette_group_result = gfx::CreatePaletteGroupFromLargePalette(room_palette, 16); if (!palette_group_result.ok()) { @@ -556,7 +564,8 @@ void Room::RenderObjectsToBackground() { // Use ObjectDrawer for pattern-based object rendering // This provides proper wall/object drawing patterns - // Pass the room-specific graphics buffer (current_gfx16_) so objects use correct tiles + // Pass the room-specific graphics buffer (current_gfx16_) so objects use + // correct tiles ObjectDrawer drawer(rom_, current_gfx16_.data()); auto status = drawer.DrawObjectList(tile_objects_, bg1_buffer_, bg2_buffer_, palette_group); @@ -761,8 +770,10 @@ void Room::ParseObjectsFromLocation(int objects_location) { } } else { // Handle door objects (placeholder for future implementation) - // tile_objects_.push_back(z3_object_door(static_cast((b2 << 8) + b1), - // 0, 0, 0, static_cast(layer))); + // tile_objects_.push_back(z3_object_door(static_cast((b2 << 8) + + // b1), + // 0, 0, 0, + // static_cast(layer))); } } } @@ -922,22 +933,17 @@ absl::StatusOr Room::FindObjectAt(int x, int y, int layer) const { bool Room::ValidateObject(const RoomObject& object) const { // Validate position (0-63 for both X and Y) - if (object.x() < 0 || object.x() > 63) - return false; - if (object.y() < 0 || object.y() > 63) - return false; + if (object.x() < 0 || object.x() > 63) return false; + if (object.y() < 0 || object.y() > 63) return false; // Validate layer (0-2) - if (object.GetLayerValue() < 0 || object.GetLayerValue() > 2) - return false; + if (object.GetLayerValue() < 0 || object.GetLayerValue() > 2) return false; // Validate object ID range - if (object.id_ < 0 || object.id_ > 0xFFF) - return false; + if (object.id_ < 0 || object.id_ > 0xFFF) return false; // Validate size for Type 1 objects - if (object.id_ < 0x100 && object.size() > 15) - return false; + if (object.id_ < 0x100 && object.size() > 15) return false; return true; } @@ -1079,8 +1085,7 @@ void Room::LoadTorches() { // Iterate through torch data to find torches for this room for (int i = 0; i < bytes_count; i += 2) { - if (i + 1 >= bytes_count) - break; + if (i + 1 >= bytes_count) break; uint8_t b1 = rom_data[torch_data + i]; uint8_t b2 = rom_data[torch_data + i + 1]; @@ -1096,8 +1101,7 @@ void Room::LoadTorches() { // Found torches for this room, read them i += 2; while (i < bytes_count) { - if (i + 1 >= bytes_count) - break; + if (i + 1 >= bytes_count) break; b1 = rom_data[torch_data + i]; b2 = rom_data[torch_data + i + 1]; @@ -1132,8 +1136,7 @@ void Room::LoadTorches() { // Skip to next room's torches i += 2; while (i < bytes_count) { - if (i + 1 >= bytes_count) - break; + if (i + 1 >= bytes_count) break; b1 = rom_data[torch_data + i]; b2 = rom_data[torch_data + i + 1]; if (b1 == 0xFF && b2 == 0xFF) { @@ -1180,8 +1183,7 @@ void Room::LoadBlocks() { // Parse blocks for this room (4 bytes per block entry) for (int i = 0; i < blocks_count; i += 4) { - if (i + 3 >= blocks_count) - break; + if (i + 3 >= blocks_count) break; uint8_t b1 = blocks_data[i]; uint8_t b2 = blocks_data[i + 1]; @@ -1229,8 +1231,9 @@ void Room::LoadPits() { room_id_, pit_entries, pit_ptr); // Pit data is stored as: room_id (2 bytes), target info (2 bytes) - // This data is already loaded in LoadRoomFromRom() into pits_ destination struct - // The pit destination (where you go when you fall) is set via SetPitsTarget() + // This data is already loaded in LoadRoomFromRom() into pits_ destination + // struct The pit destination (where you go when you fall) is set via + // SetPitsTarget() // Pits are typically represented in the layout/collision data, not as objects // The pits_ member already contains the target room and layer diff --git a/src/zelda3/dungeon/room.h b/src/zelda3/dungeon/room.h index fe67a855..7d9232e6 100644 --- a/src/zelda3/dungeon/room.h +++ b/src/zelda3/dungeon/room.h @@ -307,15 +307,14 @@ class Room { } } void SetStaircasePlane(int index, uint8_t plane) { - if (index >= 0 && index < 4) - staircase_plane_[index] = plane; + if (index >= 0 && index < 4) staircase_plane_[index] = plane; } void SetHolewarp(uint8_t holewarp) { this->holewarp = holewarp; } void SetStaircaseRoom(int index, uint8_t room) { - if (index >= 0 && index < 4) - staircase_rooms_[index] = room; + if (index >= 0 && index < 4) staircase_rooms_[index] = room; } - // SetFloor1/SetFloor2 removed - use set_floor1()/set_floor2() instead (defined above) + // SetFloor1/SetFloor2 removed - use set_floor1()/set_floor2() instead + // (defined above) void SetMessageId(uint16_t message_id) { message_id_ = message_id; } // Getters for LoadRoomFromRom function @@ -417,7 +416,8 @@ class Room { bool is_dark_; bool is_floor_ = true; - // Performance optimization: Cache room properties to avoid unnecessary re-renders + // Performance optimization: Cache room properties to avoid unnecessary + // re-renders uint8_t cached_blockset_ = 0xFF; uint8_t cached_spriteset_ = 0xFF; uint8_t cached_palette_ = 0xFF; diff --git a/src/zelda3/dungeon/room_object.cc b/src/zelda3/dungeon/room_object.cc index 262cf927..5c1394e3 100644 --- a/src/zelda3/dungeon/room_object.cc +++ b/src/zelda3/dungeon/room_object.cc @@ -16,7 +16,8 @@ struct SubtypeTableInfo { }; SubtypeTableInfo GetSubtypeTable(int object_id) { - // Heuristic: 0x00-0xFF => subtype1, 0x100-0x1FF => subtype2, >=0x200 => subtype3 + // Heuristic: 0x00-0xFF => subtype1, 0x100-0x1FF => subtype2, >=0x200 => + // subtype3 if (object_id >= 0x200) { return SubtypeTableInfo(kRoomObjectSubtype3, 0xFF); } else if (object_id >= 0x100) { @@ -47,7 +48,8 @@ ObjectOption operator~(ObjectOption option) { } // NOTE: DrawTile was legacy ZScream code that is no longer used. -// Modern rendering uses ObjectDrawer which draws directly to BackgroundBuffer bitmaps. +// Modern rendering uses ObjectDrawer which draws directly to BackgroundBuffer +// bitmaps. void RoomObject::EnsureTilesLoaded() { if (tiles_loaded_) { @@ -181,7 +183,8 @@ RoomObject RoomObject::DecodeObjectFromBytes(uint8_t b1, uint8_t b2, uint8_t b3, // Follow ZScream's parsing logic exactly if (b3 >= 0xF8) { // Type 3: xxxxxxii yyyyyyii 11111iii - // ZScream: oid = (ushort)((b3 << 4) | 0x80 + (((b2 & 0x03) << 2) + ((b1 & 0x03)))); + // ZScream: oid = (ushort)((b3 << 4) | 0x80 + (((b2 & 0x03) << 2) + ((b1 & + // 0x03)))); id = (static_cast(b3) << 4) | 0x80 | ((static_cast(b2 & 0x03) << 2) + (b1 & 0x03)); x = (b1 & 0xFC) >> 2; diff --git a/src/zelda3/dungeon/room_object.h b/src/zelda3/dungeon/room_object.h index 30a61222..20f70c87 100644 --- a/src/zelda3/dungeon/room_object.h +++ b/src/zelda3/dungeon/room_object.h @@ -160,7 +160,8 @@ class RoomObject { std::vector preview_object_data_; // Tile data storage - using Arena system for efficient memory management - // Instead of copying Tile16 vectors, we store references to Arena-managed data + // Instead of copying Tile16 vectors, we store references to Arena-managed + // data mutable std::vector tiles_; // Individual tiles like ZScream mutable bool tiles_loaded_ = false; mutable int tile_count_ = 0; diff --git a/src/zelda3/music/tracker.cc b/src/zelda3/music/tracker.cc index a9d66428..af86e512 100644 --- a/src/zelda3/music/tracker.cc +++ b/src/zelda3/music/tracker.cc @@ -123,19 +123,16 @@ short Tracker::AllocSpcCommand() { spc_command = current_spc_command_ = (SpcCommand*)realloc(current_spc_command_, m_size * sizeof(SpcCommand)); k = 1023; - while (k--) - spc_command[j].next = j + 1, j++; + while (k--) spc_command[j].next = j + 1, j++; spc_command[j].next = -1; k = 1023; - while (k--) - spc_command[j].prev = j - 1, j--; + while (k--) spc_command[j].prev = j - 1, j--; spc_command[j].prev = -1; i = j; } else spc_command = current_spc_command_; m_free = spc_command[m_free].next; - if (m_free != -1) - spc_command[m_free].prev = -1; + if (m_free != -1) spc_command[m_free].prev = -1; return i; } @@ -160,8 +157,7 @@ short Tracker::GetBlockTime(Rom& rom, short num, short prevtime) { int n = prevtime; l = num; - if (l == -1) - return 0; + if (l == -1) return 0; for (;;) { if (spc_command[l].flag & 4) { @@ -170,11 +166,9 @@ short Tracker::GetBlockTime(Rom& rom, short num, short prevtime) { k = 1; } - if (!k) - i = l; + if (!k) i = l; - if (spc_command[l].flag & 1) - n = spc_command[l].b1; + if (spc_command[l].flag & 1) n = spc_command[l].b1; l = spc_command[l].next; @@ -224,8 +218,7 @@ short Tracker::GetBlockTime(Rom& rom, short num, short prevtime) { m += spc_command[k].tim2 * spc_command2->p3; } } else { - if (spc_command2->cmd < 0xe0) - m++; + if (spc_command2->cmd < 0xe0) m++; if (spc_command2->flag & 1) { j += m * spc_command[i].b1; m = 0; @@ -235,8 +228,7 @@ short Tracker::GetBlockTime(Rom& rom, short num, short prevtime) { spc_command2->tim2 = m; spc_command2->flag |= 4; - if (i == num) - break; + if (i == num) break; i = spc_command2->prev; } @@ -278,8 +270,7 @@ short Tracker::LoadSpcCommand(Rom& rom, unsigned short addr, short bank, SongRange* sr; SpcCommand* spc_command = current_spc_command_; SpcCommand* spc_command2; - if (!addr) - return -1; + if (!addr) return -1; a = GetSpcAddr(rom, addr, bank); d = spcbank; @@ -294,8 +285,7 @@ short Tracker::LoadSpcCommand(Rom& rom, unsigned short addr, short bank, for (c = 0; c < e; c++) { if (sr[c].bank == d) { if (sr[c].start > addr) { - if (sr[c].start < f) - f = sr[c].start; + if (sr[c].start < f) f = sr[c].start; n = c; } else if (sr[c].end > addr) { for (f = sr[c].first; f != -1; f = spc_command[f].next) { @@ -307,8 +297,7 @@ short Tracker::LoadSpcCommand(Rom& rom, unsigned short addr, short bank, lastsr = c; return f; } - if (spc_command[f].flag & 1) - k = spc_command[f].b1; + if (spc_command[f].flag & 1) k = spc_command[f].b1; if (spc_command[f].cmd < 0xca) { if (k) { m -= k; @@ -338,29 +327,24 @@ short Tracker::LoadSpcCommand(Rom& rom, unsigned short addr, short bank, spc_command, sizeof(SpcCommand) * (m_size += 1024)); spc_command2 = spc_command + i; n = l + 1023; - while (l < n) - spc_command[l].next = l + 1, l++; + while (l < n) spc_command[l].next = l + 1, l++; spc_command[l].next = -1; n -= 1023; - while (l > n) - spc_command[l].prev = l - 1, l--; + while (l > n) spc_command[l].prev = l - 1, l--; spc_command[l].prev = i; spc_command2->next = l; } spc_command2->addr = g; b = a[g]; - if (!b) - break; - if (m >= t && b != 0xf9) - break; + if (!b) break; + if (m >= t && b != 0xf9) break; g++; j = 0; if (b < 128) { j = 1; k = spc_command2->b1 = b; b = a[g++]; - if (b < 128) - j = 3, spc_command2->b2 = b, b = a[g++]; + if (b < 128) j = 3, spc_command2->b2 = b, b = a[g++]; } if (b < 0xe0) { if (k) { @@ -373,12 +357,9 @@ short Tracker::LoadSpcCommand(Rom& rom, unsigned short addr, short bank, spc_command2->flag = j; if (b >= 0xe0) { b -= 0xe0; - if (op_len[b]) - spc_command2->p1 = a[g++]; - if (op_len[b] > 1) - spc_command2->p2 = a[g++]; - if (op_len[b] > 2) - spc_command2->p3 = a[g++]; + if (op_len[b]) spc_command2->p1 = a[g++]; + if (op_len[b] > 1) spc_command2->p2 = a[g++]; + if (op_len[b] > 2) spc_command2->p3 = a[g++]; if (b == 15) { m_free = spc_command2->next; spc_command[spc_command2->next].prev = -1; @@ -396,8 +377,7 @@ short Tracker::LoadSpcCommand(Rom& rom, unsigned short addr, short bank, i = spc_command2->next; break; } - if (song_range_[lastsr].endtime) - k = song_range_[lastsr].endtime; + if (song_range_[lastsr].endtime) k = song_range_[lastsr].endtime; } } i = spc_command2->next; @@ -443,10 +423,10 @@ short Tracker::LoadSpcCommand(Rom& rom, unsigned short addr, short bank, /** * @brief High-level function to load all song data from the ROM. - * (Currently commented out, but this would be the main entry point for parsing.) - * It would iterate through the main song table in the ROM, and for each song, - * recursively load all its parts and commands using LoadSpcCommand. It would - * also load instrument and sample data. + * (Currently commented out, but this would be the main entry point for + * parsing.) It would iterate through the main song table in the ROM, and for + * each song, recursively load all its parts and commands using LoadSpcCommand. + * It would also load instrument and sample data. */ void Tracker::LoadSongs(Rom& rom) { // unsigned char *b; @@ -615,8 +595,8 @@ void Tracker::LoadSongs(Rom& rom) { // numsndinst = spclen / 9; // b = GetSpcAddr(rom, 0x3c00, 0); - // zelda_wave = waves = (ZeldaWave *)malloc(sizeof(ZeldaWave) * (spclen >> 2)); - // p = spclen >> 1; + // zelda_wave = waves = (ZeldaWave *)malloc(sizeof(ZeldaWave) * (spclen >> + // 2)); p = spclen >> 1; // for (i = 0; i < p; i += 2) { // j = ((unsigned short *)b)[i]; @@ -747,8 +727,7 @@ short Tracker::SaveSpcCommand(Rom& rom, short num, short songtime, int o = 0; int p = 0; - if (i == -1) - return 0; + if (i == -1) return 0; if (i >= m_size) { printf("Error.\n"); @@ -756,13 +735,11 @@ short Tracker::SaveSpcCommand(Rom& rom, short num, short songtime, return 0; } - if (spc_command[i].flag & 8) - return spc_command[i].addr; + if (spc_command[i].flag & 8) return spc_command[i].addr; for (;;) { j = spc_command[i].prev; - if (j == -1) - break; + if (j == -1) break; i = j; } @@ -771,29 +748,23 @@ short Tracker::SaveSpcCommand(Rom& rom, short num, short songtime, l = GetBlockTime(rom, i, 0); m = i; for (;;) { - if (m == -1) - break; + if (m == -1) break; k++; spc_command2 = spc_command + m; - if (spc_command2->flag & 1) - k++, n = spc_command2->b1; - if (spc_command2->flag & 2) - k++; - if (spc_command2->cmd >= 0xe0) - k += op_len[spc_command2->cmd - 0xe0]; + if (spc_command2->flag & 1) k++, n = spc_command2->b1; + if (spc_command2->flag & 2) k++; + if (spc_command2->cmd >= 0xe0) k += op_len[spc_command2->cmd - 0xe0]; m = spc_command2->next; } songtime -= l; if (songtime > 0) { l = (songtime + 126) / 127; - if (songtime % l) - l += 2; + if (songtime % l) l += 2; l++; if (n && !songtime % n) { p = songtime / n; - if (p < l) - l = p; + if (p < l) l = p; } else p = -1; k += l; @@ -803,32 +774,25 @@ short Tracker::SaveSpcCommand(Rom& rom, short num, short songtime, b = sbl->buf; for (;;) { - if (i == -1) - break; + if (i == -1) break; spc_command2 = spc_command + i; spc_command2->addr = b - sbl->buf + sbl->start; spc_command2->flag |= 8; - if (spc_command2->flag & 1) - *(b++) = spc_command2->b1; - if (spc_command2->flag & 2) - *(b++) = spc_command2->b2; + if (spc_command2->flag & 1) *(b++) = spc_command2->b1; + if (spc_command2->flag & 2) *(b++) = spc_command2->b2; *(b++) = spc_command2->cmd; if (spc_command2->cmd >= 0xe0) { o = op_len[spc_command2->cmd - 0xe0]; if (spc_command2->cmd == 0xef) { *(short*)b = SaveSpcCommand(rom, *(short*)&(spc_command2->p1), 0, 1); - if (b) - AddSpcReloc(sbl, b - sbl->buf); + if (b) AddSpcReloc(sbl, b - sbl->buf); b[2] = spc_command2->p3; b += 3; } else { - if (o) - *(b++) = spc_command2->p1; - if (o > 1) - *(b++) = spc_command2->p2; - if (o > 2) - *(b++) = spc_command2->p3; + if (o) *(b++) = spc_command2->p1; + if (o > 1) *(b++) = spc_command2->p2; + if (o > 2) *(b++) = spc_command2->p3; } } i = spc_command2->next; @@ -844,8 +808,7 @@ short Tracker::SaveSpcCommand(Rom& rom, short num, short songtime, *(b++) = n; } - for (; songtime >= n; songtime -= n) - *(b++) = 0xc9; + for (; songtime >= n; songtime -= n) *(b++) = 0xc9; if (songtime) { *(b++) = (uint8_t)songtime; @@ -882,12 +845,10 @@ int Tracker::WriteSpcData(Rom& rom, void* buf, int len, int addr, int spc, int limit) { unsigned char* rom_data = rom.mutable_data(); - if (!len) - return addr; + if (!len) return addr; if (((addr + len + 4) & 0x7fff) > 0x7ffb) { - if (addr + 5 > limit) - goto error; + if (addr + 5 > limit) goto error; *(int*)(rom_data + addr) = 0x00010140; rom_data[addr + 4] = 0xff; addr += 5; @@ -910,11 +871,11 @@ int Tracker::WriteSpcData(Rom& rom, void* buf, int len, int addr, int spc, /** * @brief High-level function to save all modified song data back to the ROM. - * (Currently commented out, but this would orchestrate the entire save process.) - * This function would be responsible for taking all the edited, in-memory - * SongSpcBlocks, arranging them into a final binary layout, patching all the - * relocated pointers, and writing the result back into the ROM file using - * WriteSpcData. + * (Currently commented out, but this would orchestrate the entire save + * process.) This function would be responsible for taking all the edited, + * in-memory SongSpcBlocks, arranging them into a final binary layout, patching + * all the relocated pointers, and writing the result back into the ROM file + * using WriteSpcData. */ void Tracker::SaveSongs(Rom& rom) { // int i; @@ -1115,8 +1076,8 @@ void Tracker::SaveSongs(Rom& rom) { // (short *)realloc(zelda_wave->buf, (zelda_wave->end + 1) << 1); // memcpy(zelda_wave->buf, c, zelda_wave->end << 1); // free(c); - // zelda_wave->buf[zelda_wave->end] = zelda_wave->buf[zelda_wave->lopst]; - // zelda_wave2 = waves; + // zelda_wave->buf[zelda_wave->end] = + // zelda_wave->buf[zelda_wave->lopst]; zelda_wave2 = waves; // for (m = 0; m < numwave; m++, zelda_wave2++) // if (zelda_wave2->copy == i) @@ -1231,7 +1192,8 @@ void Tracker::SaveSongs(Rom& rom) { // } // // if (sed) { - // // SetDlgItemInt(sed->dlg, ID_Samp_SampleLengthEdit, sed->zelda_wave->end, + // // SetDlgItemInt(sed->dlg, ID_Samp_SampleLengthEdit, + // sed->zelda_wave->end, // // 0); SetDlgItemInt(sed->dlg, ID_Samp_LoopPointEdit, // // sed->zelda_wave->lopst, 0); @@ -1304,7 +1266,8 @@ void Tracker::SaveSongs(Rom& rom) { // return; // noerror: - // if (((!sptbl->bank) && stbl->bank < 3) || (sptbl->bank == stbl->bank)) { + // if (((!sptbl->bank) && stbl->bank < 3) || (sptbl->bank == stbl->bank)) + // { // *(unsigned short *)(stbl->buf + stbl->relocs[j]) = // sptbl->addr + k - sptbl->start; // } else { @@ -1383,8 +1346,7 @@ void Tracker::EditTrack(Rom& rom, short i) { spc_command = current_spc_command_; - if (i == -1) - return; + if (i == -1) return; if (i >= m_size) { printf("Invalid address: %04X", i); diff --git a/src/zelda3/music/tracker.h b/src/zelda3/music/tracker.h index a21e3da4..87fa1a6d 100644 --- a/src/zelda3/music/tracker.h +++ b/src/zelda3/music/tracker.h @@ -43,23 +43,23 @@ using text_buf_ty = char[512]; * This is the intermediate format used before writing data back to the ROM. */ struct SongSpcBlock { - unsigned short - start; // The starting address of this block in the virtual SPC memory space. - unsigned short len; // Length of the data buffer. - unsigned short relnum; // Number of relocation entries. - unsigned short relsz; // Allocated size of the relocation table. - unsigned short* - relocs; // Table of offsets within 'buf' that are pointers and need to be relocated. - unsigned short bank; // The target sound bank. - unsigned short addr; // The final, relocated address of this block. - unsigned char* buf; // The raw binary data for this block. - int flag; // Flags for managing the block's state. + unsigned short start; // The starting address of this block in the virtual + // SPC memory space. + unsigned short len; // Length of the data buffer. + unsigned short relnum; // Number of relocation entries. + unsigned short relsz; // Allocated size of the relocation table. + unsigned short* relocs; // Table of offsets within 'buf' that are pointers + // and need to be relocated. + unsigned short bank; // The target sound bank. + unsigned short addr; // The final, relocated address of this block. + unsigned char* buf; // The raw binary data for this block. + int flag; // Flags for managing the block's state. }; /** * @struct SongRange - * @brief A metadata structure to keep track of parsed sections of the song data. - * Used to avoid re-parsing the same data from the ROM multiple times. + * @brief A metadata structure to keep track of parsed sections of the song + * data. Used to avoid re-parsing the same data from the ROM multiple times. */ struct SongRange { unsigned short start; // Start address of this range in the ROM. @@ -141,7 +141,8 @@ struct SampleEdit { /** * @struct ZeldaInstrument - * @brief Defines an instrument for a song, mapping to a sample and ADSR settings. + * @brief Defines an instrument for a song, mapping to a sample and ADSR + * settings. */ struct ZeldaInstrument { unsigned char samp; // Index of the sample (ZeldaWave) to use. @@ -169,8 +170,8 @@ struct ZeldaSfxInstrument { /** * @struct SpcCommand - * @brief The core data structure representing a single command in a music track. - * A song track is a doubly-linked list of these commands. + * @brief The core data structure representing a single command in a music + * track. A song track is a doubly-linked list of these commands. */ struct SpcCommand { unsigned short addr; // The ROM address this command was loaded from. diff --git a/src/zelda3/overworld/overworld.cc b/src/zelda3/overworld/overworld.cc index eb682c5e..ef2075bd 100644 --- a/src/zelda3/overworld/overworld.cc +++ b/src/zelda3/overworld/overworld.cc @@ -334,8 +334,7 @@ absl::Status Overworld::ConfigureMultiAreaMap(int parent_index, parent_index + 9}; for (size_t i = 0; i < new_siblings.size(); ++i) { int sibling = new_siblings[i]; - if (sibling < 0 || sibling >= kNumOverworldMaps) - continue; + if (sibling < 0 || sibling >= kNumOverworldMaps) continue; overworld_maps_[sibling].SetAsLargeMap(parent_index, i); } break; @@ -343,8 +342,7 @@ absl::Status Overworld::ConfigureMultiAreaMap(int parent_index, case AreaSizeEnum::WideArea: new_siblings = {parent_index, parent_index + 1}; for (int sibling : new_siblings) { - if (sibling < 0 || sibling >= kNumOverworldMaps) - continue; + if (sibling < 0 || sibling >= kNumOverworldMaps) continue; overworld_maps_[sibling].SetParent(parent_index); overworld_maps_[sibling].SetAreaSize(AreaSizeEnum::WideArea); } @@ -353,8 +351,7 @@ absl::Status Overworld::ConfigureMultiAreaMap(int parent_index, case AreaSizeEnum::TallArea: new_siblings = {parent_index, parent_index + 8}; for (int sibling : new_siblings) { - if (sibling < 0 || sibling >= kNumOverworldMaps) - continue; + if (sibling < 0 || sibling >= kNumOverworldMaps) continue; overworld_maps_[sibling].SetParent(parent_index); overworld_maps_[sibling].SetAreaSize(AreaSizeEnum::TallArea); } @@ -373,8 +370,7 @@ absl::Status Overworld::ConfigureMultiAreaMap(int parent_index, if (asm_version >= 3 && asm_version != 0xFF) { // v3+: Update expanded tables for (int sibling : all_affected) { - if (sibling < 0 || sibling >= kNumOverworldMaps) - continue; + if (sibling < 0 || sibling >= kNumOverworldMaps) continue; RETURN_IF_ERROR(rom()->WriteByte(kOverworldMapParentIdExpanded + sibling, overworld_maps_[sibling].parent())); @@ -385,8 +381,7 @@ absl::Status Overworld::ConfigureMultiAreaMap(int parent_index, } else if (asm_version < 3 && asm_version != 0xFF) { // v1/v2: Update basic parent table for (int sibling : all_affected) { - if (sibling < 0 || sibling >= kNumOverworldMaps) - continue; + if (sibling < 0 || sibling >= kNumOverworldMaps) continue; RETURN_IF_ERROR(rom()->WriteByte(kOverworldMapParentId + sibling, overworld_maps_[sibling].parent())); @@ -397,8 +392,7 @@ absl::Status Overworld::ConfigureMultiAreaMap(int parent_index, } else { // Vanilla: Update parent and screen size tables for (int sibling : all_affected) { - if (sibling < 0 || sibling >= kNumOverworldMaps) - continue; + if (sibling < 0 || sibling >= kNumOverworldMaps) continue; RETURN_IF_ERROR(rom()->WriteByte(kOverworldMapParentId + sibling, overworld_maps_[sibling].parent())); @@ -441,7 +435,8 @@ absl::Status Overworld::AssembleMap32Tiles() { rom()->version_constants().kMap32TileBR}; // Check if expanded tile32 data is actually present in ROM - // The flag position should contain 0x04 for vanilla, something else for expanded + // The flag position should contain 0x04 for vanilla, something else for + // expanded uint8_t asm_version = (*rom_)[OverworldCustomASMHasBeenApplied]; uint8_t expanded_flag = rom()->data()[kMap32ExpandedFlagPos]; util::logf("Expanded tile32 flag: %d", expanded_flag); @@ -497,7 +492,8 @@ absl::Status Overworld::AssembleMap16Tiles() { int num_tile16 = kNumTile16Individual; // Check if expanded tile16 data is actually present in ROM - // The flag position should contain 0x0F for vanilla, something else for expanded + // The flag position should contain 0x0F for vanilla, something else for + // expanded uint8_t asm_version = (*rom_)[OverworldCustomASMHasBeenApplied]; uint8_t expanded_flag = rom()->data()[kMap16ExpandedFlagPos]; util::logf("Expanded tile16 flag: %d", expanded_flag); @@ -560,7 +556,6 @@ void Overworld::OrganizeMapTiles(std::vector& bytes, } absl::Status Overworld::DecompressAllMapTilesParallel() { - const auto get_ow_map_gfx_ptr = [this](int index, uint32_t map_ptr) { int p = (rom()->data()[map_ptr + 2 + (3 * index)] << 16) + (rom()->data()[map_ptr + 1 + (3 * index)] << 8) + @@ -585,15 +580,11 @@ absl::Status Overworld::DecompressAllMapTilesParallel() { int ttpos = 0; - if (p1 >= highest) - highest = p1; - if (p2 >= highest) - highest = p2; + if (p1 >= highest) highest = p1; + if (p2 >= highest) highest = p2; - if (p1 <= lowest && p1 > kBaseHighest) - lowest = p1; - if (p2 <= lowest && p2 > kBaseHighest) - lowest = p2; + if (p1 <= lowest && p1 > kBaseHighest) lowest = p1; + if (p2 <= lowest && p2 > kBaseHighest) lowest = p2; int size1, size2; auto bytes = gfx::HyruleMagicDecompress(rom()->data() + p2, &size1, 1); @@ -621,7 +612,8 @@ absl::Status Overworld::LoadOverworldMaps() { auto size = tiles16_.size(); // Performance optimization: Only build essential maps initially - // Essential maps are the first few maps of each world that are commonly accessed + // Essential maps are the first few maps of each world that are commonly + // accessed constexpr int kEssentialMapsPerWorld = 16; constexpr int kLightWorldEssential = kEssentialMapsPerWorld; constexpr int kDarkWorldEssential = @@ -750,8 +742,7 @@ absl::Status Overworld::LoadSpritesFromMap(int sprites_per_gamestate_ptr, int num_maps_per_gamestate, int game_state) { for (int i = 0; i < num_maps_per_gamestate; i++) { - if (map_parent_[i] != i) - continue; + if (map_parent_[i] != i) continue; int current_spr_ptr = sprites_per_gamestate_ptr + (i * 2); ASSIGN_OR_RETURN(auto word_addr, rom()->ReadWord(current_spr_ptr)); @@ -760,8 +751,7 @@ absl::Status Overworld::LoadSpritesFromMap(int sprites_per_gamestate_ptr, ASSIGN_OR_RETURN(uint8_t b1, rom()->ReadByte(sprite_address)); ASSIGN_OR_RETURN(uint8_t b2, rom()->ReadByte(sprite_address + 1)); ASSIGN_OR_RETURN(uint8_t b3, rom()->ReadByte(sprite_address + 2)); - if (b1 == 0xFF) - break; + if (b1 == 0xFF) break; int editor_map_index = i; if (game_state != 0) { diff --git a/src/zelda3/overworld/overworld.h b/src/zelda3/overworld/overworld.h index f1d22f23..41fcabb5 100644 --- a/src/zelda3/overworld/overworld.h +++ b/src/zelda3/overworld/overworld.h @@ -139,7 +139,7 @@ class Overworld { /** * @brief Build a map on-demand if it hasn't been built yet - * + * * This method checks if the specified map needs to be built and builds it * if necessary. Used for lazy loading optimization. */ @@ -198,7 +198,7 @@ class Overworld { * @param parent_index The parent map index * @param size The area size to configure * @return Status of the configuration - * + * * Properly sets up sibling relationships and updates ROM data for v3+. */ absl::Status ConfigureMultiAreaMap(int parent_index, AreaSizeEnum size); diff --git a/src/zelda3/overworld/overworld_entrance.cc b/src/zelda3/overworld/overworld_entrance.cc index eb7a7af0..f7b35128 100644 --- a/src/zelda3/overworld/overworld_entrance.cc +++ b/src/zelda3/overworld/overworld_entrance.cc @@ -1,5 +1,7 @@ #include "zelda3/overworld/overworld_entrance.h" + #include + #include "absl/status/status.h" #include "absl/status/statusor.h" #include "app/rom.h" @@ -15,7 +17,8 @@ absl::StatusOr> LoadEntrances(Rom* rom) { int num_entrances = 129; // Check if expanded entrance data is actually present in ROM - // The flag position should contain 0xB8 for vanilla, something else for expanded + // The flag position should contain 0xB8 for vanilla, something else for + // expanded if (rom->data()[kOverworldEntranceExpandedFlagPos] != 0xB8) { // ROM has expanded entrance data - use expanded addresses ow_entrance_map_ptr = kOverworldEntranceMapExpanded; @@ -68,11 +71,11 @@ absl::StatusOr> LoadHoles(Rom* rom) { absl::Status SaveEntrances(Rom* rom, const std::vector& entrances, bool expanded_entrances) { - auto write_entrance = [&](int index, uint32_t map_addr, uint32_t pos_addr, uint32_t id_addr) -> absl::Status { // Mirrors ZeldaFullEditor/Save.cs::SaveOWEntrances (see lines ~1081-1085) - // where MapID and MapPos are written as 16-bit words and EntranceID as a byte. + // where MapID and MapPos are written as 16-bit words and EntranceID as a + // byte. RETURN_IF_ERROR(rom->WriteShort(map_addr, entrances[index].map_id_)); RETURN_IF_ERROR(rom->WriteShort(pos_addr, entrances[index].map_pos_)); RETURN_IF_ERROR(rom->WriteByte(id_addr, entrances[index].entrance_id_)); diff --git a/src/zelda3/overworld/overworld_exit.cc b/src/zelda3/overworld/overworld_exit.cc index 850bad6e..7a70eebd 100644 --- a/src/zelda3/overworld/overworld_exit.cc +++ b/src/zelda3/overworld/overworld_exit.cc @@ -63,7 +63,8 @@ absl::StatusOr> LoadExits(Rom* rom) { void OverworldExit::UpdateMapProperties(uint16_t map_id, const void* context) { // Sync player position from drag system - // ZScream: ExitMode.cs:229-244 updates PlayerX/PlayerY, then calls UpdateMapStuff + // ZScream: ExitMode.cs:229-244 updates PlayerX/PlayerY, then calls + // UpdateMapStuff x_player_ = static_cast(x_); y_player_ = static_cast(y_); map_id_ = map_id; @@ -172,11 +173,10 @@ void OverworldExit::UpdateMapProperties(uint16_t map_id, const void* context) { } absl::Status SaveExits(Rom* rom, const std::vector& exits) { - - // ASM version 0x03 added SW support and the exit leading to Zora's Domain specifically - // needs to be updated because its camera values are incorrect. - // We only update it if it was a vanilla ROM though because we don't know if the - // user has already adjusted it or not. + // ASM version 0x03 added SW support and the exit leading to Zora's Domain + // specifically needs to be updated because its camera values are incorrect. + // We only update it if it was a vanilla ROM though because we don't know if + // the user has already adjusted it or not. uint8_t asm_version = (*rom)[OverworldCustomASMHasBeenApplied]; if (asm_version == 0x00) { // Apply special fix for Zora's Domain exit (index 0x4D) diff --git a/src/zelda3/overworld/overworld_exit.h b/src/zelda3/overworld/overworld_exit.h index 294cf987..13807813 100644 --- a/src/zelda3/overworld/overworld_exit.h +++ b/src/zelda3/overworld/overworld_exit.h @@ -48,20 +48,22 @@ constexpr int OWWhirlpoolPosition = 0x16CF8; // JP = ;016F94 /** * @class OverworldExit - * @brief Represents an overworld exit that transitions from dungeon to overworld - * + * @brief Represents an overworld exit that transitions from dungeon to + * overworld + * * Coordinate System (inherited from GameEntity): * - x_, y_: World pixel coordinates (ZScream: PlayerX/PlayerY) * - game_x_, game_y_: Map-local tile coordinates (ZScream: AreaX/AreaY) * - map_id_: Parent map ID (ZScream: MapID) - * + * * Exit-Specific Properties: * - x_player_, y_player_: Player spawn position in world (saved to ROM) * - x_scroll_, y_scroll_: Camera scroll position * - x_camera_, y_camera_: Camera center position * - room_id_: Target dungeon room ID (ZScream: RoomID) - * - is_automatic_: If true, scroll/camera auto-calculated from player position (ZScream: IsAutomatic) - * + * - is_automatic_: If true, scroll/camera auto-calculated from player position + * (ZScream: IsAutomatic) + * * ZScream Reference: ExitOW.cs, ExitMode.cs */ class OverworldExit : public GameEntity { @@ -87,9 +89,9 @@ class OverworldExit : public GameEntity { /** * @brief Constructor for loading exits from ROM - * + * * Matches ZScream ExitOW.cs constructor (lines 129-167) - * + * * CRITICAL: Does NOT modify map_id parameter (Bug 1 fix) * Uses temporary normalized_map_id for calculations only. */ @@ -138,14 +140,15 @@ class OverworldExit : public GameEntity { /** * @brief Update exit properties when moved or map changes * @param map_id Parent map ID to update to - * @param context Pointer to const Overworld for area size queries (can be nullptr for vanilla) - * + * @param context Pointer to const Overworld for area size queries (can be + * nullptr for vanilla) + * * Recalculates: * - game_x_/game_y_ (map-local tile coords) * - x_scroll_/y_scroll_ (if is_automatic_ = true) * - x_camera_/y_camera_ (if is_automatic_ = true) * - map_pos_ (VRAM location) - * + * * ZScream equivalent: ExitOW.cs:206-318 (UpdateMapStuff) */ void UpdateMapProperties(uint16_t map_id, const void* context) override; diff --git a/src/zelda3/overworld/overworld_item.cc b/src/zelda3/overworld/overworld_item.cc index 5c06f663..a7d64206 100644 --- a/src/zelda3/overworld/overworld_item.cc +++ b/src/zelda3/overworld/overworld_item.cc @@ -97,8 +97,7 @@ absl::Status SaveItems(Rom* rom, const std::vector& items) { } for (const OverworldItem& item : items) { - if (item.deleted) - continue; + if (item.deleted) continue; const int map_index = static_cast(item.room_map_id_); if (map_index < 0 || map_index >= pointer_count) { @@ -187,7 +186,8 @@ absl::Status SaveItems(Rom* rom, const std::vector& items) { static_cast( (PcToSnes(zelda3::kOverworldItemsStartDataNew) >> 16) & 0xFF))); - // Clear pointer table (write zero) to avoid stale values when pointer count shrinks + // Clear pointer table (write zero) to avoid stale values when pointer count + // shrinks for (int i = 0; i < zelda3::kNumOverworldMaps; ++i) { RETURN_IF_ERROR( rom->WriteShort(zelda3::kOverworldItemsPointersNew + (i * 2), 0x0000)); diff --git a/src/zelda3/overworld/overworld_map.cc b/src/zelda3/overworld/overworld_map.cc index 3294443d..bda96f9c 100644 --- a/src/zelda3/overworld/overworld_map.cc +++ b/src/zelda3/overworld/overworld_map.cc @@ -131,7 +131,8 @@ void OverworldMap::LoadAreaInfo() { } } else { // v3: use expanded message table and area size table - // All area sizes are now stored in the expanded table, supporting all size types + // All area sizes are now stored in the expanded table, supporting all size + // types message_id_ = (*rom_)[kOverworldMessagesExpanded + (parent_ * 2)] | ((*rom_)[kOverworldMessagesExpanded + (parent_ * 2) + 1] << 8); @@ -525,7 +526,8 @@ void OverworldMap::LoadMainBlocksetId() { parent_ < kSpecialWorldMapIdStart) { main_gfx_id_ = 0x21; } else if (parent_ >= kSpecialWorldMapIdStart) { - // Special world maps - use appropriate graphics ID based on the specific map + // Special world maps - use appropriate graphics ID based on the specific + // map if (parent_ == 0x88) { main_gfx_id_ = 0x24; } else { @@ -888,8 +890,8 @@ absl::Status OverworldMap::LoadOverlay() { } absl::Status OverworldMap::LoadVanillaOverlayData() { - - // Load vanilla overlay for this map (interactive overlays for revealing holes/changing elements) + // Load vanilla overlay for this map (interactive overlays for revealing + // holes/changing elements) int address = (kOverlayPointersBank << 16) + ((*rom_)[kOverlayPointers + (index_ * 2) + 1] << 8) + (*rom_)[kOverlayPointers + (index_ * 2)]; @@ -1037,8 +1039,7 @@ void OverworldMap::ProcessGraphicsBuffer(int index, int static_graphics_offset, } absl::Status OverworldMap::BuildTileset() { - if (current_gfx_.size() == 0) - current_gfx_.resize(0x10000, 0x00); + if (current_gfx_.size() == 0) current_gfx_.resize(0x10000, 0x00); // Process the 8 main graphics sheets (slots 0-7) for (int i = 0; i < 8; i++) { @@ -1067,8 +1068,7 @@ absl::Status OverworldMap::BuildTileset() { absl::Status OverworldMap::BuildTiles16Gfx(std::vector& tiles16, int count) { - if (current_blockset_.size() == 0) - current_blockset_.resize(0x100000, 0x00); + if (current_blockset_.size() == 0) current_blockset_.resize(0x100000, 0x00); const int offsets[] = {0x00, 0x08, 0x400, 0x408}; auto yy = 0; diff --git a/src/zelda3/overworld/overworld_version_helper.h b/src/zelda3/overworld/overworld_version_helper.h index 586da992..695fa181 100644 --- a/src/zelda3/overworld/overworld_version_helper.h +++ b/src/zelda3/overworld/overworld_version_helper.h @@ -2,6 +2,7 @@ #define YAZE_ZELDA3_OVERWORLD_VERSION_HELPER_H #include + #include "app/rom.h" #include "zelda3/common.h" @@ -16,7 +17,7 @@ enum class AreaSizeEnum { /** * @brief ROM version detection for overworld features - * + * * Centralizes version checks to distinguish between: * - Vanilla: No ZScream patches (uses parent system for large maps only) * - v1: Basic custom overworld features @@ -32,11 +33,11 @@ enum class OverworldVersion { /** * @brief Helper for ROM version detection and feature gating - * + * * Provides consistent version checking across the codebase to replace * scattered inline checks like: * if (asm_version >= 3 && asm_version != 0xFF) { ... } - * + * * With semantic helpers: * if (OverworldVersionHelper::SupportsAreaEnum(version)) { ... } */ @@ -75,12 +76,12 @@ class OverworldVersionHelper { /** * @brief Check if ROM supports area enum system (v3+ only) - * + * * Area enum system allows: * - Wide areas (2x1 screens) * - Tall areas (1x2 screens) * - Direct area size queries - * + * * Vanilla/v1/v2 use parent system with large_map_ flag only. */ static bool SupportsAreaEnum(OverworldVersion version) { @@ -89,7 +90,7 @@ class OverworldVersionHelper { /** * @brief Check if ROM uses expanded space for overworld data - * + * * v1+ ROMs use expanded pointers for: * - Map data (0x130000+) * - Sprite data (0x141438+) diff --git a/src/zelda3/palette_constants.h b/src/zelda3/palette_constants.h index cdba4ff3..2cb6a23f 100644 --- a/src/zelda3/palette_constants.h +++ b/src/zelda3/palette_constants.h @@ -132,8 +132,8 @@ constexpr PaletteGroupMetadata kDungeonMain = { .category = "Dungeon", .base_address = PaletteAddress::kDungeonMain, .palette_count = PaletteCount::kDungeonMain, - .colors_per_palette = - 90, // 90 colors: 5 full rows (0-15, 16-31, 32-47, 48-63, 64-79) + 10 colors (80-89) + .colors_per_palette = 90, // 90 colors: 5 full rows (0-15, 16-31, 32-47, + // 48-63, 64-79) + 10 colors (80-89) .colors_per_row = 16, // Display in 16-color rows for proper SNES alignment .bits_per_pixel = 4, .description = @@ -146,9 +146,9 @@ constexpr PaletteGroupMetadata kGlobalSprites = { .display_name = "Global Sprites", .category = "Sprites", .base_address = PaletteAddress::kGlobalSpritesLW, - .palette_count = 2, // 2 sets (LW and DW), each with 60 colors - .colors_per_palette = - 60, // 60 colors: 4 rows (0-15, 16-31, 32-47, 48-59) with transparent at 0, 16, 32, 48 + .palette_count = 2, // 2 sets (LW and DW), each with 60 colors + .colors_per_palette = 60, // 60 colors: 4 rows (0-15, 16-31, 32-47, 48-59) + // with transparent at 0, 16, 32, 48 .colors_per_row = 16, // Display in 16-color rows for proper SNES alignment .bits_per_pixel = 4, .description = @@ -207,8 +207,8 @@ constexpr PaletteGroupMetadata kArmor = { .category = "Equipment", .base_address = PaletteAddress::kArmor, .palette_count = PaletteCount::kArmor, - .colors_per_palette = - 15, // 15 colors (ROM stores 15, transparent added in memory for full row) + .colors_per_palette = 15, // 15 colors (ROM stores 15, transparent added in + // memory for full row) .colors_per_row = 16, // Display as full 16-color rows (with transparent at index 0) .bits_per_pixel = 4, @@ -304,9 +304,9 @@ constexpr PaletteGroupMetadata kOverworldMiniMap = { .category = "Interface", .base_address = PaletteAddress::kOverworldMiniMap, .palette_count = PaletteCount::kOverworldMiniMap, - .colors_per_palette = - 128, // 128 colors: 8 full rows (0-127) with transparent at 0, 16, 32, 48, 64, 80, 96, 112 - .colors_per_row = 16, // Display in 16-color rows + .colors_per_palette = 128, // 128 colors: 8 full rows (0-127) with + // transparent at 0, 16, 32, 48, 64, 80, 96, 112 + .colors_per_row = 16, // Display in 16-color rows .bits_per_pixel = 4, .description = "Overworld mini-map palettes: 128 colors per set (8 full rows)", diff --git a/src/zelda3/screen/inventory.cc b/src/zelda3/screen/inventory.cc index 4d7273a7..54543a40 100644 --- a/src/zelda3/screen/inventory.cc +++ b/src/zelda3/screen/inventory.cc @@ -41,8 +41,7 @@ absl::Status Inventory::Create(Rom* rom) { absl::Status Inventory::BuildTileset(Rom* rom) { tilesheets_.reserve(6 * 0x2000); - for (int i = 0; i < 6 * 0x2000; i++) - tilesheets_.push_back(0xFF); + for (int i = 0; i < 6 * 0x2000; i++) tilesheets_.push_back(0xFF); ASSIGN_OR_RETURN(tilesheets_, Load2BppGraphics(*rom)); std::vector test; for (int i = 0; i < 0x4000; i++) { @@ -127,7 +126,8 @@ absl::Status Inventory::LoadItemIcons(Rom* rom) { // - Flute (.flute) // - Bug net (.net) // - Book of Mudora (.book) - // - Bottles (.bottles) - Multiple variants (empty, red potion, green potion, etc.) + // - Bottles (.bottles) - Multiple variants (empty, red potion, green potion, + // etc.) // - Cane of Somaria (.canes) // - Cane of Byrna (.byrn) // - Magic cape (.cape) diff --git a/src/zelda3/screen/overworld_map_screen.cc b/src/zelda3/screen/overworld_map_screen.cc index 9b112aff..88505154 100644 --- a/src/zelda3/screen/overworld_map_screen.cc +++ b/src/zelda3/screen/overworld_map_screen.cc @@ -27,8 +27,8 @@ absl::Status OverworldMapScreen::Create(Rom* rom) { } // Mode 7 tiles are stored in tiled format (each tile's rows are consecutive) - // but we need linear bitmap format (all tiles' first rows, then all second rows) - // Convert from tiled to linear bitmap layout + // but we need linear bitmap format (all tiles' first rows, then all second + // rows) Convert from tiled to linear bitmap layout std::vector mode7_gfx(0x4000); int pos = 0; for (int sy = 0; sy < 16 * 1024; sy += 1024) { // 16 rows of tiles diff --git a/src/zelda3/screen/title_screen.cc b/src/zelda3/screen/title_screen.cc index 4491716e..9ba25168 100644 --- a/src/zelda3/screen/title_screen.cc +++ b/src/zelda3/screen/title_screen.cc @@ -23,7 +23,8 @@ absl::Status TitleScreen::Create(Rom* rom) { oam_bg_bitmap_.Create(256, 256, 8, std::vector(0x80000)); // Set metadata for title screen bitmaps - // Title screen uses 3BPP graphics (like all LTTP data) with composite 64-color palette + // Title screen uses 3BPP graphics (like all LTTP data) with composite + // 64-color palette tiles8_bitmap_.metadata().source_bpp = 3; tiles8_bitmap_.metadata().palette_format = 0; // Full 64-color palette tiles8_bitmap_.metadata().source_type = "graphics_sheet"; @@ -45,7 +46,8 @@ absl::Status TitleScreen::Create(Rom* rom) { oam_bg_bitmap_.metadata().source_type = "screen_buffer"; oam_bg_bitmap_.metadata().palette_colors = 64; - // Initialize composite bitmap for stacked BG rendering (256x256 = 65536 bytes) + // Initialize composite bitmap for stacked BG rendering (256x256 = 65536 + // bytes) title_composite_bitmap_.Create(256, 256, 8, std::vector(256 * 256)); title_composite_bitmap_.metadata().source_bpp = 3; title_composite_bitmap_.metadata().palette_format = 0; @@ -56,16 +58,13 @@ absl::Status TitleScreen::Create(Rom* rom) { tiles_bg1_buffer_.fill(0x492); // Default empty tile tiles_bg2_buffer_.fill(0x492); - // Load palette (title screen uses 3BPP graphics with 8 palettes of 8 colors each) - // Build composite palette from multiple sources (matches ZScream's SetColorsPalette) - // Palette 0: OverworldMainPalettes[5] - // Palette 1: OverworldAnimatedPalettes[0] - // Palette 2: OverworldAuxPalettes[3] - // Palette 3: OverworldAuxPalettes[3] - // Palette 4: HudPalettes[0] - // Palette 5: Transparent/black - // Palette 6: SpritesAux1Palettes[1] - // Palette 7: SpritesAux1Palettes[1] + // Load palette (title screen uses 3BPP graphics with 8 palettes of 8 colors + // each) Build composite palette from multiple sources (matches ZScream's + // SetColorsPalette) Palette 0: OverworldMainPalettes[5] Palette 1: + // OverworldAnimatedPalettes[0] Palette 2: OverworldAuxPalettes[3] Palette 3: + // OverworldAuxPalettes[3] Palette 4: HudPalettes[0] Palette 5: + // Transparent/black Palette 6: SpritesAux1Palettes[1] Palette 7: + // SpritesAux1Palettes[1] auto pal_group = rom->palette_group(); @@ -225,8 +224,8 @@ absl::Status TitleScreen::BuildTileset(Rom* rom) { staticgfx[14] = 112; // UI graphics staticgfx[15] = 112; // UI graphics - // Use pre-converted graphics from ROM buffer - simple and matches rest of yaze - // Title screen uses standard 3BPP graphics, no special offset needed + // Use pre-converted graphics from ROM buffer - simple and matches rest of + // yaze Title screen uses standard 3BPP graphics, no special offset needed const auto& gfx_buffer = rom->graphics_buffer(); auto& tiles8_data = tiles8_bitmap_.mutable_data(); @@ -256,7 +255,6 @@ absl::Status TitleScreen::BuildTileset(Rom* rom) { if (source_offset + 0x1000 <= gfx_buffer.size() && dest_offset + 0x1000 <= tiles8_data.size()) { - std::copy(gfx_buffer.begin() + source_offset, gfx_buffer.begin() + source_offset + 0x1000, tiles8_data.begin() + dest_offset); @@ -501,8 +499,9 @@ absl::Status TitleScreen::RenderBG1Layer() { } // Calculate source position in tiles8_bitmap_ - // tiles8_bitmap_ is 128 pixels wide, 512 pixels tall (16 sheets × 32 pixels) - // Each sheet has 256 tiles (16×16 tiles, 128×32 pixels, 0x1000 bytes) + // tiles8_bitmap_ is 128 pixels wide, 512 pixels tall (16 sheets × 32 + // pixels) Each sheet has 256 tiles (16×16 tiles, 128×32 pixels, 0x1000 + // bytes) int sheet_index = tile_id / 256; // Which sheet (0-15) int tile_in_sheet = tile_id % 256; // Tile within sheet (0-255) int src_tile_x = (tile_in_sheet % 16) * 8; @@ -526,12 +525,13 @@ absl::Status TitleScreen::RenderBG1Layer() { int dest_pos = dest_y * 256 + dest_x; // BG1 is 256 pixels wide // Copy pixel with palette application - // Graphics are 3BPP in ROM, converted to 8BPP indexed with +0x88 offset + // Graphics are 3BPP in ROM, converted to 8BPP indexed with +0x88 + // offset if (src_pos < tile8_bitmap_data.size() && dest_pos < bg1_data.size()) { uint8_t pixel_value = tile8_bitmap_data[src_pos]; - // Pixel values already include palette information from +0x88 offset - // Just copy directly (color index 0 = transparent) + // Pixel values already include palette information from +0x88 + // offset Just copy directly (color index 0 = transparent) bg1_data[dest_pos] = pixel_value; } } @@ -567,8 +567,9 @@ absl::Status TitleScreen::RenderBG2Layer() { bool v_flip = (tile_word & 0x8000) != 0; // Bit 15: vertical flip // Calculate source position in tiles8_bitmap_ - // tiles8_bitmap_ is 128 pixels wide, 512 pixels tall (16 sheets × 32 pixels) - // Each sheet has 256 tiles (16×16 tiles, 128×32 pixels, 0x1000 bytes) + // tiles8_bitmap_ is 128 pixels wide, 512 pixels tall (16 sheets × 32 + // pixels) Each sheet has 256 tiles (16×16 tiles, 128×32 pixels, 0x1000 + // bytes) int sheet_index = tile_id / 256; // Which sheet (0-15) int tile_in_sheet = tile_id % 256; // Tile within sheet (0-255) int src_tile_x = (tile_in_sheet % 16) * 8; @@ -592,12 +593,13 @@ absl::Status TitleScreen::RenderBG2Layer() { int dest_pos = dest_y * 256 + dest_x; // BG2 is 256 pixels wide // Copy pixel with palette application - // Graphics are 3BPP in ROM, converted to 8BPP indexed with +0x88 offset + // Graphics are 3BPP in ROM, converted to 8BPP indexed with +0x88 + // offset if (src_pos < tile8_bitmap_data.size() && dest_pos < bg2_data.size()) { uint8_t pixel_value = tile8_bitmap_data[src_pos]; - // Pixel values already include palette information from +0x88 offset - // Just copy directly (color index 0 = transparent) + // Pixel values already include palette information from +0x88 + // offset Just copy directly (color index 0 = transparent) bg2_data[dest_pos] = pixel_value; } } diff --git a/src/zelda3/sprite/sprite_builder.cc b/src/zelda3/sprite/sprite_builder.cc index de48db18..c329fe8e 100644 --- a/src/zelda3/sprite/sprite_builder.cc +++ b/src/zelda3/sprite/sprite_builder.cc @@ -48,8 +48,7 @@ std::string SpriteBuilder::BuildProperties() const { // Build the properties for (int i = 0; i < 27; ++i) { std::string property = "00"; - if (!properties[i].empty()) - property = properties[i]; + if (!properties[i].empty()) property = properties[i]; ss << kSpriteProperties[i] << " = $" << property << std::endl; } return ss.str(); @@ -88,9 +87,7 @@ SpriteAction& SpriteAction::SetNextAction(const std::string& nextActionName) { return *this; } -std::string SpriteAction::GetConfiguration() const { - return ""; -} +std::string SpriteAction::GetConfiguration() const { return ""; } // ============================================================================ diff --git a/src/zelda3/zelda3_labels.cc b/src/zelda3/zelda3_labels.cc index 7e10b23e..282d4b48 100644 --- a/src/zelda3/zelda3_labels.cc +++ b/src/zelda3/zelda3_labels.cc @@ -1,4 +1,5 @@ #include "zelda3/zelda3_labels.h" + #include #include #include diff --git a/src/zelda3/zelda3_labels.h b/src/zelda3/zelda3_labels.h index c1413ad6..db43787c 100644 --- a/src/zelda3/zelda3_labels.h +++ b/src/zelda3/zelda3_labels.h @@ -12,10 +12,11 @@ namespace zelda3 { /** * @struct Zelda3Labels * @brief Centralized default labels for all Zelda 3 resources - * - * This structure contains all the default names/labels for various game resources. - * These labels are embedded directly into the project file format and are always - * available to the AI agents (Ollama/Gemini) without requiring external files. + * + * This structure contains all the default names/labels for various game + * resources. These labels are embedded directly into the project file format + * and are always available to the AI agents (Ollama/Gemini) without requiring + * external files. */ struct Zelda3Labels { // Dungeon/Room names (296 rooms total) @@ -66,7 +67,8 @@ struct Zelda3Labels { /** * @brief Get a label by resource type and ID - * @param resource_type The type of resource (e.g., "room", "entrance", "sprite") + * @param resource_type The type of resource (e.g., "room", "entrance", + * "sprite") * @param id The numeric ID of the resource * @param default_value Fallback value if label not found * @return The label string diff --git a/test/benchmarks/gfx_optimization_benchmarks.cc b/test/benchmarks/gfx_optimization_benchmarks.cc index 262c70bc..86e4e67e 100644 --- a/test/benchmarks/gfx_optimization_benchmarks.cc +++ b/test/benchmarks/gfx_optimization_benchmarks.cc @@ -1,4 +1,5 @@ #include + #include #include #include diff --git a/test/e2e/canvas_selection_test.cc b/test/e2e/canvas_selection_test.cc index d3689d5a..e6ebe805 100644 --- a/test/e2e/canvas_selection_test.cc +++ b/test/e2e/canvas_selection_test.cc @@ -1,5 +1,6 @@ #define IMGUI_DEFINE_MATH_OPERATORS #include "e2e/canvas_selection_test.h" + #include "app/controller.h" #include "test_utils.h" @@ -50,8 +51,8 @@ void E2ETest_CanvasSelectionTest(ImGuiTestContext* ctx) { uint16_t new_tile3 = overworld->GetTile(75, 38); uint16_t new_tile4 = overworld->GetTile(76, 38); - // The bug is that the selection wraps around, so the pasted tiles are incorrect. - // We expect the new tiles to be different from the original tiles. + // The bug is that the selection wraps around, so the pasted tiles are + // incorrect. We expect the new tiles to be different from the original tiles. IM_CHECK_NE(orig_tile1, new_tile1); IM_CHECK_NE(orig_tile2, new_tile2); IM_CHECK_NE(orig_tile3, new_tile3); diff --git a/test/e2e/dungeon_editor_smoke_test.cc b/test/e2e/dungeon_editor_smoke_test.cc index 11beb277..1db92ce0 100644 --- a/test/e2e/dungeon_editor_smoke_test.cc +++ b/test/e2e/dungeon_editor_smoke_test.cc @@ -1,11 +1,12 @@ #include "e2e/dungeon_editor_smoke_test.h" + #include "app/controller.h" #include "imgui_test_engine/imgui_te_context.h" #include "test_utils.h" /** * @brief Quick smoke test for DungeonEditorV2 - * + * * Tests the card-based architecture: * - Independent windows (cards) can be opened/closed * - Room cards function correctly diff --git a/test/e2e/dungeon_editor_smoke_test.h b/test/e2e/dungeon_editor_smoke_test.h index 0d83949c..ce05549f 100644 --- a/test/e2e/dungeon_editor_smoke_test.h +++ b/test/e2e/dungeon_editor_smoke_test.h @@ -5,7 +5,7 @@ /** * @brief Quick smoke test for DungeonEditorV2 card-based UI - * + * * Tests basic functionality: * - Opening dungeon editor * - Opening independent cards (Rooms, Matrix, Objects, etc.) diff --git a/test/e2e/dungeon_object_rendering_e2e_tests.cc b/test/e2e/dungeon_object_rendering_e2e_tests.cc index bdcc9156..e8b0028d 100644 --- a/test/e2e/dungeon_object_rendering_e2e_tests.cc +++ b/test/e2e/dungeon_object_rendering_e2e_tests.cc @@ -1,30 +1,32 @@ /** * @file dungeon_object_rendering_e2e_tests.cc - * @brief End-to-end tests for dungeon object rendering system using imgui test engine - * - * These tests orchestrate complete user workflows for the dungeon editor, validating: + * @brief End-to-end tests for dungeon object rendering system using imgui test + * engine + * + * These tests orchestrate complete user workflows for the dungeon editor, + * validating: * - Object browser and selection * - Object placement on canvas * - Object manipulation (move, delete, edit) * - Layer management * - Save/load workflows * - Rendering quality across different scenarios - * + * * Created: October 4, 2025 * Related: docs/dungeon_editing_implementation_plan.md - * + * * ============================================================================ * UPDATE NOTICE (October 2025): Tests need rewrite for DungeonEditorV2 * ============================================================================ - * + * * These tests were written for the old monolithic DungeonEditor but need to be * updated for the new DungeonEditorV2 card-based architecture: - * + * * OLD ARCHITECTURE: * - Single "Dungeon Editor" window with tabs * - Object Selector, Canvas, Layers all in one window * - Monolithic UI structure - * + * * NEW ARCHITECTURE (DungeonEditorV2): * - Independent EditorCard windows: * - "Dungeon Controls" - main control panel @@ -35,14 +37,14 @@ * - Individual room cards (e.g., "Room 0x00###RoomCard0") * - Per-room layer visibility settings * - Dockable, closable independent windows - * + * * REQUIRED UPDATES: * 1. Change window references from "Dungeon Editor" to appropriate card names * 2. Update tab navigation to card window focus * 3. Update object placement workflow for new ObjectEditorCard * 4. Update layer controls for per-room settings * 5. Update room selection to work with new room cards - * + * * Current Status: Tests compile but may fail due to UI structure changes. * See: test/e2e/dungeon_editor_smoke_test.cc for updated test patterns. */ @@ -51,15 +53,14 @@ #include -#include "imgui.h" -#include "imgui_test_engine/imgui_te_context.h" -#include "imgui_test_engine/imgui_te_engine.h" -#include "imgui_test_engine/imgui_te_ui.h" - #include "app/controller.h" #include "app/editor/dungeon/dungeon_editor_v2.h" #include "app/platform/window.h" #include "app/rom.h" +#include "imgui.h" +#include "imgui_test_engine/imgui_te_context.h" +#include "imgui_test_engine/imgui_te_engine.h" +#include "imgui_test_engine/imgui_te_ui.h" #include "test_utils.h" #include "zelda3/dungeon/room.h" #include "zelda3/dungeon/room_object.h" @@ -129,7 +130,7 @@ class DungeonObjectRenderingE2ETests : public TestRomManager::BoundRomTest { /** * @brief Test: Navigate object browser categories - * + * * Validates: * - Tab navigation works * - Each category displays objects @@ -173,7 +174,7 @@ void DungeonObjectRenderingE2ETests::RegisterObjectBrowserTests() { /** * @brief Test: Select object from browser - * + * * Validates: * - Object can be selected by clicking * - Preview updates when object selected @@ -216,7 +217,7 @@ void RegisterObjectBrowserTests_SelectObject( /** * @brief Test: Search and filter objects - * + * * Validates: * - Search box filters object list * - Filtering by ID works @@ -259,7 +260,7 @@ void RegisterObjectBrowserTests_SearchFilter( /** * @brief Test: Place object on canvas with mouse click - * + * * Validates: * - Object preview follows mouse cursor * - Click places object at correct position @@ -314,7 +315,7 @@ void DungeonObjectRenderingE2ETests::RegisterObjectPlacementTests() { /** * @brief Test: Place object with snap to grid - * + * * Validates: * - Snap to grid option works * - Object positions align to grid @@ -359,7 +360,7 @@ void RegisterObjectPlacementTests_SnapToGrid( /** * @brief Test: Place multiple objects sequentially - * + * * Validates: * - Multiple objects can be placed * - Each placement is independent @@ -407,7 +408,7 @@ void RegisterObjectPlacementTests_MultipleObjects( /** * @brief Test: Select object by clicking on canvas - * + * * Validates: * - Click on object selects it * - Selection highlight appears @@ -449,7 +450,7 @@ void DungeonObjectRenderingE2ETests::RegisterObjectSelectionTests() { /** * @brief Test: Multi-select objects with Ctrl+drag - * + * * Validates: * - Ctrl+drag creates selection box * - All objects in box are selected @@ -498,7 +499,7 @@ void RegisterObjectSelectionTests_MultiSelect( /** * @brief Test: Move selected object with drag - * + * * Validates: * - Selected object can be dragged * - Object position updates during drag @@ -545,7 +546,7 @@ void RegisterObjectSelectionTests_MoveObject( /** * @brief Test: Delete selected object - * + * * Validates: * - Delete key removes selected object * - Object no longer in room list @@ -594,7 +595,7 @@ void RegisterObjectSelectionTests_DeleteObject( /** * @brief Test: Toggle layer visibility - * + * * Validates: * - Layer visibility checkboxes work * - Hidden layers don't render @@ -632,7 +633,7 @@ void DungeonObjectRenderingE2ETests::RegisterLayerManagementTests() { /** * @brief Test: Place objects on different layers - * + * * Validates: * - Active layer can be changed * - Objects placed on correct layer @@ -694,7 +695,7 @@ void RegisterLayerManagementTests_PlaceOnLayers( /** * @brief Test: Layer rendering order - * + * * Validates: * - Layers render in correct order (BG1 < BG2 < BG3) * - Overlapping objects render correctly @@ -748,7 +749,7 @@ void RegisterLayerManagementTests_RenderingOrder( /** * @brief Test: Save room with objects - * + * * Validates: * - Objects can be saved to ROM * - Save operation succeeds @@ -789,7 +790,7 @@ void DungeonObjectRenderingE2ETests::RegisterSaveWorkflowTests() { /** * @brief Test: Save and reload room (round-trip) - * + * * Validates: * - Objects persist after save/reload * - Object properties are preserved @@ -844,7 +845,7 @@ void RegisterSaveWorkflowTests_RoundTrip(DungeonObjectRenderingE2ETests* self) { /** * @brief Test: Save with multiple object types - * + * * Validates: * - Type1, Type2, Type3 objects all save correctly * - Encoding is correct for each type @@ -909,7 +910,7 @@ void RegisterSaveWorkflowTests_MultipleTypes( /** * @brief Test: Render all object types correctly - * + * * Validates: * - Type1 objects render * - Type2 objects render @@ -959,7 +960,7 @@ void DungeonObjectRenderingE2ETests::RegisterRenderingQualityTests() { /** * @brief Test: Render with different palettes - * + * * Validates: * - Palette switching works * - Objects render with correct colors @@ -1005,7 +1006,7 @@ void RegisterRenderingQualityTests_Palettes( /** * @brief Test: Complex room scenario rendering - * + * * Validates: * - Many objects render correctly * - Performance is acceptable @@ -1073,7 +1074,7 @@ void RegisterRenderingQualityTests_ComplexRoom( /** * @brief Test: Large room with many objects performance - * + * * Validates: * - Rendering stays performant with 100+ objects * - Frame time stays below threshold diff --git a/test/e2e/framework_smoke_test.cc b/test/e2e/framework_smoke_test.cc index baf93a83..4d4778b7 100644 --- a/test/e2e/framework_smoke_test.cc +++ b/test/e2e/framework_smoke_test.cc @@ -1,4 +1,5 @@ #include "e2e/framework_smoke_test.h" + #include "imgui.h" #include "imgui_test_engine/imgui_te_context.h" #include "test_utils.h" diff --git a/test/e2e/overworld/overworld_e2e_test.cc b/test/e2e/overworld/overworld_e2e_test.cc index 03a6156d..cb28acc6 100644 --- a/test/e2e/overworld/overworld_e2e_test.cc +++ b/test/e2e/overworld/overworld_e2e_test.cc @@ -1,4 +1,5 @@ #include + #include #include #include @@ -14,7 +15,7 @@ namespace test { /** * @brief Comprehensive End-to-End Overworld Test Suite - * + * * This test suite validates the complete overworld editing workflow: * 1. Load vanilla ROM and extract golden data * 2. Apply ZSCustomOverworld ASM patches @@ -82,15 +83,12 @@ class OverworldE2ETest : public ::testing::Test { // For now, we'll do basic validation // Check basic ROM properties - if (rom.title().empty()) - return false; - if (rom.size() < 1024 * 1024) - return false; // At least 1MB + if (rom.title().empty()) return false; + if (rom.size() < 1024 * 1024) return false; // At least 1MB // Check ASM version auto asm_version = rom.ReadByte(0x140145); - if (!asm_version.ok()) - return false; + if (!asm_version.ok()) return false; return true; } @@ -396,7 +394,8 @@ TEST_F(OverworldE2ETest, RomDependentTestSuiteIntegration) { EXPECT_LE(map.area_size(), zelda3::AreaSizeEnum::TallArea); } - // Test that sprite data is accessible (matches RomDependentTestSuite expectations) + // Test that sprite data is accessible (matches RomDependentTestSuite + // expectations) const auto& sprites = overworld.all_sprites(); EXPECT_EQ(sprites.size(), 3); // Three game states diff --git a/test/e2e/rom_dependent/e2e_rom_test.cc b/test/e2e/rom_dependent/e2e_rom_test.cc index bea8b7ce..85977253 100644 --- a/test/e2e/rom_dependent/e2e_rom_test.cc +++ b/test/e2e/rom_dependent/e2e_rom_test.cc @@ -1,4 +1,5 @@ #include + #include #include #include @@ -14,7 +15,7 @@ namespace test { /** * @brief Comprehensive End-to-End ROM testing suite - * + * * This test suite validates the complete ROM editing workflow: * 1. Load vanilla ROM * 2. Apply various edits (ROM data, graphics, etc.) diff --git a/test/e2e/zscustomoverworld/zscustomoverworld_upgrade_test.cc b/test/e2e/zscustomoverworld/zscustomoverworld_upgrade_test.cc index 67e84c25..0519e87d 100644 --- a/test/e2e/zscustomoverworld/zscustomoverworld_upgrade_test.cc +++ b/test/e2e/zscustomoverworld/zscustomoverworld_upgrade_test.cc @@ -1,4 +1,5 @@ #include + #include #include #include @@ -13,7 +14,7 @@ namespace test { /** * @brief ZSCustomOverworld upgrade testing suite - * + * * This test suite validates ZSCustomOverworld version upgrades: * 1. Vanilla -> v2 upgrade with proper address changes * 2. v2 -> v3 upgrade with expanded features diff --git a/test/integration/ai/test_ai_tile_placement.cc b/test/integration/ai/test_ai_tile_placement.cc index 239dddeb..1de176b1 100644 --- a/test/integration/ai/test_ai_tile_placement.cc +++ b/test/integration/ai/test_ai_tile_placement.cc @@ -1,9 +1,8 @@ -#include "gtest/gtest.h" - #include "absl/strings/str_format.h" #include "cli/service/ai/ai_action_parser.h" #include "cli/service/ai/ai_gui_controller.h" #include "cli/service/ai/vision_action_refiner.h" +#include "gtest/gtest.h" #ifdef YAZE_WITH_GRPC #include "cli/service/ai/gemini_ai_service.h" @@ -15,7 +14,7 @@ namespace test { /** * @brief Integration tests for AI-controlled tile placement - * + * * These tests verify the complete pipeline: * 1. Parse natural language commands * 2. Execute actions via gRPC diff --git a/test/integration/asar_integration_test.cc b/test/integration/asar_integration_test.cc index c8ed7abe..9a2c3025 100644 --- a/test/integration/asar_integration_test.cc +++ b/test/integration/asar_integration_test.cc @@ -1,4 +1,6 @@ +#include #include + #include #include @@ -7,9 +9,6 @@ #include "core/asar_wrapper.h" #include "testing.h" -#include -#include - namespace yaze { namespace test { namespace integration { diff --git a/test/integration/asar_rom_test.cc b/test/integration/asar_rom_test.cc index 72adfb96..0f783fe1 100644 --- a/test/integration/asar_rom_test.cc +++ b/test/integration/asar_rom_test.cc @@ -4,6 +4,7 @@ #endif #include + #include #include @@ -330,7 +331,8 @@ TEST_F(AsarRomIntegrationTest, GameplayModificationPatch) { // Check health modification at 0x7EF36C -> ROM offset would need calculation // For a proper test, we'd need to convert SNES addresses to ROM offsets - // Check if custom routine was inserted at 0xC000 -> ROM offset 0x18000 (in LoROM) + // Check if custom routine was inserted at 0xC000 -> ROM offset 0x18000 (in + // LoROM) const uint32_t rom_offset = 0x18000; // Bank $00:C000 in LoROM if (rom_offset < rom_copy.size()) { // Check for SEP #$20 instruction (0xE2 0x20) diff --git a/test/integration/dungeon_editor_test.h b/test/integration/dungeon_editor_test.h index 90b6bb26..8ee2deac 100644 --- a/test/integration/dungeon_editor_test.h +++ b/test/integration/dungeon_editor_test.h @@ -14,7 +14,7 @@ namespace test { /** * @brief Integration test framework using real ROM data - * + * * Updated for DungeonEditorV2 with card-based architecture */ class DungeonEditorIntegrationTest : public ::testing::Test { diff --git a/test/integration/dungeon_editor_v2_test.h b/test/integration/dungeon_editor_v2_test.h index c1dfd2af..64ae1fc5 100644 --- a/test/integration/dungeon_editor_v2_test.h +++ b/test/integration/dungeon_editor_v2_test.h @@ -13,7 +13,7 @@ namespace test { /** * @brief Integration test framework for DungeonEditorV2 - * + * * Tests the simplified component delegation architecture */ class DungeonEditorV2IntegrationTest : public ::testing::Test { diff --git a/test/integration/editor/editor_integration_test.h b/test/integration/editor/editor_integration_test.h index 848618d0..9ffa653f 100644 --- a/test/integration/editor/editor_integration_test.h +++ b/test/integration/editor/editor_integration_test.h @@ -21,12 +21,14 @@ namespace test { /** * @class EditorIntegrationTest * @brief Base class for editor integration tests - * - * This class provides common functionality for testing editors in the application. - * It sets up the test environment and provides helper methods for ROM operations. - * - * For UI interaction testing, use the ImGui test engine API directly within your test functions: - * + * + * This class provides common functionality for testing editors in the + * application. It sets up the test environment and provides helper methods for + * ROM operations. + * + * For UI interaction testing, use the ImGui test engine API directly within + * your test functions: + * * ImGuiTest* test = IM_REGISTER_TEST(engine, "test_suite", "test_name"); * test->TestFunc = [](ImGuiTestContext* ctx) { * ctx->SetRef("Window Name"); diff --git a/test/integration/editor/tile16_editor_test.cc b/test/integration/editor/tile16_editor_test.cc index 01e19d8a..74683dfd 100644 --- a/test/integration/editor/tile16_editor_test.cc +++ b/test/integration/editor/tile16_editor_test.cc @@ -1,10 +1,11 @@ #include "app/editor/overworld/tile16_editor.h" +#include + #include #include #include -#include #include "app/gfx/backend/sdl2_renderer.h" #include "app/gfx/core/bitmap.h" #include "app/gfx/render/tilemap.h" diff --git a/test/integration/zelda3/dungeon_editor_system_integration_test.cc b/test/integration/zelda3/dungeon_editor_system_integration_test.cc index e1b023a4..3896b9d2 100644 --- a/test/integration/zelda3/dungeon_editor_system_integration_test.cc +++ b/test/integration/zelda3/dungeon_editor_system_integration_test.cc @@ -1,4 +1,5 @@ #include + #include #include #include diff --git a/test/integration/zelda3/dungeon_object_rendering_tests.cc b/test/integration/zelda3/dungeon_object_rendering_tests.cc index 5b89cfd8..84bc18c5 100644 --- a/test/integration/zelda3/dungeon_object_rendering_tests.cc +++ b/test/integration/zelda3/dungeon_object_rendering_tests.cc @@ -1,16 +1,13 @@ // Integration tests for dungeon object rendering using ObjectDrawer -// Updated for DungeonEditorV2 architecture - uses ObjectDrawer (production system) -// instead of the obsolete ObjectRenderer +// Updated for DungeonEditorV2 architecture - uses ObjectDrawer (production +// system) instead of the obsolete ObjectRenderer #ifndef IMGUI_DEFINE_MATH_OPERATORS #define IMGUI_DEFINE_MATH_OPERATORS #endif -#include "zelda3/dungeon/object_drawer.h" -#include "zelda3/dungeon/room.h" -#include "zelda3/dungeon/room_object.h" - #include + #include #include #include @@ -20,13 +17,16 @@ #include "app/rom.h" #include "test_utils.h" #include "testing.h" +#include "zelda3/dungeon/object_drawer.h" +#include "zelda3/dungeon/room.h" +#include "zelda3/dungeon/room_object.h" namespace yaze { namespace test { /** * @brief Tests for ObjectDrawer with realistic dungeon scenarios - * + * * These tests validate that ObjectDrawer correctly renders dungeon objects * to BackgroundBuffers using pattern-based drawing routines. */ diff --git a/test/integration/zelda3/dungeon_object_rendering_tests_new.cc b/test/integration/zelda3/dungeon_object_rendering_tests_new.cc index 2fbe7edb..02aba303 100644 --- a/test/integration/zelda3/dungeon_object_rendering_tests_new.cc +++ b/test/integration/zelda3/dungeon_object_rendering_tests_new.cc @@ -1,12 +1,9 @@ // Integration tests for dungeon object rendering using ObjectDrawer -// Updated for DungeonEditorV2 architecture - uses ObjectDrawer (production system) -// instead of the obsolete ObjectRenderer - -#include "zelda3/dungeon/object_drawer.h" -#include "zelda3/dungeon/room.h" -#include "zelda3/dungeon/room_object.h" +// Updated for DungeonEditorV2 architecture - uses ObjectDrawer (production +// system) instead of the obsolete ObjectRenderer #include + #include #include #include @@ -16,13 +13,16 @@ #include "app/rom.h" #include "test_utils.h" #include "testing.h" +#include "zelda3/dungeon/object_drawer.h" +#include "zelda3/dungeon/room.h" +#include "zelda3/dungeon/room_object.h" namespace yaze { namespace test { /** * @brief Tests for ObjectDrawer with realistic dungeon scenarios - * + * * These tests validate that ObjectDrawer correctly renders dungeon objects * to BackgroundBuffers using pattern-based drawing routines. */ diff --git a/test/integration/zelda3/dungeon_rendering_test.cc b/test/integration/zelda3/dungeon_rendering_test.cc index bcc8200b..4a281784 100644 --- a/test/integration/zelda3/dungeon_rendering_test.cc +++ b/test/integration/zelda3/dungeon_rendering_test.cc @@ -1,9 +1,8 @@ -#include "gtest/gtest.h" - #include "absl/status/status.h" #include "app/gfx/background_buffer.h" #include "app/gfx/snes_palette.h" #include "app/rom.h" +#include "gtest/gtest.h" #include "zelda3/dungeon/object_drawer.h" #include "zelda3/dungeon/object_parser.h" #include "zelda3/dungeon/room.h" diff --git a/test/integration/zelda3/message_test.cc b/test/integration/zelda3/message_test.cc index 507b3c69..3be8a41d 100644 --- a/test/integration/zelda3/message_test.cc +++ b/test/integration/zelda3/message_test.cc @@ -1,4 +1,5 @@ #include + #include #include "app/editor/message/message_data.h" @@ -211,7 +212,8 @@ TEST_F(MessageRomTest, BuildDictionaryEntries_CorrectSize) { TEST_F(MessageRomTest, ParseMessageData_CommandWithArgument_NoExtraCharacters) { // This test specifically checks for the bug where command arguments // were being incorrectly parsed as characters (e.g., capital 'A' after [W]) - // The bug was caused by using a range-based for loop while also tracking position + // The bug was caused by using a range-based for loop while also tracking + // position // Message: [W:01]ABC // Bytes: 0x6B (W command), 0x01 (argument), 0x00 (A), 0x01 (B), 0x02 (C) diff --git a/test/integration/zelda3/overworld_integration_test.cc b/test/integration/zelda3/overworld_integration_test.cc index af380975..634badee 100644 --- a/test/integration/zelda3/overworld_integration_test.cc +++ b/test/integration/zelda3/overworld_integration_test.cc @@ -1,4 +1,5 @@ #include + #include #include #include @@ -13,9 +14,10 @@ namespace yaze { namespace zelda3 { /** - * @brief Comprehensive overworld integration test that validates YAZE C++ - * implementation against ZScream C# logic and existing test infrastructure - * + * @brief Comprehensive overworld integration test that validates YAZE C++ + * implementation against ZScream C# logic and existing test + * infrastructure + * * This test suite: * 1. Validates overworld loading logic matches ZScream behavior * 2. Tests integration with ZSCustomOverworld versions (vanilla, v2, v3) @@ -78,7 +80,8 @@ class OverworldIntegrationTest : public ::testing::Test { mock_rom_data_[0x012844 + i] = 0x00; // Small areas } - // Setup entrance data (matches ZScream Constants.OWEntranceMap/Pos/EntranceId) + // Setup entrance data (matches ZScream + // Constants.OWEntranceMap/Pos/EntranceId) for (int i = 0; i < 129; i++) { mock_rom_data_[0x0DB96F + (i * 2)] = i & 0xFF; // Map ID mock_rom_data_[0x0DB96F + (i * 2) + 1] = (i >> 8) & 0xFF; @@ -267,7 +270,8 @@ TEST_F(OverworldIntegrationTest, RomDependentTestSuiteCompatibility) { << "Real ROM required for RomDependentTestSuite compatibility testing"; } - // Test that our overworld loading works with the same patterns as RomDependentTestSuite + // Test that our overworld loading works with the same patterns as + // RomDependentTestSuite auto status = overworld_->Load(rom_.get()); ASSERT_TRUE(status.ok()); @@ -288,7 +292,8 @@ TEST_F(OverworldIntegrationTest, RomDependentTestSuiteCompatibility) { EXPECT_LE(map.area_size(), AreaSizeEnum::TallArea); } - // Test that sprite data is accessible (matches RomDependentTestSuite expectations) + // Test that sprite data is accessible (matches RomDependentTestSuite + // expectations) const auto& sprites = overworld_->sprites(0); EXPECT_EQ(sprites.size(), 3); // Three game states @@ -359,8 +364,8 @@ TEST_F(OverworldIntegrationTest, ZScreamCoordinateCompatibility) { // int p = mapPos >> 1; // int x = p % 64; // int y = p >> 6; - // int real_x = (x * 16) + (((mapId % 64) - (((mapId % 64) / 8) * 8)) * 512); - // int real_y = (y * 16) + (((mapId % 64) / 8) * 512); + // int real_x = (x * 16) + (((mapId % 64) - (((mapId % 64) / 8) * 8)) * + // 512); int real_y = (y * 16) + (((mapId % 64) / 8) * 512); uint16_t map_pos = entrance.map_pos_; uint16_t map_id = entrance.map_id_; @@ -387,8 +392,8 @@ TEST_F(OverworldIntegrationTest, ZScreamCoordinateCompatibility) { // int p = (mapPos + 0x400) >> 1; // int x = p % 64; // int y = p >> 6; - // int real_x = (x * 16) + (((mapId % 64) - (((mapId % 64) / 8) * 8)) * 512); - // int real_y = (y * 16) + (((mapId % 64) / 8) * 512); + // int real_x = (x * 16) + (((mapId % 64) - (((mapId % 64) / 8) * 8)) * + // 512); int real_y = (y * 16) + (((mapId % 64) / 8) * 512); uint16_t map_pos = hole.map_pos_; uint16_t map_id = hole.map_id_; diff --git a/test/integration/zelda3/room_integration_test.cc b/test/integration/zelda3/room_integration_test.cc index 7ccc8e8f..9d654c2d 100644 --- a/test/integration/zelda3/room_integration_test.cc +++ b/test/integration/zelda3/room_integration_test.cc @@ -277,8 +277,7 @@ TEST_F(RoomIntegrationTest, BinaryDataExactMatch) { break; } } - if (might_be_final) - break; + if (might_be_final) break; } } @@ -319,12 +318,9 @@ TEST_F(RoomIntegrationTest, KnownRoomData) { bool found_layer1 = false; for (const auto& obj : objects) { - if (obj.id_ < 0x100) - found_type1 = true; - if (obj.GetLayerValue() == 0) - found_layer0 = true; - if (obj.GetLayerValue() == 1) - found_layer1 = true; + if (obj.id_ < 0x100) found_type1 = true; + if (obj.GetLayerValue() == 0) found_layer0 = true; + if (obj.GetLayerValue() == 1) found_layer1 = true; } EXPECT_TRUE(found_type1) << "Should have Type 1 objects"; diff --git a/test/integration/zelda3/sprite_position_test.cc b/test/integration/zelda3/sprite_position_test.cc index 444424a0..f3258ca6 100644 --- a/test/integration/zelda3/sprite_position_test.cc +++ b/test/integration/zelda3/sprite_position_test.cc @@ -1,4 +1,5 @@ #include + #include #include #include @@ -125,7 +126,6 @@ TEST_F(SpritePositionTest, MapCoordinateCalculations) { if (!sprite.deleted() && sprite.map_id() < 0x40 + (current_world * 0x40) && sprite.map_id() >= (current_world * 0x40)) { - // Calculate map position int sprite_map_id = sprite.map_id(); int local_map_index = sprite_map_id - (current_world * 0x40); diff --git a/test/mocks/mock_rom.h b/test/mocks/mock_rom.h index 5947bf10..d0476882 100644 --- a/test/mocks/mock_rom.h +++ b/test/mocks/mock_rom.h @@ -4,16 +4,16 @@ #include #include -#include "testing.h" - #include "app/rom.h" +#include "testing.h" namespace yaze { namespace test { /** - * @brief Enhanced ROM for testing that behaves like a real ROM but with test data - * + * @brief Enhanced ROM for testing that behaves like a real ROM but with test + * data + * * This class extends Rom to provide testing utilities while maintaining * all the real ROM functionality. Instead of mocking methods, it loads * real test data into the ROM. diff --git a/test/test_conversation_minimal.cc b/test/test_conversation_minimal.cc index edb9b673..eed96fab 100644 --- a/test/test_conversation_minimal.cc +++ b/test/test_conversation_minimal.cc @@ -1,4 +1,5 @@ #include + #include "app/rom.h" #include "cli/service/agent/conversational_agent_service.h" #include "cli/service/ai/service_factory.h" diff --git a/test/test_utils.cc b/test/test_utils.cc index af43d3ca..4a710585 100644 --- a/test/test_utils.cc +++ b/test/test_utils.cc @@ -1,4 +1,5 @@ #include "test_utils.h" + #include "app/controller.h" namespace yaze { diff --git a/test/test_utils.h b/test/test_utils.h index eb4f2fdd..1cd0720a 100644 --- a/test/test_utils.h +++ b/test/test_utils.h @@ -5,15 +5,15 @@ #define IMGUI_DEFINE_MATH_OPERATORS #endif +#include +#include + #include #include #include #include #include -#include -#include - #include "absl/strings/str_format.h" #include "app/rom.h" #include "imgui_test_engine/imgui_te_context.h" diff --git a/test/testing.h b/test/testing.h index d0fbfaa1..bbd4f8ae 100644 --- a/test/testing.h +++ b/test/testing.h @@ -23,9 +23,7 @@ namespace test { // StatusIs is a matcher that matches a status that has the same code and // message as the expected status. -MATCHER_P(StatusIs, status, "") { - return arg.code() == status; -} +MATCHER_P(StatusIs, status, "") { return arg.code() == status; } // Support for testing absl::StatusOr. template @@ -42,9 +40,7 @@ template return ::testing::AssertionSuccess(); } -MATCHER_P(IsOkAndHolds, value, "") { - return IsOkAndHolds(arg, value); -} +MATCHER_P(IsOkAndHolds, value, "") { return IsOkAndHolds(arg, value); } // Helper to test if a StatusOr contains an error with a specific message MATCHER_P(StatusIsWithMessage, message, "") { diff --git a/test/unit/core/asar_wrapper_test.cc b/test/unit/core/asar_wrapper_test.cc index 44469ace..78ed474d 100644 --- a/test/unit/core/asar_wrapper_test.cc +++ b/test/unit/core/asar_wrapper_test.cc @@ -1,11 +1,13 @@ #include "core/asar_wrapper.h" -#include "test_utils.h" #include #include + #include #include +#include "test_utils.h" + namespace yaze { namespace core { namespace { diff --git a/test/unit/core/hex_test.cc b/test/unit/core/hex_test.cc index d105b43c..50ebed32 100644 --- a/test/unit/core/hex_test.cc +++ b/test/unit/core/hex_test.cc @@ -1,7 +1,7 @@ -#include "testing.h" - #include "util/hex.h" +#include "testing.h" + namespace yaze { namespace test { diff --git a/test/unit/gfx/snes_tile_test.cc b/test/unit/gfx/snes_tile_test.cc index 6abdff58..edd05cb6 100644 --- a/test/unit/gfx/snes_tile_test.cc +++ b/test/unit/gfx/snes_tile_test.cc @@ -43,8 +43,9 @@ TEST(SnesTileTest, UnpackBppTile) { EXPECT_EQ(tile2bpp.data[63], 3); // Last pixel: 1|1<<1 = 3 // Test 4bpp tile unpacking - // According to SnesLab: First planes 1&2 intertwined, then planes 3&4 intertwined - // 32 bytes total: 16 bytes for planes 1&2, then 16 bytes for planes 3&4 + // According to SnesLab: First planes 1&2 intertwined, then planes 3&4 + // intertwined 32 bytes total: 16 bytes for planes 1&2, then 16 bytes for + // planes 3&4 std::vector data4bpp = { // Planes 1&2 intertwined (rows 0-7) 0x81, 0x80, // Row 0: bp1=10000001, bp2=10000000 diff --git a/test/unit/gui/canvas_automation_api_test.cc b/test/unit/gui/canvas_automation_api_test.cc index 1c6f88cc..f85db408 100644 --- a/test/unit/gui/canvas_automation_api_test.cc +++ b/test/unit/gui/canvas_automation_api_test.cc @@ -316,7 +316,8 @@ TEST_F(CanvasAutomationAPITest, CenterOn_ValidTile) { api_->CenterOn(0, 0); api_->CenterOn(20, 20); - // Verify scroll position changed (should be non-zero after centering on non-origin) + // Verify scroll position changed (should be non-zero after centering on + // non-origin) ImVec2 scroll = canvas_->scrolling(); // Scroll values will depend on canvas size, just verify they're set } diff --git a/test/unit/gui/canvas_coordinate_sync_test.cc b/test/unit/gui/canvas_coordinate_sync_test.cc index ad3e3adb..e57f7ef6 100644 --- a/test/unit/gui/canvas_coordinate_sync_test.cc +++ b/test/unit/gui/canvas_coordinate_sync_test.cc @@ -1,8 +1,7 @@ -#include "app/gui/canvas/canvas.h" - #include #include +#include "app/gui/canvas/canvas.h" #include "testing.h" namespace yaze { @@ -150,8 +149,8 @@ TEST_F(CanvasCoordinateSyncTest, MapCalculation_LargeMaps) { // ============================================================================ TEST_F(CanvasCoordinateSyncTest, HoverPosition_ScaleInvariant) { - // REGRESSION TEST: Hover position should be in world space regardless of scale - // The bug was scale-dependent because it used screen coordinates + // REGRESSION TEST: Hover position should be in world space regardless of + // scale The bug was scale-dependent because it used screen coordinates auto test_hover_at_scale = [&](float scale) { canvas_->set_global_scale(scale); @@ -184,7 +183,8 @@ TEST_F(CanvasCoordinateSyncTest, OverworldMapHighlight_UsesHoverNotDrawn) { // The pattern used in DrawOverworldEdits (line 664) for painting: auto drawn_pos = canvas_->drawn_tile_position(); - // The pattern that SHOULD be used in CheckForCurrentMap (line 1041) for highlighting: + // The pattern that SHOULD be used in CheckForCurrentMap (line 1041) for + // highlighting: auto hover_pos = canvas_->hover_mouse_pos(); // These are different methods for different purposes: diff --git a/test/unit/rom/rom_test.cc b/test/unit/rom/rom_test.cc index 7ebc08de..4e6c089c 100644 --- a/test/unit/rom/rom_test.cc +++ b/test/unit/rom/rom_test.cc @@ -196,7 +196,8 @@ TEST_F(RomTest, SaveTruncatesExistingFile) { #if defined(__linux__) GTEST_SKIP(); #endif - // Prepare ROM data and save to a temp file twice; second save should overwrite, not append + // Prepare ROM data and save to a temp file twice; second save should + // overwrite, not append EXPECT_OK(rom_.LoadFromData(kMockRomData, /*z3_load=*/false)); const char* tmp_name = "test_temp_rom.sfc"; @@ -211,7 +212,8 @@ TEST_F(RomTest, SaveTruncatesExistingFile) { EXPECT_OK(rom_.WriteByte(0, 0xEE)); EXPECT_OK(rom_.SaveToFile(settings)); - // Load the saved file and verify size equals original data size and first byte matches + // Load the saved file and verify size equals original data size and first + // byte matches Rom verify; EXPECT_OK(verify.LoadFromFile(tmp_name, /*z3_load=*/false)); EXPECT_EQ(verify.size(), kMockRomData.size()); diff --git a/test/unit/zelda3/dungeon/object_rendering_test.cc b/test/unit/zelda3/dungeon/object_rendering_test.cc index 372e654b..e3f170ec 100644 --- a/test/unit/zelda3/dungeon/object_rendering_test.cc +++ b/test/unit/zelda3/dungeon/object_rendering_test.cc @@ -1,9 +1,8 @@ -#include "gtest/gtest.h" - #include "absl/status/status.h" #include "app/gfx/background_buffer.h" #include "app/gfx/snes_palette.h" #include "app/rom.h" +#include "gtest/gtest.h" #include "zelda3/dungeon/object_drawer.h" #include "zelda3/dungeon/object_parser.h" #include "zelda3/dungeon/room_object.h" diff --git a/test/unit/zelda3/dungeon/room_manipulation_test.cc b/test/unit/zelda3/dungeon/room_manipulation_test.cc index f15f90c4..142d48ba 100644 --- a/test/unit/zelda3/dungeon/room_manipulation_test.cc +++ b/test/unit/zelda3/dungeon/room_manipulation_test.cc @@ -1,6 +1,7 @@ // Tests for Room object manipulation methods (Phase 3) #include + #include "app/rom.h" #include "zelda3/dungeon/room.h" #include "zelda3/dungeon/room_object.h" diff --git a/test/unit/zelda3/dungeon/room_object_encoding_test.cc b/test/unit/zelda3/dungeon/room_object_encoding_test.cc index bb0c80e0..59a04614 100644 --- a/test/unit/zelda3/dungeon/room_object_encoding_test.cc +++ b/test/unit/zelda3/dungeon/room_object_encoding_test.cc @@ -5,10 +5,10 @@ // correctly for all three object types (Type1, Type2, Type3) based on // ZScream's proven implementation. -#include "zelda3/dungeon/room_object.h" - #include +#include "zelda3/dungeon/room_object.h" + namespace yaze { namespace zelda3 { namespace { diff --git a/test/unit/zelda3/dungeon_component_unit_test.cc b/test/unit/zelda3/dungeon_component_unit_test.cc index 0346d481..efd80b0d 100644 --- a/test/unit/zelda3/dungeon_component_unit_test.cc +++ b/test/unit/zelda3/dungeon_component_unit_test.cc @@ -1,4 +1,5 @@ #include + #include // Test the individual components independently @@ -10,7 +11,7 @@ namespace test { /** * @brief Unit tests for individual dungeon components - * + * * These tests validate component behavior without requiring ROM files * or complex graphics initialization. */ diff --git a/test/unit/zelda3/object_parser_structs_test.cc b/test/unit/zelda3/object_parser_structs_test.cc index fa7dc1d9..4eb795ca 100644 --- a/test/unit/zelda3/object_parser_structs_test.cc +++ b/test/unit/zelda3/object_parser_structs_test.cc @@ -1,6 +1,5 @@ -#include "zelda3/dungeon/object_parser.h" - #include "gtest/gtest.h" +#include "zelda3/dungeon/object_parser.h" namespace yaze { namespace test { diff --git a/test/unit/zelda3/overworld_test.cc b/test/unit/zelda3/overworld_test.cc index 78a4e934..1e83bf37 100644 --- a/test/unit/zelda3/overworld_test.cc +++ b/test/unit/zelda3/overworld_test.cc @@ -1,8 +1,10 @@ +#include "zelda3/overworld/overworld.h" + #include + #include #include "app/rom.h" -#include "zelda3/overworld/overworld.h" #include "zelda3/overworld/overworld_map.h" namespace yaze { diff --git a/test/unit/zelda3/test_dungeon_objects.h b/test/unit/zelda3/test_dungeon_objects.h index 9a43f9d1..92630355 100644 --- a/test/unit/zelda3/test_dungeon_objects.h +++ b/test/unit/zelda3/test_dungeon_objects.h @@ -14,7 +14,7 @@ namespace test { /** * @brief Simplified test framework for dungeon object rendering - * + * * This provides a clean, focused testing environment for dungeon object * functionality without the complexity of full integration tests. */ diff --git a/test/yaze_test.cc b/test/yaze_test.cc index c1aa50cc..29addb9b 100644 --- a/test/yaze_test.cc +++ b/test/yaze_test.cc @@ -7,6 +7,7 @@ #include #include + #include #include #include @@ -219,8 +220,7 @@ void ConfigureTestFilters(const TestConfig& config) { if (!filters.empty()) { std::string filter_string; for (size_t i = 0; i < filters.size(); i++) { - if (i > 0) - filter_string += ":"; + if (i > 0) filter_string += ":"; filter_string += filters[i]; } @@ -284,12 +284,14 @@ int main(int argc, char* argv[]) { ImGuiConfigFlags_NavEnableKeyboard; // Enable Keyboard Controls io.ConfigFlags |= ImGuiConfigFlags_DockingEnable; // Enable Docking io.ConfigFlags |= - ImGuiConfigFlags_ViewportsEnable; // Enable Multi-Viewport / Platform Windows + ImGuiConfigFlags_ViewportsEnable; // Enable Multi-Viewport / Platform + // Windows // Setup Dear ImGui style ImGui::StyleColorsDark(); - // When viewports are enabled we tweak WindowRounding/WindowBg so platform windows can look identical to regular ones. + // When viewports are enabled we tweak WindowRounding/WindowBg so platform + // windows can look identical to regular ones. ImGuiStyle& style = ImGui::GetStyle(); if (io.ConfigFlags & ImGuiConfigFlags_ViewportsEnable) { style.WindowRounding = 0.0f; diff --git a/test/yaze_test_ci.cc b/test/yaze_test_ci.cc index 963f52d2..d6e2dd6f 100644 --- a/test/yaze_test_ci.cc +++ b/test/yaze_test_ci.cc @@ -3,6 +3,7 @@ // to ensure reliable test discovery and execution in automated environments #include + #include #include "absl/debugging/failure_signal_handler.h"