// The SDL side of VulkanWindow: events and input forwarding, cursor, screen keyboard, logical size, screenshots on disk. #include "vulkan_window.h" #include "input_keymap.h" #include "texture_decode.h" #include "ui_scale.h" #include "ui_quality.h" #ifdef MT_NATIVE_HAS_LIVE_CLIENT #include "platform/ScriptLib/PythonBoot.h" #endif #include #include #include #include #include #include #include namespace mt_host { namespace { #ifdef MT_NATIVE_HAS_LIVE_CLIENT SDL_Cursor* load_game_cursor(int shape) { static constexpr std::array images = { "cursor.sub", "cursor_attack.sub", "cursor_attack.sub", "cursor_talk.sub", "cursor_no.sub", "cursor_pick.sub", "cursor_door.sub", "cursor_chair.sub", "cursor_chair.sub", "cursor_buy.sub", "cursor_sell.sub", "cursor_camera_rotate.sub", "cursor_hsize.sub", "cursor_vsize.sub", "cursor_hvsize.sub"}; if (shape < 0 || shape >= static_cast(images.size())) return nullptr; const std::string sub_path = std::string("d:/ymir work/ui/cursor/") + images[shape]; std::vector sub_bytes; if (!read_live_pack_texture(sub_path, sub_bytes)) return nullptr; std::unordered_map tokens; std::istringstream input(std::string(sub_bytes.begin(), sub_bytes.end())); std::string line; while (std::getline(input, line)) { std::istringstream fields(line); std::string key, value; if (!(fields >> key >> value)) continue; if (!value.empty() && value.front() == '"') { value.erase(0, 1); if (!value.empty() && value.back() == '"') value.pop_back(); } std::transform(key.begin(), key.end(), key.begin(), [](unsigned char ch) { return std::tolower(ch); }); tokens[key] = value; } if (tokens["title"] != "subimage" || tokens["image"].empty()) return nullptr; const std::string image_path = tokens["version"] == "2.0" ? std::string("d:/ymir work/ui/cursor/") + tokens["image"] : std::string("d:/ymir work/ui/") + tokens["image"]; std::vector image_bytes; if (!read_live_pack_texture(image_path, image_bytes)) return nullptr; const auto image = decode_texture_bytes(image_bytes.data(), image_bytes.size()); if (!image.ok()) return nullptr; const int left = std::atoi(tokens["left"].c_str()); const int top = std::atoi(tokens["top"].c_str()); const int right = std::atoi(tokens["right"].c_str()); const int bottom = std::atoi(tokens["bottom"].c_str()); if (left < 0 || top < 0 || right <= left || bottom <= top || right > image.w || bottom > image.h) return nullptr; const int width = right - left, height = bottom - top; std::vector pixels(std::size_t(width) * height * 4); for (int y = 0; y < height; ++y) std::memcpy(pixels.data() + std::size_t(y) * width * 4, image.rgba.data() + (std::size_t(top + y) * image.w + left) * 4, std::size_t(width) * 4); SDL_Surface* surface = SDL_CreateSurfaceFrom(width, height, SDL_PIXELFORMAT_RGBA32, pixels.data(), width * 4); if (!surface) return nullptr; const int hot_x = shape >= 12 ? std::min(16, width - 1) : 0; const int hot_y = shape >= 12 ? std::min(16, height - 1) : 0; SDL_Cursor* cursor = SDL_CreateColorCursor(surface, hot_x, hot_y); SDL_DestroySurface(surface); return cursor; } #endif } // namespace #ifdef MT_NATIVE_HAS_LIVE_CLIENT void VulkanWindow::enable_game_hardware_cursor() { hardware_cursor_enabled_ = true; for (int shape = 0; shape < static_cast(game_cursors_.size()); ++shape) { game_cursors_[shape] = load_game_cursor(shape); } fallback_cursor_ = SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_DEFAULT); SDL_SetCursor(game_cursors_[0] ? game_cursors_[0] : fallback_cursor_); SDL_ShowCursor(); os_cursor_hidden_ = false; } void VulkanWindow::sync_game_cursor() { if (!hardware_cursor_enabled_) return; const bool visible = !touch_controller.is_enabled() && PythonBoot::CursorVisible() && !PythonBoot::IsSoftwareCursorVisible(); if (visible == os_cursor_hidden_) { if (visible) SDL_ShowCursor(); else SDL_HideCursor(); os_cursor_hidden_ = !visible; } if (!visible) return; const int shape = PythonBoot::CursorShape(); if (shape == current_cursor_shape_) return; SDL_Cursor* cursor = shape >= 0 && shape < static_cast(game_cursors_.size()) ? game_cursors_[shape] : nullptr; if (cursor || fallback_cursor_) SDL_SetCursor(cursor ? cursor : fallback_cursor_); current_cursor_shape_ = shape; } #endif void VulkanWindow::write_bmp(const std::string& path, const std::uint8_t* pixels) const { const std::uint32_t w = extent_.width, h = extent_.height; const bool rgba = swapchain_format_ == VK_FORMAT_R8G8B8A8_UNORM || swapchain_format_ == VK_FORMAT_R8G8B8A8_SRGB; std::vector file(54 + std::size_t(w) * h * 4); auto put32 = [&](std::size_t at, std::uint32_t value) { std::memcpy(&file[at], &value, 4); }; file[0] = 'B'; file[1] = 'M'; put32(2, std::uint32_t(file.size())); put32(10, 54); put32(14, 40); put32(18, w); put32(22, h); put32(26, 1u | (32u << 16)); put32(34, w * h * 4); for (std::uint32_t y = 0; y < h; ++y) for (std::uint32_t x = 0; x < w; ++x) { const std::uint8_t* src = pixels + (std::size_t(y) * w + x) * 4; std::uint8_t* dst = &file[54 + (std::size_t(h - 1 - y) * w + x) * 4]; dst[0] = rgba ? src[2] : src[0]; dst[1] = src[1]; dst[2] = rgba ? src[0] : src[2]; dst[3] = 255; } std::ofstream out(path, std::ios::binary); out.write(reinterpret_cast(file.data()), std::streamsize(file.size())); } double VulkanWindow::input_idle_seconds() const { if (fingers_down_ > 0 || buttons_down_ > 0) return 0.0; return std::chrono::duration(std::chrono::steady_clock::now() - last_input_).count(); } void VulkanWindow::request_screenshot(std::string path, std::uint64_t frame) { screenshot_path_ = std::move(path); screenshot_frame_ = frame; } bool VulkanWindow::request_frame(FrameSink sink) { if (!swapchain_readable_) return false; frame_sinks_.push_back(std::move(sink)); return true; } std::uint32_t VulkanWindow::logical_width() const { int w = 0, h = 0; if (window_) SDL_GetWindowSize(window_, &w, &h); // The UI size setting (ui_scale.h; always on Android, MT_UI_HEIGHT on the desktop) fixes the logical // height and keeps the device aspect ratio on wider phone displays. if (const int ui_h = mt_host::ui_height(); ui_h > 0 && w > 0 && h > 0) return std::max(1, int(std::lround(double(w) * ui_h / h))); return w > 0 ? static_cast(w) : extent_.width; } std::uint32_t VulkanWindow::logical_height() const { int w = 0, h = 0; if (window_) SDL_GetWindowSize(window_, &w, &h); if (const int ui_h = mt_host::ui_height(); ui_h > 0 && w > 0 && h > 0) return std::uint32_t(ui_h); return h > 0 ? static_cast(h) : extent_.height; } int VulkanWindow::ui_safe_inset() const { int pw = 0, ph = 0; if (safe_inset_px_ <= 0 || !window_ || !SDL_GetWindowSizeInPixels(window_, &pw, &ph) || ph <= 0) return 0; return int(std::lround(double(safe_inset_px_) * logical_height() / ph)); } void VulkanWindow::sync_screen_keyboard() { const bool want = touch_controller.wants_screen_keyboard(); const unsigned serial = touch_controller.screen_keyboard_serial(); if (want && (!SDL_TextInputActive(window_) || serial != screen_keyboard_serial_)) { SDL_PropertiesID props = SDL_CreateProperties(); SDL_SetNumberProperty(props, SDL_PROP_TEXTINPUT_TYPE_NUMBER, SDL_TEXTINPUT_TYPE_TEXT); SDL_SetNumberProperty(props, SDL_PROP_TEXTINPUT_CAPITALIZATION_NUMBER, SDL_CAPITALIZE_NONE); SDL_SetBooleanProperty(props, SDL_PROP_TEXTINPUT_AUTOCORRECT_BOOLEAN, false); SDL_StartTextInputWithProperties(window_, props); SDL_DestroyProperties(props); } else if (!want && SDL_TextInputActive(window_)) { SDL_StopTextInput(window_); } screen_keyboard_serial_ = serial; } bool VulkanWindow::poll(bool forward_to_live_client) { #ifdef MT_NATIVE_HAS_LIVE_CLIENT auto map_mouse = [&](float wx, float wy, int& ox, int& oy) { int win_w = 0, win_h = 0; SDL_GetWindowSize(window_, &win_w, &win_h); unsigned ui_w = extent_.width ? extent_.width : 960; unsigned ui_h = extent_.height ? extent_.height : 640; UIRenderGetSize(&ui_w, &ui_h); if (win_w > 0 && win_h > 0 && ui_w > 0 && ui_h > 0) { ox = static_cast(std::lround(wx * float(ui_w) / float(win_w))); oy = static_cast(std::lround(wy * float(ui_h) / float(win_h))); } else { ox = static_cast(std::lround(wx)); oy = static_cast(std::lround(wy)); } }; std::optional> pending_mouse_move; auto flush_mouse_move = [&] { if (!pending_mouse_move) return; const auto [mx, my] = *pending_mouse_move; pending_mouse_move.reset(); last_mx_ = mx; last_my_ = my; if (touch_controller.is_enabled() && touch_controller.on_mouse_motion(mx, my)) return; PythonBoot::UIMouseMove(mx, my); }; #endif SDL_Event event; while (SDL_PollEvent(&event)) { note_input(event); #ifdef MT_NATIVE_HAS_LIVE_CLIENT // Touches arrive as SDL_EVENT_FINGER_*; the touch-synthesized mouse copy // would register as a second finger (101) and turn every drag into a pinch. if (touch_controller.is_enabled() && ((event.type == SDL_EVENT_MOUSE_MOTION && event.motion.which == SDL_TOUCH_MOUSEID) || ((event.type == SDL_EVENT_MOUSE_BUTTON_DOWN || event.type == SDL_EVENT_MOUSE_BUTTON_UP) && event.button.which == SDL_TOUCH_MOUSEID))) continue; if (forward_to_live_client && event.type == SDL_EVENT_MOUSE_MOTION) { int mx = 0, my = 0; map_mouse(event.motion.x, event.motion.y, mx, my); pending_mouse_move = std::pair{mx, my}; continue; } // Preserve event order at button/key/focus boundaries while collapsing // high-frequency motion into the most recent position. flush_mouse_move(); #endif if (event.type == SDL_EVENT_QUIT) return false; if (event.type == SDL_EVENT_WINDOW_RESIZED || event.type == SDL_EVENT_WINDOW_PIXEL_SIZE_CHANGED || event.type == SDL_EVENT_WINDOW_DISPLAY_SCALE_CHANGED || event.type == SDL_EVENT_WINDOW_DISPLAY_CHANGED) { int ew = 0, eh = 0; SDL_GetWindowSize(window_, &ew, &eh); touch_controller.update_screen_size(int(logical_width()), int(logical_height()), ui_safe_inset()); #ifdef MT_NATIVE_HAS_LIVE_CLIENT if (forward_to_live_client && ew > 0 && eh > 0) { PythonBoot::SetUISafeInset(ui_safe_inset()); PythonBoot::SetUISize(int(logical_width()), int(logical_height())); } #endif recreate_swapchain(); #ifdef MT_NATIVE_HAS_LIVE_CLIENT if (forward_to_live_client) { int scale = font_raster_scale(float(width()) / float(std::max(1u, logical_width()))); if (const char* env = std::getenv("MT_FONT_OVERSAMPLE")) scale = std::max(1, std::atoi(env)); UISetFontOversample(scale); } #endif continue; } if (event.type == SDL_EVENT_FINGER_DOWN) { touch_controller.on_finger_down(event.tfinger.fingerID, event.tfinger.x, event.tfinger.y); continue; } else if (event.type == SDL_EVENT_FINGER_MOTION) { touch_controller.on_finger_motion(event.tfinger.fingerID, event.tfinger.x, event.tfinger.y); continue; } else if (event.type == SDL_EVENT_FINGER_CANCELED) { touch_controller.cancel_gestures(); continue; } else if (event.type == SDL_EVENT_FINGER_UP) { touch_controller.on_finger_up(event.tfinger.fingerID, event.tfinger.x, event.tfinger.y); continue; } #ifdef MT_NATIVE_HAS_LIVE_CLIENT if (forward_to_live_client) { if (event.type == SDL_EVENT_WINDOW_FOCUS_GAINED || event.type == SDL_EVENT_WINDOW_FOCUS_LOST) PythonBoot::UIActivate(event.type == SDL_EVENT_WINDOW_FOCUS_GAINED); if (!hardware_cursor_enabled_ && (event.type == SDL_EVENT_WINDOW_MOUSE_ENTER || event.type == SDL_EVENT_WINDOW_FOCUS_GAINED)) { std::printf(">>> SDL MOUSE ENTER/FOCUS GAINED\n"); SDL_HideCursor(); os_cursor_hidden_ = true; } else if (event.type == SDL_EVENT_WINDOW_FOCUS_LOST) { touch_controller.cancel_gestures(); SDL_CaptureMouse(false); PythonBoot::UIMouseButton(2, false, last_mx_, last_my_); PythonBoot::UIMouseButton(3, false, last_mx_, last_my_); PythonBoot::UIMouseButton(1, false, last_mx_, last_my_); } if (event.type == SDL_EVENT_MOUSE_BUTTON_DOWN || event.type == SDL_EVENT_MOUSE_BUTTON_UP) { const bool pressed = event.type == SDL_EVENT_MOUSE_BUTTON_DOWN; int btn = 0; if (event.button.button == SDL_BUTTON_LEFT) btn = 1; else if (event.button.button == SDL_BUTTON_RIGHT) btn = 2; else if (event.button.button == SDL_BUTTON_MIDDLE) btn = 3; if (btn) { int mx = 0, my = 0; map_mouse(event.button.x, event.button.y, mx, my); last_mx_ = mx; last_my_ = my; if (touch_controller.is_enabled()) { if (touch_controller.on_mouse_button(btn, pressed, mx, my)) { continue; } } SDL_CaptureMouse(SDL_GetMouseState(nullptr, nullptr) != 0); PythonBoot::UIMouseButton(btn, pressed, mx, my); } } else if (event.type == SDL_EVENT_MOUSE_WHEEL) { PythonBoot::UIMouseWheel(int(event.wheel.y * 120.0f)); } else if (event.type == SDL_EVENT_KEY_DOWN || event.type == SDL_EVENT_KEY_UP) { const bool pressed = event.type == SDL_EVENT_KEY_DOWN; // Android back = ESC: closes the top window, or opens the system menu (game.py). if (event.key.scancode == SDL_SCANCODE_AC_BACK) event.key.scancode = SDL_SCANCODE_ESCAPE; if (pressed) { if (const int vk = sdl_scancode_to_vk(event.key.scancode)) PythonBoot::UIIMEKeyDown(vk); if (event.key.scancode == SDL_SCANCODE_BACKSPACE) PythonBoot::UIChar(8); else if (event.key.scancode == SDL_SCANCODE_TAB) PythonBoot::UIChar(9); else if (event.key.scancode == SDL_SCANCODE_RETURN || event.key.scancode == SDL_SCANCODE_KP_ENTER) PythonBoot::UIChar(13); else if (event.key.scancode == SDL_SCANCODE_ESCAPE) PythonBoot::UIChar(27); } if (!event.key.repeat) { if (const int dik = sdl_scancode_to_dik(event.key.scancode)) PythonBoot::UIKey(dik, pressed); } } else if (event.type == SDL_EVENT_TEXT_INPUT && event.text.text) { const auto* s = reinterpret_cast(event.text.text); while (*s) { unsigned cp = 0; if (*s < 0x80u) { cp = *s++; } else if ((*s & 0xE0u) == 0xC0u && (s[1] & 0xC0u) == 0x80u) { cp = ((*s & 0x1Fu) << 6) | (s[1] & 0x3Fu); s += 2; } else if ((*s & 0xF0u) == 0xE0u && (s[1] & 0xC0u) == 0x80u && (s[2] & 0xC0u) == 0x80u) { cp = ((*s & 0x0Fu) << 12) | ((s[1] & 0x3Fu) << 6) | (s[2] & 0x3Fu); s += 3; } else if ((*s & 0xF8u) == 0xF0u && (s[1] & 0xC0u) == 0x80u && (s[2] & 0xC0u) == 0x80u && (s[3] & 0xC0u) == 0x80u) { cp = ((*s & 0x07u) << 18) | ((s[1] & 0x3Fu) << 12) | ((s[2] & 0x3Fu) << 6) | (s[3] & 0x3Fu); s += 4; } else { ++s; continue; } if (cp >= 32u && cp != 127u) PythonBoot::UIChar(cp); } } } #else (void)forward_to_live_client; #endif } #ifdef MT_NATIVE_HAS_LIVE_CLIENT flush_mouse_move(); #endif touch_controller.update(); if (touch_controller.is_enabled()) sync_screen_keyboard(); #ifdef MT_NATIVE_HAS_LIVE_CLIENT if (forward_to_live_client && !hardware_cursor_enabled_ && !os_cursor_hidden_ && !touch_controller.is_enabled()) { SDL_HideCursor(); os_cursor_hidden_ = true; } #endif return true; } void VulkanWindow::update_fps_counter() { const auto now = std::chrono::steady_clock::now(); if (fps_frames_++ == 0) { fps_window_start_ = now; return; } const double elapsed = std::chrono::duration(now - fps_window_start_).count(); if (elapsed >= 0.5) { fps_ = int(std::lround((fps_frames_ - 1) / elapsed)); fps_frames_ = 1; fps_window_start_ = now; } } void VulkanWindow::note_input(const SDL_Event& event) { switch (event.type) { case SDL_EVENT_FINGER_DOWN: ++fingers_down_; break; case SDL_EVENT_FINGER_UP: case SDL_EVENT_FINGER_CANCELED: fingers_down_ = std::max(0, fingers_down_ - 1); break; case SDL_EVENT_MOUSE_BUTTON_DOWN: ++buttons_down_; break; case SDL_EVENT_MOUSE_BUTTON_UP: buttons_down_ = std::max(0, buttons_down_ - 1); break; case SDL_EVENT_WINDOW_FOCUS_LOST: case SDL_EVENT_WILL_ENTER_BACKGROUND: // An up event lost with the focus must not keep the client out of the idle rate for good. fingers_down_ = buttons_down_ = 0; break; case SDL_EVENT_FINGER_MOTION: case SDL_EVENT_MOUSE_MOTION: case SDL_EVENT_MOUSE_WHEEL: case SDL_EVENT_KEY_DOWN: case SDL_EVENT_KEY_UP: case SDL_EVENT_TEXT_INPUT: case SDL_EVENT_WINDOW_FOCUS_GAINED: case SDL_EVENT_DID_ENTER_FOREGROUND: break; default: return; } last_input_ = std::chrono::steady_clock::now(); } } // namespace mt_host