Debian Codegraph @

Source/Core/VideoCommon/OnScreenUI.cpp

raw symbols SCIP
1 // Copyright 2023 Dolphin Emulator Project
2 // SPDX-License-Identifier: GPL-2.0-or-later
3
4 #include "VideoCommon/OnScreenUI.h"
5
6 #include "Common/CommonPaths.h"
7 #include "Common/EnumMap.h"
8 #include "Common/FileUtil.h"
9 #include "Common/Profiler.h"
10 #include "Common/Timer.h"
11
12 #include "Core/AchievementManager.h"
13 #include "Core/Config/AchievementSettings.h"
14 #include "Core/Config/GraphicsSettings.h"
15 #include "Core/Config/MainSettings.h"
16 #include "Core/Config/NetplaySettings.h"
17 #include "Core/Movie.h"
18 #include "Core/System.h"
19
20 #include "VideoCommon/AbstractGfx.h"
21 #include "VideoCommon/AbstractPipeline.h"
22 #include "VideoCommon/AbstractShader.h"
23 #include "VideoCommon/AbstractStagingTexture.h"
24 #include "VideoCommon/FramebufferShaderGen.h"
25 #include "VideoCommon/NetPlayChatUI.h"
26 #include "VideoCommon/NetPlayGolfUI.h"
27 #include "VideoCommon/OnScreenDisplay.h"
28 #include "VideoCommon/PerformanceMetrics.h"
29 #include "VideoCommon/Present.h"
30 #include "VideoCommon/Statistics.h"
31 #include "VideoCommon/VertexManagerBase.h"
32 #include "VideoCommon/VideoConfig.h"
33
34 #include <inttypes.h>
35 #include <mutex>
36
37 #include <imgui.h>
38 #include <implot.h>
39
40 namespace VideoCommon
41 {
42 bool OnScreenUI::Initialize(u32 width, u32 height, float scale)
43 {
44 std::unique_lock<std::mutex> imgui_lock(m_imgui_mutex);
45
46 if (!IMGUI_CHECKVERSION())
47 {
48 PanicAlertFmt("ImGui version check failed");
49 return false;
50 }
51 if (!ImGui::CreateContext())
52 {
53 PanicAlertFmt("Creating ImGui context failed");
54 return false;
55 }
56 if (!ImPlot::CreateContext())
57 {
58 PanicAlertFmt("Creating ImPlot context failed");
59 return false;
60 }
61
62 // Don't create an ini file. TODO: Do we want this in the future?
63 ImGui::GetIO().IniFilename = nullptr;
64 SetScale(scale);
65
66 PortableVertexDeclaration vdecl = {};
67 vdecl.position = {ComponentFormat::Float, 2, offsetof(ImDrawVert, pos), true, false};
68 vdecl.texcoords[0] = {ComponentFormat::Float, 2, offsetof(ImDrawVert, uv), true, false};
69 vdecl.colors[0] = {ComponentFormat::UByte, 4, offsetof(ImDrawVert, col), true, false};
70 vdecl.stride = sizeof(ImDrawVert);
71 m_imgui_vertex_format = g_gfx->CreateNativeVertexFormat(vdecl);
72 if (!m_imgui_vertex_format)
73 {
74 PanicAlertFmt("Failed to create ImGui vertex format");
75 return false;
76 }
77
78 // Font defaults
79 ImGuiIO& io = ImGui::GetIO();
80 m_imgui_textures.clear();
81
82 // User supplied font
83 std::string file = File::GetUserPath(D_LOAD_IDX) + "OSD_Font.ttf";
84
85 bool font_exists = File::Exists(file);
86 if (!font_exists)
87 {
88 // Default supplied font
89 file = File::GetSysDirectory() + DIR_SEP + RESOURCES_DIR + DIR_SEP + "OSD_Font.ttf";
90 font_exists = File::Exists(file);
91 }
92
93 if (font_exists)
94 {
95 io.Fonts->Clear();
96 io.Fonts->AddFontFromFileTTF(file.c_str());
97 }
98
99 // Setup new font management behavior
100 io.BackendFlags |= ImGuiBackendFlags_RendererHasTextures | ImGuiBackendFlags_RendererHasVtxOffset;
101
102 if (!RecompileImGuiPipeline())
103 return false;
104
105 m_imgui_last_frame_time = Common::Timer::NowUs();
106 m_ready = true;
107 BeginImGuiFrameUnlocked(width, height); // lock is already held
108
109 return true;
110 }
111
112 OnScreenUI::~OnScreenUI()
113 {
114 std::unique_lock<std::mutex> imgui_lock(m_imgui_mutex);
115
116 ImGui::EndFrame();
117 ImPlot::DestroyContext();
118 ImGui::DestroyContext();
119 m_imgui_textures.clear();
120 }
121
122 bool OnScreenUI::RecompileImGuiPipeline()
123 {
124 if (g_presenter->GetBackbufferFormat() == AbstractTextureFormat::Undefined)
125 {
126 // No backbuffer (nogui) means no imgui rendering will happen
127 // Some backends don't like making pipelines with no render targets
128 return true;
129 }
130
131 const bool linear_space_output =
132 g_presenter->GetBackbufferFormat() == AbstractTextureFormat::RGBA16F;
133
134 std::unique_ptr<AbstractShader> vertex_shader = g_gfx->CreateShaderFromSource(
135 ShaderStage::Vertex, FramebufferShaderGen::GenerateImGuiVertexShader(), nullptr,
136 "ImGui vertex shader");
137 std::unique_ptr<AbstractShader> pixel_shader = g_gfx->CreateShaderFromSource(
138 ShaderStage::Pixel, FramebufferShaderGen::GenerateImGuiPixelShader(linear_space_output),
139 nullptr, "ImGui pixel shader");
140 if (!vertex_shader || !pixel_shader)
141 {
142 PanicAlertFmt("Failed to compile ImGui shaders");
143 return false;
144 }
145
146 // GS is used to render the UI to both eyes in stereo modes.
147 std::unique_ptr<AbstractShader> geometry_shader;
148 if (g_gfx->UseGeometryShaderForUI())
149 {
150 geometry_shader = g_gfx->CreateShaderFromSource(
151 ShaderStage::Geometry, FramebufferShaderGen::GeneratePassthroughGeometryShader(1, 1),
152 nullptr, "ImGui passthrough geometry shader");
153 if (!geometry_shader)
154 {
155 PanicAlertFmt("Failed to compile ImGui geometry shader");
156 return false;
157 }
158 }
159
160 AbstractPipelineConfig pconfig = {};
161 pconfig.vertex_format = m_imgui_vertex_format.get();
162 pconfig.vertex_shader = vertex_shader.get();
163 pconfig.geometry_shader = geometry_shader.get();
164 pconfig.pixel_shader = pixel_shader.get();
165 pconfig.rasterization_state = RenderState::GetNoCullRasterizationState(PrimitiveType::Triangles);
166 pconfig.depth_state = RenderState::GetNoDepthTestingDepthState();
167 pconfig.blending_state = RenderState::GetNoBlendingBlendState();
168 pconfig.blending_state.blend_enable = true;
169 pconfig.blending_state.src_factor = SrcBlendFactor::SrcAlpha;
170 pconfig.blending_state.dst_factor = DstBlendFactor::InvSrcAlpha;
171 pconfig.blending_state.src_factor_alpha = SrcBlendFactor::Zero;
172 pconfig.blending_state.dst_factor_alpha = DstBlendFactor::One;
173 pconfig.framebuffer_state.color_texture_format = g_presenter->GetBackbufferFormat();
174 pconfig.framebuffer_state.depth_texture_format = AbstractTextureFormat::Undefined;
175 pconfig.framebuffer_state.samples = 1;
176 pconfig.framebuffer_state.per_sample_shading = false;
177 pconfig.usage = AbstractPipelineUsage::Utility;
178 m_imgui_pipeline = g_gfx->CreatePipeline(pconfig);
179 if (!m_imgui_pipeline)
180 {
181 PanicAlertFmt("Failed to create imgui pipeline");
182 return false;
183 }
184
185 return true;
186 }
187
188 void OnScreenUI::BeginImGuiFrame(u32 width, u32 height)
189 {
190 std::unique_lock<std::mutex> imgui_lock(m_imgui_mutex);
191 BeginImGuiFrameUnlocked(width, height);
192 }
193
194 void OnScreenUI::BeginImGuiFrameUnlocked(u32 width, u32 height)
195 {
196 m_backbuffer_width = width;
197 m_backbuffer_height = height;
198
199 const u64 current_time_us = Common::Timer::NowUs();
200 const u64 time_diff_us = current_time_us - m_imgui_last_frame_time;
201 const float time_diff_secs = static_cast<float>(time_diff_us / 1000000.0);
202 m_imgui_last_frame_time = current_time_us;
203
204 // Update I/O with window dimensions.
205 ImGuiIO& io = ImGui::GetIO();
206 io.DisplaySize =
207 ImVec2(static_cast<float>(m_backbuffer_width), static_cast<float>(m_backbuffer_height));
208 io.DeltaTime = time_diff_secs;
209
210 ImGui::NewFrame();
211 }
212
213 void OnScreenUI::DrawImGui()
214 {
215 ImDrawData* draw_data = ImGui::GetDrawData();
216 if (!draw_data)
217 return;
218
219 g_gfx->SetViewport(0.0f, 0.0f, static_cast<float>(m_backbuffer_width),
220 static_cast<float>(m_backbuffer_height), 0.0f, 1.0f);
221
222 // Uniform buffer for draws.
223 struct ImGuiUbo
224 {
225 float u_rcp_viewport_size_mul2[2];
226 float padding[2];
227 };
228 ImGuiUbo ubo = {{1.0f / m_backbuffer_width * 2.0f, 1.0f / m_backbuffer_height * 2.0f}};
229
230 // Set up common state for drawing.
231 g_gfx->SetPipeline(m_imgui_pipeline.get());
232 g_gfx->SetSamplerState(0, RenderState::GetPointSamplerState());
233 g_vertex_manager->UploadUtilityUniforms(&ubo, sizeof(ubo));
234
235 for (int i = 0; i < draw_data->CmdListsCount; i++)
236 {
237 const ImDrawList* cmdlist = draw_data->CmdLists[i];
238 if (cmdlist->VtxBuffer.empty() || cmdlist->IdxBuffer.empty())
239 return;
240
241 u32 base_vertex, base_index;
242 g_vertex_manager->UploadUtilityVertices(cmdlist->VtxBuffer.Data, sizeof(ImDrawVert),
243 cmdlist->VtxBuffer.Size, cmdlist->IdxBuffer.Data,
244 cmdlist->IdxBuffer.Size, &base_vertex, &base_index);
245
246 for (const ImDrawCmd& cmd : cmdlist->CmdBuffer)
247 {
248 if (cmd.UserCallback)
249 {
250 cmd.UserCallback(cmdlist, &cmd);
251 continue;
252 }
253
254 g_gfx->SetScissorRect(g_gfx->ConvertFramebufferRectangle(
255 MathUtil::Rectangle<int>(
256 static_cast<int>(cmd.ClipRect.x), static_cast<int>(cmd.ClipRect.y),
257 static_cast<int>(cmd.ClipRect.z), static_cast<int>(cmd.ClipRect.w)),
258 g_gfx->GetCurrentFramebuffer()));
259 g_gfx->SetTexture(0, reinterpret_cast<const AbstractTexture*>(cmd.GetTexID()));
260 g_gfx->DrawIndexed(base_index, cmd.ElemCount, base_vertex);
261 base_index += cmd.ElemCount;
262 }
263 }
264
265 // Some capture software (such as OBS) hooks SwapBuffers and uses glBlitFramebuffer to copy our
266 // back buffer just before swap. Because glBlitFramebuffer honors the scissor test, the capture
267 // itself will be clipped to whatever bounds were last set by ImGui, resulting in a rather useless
268 // capture whenever any ImGui windows are open. We'll reset the scissor rectangle to the entire
269 // viewport here to avoid this problem.
270 g_gfx->SetScissorRect(g_gfx->ConvertFramebufferRectangle(
271 MathUtil::Rectangle<int>(0, 0, m_backbuffer_width, m_backbuffer_height),
272 g_gfx->GetCurrentFramebuffer()));
273 }
274
275 // Create On-Screen-Messages
276 void OnScreenUI::DrawDebugText()
277 {
278 if (Config::Get(Config::MAIN_MOVIE_SHOW_OSD))
279 {
280 // Position under the FPS display.
281 ImGui::SetNextWindowPos(
282 ImVec2(ImGui::GetIO().DisplaySize.x - ImGui::GetFontSize() * m_backbuffer_scale,
283 80.f * m_backbuffer_scale),
284 ImGuiCond_FirstUseEver, ImVec2(1.0f, 0.0f));
285 ImGui::SetNextWindowSizeConstraints(ImVec2(5.0f * ImGui::GetFontSize() * m_backbuffer_scale,
286 2.1f * ImGui::GetFontSize() * m_backbuffer_scale),
287 ImGui::GetIO().DisplaySize);
288 if (ImGui::Begin("Movie", nullptr, ImGuiWindowFlags_NoFocusOnAppearing))
289 {
290 auto& movie = Core::System::GetInstance().GetMovie();
291 if (movie.IsPlayingInput())
292 {
293 ImGui::Text("Frame: %" PRIu64 " / %" PRIu64, movie.GetCurrentFrame(),
294 movie.GetTotalFrames());
295 ImGui::Text("Input: %" PRIu64 " / %" PRIu64, movie.GetCurrentInputCount(),
296 movie.GetTotalInputCount());
297 }
298 else if (Config::Get(Config::MAIN_SHOW_FRAME_COUNT))
299 {
300 ImGui::Text("Frame: %" PRIu64, movie.GetCurrentFrame());
301 if (movie.IsRecordingInput())
302 ImGui::Text("Input: %" PRIu64, movie.GetCurrentInputCount());
303 }
304 if (Config::Get(Config::MAIN_SHOW_LAG))
305 ImGui::Text("Lag: %" PRIu64 "\n", movie.GetCurrentLagCount());
306 if (Config::Get(Config::MAIN_MOVIE_SHOW_INPUT_DISPLAY))
307 ImGui::TextUnformatted(movie.GetInputDisplay().c_str());
308 if (Config::Get(Config::MAIN_MOVIE_SHOW_RTC))
309 ImGui::TextUnformatted(movie.GetRTCDisplay().c_str());
310 if (Config::Get(Config::MAIN_MOVIE_SHOW_RERECORD))
311 ImGui::TextUnformatted(movie.GetRerecords().c_str());
312 }
313 ImGui::End();
314 }
315
316 if (g_ActiveConfig.bOverlayStats)
317 g_stats.Display();
318
319 if (Config::Get(Config::GFX_SHOW_NETPLAY_MESSAGES) && g_netplay_chat_ui)
320 g_netplay_chat_ui->Display();
321
322 if (Config::Get(Config::NETPLAY_GOLF_MODE_OVERLAY) && g_netplay_golf_ui)
323 g_netplay_golf_ui->Display();
324
325 if (g_ActiveConfig.bOverlayProjStats)
326 g_stats.DisplayProj();
327
328 if (g_ActiveConfig.bOverlayScissorStats)
329 g_stats.DisplayScissor();
330
331 const std::string profile_output = Common::Profiler::ToString();
332 if (!profile_output.empty())
333 ImGui::TextUnformatted(profile_output.c_str());
334 }
335
336 void OnScreenUI::DrawChallengesAndLeaderboards()
337 {
338 if (!Config::Get(Config::MAIN_OSD_MESSAGES))
339 return;
340 #ifdef USE_RETRO_ACHIEVEMENTS
341 auto& instance = AchievementManager::GetInstance();
342 std::lock_guard lg{instance.GetLock()};
343 const bool challenge_indicators_enabled = Config::Get(Config::RA_CHALLENGE_INDICATORS_ENABLED);
344 const bool challenges_updated = instance.AreChallengesUpdated();
345 const auto& challenges = instance.GetActiveChallenges();
346
347 if (!challenge_indicators_enabled)
348 {
349 if (challenges_updated)
350 instance.ResetChallengesUpdated();
351 if (!m_challenge_texture_map.empty())
352 m_challenge_texture_map.clear();
353 }
354 else if (challenges_updated || m_challenge_texture_map.size() != challenges.size())
355 {
356 if (challenges_updated)
357 instance.ResetChallengesUpdated();
358 m_challenge_texture_map.clear();
359 for (const auto& name : challenges)
360 {
361 const auto& icon = instance.GetAchievementBadge(name, false);
362 const u32 width = icon.width;
363 const u32 height = icon.height;
364 TextureConfig tex_config(width, height, 1, 1, 1, AbstractTextureFormat::RGBA8, 0,
365 AbstractTextureType::Texture_2DArray);
366 auto res = m_challenge_texture_map.insert_or_assign(name, g_gfx->CreateTexture(tex_config));
367 res.first->second->Load(0, width, height, width, icon.data.data(),
368 sizeof(u32) * width * height);
369 }
370 }
371
372 float leaderboard_y = ImGui::GetIO().DisplaySize.y;
373 if (challenge_indicators_enabled && !m_challenge_texture_map.empty())
374 {
375 float scale = ImGui::GetIO().DisplaySize.y / 1024.0;
376 ImGui::SetNextWindowSize(ImVec2(0, 0));
377 ImGui::SetNextWindowPos(ImVec2(ImGui::GetIO().DisplaySize.x, ImGui::GetIO().DisplaySize.y), 0,
378 ImVec2(1, 1));
379 if (ImGui::Begin("Challenges", nullptr,
380 ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoInputs |
381 ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoSavedSettings |
382 ImGuiWindowFlags_NoScrollbar | ImGuiWindowFlags_NoNav |
383 ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoFocusOnAppearing))
384 {
385 for (auto& [name, texture] : m_challenge_texture_map)
386 {
387 ImGui::Image(*texture.get(), ImVec2(static_cast<float>(texture->GetWidth()) * scale,
388 static_cast<float>(texture->GetHeight()) * scale));
389 ImGui::SameLine();
390 }
391 }
392 leaderboard_y -= ImGui::GetWindowHeight();
393 ImGui::End();
394 }
395
396 const auto& leaderboard_progress = instance.GetActiveLeaderboards();
397 if (Config::Get(Config::RA_LEADERBOARD_TRACKER_ENABLED) && !leaderboard_progress.empty())
398 {
399 ImGui::SetNextWindowPos(ImVec2(ImGui::GetIO().DisplaySize.x, leaderboard_y), 0,
400 ImVec2(1.0, 1.0));
401 ImGui::SetNextWindowSize(ImVec2(0.0f, 0.0f));
402 if (ImGui::Begin("Leaderboards", nullptr,
403 ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoInputs |
404 ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoSavedSettings |
405 ImGuiWindowFlags_NoScrollbar | ImGuiWindowFlags_NoNav |
406 ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoFocusOnAppearing))
407 {
408 for (const auto& value : leaderboard_progress)
409 ImGui::TextUnformatted(value.c_str());
410 }
411 ImGui::End();
412 }
413 #endif // USE_RETRO_ACHIEVEMENTS
414 }
415
416 void OnScreenUI::Finalize()
417 {
418 auto lock = GetImGuiLock();
419
420 auto& perf_metrics = Core::System::GetInstance().GetPerfMetrics();
421 perf_metrics.DrawImGuiStats(m_backbuffer_scale);
422 DrawDebugText();
423 OSD::DrawMessages();
424 DrawChallengesAndLeaderboards();
425 ImGui::Render();
426
427 // Check for font changes
428 ImGuiStyle& style = ImGui::GetStyle();
429 const int size = Config::Get(Config::MAIN_OSD_FONT_SIZE);
430 if (size != style.FontSizeBase)
431 style.FontSizeBase = static_cast<float>(size);
432
433 // Create or update fonts.
434 ImDrawData* draw_data = ImGui::GetDrawData();
435 if (draw_data->Textures != nullptr)
436 for (ImTextureData* tex : *draw_data->Textures)
437 if (tex->Status != ImTextureStatus_OK)
438 UpdateImguiTexture(tex);
439 }
440
441 void OnScreenUI::UpdateImguiTexture(ImTextureData* tex)
442 {
443 if (tex->Status == ImTextureStatus_WantCreate)
444 {
445 // Create new font texture.
446 IM_ASSERT(tex->TexID == ImTextureID_Invalid);
447 IM_ASSERT(tex->Format == ImTextureFormat_RGBA32);
448
449 TextureConfig font_tex_config(tex->Width, tex->Height, 1, 1, 1, AbstractTextureFormat::RGBA8, 0,
450 AbstractTextureType::Texture_2DArray);
451 std::unique_ptr<AbstractTexture> font_tex =
452 g_gfx->CreateTexture(font_tex_config, "ImGui font texture");
453
454 if (!font_tex)
455 {
456 PanicAlertFmt("Failed to create ImGui texture");
457 return;
458 }
459
460 font_tex->Load(0, tex->Width, tex->Height, tex->Width, tex->Pixels,
461 sizeof(u32) * tex->Width * tex->Height);
462
463 tex->SetTexID(static_cast<ImTextureID>(*font_tex.get()));
464 // Keeps the texture alive.
465 m_imgui_textures.push_back(std::move(font_tex));
466 tex->SetStatus(ImTextureStatus_OK);
467 }
468 else if (tex->Status == ImTextureStatus_WantUpdates)
469 {
470 AbstractTexture* font_tex = reinterpret_cast<AbstractTexture*>(tex->GetTexID());
471
472 if (!font_tex || tex->TexID == ImTextureID_Invalid)
473 {
474 PanicAlertFmt("ImGui texture not created before update");
475 return;
476 }
477
478 for (const ImTextureRect& r : tex->Updates)
479 {
480 // Rect of texture that will be updated.
481 const int x_offset = static_cast<int>(r.x);
482 const int y_offset = static_cast<int>(r.y);
483 const int width = static_cast<int>(r.w);
484 const int height = static_cast<int>(r.h);
485
486 // Create a staging texture to update the font texture with.
487 TextureConfig font_tex_config(width, height, 1, 1, 1, AbstractTextureFormat::RGBA8, 0,
488 AbstractTextureType::Texture_2DArray);
489 std::unique_ptr<AbstractStagingTexture> stage =
490 g_gfx->CreateStagingTexture(StagingTextureType::Upload, font_tex_config);
491
492 const int src_pitch = width * tex->BytesPerPixel;
493
494 // Write to staging texture.
495 for (int y = 0; y < height; y++)
496 {
497 const MathUtil::Rectangle<int> rect_line = {0, y, width, y + 1};
498 stage->WriteTexels(rect_line, tex->GetPixelsAt(x_offset, y_offset + y), src_pitch);
499 }
500
501 // Copy to font texture.
502 const MathUtil::Rectangle<int> rect_staging = {0, 0, width, height};
503 const MathUtil::Rectangle<int> rect_target = {x_offset, y_offset, width + x_offset,
504 height + y_offset};
505
506 stage->CopyToTexture(rect_staging, font_tex, rect_target, 0, 0);
507 }
508
509 tex->SetStatus(ImTextureStatus_OK);
510 }
511 else if (tex->Status == ImTextureStatus_WantDestroy && tex->UnusedFrames > 0)
512 {
513 AbstractTexture* font_tex = reinterpret_cast<AbstractTexture*>(tex->GetTexID());
514
515 tex->SetTexID(ImTextureID_Invalid);
516
517 m_imgui_textures.erase(
518 std::find_if(m_imgui_textures.begin(), m_imgui_textures.end(),
519 [font_tex](auto& element) { return element.get() == font_tex; }));
520
521 tex->Status = ImTextureStatus_Destroyed;
522 }
523 }
524
525 std::unique_lock<std::mutex> OnScreenUI::GetImGuiLock()
526 {
527 return std::unique_lock<std::mutex>(m_imgui_mutex);
528 }
529
530 void OnScreenUI::SetScale(float backbuffer_scale)
531 {
532 ImGui::GetIO().DisplayFramebufferScale.x = backbuffer_scale;
533 ImGui::GetIO().DisplayFramebufferScale.y = backbuffer_scale;
534
535 // ScaleAllSizes scales in-place, so calling it twice will double-apply the scale
536 // Reset the style first so that the scale is applied to the base style, not an already-scaled one
537 ImGuiStyle& style = ImGui::GetStyle();
538 style = {};
539 style.FontScaleMain = backbuffer_scale;
540 style.WindowRounding = 7.0f;
541 style.ScaleAllSizes(backbuffer_scale);
542
543 m_backbuffer_scale = backbuffer_scale;
544 }
545 void OnScreenUI::SetKeyMap(const DolphinKeyMap& key_map)
546 {
547 static constexpr DolphinKeyMap dolphin_to_imgui_map = {
548 ImGuiKey_Tab, ImGuiKey_LeftArrow, ImGuiKey_RightArrow, ImGuiKey_UpArrow,
549 ImGuiKey_DownArrow, ImGuiKey_PageUp, ImGuiKey_PageDown, ImGuiKey_Home,
550 ImGuiKey_End, ImGuiKey_Insert, ImGuiKey_Delete, ImGuiKey_Backspace,
551 ImGuiKey_Space, ImGuiKey_Enter, ImGuiKey_Escape, ImGuiKey_KeypadEnter,
552 ImGuiKey_A, ImGuiKey_C, ImGuiKey_V, ImGuiKey_X,
553 ImGuiKey_Y, ImGuiKey_Z,
554 };
555
556 auto lock = GetImGuiLock();
557
558 if (!ImGui::GetCurrentContext())
559 return;
560
561 m_dolphin_to_imgui_map.clear();
562 for (int dolphin_key = 0; dolphin_key <= static_cast<int>(DolphinKey::Z); dolphin_key++)
563 {
564 const int imgui_key = dolphin_to_imgui_map[DolphinKey(dolphin_key)];
565 if (imgui_key >= 0)
566 {
567 const int mapped_key = key_map[DolphinKey(dolphin_key)];
568 m_dolphin_to_imgui_map[mapped_key & 0x1FF] = imgui_key;
569 }
570 }
571 }
572
573 void OnScreenUI::SetKey(u32 key, bool is_down, const char* chars)
574 {
575 auto lock = GetImGuiLock();
576 if (auto iter = m_dolphin_to_imgui_map.find(key); iter != m_dolphin_to_imgui_map.end())
577 ImGui::GetIO().AddKeyEvent((ImGuiKey)iter->second, is_down);
578
579 if (chars)
580 ImGui::GetIO().AddInputCharactersUTF8(chars);
581 }
582
583 void OnScreenUI::SetMousePos(float x, float y)
584 {
585 auto lock = GetImGuiLock();
586
587 ImGui::GetIO().AddMousePosEvent(x, y);
588 }
589
590 void OnScreenUI::SetMousePress(u32 button_mask)
591 {
592 auto lock = GetImGuiLock();
593
594 for (size_t i = 0; i < std::size(ImGui::GetIO().MouseDown); i++)
595 {
596 ImGui::GetIO().AddMouseButtonEvent(static_cast<int>(i), (button_mask & (1u << i)) != 0);
597 }
598 }
599
600 } // namespace VideoCommon