diff --git a/editor/Exporter.cpp b/editor/Exporter.cpp index af6f62b81..6e2c3f93b 100644 --- a/editor/Exporter.cpp +++ b/editor/Exporter.cpp @@ -30,6 +30,7 @@ #include #include #include +#include #include using namespace doriax; @@ -2472,6 +2473,9 @@ bool editor::Exporter::copyEngine() { projectSettings += indent + std::string("set(DORIAX_STOREKIT ") + (project->getIOSProjectSettings().storeKitEnabled ? "ON" : "OFF") + ")"; projectSettings += indent + "set(DORIAX_WEB_PORTAL " + Stream::webPortalTypeToString(project->getWebProjectSettings().portal) + ")"; projectSettings += indent + "set(DORIAX_WEB_PORTAL_GAME_ID \"" + escapeCMakeCString(project->getWebProjectSettings().portalGameId) + "\")"; + std::ostringstream maxPixelRatio; + maxPixelRatio << project->getWebProjectSettings().maxPixelRatio; + projectSettings += indent + "set(DORIAX_WEB_MAX_PIXEL_RATIO " + maxPixelRatio.str() + ")"; cmakeContent.replace(projectSettingsPos, projectSettingsMarker.size(), projectSettings); } else { Out::warning("Exported CMakeLists.txt is missing the project settings marker; using platform defaults"); diff --git a/editor/Project.h b/editor/Project.h index fef0fc4a9..feef8c2a0 100644 --- a/editor/Project.h +++ b/editor/Project.h @@ -225,6 +225,8 @@ namespace doriax::editor{ std::string headInclude; bool resizeCanvasToWindow = true; bool hideEmscriptenUI = false; + // Most framebuffer pixels per CSS pixel, 1 or more + float maxPixelRatio = 2.0f; // Its SDK is loaded for the WebPortal class WebPortalType portal = WebPortalType::NONE; // For portals that identify the game, like GameDistribution diff --git a/editor/Stream.cpp b/editor/Stream.cpp index 19018c9ae..1a06841fb 100644 --- a/editor/Stream.cpp +++ b/editor/Stream.cpp @@ -2046,6 +2046,7 @@ YAML::Node editor::Stream::encodeProject(Project* project) { if (!web.headInclude.empty()) webNode["headInclude"] = web.headInclude; if (web.resizeCanvasToWindow != defaultWeb.resizeCanvasToWindow) webNode["resizeCanvasToWindow"] = web.resizeCanvasToWindow; if (web.hideEmscriptenUI != defaultWeb.hideEmscriptenUI) webNode["hideEmscriptenUI"] = web.hideEmscriptenUI; + if (web.maxPixelRatio != defaultWeb.maxPixelRatio) webNode["maxPixelRatio"] = web.maxPixelRatio; if (web.portal != defaultWeb.portal) webNode["portal"] = webPortalTypeToString(web.portal); if (!web.portalGameId.empty()) webNode["portalGameId"] = web.portalGameId; if (webNode.size() != 0) root["web"] = webNode; @@ -2389,6 +2390,7 @@ void editor::Stream::decodeProject(Project* project, const YAML::Node& node, con if (webNode["headInclude"]) web.headInclude = webNode["headInclude"].as(); if (webNode["resizeCanvasToWindow"].IsDefined()) web.resizeCanvasToWindow = webNode["resizeCanvasToWindow"].as(); if (webNode["hideEmscriptenUI"].IsDefined()) web.hideEmscriptenUI = webNode["hideEmscriptenUI"].as(); + if (webNode["maxPixelRatio"]) web.maxPixelRatio = std::max(1.0f, webNode["maxPixelRatio"].as()); if (webNode["portal"]) web.portal = stringToWebPortalType(webNode["portal"].as()); if (webNode["portalGameId"]) web.portalGameId = webNode["portalGameId"].as(); } diff --git a/editor/ai/EditorActionExecutor.cpp b/editor/ai/EditorActionExecutor.cpp index 23f3a530f..53ac5c406 100644 --- a/editor/ai/EditorActionExecutor.cpp +++ b/editor/ai/EditorActionExecutor.cpp @@ -7542,6 +7542,7 @@ ActionResult EditorActionExecutor::setProjectSettings(const Json& arguments) { WebProjectSettings& web = project->getWebProjectSettings(); if (arguments.contains("web_resize_canvas")) web.resizeCanvasToWindow = arguments["web_resize_canvas"].get(); if (arguments.contains("web_hide_emscripten_ui")) web.hideEmscriptenUI = arguments["web_hide_emscripten_ui"].get(); + if (arguments.contains("web_max_pixel_ratio")) web.maxPixelRatio = arguments["web_max_pixel_ratio"].get(); if (!project->saveProjectFile()) { return failResult("Failed to save the project settings."); @@ -7554,7 +7555,7 @@ ActionResult EditorActionExecutor::setProjectSettings(const Json& arguments) { {"window", {{"width", project->getWindowWidth()}, {"height", project->getWindowHeight()}}}, {"vsync", project->isVSyncEnabled()}, {"loading", loadingSettingsJson(project->getLoadingSettings())}, - {"web", {{"resize_canvas", web.resizeCanvasToWindow}, {"hide_emscripten_ui", web.hideEmscriptenUI}}}}); + {"web", {{"resize_canvas", web.resizeCanvasToWindow}, {"hide_emscripten_ui", web.hideEmscriptenUI}, {"max_pixel_ratio", web.maxPixelRatio}}}}); } ActionResult EditorActionExecutor::createProject(const Json& arguments) { diff --git a/editor/ai/EditorActionRegistry.cpp b/editor/ai/EditorActionRegistry.cpp index df8aabb0f..38fed417c 100644 --- a/editor/ai/EditorActionRegistry.cpp +++ b/editor/ai/EditorActionRegistry.cpp @@ -1252,7 +1252,8 @@ const std::vector& cachedTools() { {"loading_timeout", numberSchema("Seconds without load progress before a load stops waiting")}, {"async_loading", boolSchema("Load files on worker threads while the loading scene is shown")}, {"web_resize_canvas", boolSchema("Web export: the canvas fills the browser window")}, - {"web_hide_emscripten_ui", boolSchema("Web export: hide the Emscripten logo, status and console around the canvas")} + {"web_hide_emscripten_ui", boolSchema("Web export: hide the Emscripten logo, status and console around the canvas")}, + {"web_max_pixel_ratio", numberSchema("Web export: most pixels drawn per CSS pixel on phones and HiDPI screens, 1 or more. Lower costs less GPU time")} }), false }, @@ -2030,6 +2031,9 @@ ValidationResult EditorActionRegistry::validate(const std::string& name, const J return fail(std::string("set_project_settings ") + key + " must be a non-negative number."); } } + if (arguments.contains("web_max_pixel_ratio") && (!arguments["web_max_pixel_ratio"].is_number() || arguments["web_max_pixel_ratio"].get() < 1.0)) { + return fail("set_project_settings web_max_pixel_ratio must be a number of at least 1."); + } for (const char* key : {"vsync", "async_loading", "web_resize_canvas", "web_hide_emscripten_ui"}) { if (arguments.contains(key) && !arguments[key].is_boolean()) { return fail(std::string("set_project_settings ") + key + " must be a boolean."); diff --git a/editor/window/dialog/ProjectSettingsWindow.cpp b/editor/window/dialog/ProjectSettingsWindow.cpp index faf931e16..192d965ef 100644 --- a/editor/window/dialog/ProjectSettingsWindow.cpp +++ b/editor/window/dialog/ProjectSettingsWindow.cpp @@ -861,6 +861,7 @@ void ProjectSettingsWindow::open(Project* project) { snprintf(m_webHeadIncludeBuffer, sizeof(m_webHeadIncludeBuffer), "%s", web.headInclude.c_str()); m_webResizeCanvasToWindow = web.resizeCanvasToWindow; m_webHideEmscriptenUI = web.hideEmscriptenUI; + m_webMaxPixelRatio = web.maxPixelRatio; m_webPortalIndex = findWebPortalIndex(web.portal); snprintf(m_webPortalGameIdBuffer, sizeof(m_webPortalGameIdBuffer), "%s", web.portalGameId.c_str()); @@ -1418,6 +1419,15 @@ void ProjectSettingsWindow::drawWebSettings() { ImGui::Checkbox("##WebHideEmscriptenUI", &m_webHideEmscriptenUI); endSettingsRow("Hide the standard logo, status, controls and output console. Runtime scripts remain active. Custom HTML elements are not removed."); + const WebProjectSettings defaults; + if (beginSettingsRow("Max Pixel Ratio", m_webMaxPixelRatio != defaults.maxPixelRatio)) { + m_webMaxPixelRatio = defaults.maxPixelRatio; + } + ImGui::SetNextItemWidth(-helpMarkerWidth()); + UIUtils::inputFloat("##WebMaxPixelRatio", &m_webMaxPixelRatio, 0.25f, 1.0f, "%.2f"); + m_webMaxPixelRatio = std::isfinite(m_webMaxPixelRatio) ? std::max(m_webMaxPixelRatio, 1.0f) : defaults.maxPixelRatio; + endSettingsRow("Most pixels drawn per CSS pixel on phones and HiDPI screens. Higher is sharper and costs more GPU time. 1 ignores the screen density."); + drawComboSetting("Game Portal", "##WebPortal", webPortalNames, webPortalCount, m_webPortalIndex, findWebPortalIndex(WebPortalType::NONE), "Loads this portal's SDK for the WebPortal class: ads and gameplay events. Each portal needs its own export."); @@ -1756,6 +1766,7 @@ bool ProjectSettingsWindow::applySettings() { applyTextBuffer(web.headInclude, m_webHeadIncludeBuffer); web.resizeCanvasToWindow = m_webResizeCanvasToWindow; web.hideEmscriptenUI = m_webHideEmscriptenUI; + web.maxPixelRatio = m_webMaxPixelRatio; web.portal = webPortalValues[std::clamp(m_webPortalIndex, 0, webPortalCount - 1)]; applyTextBuffer(web.portalGameId, m_webPortalGameIdBuffer); diff --git a/editor/window/dialog/ProjectSettingsWindow.h b/editor/window/dialog/ProjectSettingsWindow.h index 8f354a5c7..1150b00dd 100644 --- a/editor/window/dialog/ProjectSettingsWindow.h +++ b/editor/window/dialog/ProjectSettingsWindow.h @@ -60,6 +60,7 @@ namespace doriax::editor { char m_webHeadIncludeBuffer[2048] = {0}; bool m_webResizeCanvasToWindow = true; bool m_webHideEmscriptenUI = false; + float m_webMaxPixelRatio = 2.0f; int m_webPortalIndex = 0; char m_webPortalGameIdBuffer[128] = {0}; char m_linuxApplicationNameBuffer[256] = {0}; diff --git a/engine/CMakeLists.txt b/engine/CMakeLists.txt index 077292776..4c7fb87f2 100644 --- a/engine/CMakeLists.txt +++ b/engine/CMakeLists.txt @@ -14,6 +14,7 @@ set(DORIAX_WEB_PORTALS none crazygames poki gamedistribution yandex youtube) set(DORIAX_WEB_PORTAL none CACHE STRING "Game portal SDK of web builds") set_property(CACHE DORIAX_WEB_PORTAL PROPERTY STRINGS ${DORIAX_WEB_PORTALS}) set(DORIAX_WEB_PORTAL_GAME_ID "" CACHE STRING "Game ID for web portals that need one, like GameDistribution") +set(DORIAX_WEB_MAX_PIXEL_RATIO 2 CACHE STRING "Most framebuffer pixels per CSS pixel of web builds") # ============================================================= # STANDALONE PROJECT SETUP @@ -212,10 +213,13 @@ if(CMAKE_SOURCE_DIR STREQUAL CMAKE_CURRENT_SOURCE_DIR) endif() if(NOT DORIAX_WEB_PORTAL STREQUAL "none") string(TOUPPER "${DORIAX_WEB_PORTAL}" WEB_PORTAL_NAME) - # only WebPortals.cpp reads them, so switching portals rebuilds that file alone - set_property(SOURCE ${DORIAX_ROOT}/platform/emscripten/WebPortals.cpp APPEND PROPERTY COMPILE_DEFINITIONS + # only these files read them, so switching portals rebuilds no other + set_property(SOURCE ${DORIAX_ROOT}/platform/emscripten/WebPortals.cpp ${DORIAX_ROOT}/platform/emscripten/DoriaxWeb.cpp + APPEND PROPERTY COMPILE_DEFINITIONS "DORIAX_WEB_PORTAL_${WEB_PORTAL_NAME}" "DORIAX_WEB_PORTAL_GAME_ID=\"${DORIAX_WEB_PORTAL_GAME_ID}\"") endif() + set_property(SOURCE ${DORIAX_ROOT}/platform/emscripten/DoriaxWeb.cpp APPEND PROPERTY COMPILE_DEFINITIONS + "DORIAX_WEB_MAX_PIXEL_RATIO=${DORIAX_WEB_MAX_PIXEL_RATIO}") set(CMAKE_EXECUTABLE_SUFFIX ".html") diff --git a/engine/core/Engine.cpp b/engine/core/Engine.cpp index db424d26c..74326e1f8 100644 --- a/engine/core/Engine.cpp +++ b/engine/core/Engine.cpp @@ -1323,13 +1323,14 @@ void Engine::systemShutdown(){ } void Engine::systemPause(){ - AudioSystem::pauseAll(); + // first, so audio the game pauses here stays paused after the resume Engine::onPause.call(); + AudioSystem::systemPause(); paused = true; } void Engine::systemResume(){ - AudioSystem::resumeAll(); + AudioSystem::systemResume(); Engine::onResume.call(); paused = false; } diff --git a/engine/core/subsystem/AudioSystem.cpp b/engine/core/subsystem/AudioSystem.cpp index 15a8dff5a..d46ff7f14 100644 --- a/engine/core/subsystem/AudioSystem.cpp +++ b/engine/core/subsystem/AudioSystem.cpp @@ -17,6 +17,8 @@ bool AudioSystem::inited = false; float AudioSystem::globalVolume = 1.0; bool AudioSystem::muted = false; +std::vector AudioSystem::systemPausedVoices; + AudioSystem::AudioSystem(Scene* scene): SubSystem(scene){ signature.set(scene->getComponentId()); @@ -215,6 +217,31 @@ void AudioSystem::resumeAll(){ } } +void AudioSystem::systemPause(){ + if (!inited) { + return; + } + + SoLoud::Soloud& soloud = getSoloud(); + soloud.lockAudioMutex_internal(); + for (unsigned int i = 0; i < soloud.mHighestVoice; i++) { + if (soloud.mVoice[i] && !(soloud.mVoice[i]->mFlags & SoLoud::AudioSourceInstance::PAUSED)) { + systemPausedVoices.push_back(soloud.getHandleFromVoice_internal(i)); + soloud.setVoicePause_internal(i, true); + } + } + soloud.unlockAudioMutex_internal(); +} + +void AudioSystem::systemResume(){ + if (inited) { + for (unsigned int handle : systemPausedVoices) { + getSoloud().setPause(handle, false); + } + } + systemPausedVoices.clear(); +} + void AudioSystem::checkActive(){ if (inited) { if (getSoloud().getVoiceCount() == 0){ diff --git a/engine/core/subsystem/AudioSystem.h b/engine/core/subsystem/AudioSystem.h index a5af45e11..655e312f8 100644 --- a/engine/core/subsystem/AudioSystem.h +++ b/engine/core/subsystem/AudioSystem.h @@ -8,6 +8,8 @@ #include "component/SoundComponent.h" +#include + namespace SoLoud{ class Soloud; } @@ -16,6 +18,8 @@ namespace doriax{ class DORIAX_API AudioSystem : public SubSystem { + friend class Engine; + private: static bool inited; @@ -24,6 +28,13 @@ namespace doriax{ static float globalVolume; static bool muted; + // voices to resume, the game's own pauses are kept + static std::vector systemPausedVoices; + + // Called by Engine + static void systemPause(); + static void systemResume(); + Vector3 cameraLastPosition; bool outputRequested = false; diff --git a/engine/platform/emscripten/DoriaxWeb.cpp b/engine/platform/emscripten/DoriaxWeb.cpp index c51c9404f..be0e26968 100644 --- a/engine/platform/emscripten/DoriaxWeb.cpp +++ b/engine/platform/emscripten/DoriaxWeb.cpp @@ -30,6 +30,8 @@ bool DoriaxWeb::enabledIDB; int DoriaxWeb::screenWidth; int DoriaxWeb::screenHeight; +double DoriaxWeb::pixelRatio = 1.0; + double DoriaxWeb::mousePosX; double DoriaxWeb::mousePosY; @@ -37,12 +39,18 @@ int DoriaxWeb::sampleCount = 0; bool DoriaxWeb::quitRequested = false; +unsigned int DoriaxWeb::pauseReasons = 0; + DoriaxWeb::GamepadState DoriaxWeb::gamepads[DORIAX_WEB_MAX_GAMEPADS]; #ifndef DORIAX_STORAGE_ID #define DORIAX_STORAGE_ID "Doriax" #endif +#ifndef DORIAX_WEB_MAX_PIXEL_RATIO +#define DORIAX_WEB_MAX_PIXEL_RATIO 2.0 +#endif + // miniaudio only resumes its AudioContext on click or touchend static void resumeAudio(){ EM_ASM({ @@ -167,6 +175,10 @@ int DoriaxWeb::init(int argc, char **argv){ ret = emscripten_set_touchcancel_callback(canvas.c_str(), 0, true, touch_callback); ret = emscripten_set_webglcontextlost_callback(canvas.c_str(), 0, true, webgl_context_callback); ret = emscripten_set_webglcontextrestored_callback(canvas.c_str(), 0, true, webgl_context_callback); + // YouTube Playables pauses the game itself and forbids the Page Visibility API +#ifndef DORIAX_WEB_PORTAL_YOUTUBE + ret = emscripten_set_visibilitychange_callback(0, true, visibility_callback); +#endif // necessary if canvas size is relative by window //ret = emscripten_set_resize_callback(EMSCRIPTEN_EVENT_TARGET_WINDOW, 0, 1, resize_callback); @@ -212,7 +224,7 @@ int DoriaxWeb::init(int argc, char **argv){ DoriaxWeb::screenWidth = sWidth; DoriaxWeb::screenHeight = sHeight; doriax::Engine::systemViewLoaded(); - changeCanvasSize(sWidth, sHeight); + setFramebufferSize(sWidth, sHeight); emscripten_request_animation_frame_loop(renderLoop, 0); @@ -235,9 +247,45 @@ void DoriaxWeb::unregisterCallbacks(){ emscripten_set_touchcancel_callback(canvas.c_str(), 0, true, NULL); emscripten_set_webglcontextlost_callback(canvas.c_str(), 0, true, NULL); emscripten_set_webglcontextrestored_callback(canvas.c_str(), 0, true, NULL); +#ifndef DORIAX_WEB_PORTAL_YOUTUBE + emscripten_set_visibilitychange_callback(0, true, NULL); +#endif +} + +void DoriaxWeb::setPaused(PauseReason reason, bool paused){ + const unsigned int flag = 1u << static_cast(reason); + const unsigned int previous = pauseReasons; + pauseReasons = paused ? (previous | flag) : (previous & ~flag); + + if (pauseReasons != 0 && previous == 0){ + doriax::Engine::systemPause(); + }else if (pauseReasons == 0 && previous != 0){ + doriax::Engine::systemResume(); + } } void DoriaxWeb::changeCanvasSize(int width, int height){ + emscripten_set_element_css_size(canvas.c_str(), width, height); +} + +// without the border, which shows no framebuffer +bool DoriaxWeb::getCanvasCssSize(double& width, double& height){ + if (emscripten_get_element_css_size(canvas.c_str(), &width, &height) != EMSCRIPTEN_RESULT_SUCCESS) + return false; + + width -= EM_ASM_INT({ + var element = document.querySelector(UTF8ToString($0)); + return element.offsetWidth - element.clientWidth; + }, canvas.c_str()); + height -= EM_ASM_INT({ + var element = document.querySelector(UTF8ToString($0)); + return element.offsetHeight - element.clientHeight; + }, canvas.c_str()); + + return true; +} + +void DoriaxWeb::setFramebufferSize(int width, int height){ emscripten_set_canvas_element_size(canvas.c_str(), width, height); DoriaxWeb::screenWidth = width; @@ -245,6 +293,33 @@ void DoriaxWeb::changeCanvasSize(int width, int height){ doriax::Engine::systemViewChanged(); } +// Engine applies the project's Scaling mode to the size the canvas has on the page +void DoriaxWeb::updateFramebufferSize(){ + double cssWidth = 0, cssHeight = 0; + if (!getCanvasCssSize(cssWidth, cssHeight)) + return; + + // a page wider than a phone's screen is shown zoomed out, over fewer device pixels + const double deviceRatio = EM_ASM_DOUBLE({ + var zoom = window.visualViewport ? window.visualViewport.scale : 1; + return window.devicePixelRatio * Math.min(zoom, 1); + }); + pixelRatio = fmin(deviceRatio, DORIAX_WEB_MAX_PIXEL_RATIO); + + const int width = (int)round(cssWidth * pixelRatio); + const int height = (int)round(cssHeight * pixelRatio); + if (width <= 0 || height <= 0 || (width == screenWidth && height == screenHeight)) + return; + + setFramebufferSize(width, height); + + // a canvas with no CSS size takes the framebuffer's, and would grow every frame + double newWidth = 0, newHeight = 0; + getCanvasCssSize(newWidth, newHeight); + if (fabs(newWidth - cssWidth) > 2.0 || fabs(newHeight - cssHeight) > 2.0) + changeCanvasSize((int)round(cssWidth), (int)round(cssHeight)); +} + bool DoriaxWeb::isFullscreen(){ EmscriptenFullscreenChangeEvent fsce; EMSCRIPTEN_RESULT ret = emscripten_get_fullscreen_status(&fsce); @@ -255,7 +330,7 @@ bool DoriaxWeb::isFullscreen(){ void DoriaxWeb::requestFullscreen(){ EmscriptenFullscreenStrategy strategy; strategy.scaleMode = EMSCRIPTEN_FULLSCREEN_SCALE_STRETCH; - strategy.canvasResolutionScaleMode = EMSCRIPTEN_FULLSCREEN_CANVAS_SCALE_STDDEF; + strategy.canvasResolutionScaleMode = EMSCRIPTEN_FULLSCREEN_CANVAS_SCALE_NONE; // renderLoop sizes it strategy.filteringMode = EMSCRIPTEN_FULLSCREEN_FILTERING_DEFAULT; strategy.canvasResizedCallback = canvas_resize; strategy.canvasResizedCallbackUserData = NULL; @@ -434,17 +509,7 @@ EM_BOOL DoriaxWeb::renderLoop(double time, void* userdata){ pollGamepads(); - // CSS size is the input coordinate space as well as the visible surface. - // Update the framebuffer before drawing; Engine applies the project's - // Scaling mode (including intentional stretching) to this actual size. - double cssWidth = 0, cssHeight = 0; - if (emscripten_get_element_css_size(canvas.c_str(), &cssWidth, &cssHeight) == EMSCRIPTEN_RESULT_SUCCESS) { - const int width = (int)round(cssWidth); - const int height = (int)round(cssHeight); - if (width > 0 && height > 0 && (width != screenWidth || height != screenHeight)) { - changeCanvasSize(width, height); - } - } + updateFramebufferSize(); doriax::Engine::systemDraw(); @@ -577,16 +642,18 @@ EM_BOOL DoriaxWeb::mouse_callback(int eventType, const EmscriptenMouseEvent *e, bool mouseLocked = pointerLockStatus.isActive; if (!mouseLocked){ - if (e->targetX < 0) return 0; - if (e->targetY < 0) return 0; - if (e->targetX > width) return 0; - if (e->targetY > height) return 0; - - mousePosX = e->targetX; - mousePosY = e->targetY; + const double x = e->targetX * pixelRatio; + const double y = e->targetY * pixelRatio; + if (x < 0) return 0; + if (y < 0) return 0; + if (x > width) return 0; + if (y > height) return 0; + + mousePosX = x; + mousePosY = y; }else{ - mousePosX += e->movementX; - mousePosY += e->movementY; + mousePosX += e->movementX * pixelRatio; + mousePosY += e->movementY * pixelRatio; } int modifiers = 0; @@ -643,21 +710,21 @@ EM_BOOL DoriaxWeb::touch_callback(int emsc_type, const EmscriptenTouchEvent* ems for (int i = 0; i < emsc_event->numTouches; i++) { const EmscriptenTouchPoint* src = &emsc_event->touches[i]; if (!src->isChanged) continue; - doriax::Engine::systemTouchStart((int)src->identifier, src->targetX, src->targetY); + doriax::Engine::systemTouchStart((int)src->identifier, src->targetX * pixelRatio, src->targetY * pixelRatio); } break; case EMSCRIPTEN_EVENT_TOUCHMOVE: for (int i = 0; i < emsc_event->numTouches; i++) { const EmscriptenTouchPoint* src = &emsc_event->touches[i]; if (!src->isChanged) continue; - doriax::Engine::systemTouchMove((int)src->identifier, src->targetX, src->targetY); + doriax::Engine::systemTouchMove((int)src->identifier, src->targetX * pixelRatio, src->targetY * pixelRatio); } break; case EMSCRIPTEN_EVENT_TOUCHEND: for (int i = 0; i < emsc_event->numTouches; i++) { const EmscriptenTouchPoint* src = &emsc_event->touches[i]; if (!src->isChanged) continue; - doriax::Engine::systemTouchEnd((int)src->identifier, src->targetX, src->targetY); + doriax::Engine::systemTouchEnd((int)src->identifier, src->targetX * pixelRatio, src->targetY * pixelRatio); } break; case EMSCRIPTEN_EVENT_TOUCHCANCEL: { @@ -690,14 +757,24 @@ EM_BOOL DoriaxWeb::touch_callback(int emsc_type, const EmscriptenTouchEvent* ems EM_BOOL DoriaxWeb::webgl_context_callback(int emsc_type, const void* reserved, void* user_data) { switch (emsc_type) { - case EMSCRIPTEN_EVENT_WEBGLCONTEXTLOST: doriax::Engine::systemPause(); break; - case EMSCRIPTEN_EVENT_WEBGLCONTEXTRESTORED: doriax::Engine::systemResume(); break; + case EMSCRIPTEN_EVENT_WEBGLCONTEXTLOST: setPaused(PauseReason::CONTEXT_LOST, true); break; + case EMSCRIPTEN_EVENT_WEBGLCONTEXTRESTORED: setPaused(PauseReason::CONTEXT_LOST, false); break; default: break; } return 0; } +EM_BOOL DoriaxWeb::visibility_callback(int eventType, const EmscriptenVisibilityChangeEvent *e, void *userData) { + setPaused(PauseReason::HIDDEN, e->hidden); + + // no frame may come before the page closes + if (e->hidden && syncWaitTime > 0) + syncFileSystemNow(); + + return 0; +} + int DoriaxWeb::doriax_mouse_button(int button){ if (button == 0) return D_MOUSE_BUTTON_1; if (button == 2) return D_MOUSE_BUTTON_2; diff --git a/engine/platform/emscripten/DoriaxWeb.h b/engine/platform/emscripten/DoriaxWeb.h index 33c9bb06e..5c152f755 100644 --- a/engine/platform/emscripten/DoriaxWeb.h +++ b/engine/platform/emscripten/DoriaxWeb.h @@ -26,9 +26,13 @@ class DoriaxWeb: public doriax::System{ static int syncWaitTime; static bool enabledIDB; + // framebuffer size static int screenWidth; static int screenHeight; + // framebuffer pixels per CSS pixel, the unit of input events + static double pixelRatio; + static double mousePosX; static double mousePosY; @@ -36,6 +40,8 @@ class DoriaxWeb: public doriax::System{ static bool quitRequested; + static unsigned int pauseReasons; + static GamepadState gamepads[DORIAX_WEB_MAX_GAMEPADS]; static EM_BOOL key_callback(int eventType, const EmscriptenKeyboardEvent *e, void *userData); @@ -46,9 +52,14 @@ class DoriaxWeb: public doriax::System{ static EM_BOOL canvas_resize(int eventType, const void *reserved, void *userData); static EM_BOOL webgl_context_callback(int emsc_type, const void* reserved, void* user_data); + static EM_BOOL visibility_callback(int eventType, const EmscriptenVisibilityChangeEvent *e, void *userData); static EM_BOOL renderLoop(double time, void* userdata); + static bool getCanvasCssSize(double& width, double& height); + static void setFramebufferSize(int width, int height); + static void updateFramebufferSize(); + static void unregisterCallbacks(); static void syncFileSystemNow(); @@ -63,13 +74,24 @@ class DoriaxWeb: public doriax::System{ public: + enum class PauseReason{ + AD, + PORTAL, + HIDDEN, + CONTEXT_LOST + }; + DoriaxWeb(); static void setEnabledIDB(bool enabledIDB); static int init(int argc, char **argv); + // CSS size of the canvas, which the framebuffer follows static void changeCanvasSize(int width, int height); + // The game resumes when no reason is left + static void setPaused(PauseReason reason, bool paused); + virtual int getScreenWidth() override; virtual int getScreenHeight() override; diff --git a/engine/platform/emscripten/WebPortals.cpp b/engine/platform/emscripten/WebPortals.cpp index 0c009d4ac..afc6120b9 100644 --- a/engine/platform/emscripten/WebPortals.cpp +++ b/engine/platform/emscripten/WebPortals.cpp @@ -9,28 +9,12 @@ #include #include -#include "Engine.h" #include "service/WebPortal.h" #include "subsystem/AudioSystem.h" using namespace doriax; namespace { - // The game stays paused while one of its ads plays or the portal asks for it - bool pausedForAd = false; - bool pausedByPortal = false; - - void setPaused(bool& reason, bool paused){ - const bool wasPaused = pausedForAd || pausedByPortal; - reason = paused; - const bool isPaused = pausedForAd || pausedByPortal; - if (isPaused && !wasPaused){ - Engine::systemPause(); - }else if (wasPaused && !isPaused){ - Engine::systemResume(); - } - } - // Logic shared by the portals. Calls wait for the SDK; ads and saves report any failure. class ScriptPortal: public WebPortalBackend{ public: @@ -493,13 +477,13 @@ extern "C" { EMSCRIPTEN_KEEPALIVE void webportal_ad_started_callback(int type) { - setPaused(pausedForAd, true); + DoriaxWeb::setPaused(DoriaxWeb::PauseReason::AD, true); WebPortal::systemAdStarted(static_cast(type)); } EMSCRIPTEN_KEEPALIVE void webportal_ad_finished_callback(int type) { - setPaused(pausedForAd, false); + DoriaxWeb::setPaused(DoriaxWeb::PauseReason::AD, false); WebPortal::systemAdFinished(static_cast(type)); } @@ -507,7 +491,7 @@ extern "C" { EMSCRIPTEN_KEEPALIVE void webportal_ad_error_callback(int type, const char* code, const char* message, int started) { if (started){ - setPaused(pausedForAd, false); + DoriaxWeb::setPaused(DoriaxWeb::PauseReason::AD, false); } WebPortal::systemAdError(static_cast(type), code, message); } @@ -515,7 +499,7 @@ extern "C" { // pauses the portal asks for itself, like its startup ad or splash screen EMSCRIPTEN_KEEPALIVE void webportal_pause_callback(int paused) { - setPaused(pausedByPortal, paused != 0); + DoriaxWeb::setPaused(DoriaxWeb::PauseReason::PORTAL, paused != 0); } EMSCRIPTEN_KEEPALIVE