Repository navigation
Expand file tree
/
Copy pathdebug_panel.cpp
More file actions
776 lines (758 loc) · 46.9 KB
/
Copy pathdebug_panel.cpp
File metadata and controls
776 lines (758 loc) · 46.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
#include "eb/debug_panel.hpp"
#include "eb/display_settings.hpp"
// Both panels are host UI only. The runtime panel edits display preferences,
// emits debug commands, and reads snapshots; startup emits import paths.
// Neither receives a bus, CPU, or mutable game-memory reference.
#include "imgui.h"
#include "backends/imgui_impl_opengl2.h"
#include "backends/imgui_impl_sdl2.h"
#include <algorithm>
#include <array>
#include <cmath>
#include <cctype>
#include <filesystem>
#include <stdexcept>
#include <utility>
#include <vector>
namespace eb {
struct DebugPanel::Impl {
// Each panel owns its ImGui context and explicitly selects it before use.
ImGuiContext* context{};
bool visible{}, focus_next_frame{};
bool bar_mouse_down{}, open_confirmation{}, cancel_confirmation{};
float menu_height = 19.0f;
GameDebugSettings game_settings;
ControllerSettings controller_settings;
std::optional<GameDebugRequest> game_action;
std::array<bool,4> party{};
bool party_editing{};
unsigned destination{};
ImGuiTextFilter destination_filter;
std::optional<PanelAction> action, confirmation;
unsigned confirmation_cache{};
std::string action_status;
std::array<char, 129> snapshot_name{};
std::string selected_snapshot, delete_snapshot, snapshot_status;
std::optional<SaveStateSnapshotRequest> snapshot_action;
};
DebugPanel::DebugPanel(SDL_Window* window, SDL_GLContext context): impl_(std::make_unique<Impl>()) {
IMGUI_CHECKVERSION();
impl_->context = ImGui::CreateContext();
auto& io = ImGui::GetIO();
io.IniFilename = nullptr; // Display settings are owned by the frontend.
io.LogFilename = nullptr;
io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard;
// Controller input stays with the game; this panel uses keyboard and mouse.
ImGui::StyleColorsDark();
auto& style = ImGui::GetStyle();
style.WindowRounding = 8.0f;
style.FrameRounding = 4.0f;
style.WindowPadding = ImVec2(16.0f, 14.0f);
style.ItemSpacing = ImVec2(10.0f, 10.0f);
style.Colors[ImGuiCol_WindowBg] = ImVec4(0.075f, 0.085f, 0.11f, 0.98f);
style.Colors[ImGuiCol_TitleBgActive] = ImVec4(0.12f, 0.19f, 0.27f, 1.0f);
style.Colors[ImGuiCol_CheckMark] = ImVec4(0.35f, 0.75f, 0.95f, 1.0f);
if (!ImGui_ImplSDL2_InitForOpenGL(window, context)) {
ImGui::DestroyContext(impl_->context);
throw std::runtime_error("Could not initialize the debug panel SDL backend");
}
if (!ImGui_ImplOpenGL2_Init()) {
// Construction is not complete yet, so unwind the already-live backend
// here rather than relying on the object's destructor to be called.
ImGui_ImplSDL2_Shutdown();
ImGui::DestroyContext(impl_->context);
throw std::runtime_error("Could not initialize the debug panel OpenGL backend");
}
}
DebugPanel::~DebugPanel() {
// Backends release GL/SDL resources while their host context still exists.
ImGui::SetCurrentContext(impl_->context);
ImGui_ImplOpenGL2_Shutdown();
ImGui_ImplSDL2_Shutdown();
ImGui::DestroyContext(impl_->context);
}
bool DebugPanel::process_event(const SDL_Event& event) {
ImGui::SetCurrentContext(impl_->context);
ImGui_ImplSDL2_ProcessEvent(&event);
// Use key transitions, not repeat events, for toggle actions. Consuming F1
// on both down/up also keeps it from leaking into any gameplay handler.
if (event.type == SDL_KEYDOWN && event.key.keysym.sym == SDLK_F1) {
if (!event.key.repeat && !impl_->confirmation) set_visible(!visible());
return true;
}
if (event.type == SDL_KEYUP && event.key.keysym.sym == SDLK_F1) return true;
if (visible() && event.type == SDL_KEYDOWN && event.key.keysym.sym == SDLK_ESCAPE) {
if (!event.key.repeat) {
if (impl_->confirmation) impl_->cancel_confirmation = true;
else if (!impl_->delete_snapshot.empty()) impl_->delete_snapshot.clear();
else set_visible(false);
}
return true;
}
// Merely hovering over the persistent bar must not pause game controls.
// Its mouse interaction is captured, while F1 remains the keyboard entry.
if (event.type == SDL_MOUSEBUTTONDOWN && event.button.y >= 0 && event.button.y < impl_->menu_height)
impl_->bar_mouse_down = true;
if (event.type == SDL_MOUSEBUTTONUP) {
const bool owned = impl_->bar_mouse_down || event.button.y < impl_->menu_height;
impl_->bar_mouse_down = false;
if (owned) return true;
}
if (event.type == SDL_MOUSEMOTION && event.motion.y < impl_->menu_height) return true;
if (!captures_game_input()) return false;
// Capture physical gameplay input for the entire visible panel, including
// when the mouse is outside it. The simulation itself continues to advance.
switch (event.type) {
case SDL_KEYDOWN: case SDL_KEYUP: case SDL_TEXTINPUT: case SDL_TEXTEDITING:
case SDL_MOUSEBUTTONDOWN: case SDL_MOUSEBUTTONUP: case SDL_MOUSEMOTION: case SDL_MOUSEWHEEL:
case SDL_CONTROLLERBUTTONDOWN: case SDL_CONTROLLERBUTTONUP: case SDL_CONTROLLERAXISMOTION:
return true;
default:
return false;
}
}
bool DebugPanel::captures_game_input() const { return impl_->visible || impl_->bar_mouse_down || impl_->confirmation.has_value(); }
bool DebugPanel::visible() const { return impl_->visible; }
void DebugPanel::set_visible(bool visible) {
// Focus once on opening; stealing focus each frame would break text edits.
if (visible && !impl_->visible) impl_->focus_next_frame = true;
if (!visible) impl_->delete_snapshot.clear();
impl_->visible = visible;
}
std::optional<PanelAction> DebugPanel::take_action() { return std::exchange(impl_->action, std::nullopt); }
void DebugPanel::set_action_status(std::string status) { impl_->action_status = std::move(status); }
float DebugPanel::menu_height() const { return impl_->menu_height; }
const GameDebugSettings& DebugPanel::game_settings() const {return impl_->game_settings;}
void DebugPanel::set_game_settings(GameDebugSettings settings) {
impl_->game_settings = settings;
impl_->party_editing = false;
}
const ControllerSettings& DebugPanel::controller_settings() const { return impl_->controller_settings; }
void DebugPanel::set_controller_settings(ControllerSettings settings) {
for (auto& button : settings.bindings)
if (button < -1 || button >= SDL_CONTROLLER_BUTTON_MAX) button = -1;
settings.stick_deadzone = std::clamp(settings.stick_deadzone, 0, 32766);
impl_->controller_settings = settings;
}
std::optional<GameDebugRequest> DebugPanel::take_game_action() {return std::exchange(impl_->game_action,std::nullopt);}
std::optional<SaveStateSnapshotRequest> DebugPanel::take_snapshot_action() {
return std::exchange(impl_->snapshot_action, std::nullopt);
}
void DebugPanel::draw(DisplaySettings& settings, const DebugDiagnostics& diagnostics) {
ImGui::SetCurrentContext(impl_->context);
ImGui_ImplOpenGL2_NewFrame();
ImGui_ImplSDL2_NewFrame();
ImGui::NewFrame();
const auto mouse=ImGui::GetIO().MousePos;
const bool bar_visible=!diagnostics.fullscreen || (mouse.x>=0 && mouse.x<ImGui::GetIO().DisplaySize.x &&
mouse.y>=0 && mouse.y<impl_->menu_height) || impl_->bar_mouse_down;
if (bar_visible && ImGui::BeginMainMenuBar()) {
impl_->menu_height = ImGui::GetWindowHeight();
// Keep gameplay Enter/arrows from activating a previously clicked bar
// item. F1/F11 are explicit shortcuts; the floating window supports nav.
ImGui::PushItemFlag(ImGuiItemFlags_NoNav, true);
if (ImGui::MenuItem("Settings (F1)", nullptr, impl_->visible) && !impl_->confirmation)
set_visible(!visible());
if (ImGui::MenuItem(diagnostics.fullscreen ? "Windowed (F11)" : "Fullscreen (F11)"))
impl_->action = PanelAction::ToggleFullscreen;
ImGui::PopItemFlag();
ImGui::EndMainMenuBar();
}
if (impl_->visible) {
// Constrain the window to current drawable space, including the smallest
// native-size window. ImGui supplies scrolling when content cannot fit.
const auto display = ImGui::GetIO().DisplaySize;
const float margin = std::min(18.0f, std::min(display.x, display.y) * 0.04f);
const ImVec2 available(std::max(1.0f, display.x - 2 * margin), std::max(1.0f, display.y - impl_->menu_height - 2 * margin));
ImGui::SetNextWindowPos(ImVec2(margin, impl_->menu_height + margin), ImGuiCond_Appearing);
ImGui::SetNextWindowSize(ImVec2(std::min(480.0f, available.x), std::min(410.0f, available.y)), ImGuiCond_FirstUseEver);
ImGui::SetNextWindowSizeConstraints(ImVec2(std::min(180.0f, available.x), std::min(140.0f, available.y)), available);
if (impl_->focus_next_frame) {
ImGui::SetNextWindowFocus();
impl_->focus_next_frame = false;
}
const auto title = diagnostics.game_title + " control panel###EBControlPanel";
// The ### suffix gives the window a stable identity across title changes.
if (ImGui::Begin(title.c_str(), &impl_->visible)) {
if (ImGui::BeginTabBar("Control panel tabs")) {
if (ImGui::BeginTabItem("Display")) {
ImGui::Spacing();
ImGui::Checkbox("Widescreen", &settings.widescreen);
ImGui::BeginDisabled(!settings.widescreen);
constexpr std::array<const char*, 11> labels{
"Game (256:224)", "4:3", "16:10 (Steam Deck / Mac)", "16:9", "21:9", "Window", "Custom",
"MacBook Air 13 (2560:1664)", "MacBook Air 15 (2880:1864)",
"MacBook Pro 14 (3024:1964)", "MacBook Pro 16 (3456:2234)"};
constexpr std::array<AspectRatio, 11> values{
AspectRatio::Native, AspectRatio::FourThree, AspectRatio::SixteenTen,
AspectRatio::SixteenNine, AspectRatio::TwentyOneNine, AspectRatio::Window, AspectRatio::Custom,
AspectRatio::MacBookAir13, AspectRatio::MacBookAir15,
AspectRatio::MacBookPro14, AspectRatio::MacBookPro16};
const auto current = std::find(values.begin(), values.end(), settings.aspect);
// Keep the combo index local: the saved enum is not assumed
// to be a valid array subscript after loading preferences.
const auto index = current == values.end() ? 0 : current - values.begin();
const bool narrow = ImGui::GetContentRegionAvail().x < 280.0f;
// Stack labels on narrow windows so every control remains
// reachable without requiring a larger desktop resolution.
if (narrow) ImGui::TextUnformatted("Aspect ratio");
ImGui::SetNextItemWidth(narrow ? -1.0f : 190.0f);
if (ImGui::BeginCombo(narrow ? "##Aspect ratio" : "Aspect ratio", labels[index])) {
for (std::size_t i = 0; i < labels.size(); ++i) {
const bool selected = settings.aspect == values[i];
if (ImGui::Selectable(labels[i], selected)) settings.aspect = values[i];
if (selected) ImGui::SetItemDefaultFocus();
}
ImGui::EndCombo();
}
if (settings.aspect == AspectRatio::Custom) {
if (narrow) ImGui::TextUnformatted("Width / height");
ImGui::SetNextItemWidth(narrow ? -1.0f : 190.0f);
if (ImGui::InputFloat(narrow ? "##Width / height" : "Width / height", &settings.custom_aspect, 0.01f, 0.1f, "%.3f")) {
if (!std::isfinite(settings.custom_aspect)) settings.custom_aspect = 16.0f / 9.0f;
settings.custom_aspect = std::clamp(settings.custom_aspect, 256.0f / 224.0f, 1024.0f / 224.0f);
}
ImGui::TextDisabled("For example, 1.778 is approximately 16:9.");
}
ImGui::EndDisabled();
ImGui::Spacing();
// This is independent of widescreen and never changes game
// timing. The frontend applies it to the completed picture.
ImGui::Checkbox("Photosensitivity filter", &settings.reduce_flashing);
ImGui::TextWrapped("Uses console brightness with temporal smoothing for PSI effects and Giygas.");
ImGui::Spacing();
if (ImGui::Button("Restore game display")) settings = DisplaySettings{};
ImGui::Spacing();
ImGui::Checkbox("Variable refresh rate (VRR)", &settings.variable_refresh);
if (ImGui::IsItemHovered())
ImGui::SetTooltip("Cap presentation below the monitor maximum with vsync.\nRequires VRR enabled on your display and in your graphics settings.\nFullscreen may be required by your desktop. This does not enable driver VRR.");
ImGui::Spacing();
ImGui::SetNextItemWidth(190.0f);
const auto fps_label = settings.frame_limit == 0 ? std::string("Uncapped") :
settings.frame_limit == 60 ? std::string("Native (~60 FPS)") : std::to_string(settings.frame_limit) + " FPS";
if (ImGui::BeginCombo("Frame rate", fps_label.c_str())) {
for (int limit : {60, 90, 120, 144, 165, 240, 300, 0}) {
const auto label = limit == 0 ? std::string("Uncapped") : limit == 60 ?
std::string("Native (~60 FPS)") : std::to_string(limit) + " FPS";
if (ImGui::Selectable(label.c_str(), settings.frame_limit == limit)) settings.frame_limit = limit;
}
ImGui::EndCombo();
}
if (ImGui::IsItemHovered())
ImGui::SetTooltip("Higher rates affect presentation, not gameplay or audio speed.\nVRR limits output to the display range. Without VRR, higher rates disable vsync and may tear.");
ImGui::BeginDisabled(!settings.high_frame_rate());
ImGui::Checkbox("Direct scene rendering", &settings.direct_rendering);
if (ImGui::IsItemHovered())
ImGui::SetTooltip("Draw source tiles and sprites at the selected frame rate.\nSmooths camera and actor positions without blending game frames.\nAdds one game frame of visual latency. Unsupported effects keep their original frames.");
if (!settings.direct_rendering) {
ImGui::Checkbox("Interpolate frames", &settings.interpolate_frames);
if (ImGui::IsItemHovered())
ImGui::SetTooltip("Legacy image-based frame generation.\nMay produce ghosting around moving objects. Leave off to repeat original frames.");
}
ImGui::EndDisabled();
ImGui::Spacing();
ImGui::Checkbox("CRT Filter", &settings.crt_filter);
if (ImGui::IsItemHovered())
ImGui::SetTooltip("Flat CRT-Lottes Fast filter: scanlines and aperture-grille detail.\nBrightness compensated for OLED. No curvature or temporal ghosting.");
ImGui::TextDisabled("F1 or Escape closes this panel.");
ImGui::TextWrapped("The game continues while this panel is open. Close it to resume controls.");
ImGui::EndTabItem();
}
if (ImGui::BeginTabItem("Diagnostics")) {
ImGui::Spacing();
ImGui::Text("Game frame: %llu", static_cast<unsigned long long>(diagnostics.frames));
ImGui::Text("Canvas: %d x %d", diagnostics.source_width, diagnostics.source_height);
ImGui::Text("Window: %d x %d", diagnostics.drawable_width, diagnostics.drawable_height);
ImGui::Separator();
ImGui::Text("CPU instructions: %llu", static_cast<unsigned long long>(diagnostics.cpu_instructions));
ImGui::Text("SPC instructions: %llu", static_cast<unsigned long long>(diagnostics.spc_instructions));
ImGui::Text("Master clocks: %llu", static_cast<unsigned long long>(diagnostics.master_clocks));
ImGui::Text("Audio frames: %llu", static_cast<unsigned long long>(diagnostics.audio_frames));
ImGui::Separator();
ImGui::TextWrapped("%s", diagnostics.cpu_state.c_str());
ImGui::TextWrapped("%s", diagnostics.spc_state.c_str());
ImGui::EndTabItem();
}
if (ImGui::BeginTabItem("Assets")) {
ImGui::TextWrapped("Switch between your imported game versions or clear a local asset cache.");
if (!diagnostics.custom_asset_status.empty()) ImGui::TextWrapped("%s", diagnostics.custom_asset_status.c_str());
if (!impl_->action_status.empty()) ImGui::TextWrapped("%s", impl_->action_status.c_str());
for (unsigned index = 0; index < diagnostics.cache.size(); ++index) {
const auto& cache = diagnostics.cache[index];
ImGui::PushID(int(index));
ImGui::Separator();
const auto title = cache.title.empty() ? (index ? "Mother 2 (Japanese)" : "EarthBound (US)") : cache.title.c_str();
ImGui::TextUnformatted(title);
ImGui::TextDisabled("%s%s", cache.present ? "Imported" : "Import needed", cache.active ? " - current game" : "");
if (!cache.path.empty()) ImGui::TextWrapped("%s", cache.path.c_str());
if (ImGui::Button("Switch game")) {
impl_->confirmation = index ? PanelAction::SwitchMother2 : PanelAction::SwitchEarthBound;
impl_->confirmation_cache = index;
impl_->open_confirmation = true;
}
if (ImGui::GetContentRegionAvail().x >= 360.0f) ImGui::SameLine();
ImGui::BeginDisabled(!cache.present);
if (ImGui::Button("Clear imported assets")) {
impl_->confirmation = index ? PanelAction::ClearMother2Assets : PanelAction::ClearEarthBoundAssets;
impl_->confirmation_cache = index;
impl_->open_confirmation = true;
}
ImGui::EndDisabled();
ImGui::PopID();
}
ImGui::EndTabItem();
}
if (ImGui::BeginTabItem("Debug")) {
if (!diagnostics.machine_debug_available)
ImGui::TextWrapped("Machine debug controls are unavailable in a native session.");
ImGui::BeginDisabled(!diagnostics.machine_debug_available);
ImGui::Checkbox("Infinite health (999/999)", &impl_->game_settings.infinite_hp);
ImGui::Checkbox("Infinite PSI / PP (999/999)", &impl_->game_settings.infinite_pp);
ImGui::Checkbox("Noclip", &impl_->game_settings.noclip);
ImGui::Checkbox("Enemies ignore you", &impl_->game_settings.enemies_ignore);
ImGui::Checkbox("Player does max damage", &impl_->game_settings.player_max_damage);
ImGui::TextWrapped("Enemies ignore you prevents overworld pursuit and contact battles. Story battles still work.");
ImGui::Separator();
const auto& state=diagnostics.game_debug;
ImGui::BeginDisabled(!state.ready || state.busy);
const auto places=debug_destinations();
ImGui::SetNextItemWidth(-1);
if(ImGui::BeginCombo("##Teleport destination",places[impl_->destination].name,ImGuiComboFlags_HeightLargest)) {
if(ImGui::IsWindowAppearing())ImGui::SetKeyboardFocusHere();
impl_->destination_filter.Draw("Search places",-1);
ImGui::TextDisabled("385 areas, all scripted warps and door entrances");
if(ImGui::BeginChild("Destinations",ImVec2(0,std::min(200.0f,std::max(50.0f,display.y-100))))) {
for(unsigned i=0;i<places.size();++i)if(impl_->destination_filter.PassFilter(places[i].name)) {
if(ImGui::Selectable(places[i].name,i==impl_->destination)) {impl_->destination=i;ImGui::CloseCurrentPopup();}
if(ImGui::IsItemHovered())ImGui::SetTooltip("%s",places[i].name);
}
}
ImGui::EndChild();
ImGui::EndCombo();
}
if(ImGui::Button("Teleport now"))
impl_->game_action=GameDebugRequest{GameDebugRequest::Kind::Teleport,places[impl_->destination].id,{}};
ImGui::SeparatorText("Party members");
if(!impl_->party_editing)impl_->party=state.party;
constexpr const char* names[]{"Ness","Paula","Jeff","Poo"};
for(unsigned i=0;i<4;++i) {
if(i && ImGui::GetContentRegionAvail().x>280)ImGui::SameLine();
if(ImGui::Checkbox(names[i],&impl_->party[i]))impl_->party_editing=true;
}
const bool any=std::any_of(impl_->party.begin(),impl_->party.end(),[](bool member){return member;});
ImGui::BeginDisabled(!any);
if(ImGui::Button("Apply party")) {
impl_->game_action=GameDebugRequest{GameDebugRequest::Kind::Party,0,impl_->party};
impl_->party_editing=false;
}
ImGui::EndDisabled();
ImGui::EndDisabled();
ImGui::TextWrapped("Keep at least one playable member. Guest companions stay with the party.");
if(!state.status.empty())ImGui::TextWrapped("%s",state.status.c_str());
else if(!state.ready)ImGui::TextWrapped("Load a game to use teleport and party controls.");
ImGui::TextWrapped("Debug changes can affect saved progress. Cheat switches reset when you restart or switch games.");
ImGui::EndDisabled();
ImGui::SeparatorText("Presentation");
ImGui::Checkbox("Experimental frame pacing", &settings.experimental_frame_pacing);
ImGui::TextWrapped("Prioritize game updates over extra high-FPS draws. May lower displayed FPS. Only affects rates above Native; off by default.");
ImGui::SeparatorText("Save state snapshots");
ImGui::TextWrapped("Save the current moment and return to it later. Snapshots are kept separately from your in-game save.");
const auto find_snapshot = [&](const std::string& id) {
return std::find_if(diagnostics.snapshots.begin(), diagnostics.snapshots.end(),
[&](const SaveStateSnapshotInfo& snapshot) { return snapshot.id == id; });
};
if (!impl_->selected_snapshot.empty() && find_snapshot(impl_->selected_snapshot) == diagnostics.snapshots.end()) {
impl_->selected_snapshot.clear();
impl_->delete_snapshot.clear();
}
if (!impl_->delete_snapshot.empty() && find_snapshot(impl_->delete_snapshot) == diagnostics.snapshots.end())
impl_->delete_snapshot.clear();
ImGui::SetNextItemWidth(-1);
ImGui::InputTextWithHint("##Snapshot name", "Snapshot name", impl_->snapshot_name.data(), impl_->snapshot_name.size());
const bool has_name = std::any_of(impl_->snapshot_name.begin(),
impl_->snapshot_name.begin() + std::char_traits<char>::length(impl_->snapshot_name.data()),
[](unsigned char value) { return !std::isspace(value); });
ImGui::BeginDisabled(!diagnostics.snapshots_available || !has_name);
if (ImGui::Button("Save snapshot"))
impl_->snapshot_action = SaveStateSnapshotRequest{SaveStateSnapshotRequest::Kind::Save, impl_->snapshot_name.data()};
ImGui::EndDisabled();
if (ImGui::GetContentRegionAvail().x >= 250.0f) ImGui::SameLine();
if (ImGui::Button("Refresh snapshots"))
impl_->snapshot_action = SaveStateSnapshotRequest{SaveStateSnapshotRequest::Kind::Refresh, {}};
ImGui::TextDisabled("%zu snapshot%s for %s", diagnostics.snapshots.size(),
diagnostics.snapshots.size() == 1 ? "" : "s", diagnostics.game_title.c_str());
if (ImGui::BeginChild("Snapshot list", ImVec2(0, 108), ImGuiChildFlags_Borders)) {
if (diagnostics.snapshots.empty()) ImGui::TextWrapped("No snapshots yet. Enter a name and save your current moment.");
for (const auto& snapshot : diagnostics.snapshots) {
ImGui::PushID(snapshot.id.c_str());
const bool selected = impl_->selected_snapshot == snapshot.id;
const auto row_height = ImGui::GetTextLineHeight() * 2 + 4;
if (ImGui::Selectable("##Snapshot entry", selected, 0, ImVec2(0, row_height))) {
impl_->selected_snapshot = snapshot.id;
impl_->delete_snapshot.clear();
}
// Render labels literally: user names may contain ImGui's
// ## marker, and their IDs must remain stable while renamed.
const auto row = ImGui::GetItemRectMin();
auto* painter = ImGui::GetWindowDrawList();
painter->AddText(row, ImGui::GetColorU32(ImGuiCol_Text), snapshot.name.c_str());
const auto details = snapshot.created_at + " | Frame " + std::to_string(snapshot.frames);
painter->AddText(ImVec2(row.x, row.y + ImGui::GetTextLineHeight() + 2),
ImGui::GetColorU32(ImGuiCol_TextDisabled), details.c_str());
if (ImGui::IsItemHovered()) ImGui::SetTooltip("%s\n%s", snapshot.name.c_str(), details.c_str());
ImGui::PopID();
}
}
ImGui::EndChild();
ImGui::BeginDisabled(!diagnostics.snapshots_available || impl_->selected_snapshot.empty());
if (ImGui::Button("Load selected")) {
impl_->snapshot_action = SaveStateSnapshotRequest{SaveStateSnapshotRequest::Kind::Load, impl_->selected_snapshot};
impl_->delete_snapshot.clear();
}
ImGui::EndDisabled();
if (ImGui::GetContentRegionAvail().x >= 260.0f) ImGui::SameLine();
ImGui::BeginDisabled(impl_->selected_snapshot.empty());
const bool confirm_delete = ImGui::Button("Delete selected");
if (confirm_delete) impl_->delete_snapshot = impl_->selected_snapshot;
ImGui::EndDisabled();
if (!impl_->delete_snapshot.empty()) {
const auto pending = find_snapshot(impl_->delete_snapshot);
ImGui::TextWrapped("Delete \"%s\"?", pending->name.c_str());
if (ImGui::Button("Confirm delete")) {
impl_->snapshot_action = SaveStateSnapshotRequest{SaveStateSnapshotRequest::Kind::Delete, impl_->delete_snapshot};
impl_->delete_snapshot.clear();
}
if (ImGui::GetContentRegionAvail().x >= 250.0f) ImGui::SameLine();
if (ImGui::Button("Cancel delete")) impl_->delete_snapshot.clear();
if (confirm_delete) ImGui::SetScrollHereY(1);
}
if (!diagnostics.snapshot_status.empty()) {
ImGui::TextWrapped("%s", diagnostics.snapshot_status.c_str());
// Keep operation feedback reachable even when the Debug
// tab's earlier controls have filled a small window.
if (impl_->snapshot_status != diagnostics.snapshot_status) ImGui::SetScrollHereY(1);
}
impl_->snapshot_status = diagnostics.snapshot_status;
if (!diagnostics.snapshots_available) ImGui::TextWrapped("Start a game to save or load snapshots.");
ImGui::EndTabItem();
}
if (ImGui::BeginTabItem("Controller")) {
const auto& controller = diagnostics.controller;
if (controller.connected)
ImGui::TextWrapped("Connected: %s", controller.name.c_str());
else
ImGui::TextUnformatted("Controller disconnected");
std::string held;
if (controller.connected) {
for (int button = 0; button < SDL_CONTROLLER_BUTTON_MAX; ++button) {
if (!controller.pressed[button]) continue;
if (!held.empty()) held += ", ";
held += controller_button_name(button, controller.nintendo_layout);
}
}
ImGui::TextWrapped("Buttons held: %s", held.empty() ? "None" : held.c_str());
ImGui::Text("Left stick: %d, %d", controller.connected ? controller.stick_x : 0,
controller.connected ? controller.stick_y : 0);
ImGui::SetNextItemWidth(-1);
ImGui::SliderInt("##Controller stick deadzone", &impl_->controller_settings.stick_deadzone, 0, 32766,
"Stick deadzone: %d");
if (ImGui::Button("Restore controller defaults")) impl_->controller_settings = ControllerSettings{};
ImGui::TextWrapped("Choose which controller button sends each SNES button. Changes apply immediately. Pressed inputs stay visible while game controls are paused by this panel.");
if (ImGui::BeginTable("Controller bindings", 3,
ImGuiTableFlags_BordersInnerV | ImGuiTableFlags_RowBg | ImGuiTableFlags_SizingStretchProp)) {
ImGui::TableSetupColumn("SNES", ImGuiTableColumnFlags_WidthFixed, 42);
ImGui::TableSetupColumn("Controller button", ImGuiTableColumnFlags_WidthStretch);
ImGui::TableSetupColumn("Input", ImGuiTableColumnFlags_WidthFixed, 48);
ImGui::TableHeadersRow();
for (std::size_t index = 0; index < snes_button_names.size(); ++index) {
ImGui::PushID(int(index));
ImGui::TableNextRow();
ImGui::TableSetColumnIndex(0);
const bool output_pressed = controller.connected && (controller.game_buttons & (1u << (15 - index)));
if (output_pressed)
ImGui::TextColored(ImVec4(0.35f, 0.95f, 0.55f, 1), "%s *", snes_button_names[index]);
else ImGui::TextUnformatted(snes_button_names[index]);
ImGui::TableSetColumnIndex(1);
auto& binding = impl_->controller_settings.bindings[index];
ImGui::SetNextItemWidth(-1);
if (ImGui::BeginCombo("##Controller source", controller_button_name(binding, controller.nintendo_layout))) {
for (int button = -1; button < SDL_CONTROLLER_BUTTON_MAX; ++button) {
const bool selected = binding == button;
if (ImGui::Selectable(controller_button_name(button, controller.nintendo_layout), selected)) binding = button;
if (selected) ImGui::SetItemDefaultFocus();
}
ImGui::EndCombo();
}
ImGui::TableSetColumnIndex(2);
if (controller.connected && binding >= 0 && binding < SDL_CONTROLLER_BUTTON_MAX && controller.pressed[binding])
ImGui::TextColored(ImVec4(0.35f, 0.95f, 0.55f, 1), "Pressed");
else ImGui::TextDisabled("-");
ImGui::PopID();
}
ImGui::EndTable();
}
ImGui::TextDisabled("* marks a pressed SNES output.");
ImGui::EndTabItem();
}
ImGui::EndTabBar();
}
if (impl_->confirmation) {
const bool clearing = *impl_->confirmation == PanelAction::ClearEarthBoundAssets ||
*impl_->confirmation == PanelAction::ClearMother2Assets;
const char* popup = clearing ? "Clear imported assets?" : "Switch game?";
if (impl_->open_confirmation) {
ImGui::OpenPopup(popup);
impl_->open_confirmation = false;
}
ImGui::SetNextWindowSizeConstraints(ImVec2(std::min(180.0f, available.x), 0), available);
ImGui::SetNextWindowSize(ImVec2(std::min(430.0f, available.x), 0), ImGuiCond_Appearing);
if (ImGui::BeginPopupModal(popup, nullptr, ImGuiWindowFlags_AlwaysAutoResize)) {
const auto& cache = diagnostics.cache[impl_->confirmation_cache];
ImGui::TextWrapped("%s", cache.title.c_str());
if (clearing) {
ImGui::TextWrapped("Only this imported asset cache will be removed:");
ImGui::TextWrapped("%s", cache.path.c_str());
ImGui::TextWrapped("Your ROM and saves are kept. You can keep playing; a fresh import will be needed the next time this game starts.");
} else {
ImGui::TextWrapped("Save in-game first. Switching restarts the selected game and loses unsaved progress.");
if (!cache.present) ImGui::TextWrapped("You will be asked to import your own ROM for this version.");
}
ImGui::Spacing();
if (ImGui::Button(clearing ? "Clear imported assets" : "Switch and restart")) {
impl_->action = impl_->confirmation;
impl_->confirmation.reset();
impl_->cancel_confirmation = false;
ImGui::CloseCurrentPopup();
}
if (ImGui::GetContentRegionAvail().x >= 340.0f) ImGui::SameLine();
if (ImGui::Button("Cancel") || impl_->cancel_confirmation) {
impl_->cancel_confirmation = false;
impl_->confirmation.reset();
ImGui::CloseCurrentPopup();
}
ImGui::EndPopup();
}
}
}
ImGui::End();
}
if (!impl_->visible) impl_->delete_snapshot.clear();
ImGui::Render();
// main draws the completed game image first and swaps only after this call.
ImGui_ImplOpenGL2_RenderDrawData(ImGui::GetDrawData());
}
namespace {
// ImGui/SDL paths use UTF-8. Native filesystem paths may use UTF-16 on Windows;
// convert explicitly rather than relying on the system's current code page.
std::filesystem::path native_path(const std::string& path) {
return std::filesystem::path(std::u8string(path.begin(), path.end()));
}
std::string path_text(const std::filesystem::path& path) {
const auto text = path.u8string();
return std::string(text.begin(), text.end());
}
template<std::size_t N> void set_text(std::array<char, N>& buffer, const std::string& text) {
// ImGui edits fixed buffers in place; always reserve a terminating NUL.
const auto count = std::min(text.size(), N - 1);
std::copy_n(text.data(), count, buffer.data());
buffer[count] = 0;
}
} // namespace
struct AssetImportPanel::Impl {
struct Entry { std::filesystem::path path; std::string name; bool directory; };
ImGuiContext* context{};
std::array<char, 4096> path{}, directory_text{};
std::filesystem::path directory;
std::vector<Entry> entries;
std::optional<std::string> request;
// Import errors and directory-navigation errors are separate so browsing
// another folder does not hide a failed ROM validation from the user.
std::string error, status, browser_error, selected;
bool exit{}, browser_open{}, show_all{};
void refresh() {
// Refresh on explicit navigation/filter changes, not every frame. Error
// codes let an inaccessible folder remain editable instead of exiting UI.
entries.clear();
browser_error.clear();
selected.clear();
set_text(directory_text, path_text(directory));
std::error_code ec;
std::filesystem::directory_iterator iterator(directory, ec), end;
if (ec) { browser_error = ec.message(); return; }
while (iterator != end) {
const auto& entry = *iterator;
const bool is_directory = entry.is_directory(ec);
if (!ec) {
auto extension = path_text(entry.path().extension());
std::transform(extension.begin(), extension.end(), extension.begin(),
[](unsigned char c) { return static_cast<char>(std::tolower(c)); });
if (is_directory || show_all || extension == ".sfc" || extension == ".smc")
entries.push_back({entry.path(), path_text(entry.path().filename()), is_directory});
}
ec.clear();
iterator.increment(ec);
if (ec) { browser_error = ec.message(); break; }
}
std::sort(entries.begin(), entries.end(), [](const Entry& a, const Entry& b) {
// Folders first, then stable lexical ordering for predictable browsing.
if (a.directory != b.directory) return a.directory > b.directory;
return a.name < b.name;
});
}
void choose(const std::string& chosen) {
// Selecting a file only fills the form. Import is a separate user action.
set_text(path, chosen);
browser_open = false;
error.clear();
}
void request_import() {
// File I/O and compatibility checks belong to the frontend after draw.
if (!path[0]) { error = "Choose a ROM file first."; return; }
request = std::string(path.data());
error.clear();
}
};
AssetImportPanel::AssetImportPanel(SDL_Window* window, SDL_GLContext context): impl_(std::make_unique<Impl>()) {
IMGUI_CHECKVERSION();
impl_->context = ImGui::CreateContext();
ImGui::GetIO().IniFilename = nullptr;
ImGui::GetIO().LogFilename = nullptr;
ImGui::GetIO().ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard;
ImGui::StyleColorsDark();
auto& style = ImGui::GetStyle();
style.WindowRounding = 8.0f;
style.FrameRounding = 4.0f;
style.WindowPadding = ImVec2(20.0f, 20.0f);
style.ItemSpacing = ImVec2(10.0f, 12.0f);
if (!ImGui_ImplSDL2_InitForOpenGL(window, context)) {
ImGui::DestroyContext(impl_->context);
throw std::runtime_error("Could not initialize the import screen SDL backend");
}
if (!ImGui_ImplOpenGL2_Init()) {
ImGui_ImplSDL2_Shutdown();
ImGui::DestroyContext(impl_->context);
throw std::runtime_error("Could not initialize the import screen OpenGL backend");
}
const char* home = SDL_getenv("HOME");
// A familiar starting directory on either platform; typing a full path and
// drag-and-drop remain available if the home directory cannot be resolved.
if (!home || !*home) home = SDL_getenv("USERPROFILE");
std::error_code ec;
impl_->directory = home && *home ? native_path(home) : std::filesystem::current_path(ec);
if (ec) impl_->directory = std::filesystem::path(".");
}
AssetImportPanel::~AssetImportPanel() {
ImGui::SetCurrentContext(impl_->context);
ImGui_ImplOpenGL2_Shutdown();
ImGui_ImplSDL2_Shutdown();
ImGui::DestroyContext(impl_->context);
}
void AssetImportPanel::process_event(const SDL_Event& event) {
ImGui::SetCurrentContext(impl_->context);
ImGui_ImplSDL2_ProcessEvent(&event);
if (event.type == SDL_QUIT) impl_->exit = true;
if (event.type == SDL_KEYDOWN && !event.key.repeat && event.key.keysym.sym == SDLK_ESCAPE) {
// Escape backs out of the browser before it exits first-run setup.
if (impl_->browser_open) impl_->browser_open = false;
else impl_->exit = true;
}
// Copy the drop path now; main owns and frees SDL's allocated event payload.
if (event.type == SDL_DROPFILE && event.drop.file) impl_->choose(event.drop.file);
}
void AssetImportPanel::draw() {
ImGui::SetCurrentContext(impl_->context);
ImGui_ImplOpenGL2_NewFrame();
ImGui_ImplSDL2_NewFrame();
ImGui::NewFrame();
const auto size = ImGui::GetIO().DisplaySize;
ImGui::SetNextWindowPos(ImVec2(size.x * 0.5f, size.y * 0.5f), ImGuiCond_Always, ImVec2(0.5f, 0.5f));
ImGui::SetNextWindowSize(ImVec2(std::max(1.0f, std::min(640.0f, size.x - 16.0f)),
std::max(1.0f, std::min(370.0f, size.y - 16.0f))), ImGuiCond_Always);
if (ImGui::Begin("EarthBound / Mother 2", nullptr, ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoResize)) {
ImGui::TextWrapped("Import your ROM to get started");
ImGui::TextWrapped("Choose your own US EarthBound or Japanese Mother 2 ROM. Compatibility is checked before starting the game.");
ImGui::Spacing();
ImGui::TextUnformatted("ROM file");
ImGui::SetNextItemWidth(std::max(100.0f, ImGui::GetContentRegionAvail().x - 88.0f));
if (ImGui::InputText("##ROM file", impl_->path.data(), impl_->path.size(), ImGuiInputTextFlags_EnterReturnsTrue))
impl_->request_import();
ImGui::SameLine();
if (ImGui::Button("Browse...")) {
if (impl_->path[0]) {
const auto parent = native_path(impl_->path.data()).parent_path();
if (!parent.empty()) impl_->directory = parent;
}
impl_->browser_open = true;
impl_->refresh();
}
ImGui::TextDisabled("You can also drop a .sfc or .smc file here.");
if (!impl_->error.empty()) {
ImGui::PushStyleColor(ImGuiCol_Text, ImVec4(1.0f, 0.48f, 0.42f, 1.0f));
ImGui::TextWrapped("%s", impl_->error.c_str());
ImGui::PopStyleColor();
}
if (!impl_->status.empty()) ImGui::TextWrapped("%s", impl_->status.c_str());
ImGui::Spacing();
const auto import_width = std::min(150.0f, std::max(100.0f, ImGui::GetContentRegionAvail().x - 60.0f));
if (ImGui::Button("Import and play", ImVec2(import_width, 0))) impl_->request_import();
ImGui::SameLine();
if (ImGui::Button("Exit")) impl_->exit = true;
}
ImGui::End();
if (impl_->browser_open) ImGui::OpenPopup("Choose a ROM");
ImGui::SetNextWindowSize(ImVec2(std::max(1.0f, std::min(660.0f, size.x - 16.0f)),
std::max(1.0f, std::min(510.0f, size.y - 16.0f))), ImGuiCond_Always);
if (ImGui::BeginPopupModal("Choose a ROM", &impl_->browser_open, ImGuiWindowFlags_NoResize)) {
if (ImGui::Button("Up")) {
if (const auto parent = impl_->directory.parent_path(); !parent.empty()) impl_->directory = parent;
impl_->refresh();
}
ImGui::SameLine();
ImGui::SetNextItemWidth(-1.0f);
if (ImGui::InputText("##Folder", impl_->directory_text.data(), impl_->directory_text.size(),
ImGuiInputTextFlags_EnterReturnsTrue)) {
impl_->directory = native_path(impl_->directory_text.data());
impl_->refresh();
}
if (ImGui::Checkbox("Show all files", &impl_->show_all)) impl_->refresh();
if (!impl_->browser_error.empty()) ImGui::TextWrapped("%s", impl_->browser_error.c_str());
// Defer folder entry until iteration ends: refresh replaces entries and
// would invalidate the current range-for iterator if performed inline.
std::optional<std::filesystem::path> enter;
if (ImGui::BeginChild("Directory contents", ImVec2(0, std::max(80.0f, ImGui::GetContentRegionAvail().y - 60.0f)), ImGuiChildFlags_Borders)) {
for (const auto& entry : impl_->entries) {
const auto label = (entry.directory ? "[Folder] " : "") + entry.name;
if (ImGui::Selectable(label.c_str(), impl_->selected == path_text(entry.path), ImGuiSelectableFlags_AllowDoubleClick)) {
impl_->selected = path_text(entry.path);
if (ImGui::IsMouseDoubleClicked(0)) {
if (entry.directory) enter = entry.path;
else impl_->choose(impl_->selected);
}
}
}
}
ImGui::EndChild();
if (enter) { impl_->directory = *enter; impl_->refresh(); }
ImGui::BeginDisabled(impl_->selected.empty());
if (ImGui::Button("Choose", ImVec2(100.0f, 0))) {
const auto selected = native_path(impl_->selected);
std::error_code ec;
if (std::filesystem::is_directory(selected, ec)) { impl_->directory = selected; impl_->refresh(); }
else impl_->choose(impl_->selected);
}
ImGui::EndDisabled();
ImGui::SameLine();
if (ImGui::Button("Cancel")) impl_->browser_open = false;
if (!impl_->browser_open) ImGui::CloseCurrentPopup();
ImGui::EndPopup();
}
ImGui::Render();
ImGui_ImplOpenGL2_RenderDrawData(ImGui::GetDrawData());
}
// Transfer each request exactly once; validation failures can safely return to
// the same form and require another explicit attempt.
std::optional<std::string> AssetImportPanel::take_import_request() { return std::exchange(impl_->request, std::nullopt); }
bool AssetImportPanel::exit_requested() const { return impl_->exit; }
void AssetImportPanel::set_error(std::string error) { impl_->error = std::move(error); impl_->status.clear(); }
void AssetImportPanel::set_status(std::string status) { impl_->status = std::move(status); impl_->error.clear(); }
} // namespace eb