Skip to content

A fast 2D and 3D game engine — TypeScript SDK, C++/WebAssembly core, visual editor. Ship one project to web, desktop, WeChat MiniGames, playable ads, and native Android / iOS.

19.8 KB
Raw Blame
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
/**
 * @file    Host.hpp
 * @brief   The host's public contract: the platform seam every OS answers, and
 *          the handful of entry points its event loop drives.
 * @details Three layers run a native Estella game, and only the first is C++:
 *          1. This host — boots Dawn, installs the es_* bindings as globals,
 *             feeds host touch to JS, reads packaged assets, and renders.
 *          2. The SDK bundle (dist/index.native.bundled.js, embedded): the real
 *             esengine TS SDK — createNativeApp / World / Input — as `ESEngine`.
 *          3. The game: an editor export (game.config.json + cooked assets +
 *             scenes) packaged with the app, booted by bootstrap.js through
 *             ESEngine.initNativeGame.
 *
 *          The host itself is split by concern: Runtime.hpp owns the JS runtime
 *          (the engine is behind js/esjs.hpp) and the shared state, bindings/ owns the es_* surface (one TU
 *          per pillar), and Host.cpp owns boot, the frame and lifecycle.
 *          Everything that differs between Android and iOS lives behind
 *          {@link eshost::Platform}; the glue (platform/android.cpp,
 *          platform/ios.mm) implements it and owns the event loop.
 *
 * @author  ESEngine Team
 * @date    2026
 *
 * @copyright Copyright (c) 2026 ESEngine Team
 *            Licensed under the Apache License, Version 2.0.
 */
#pragma once

#include <chrono>
#include <functional>
#include <string>
#include <utility>
#include <vector>

#include "esengine/core/Types.hpp"
#include "esengine/renderer/webgpu/WebGPUDevice.hpp"
#include "FramePacer.hpp"

namespace eshost {

/** One HTTP request the host performs off the main thread. `id` matches the
 *  reply back to its JS callback; `wantText` selects a string vs ArrayBuffer body. */
struct FetchRequest {
    int id = 0;
    std::string method;     ///< GET / POST / ...
    std::string url;
    std::vector<std::pair<std::string, std::string>> headers;
    std::vector<esengine::u8> body;
    bool wantText = false;
};

/** The reply the platform hands back via {@link deliverFetch}. A non-empty
 *  `error` rejects the JS promise; otherwise the body is delivered per `isText`. */
struct FetchResult {
    int id = 0;
    bool ok = false;
    int status = 0;
    std::string statusText;
    std::vector<std::pair<std::string, std::string>> headers;
    std::vector<esengine::u8> body;
    bool isText = false;
    std::string error;
};

/**
 * Which face draws a glyph: the file it lives in (`path`, empty when the platform
 * found nothing) and which face inside it (`faceIndex`, for a collection — .ttc).
 * Only the answer: opening the file is the rasterizer's, once per face for the
 * life of the host (media/glyph_raster.cpp). Every platform used to read the
 * whole file into this on every call, which is every glyph rasterized, and a CJK
 * system font is tens of MB: a frame stalled each time a new glyph appeared
 * (issue #106).
 */
struct FontMatch {
    std::string path;
    int faceIndex = 0;
    /**
     * What the matched file does NOT provide of the style that was asked for, so
     * the rasterizer can synthesize it — which is what a browser does when a
     * family has no bold or no italic. Android's system font is one VARIABLE file
     * for every weight and stb_truetype renders its default instance, so a bold
     * request comes back regular and this is how anyone finds out.
     */
    bool syntheticBold = false;
    bool syntheticItalic = false;
};

/** One gamepad in the W3C "standard mapping" layout, as GamepadSnapshot carries
 *  it — a second layout would make a game's button indices mean different buttons
 *  per platform. `buttons` is indexed by GamepadButton and analog in [0,1]; `axes`
 *  by GamepadAxis, signed in [-1,1]. */
struct GamepadState {
    int index = 0;
    bool connected = false;
    float buttons[17]{};
    float axes[4]{};
};

/**
 * @brief The platform seam: what the host needs that Android and iOS answer
 *        differently. The glue implements it; host_core owns everything else.
 */
struct MotionState {
    double timestamp = 0;
    float acceleration[3]{};
    float gyroscope[3]{};
    bool hasAcceleration = false;
    bool hasGyroscope = false;
};

struct Platform {
    virtual int deviceCapabilities() const { return 0; }
    virtual bool startMotion(bool, bool, int) { return false; }
    virtual void stopMotion() {}
    virtual bool pollMotion(MotionState&) { return false; }
    virtual bool vibrate(int, int) { return false; }
    virtual bool keepScreenOn(bool) { return false; }
    /** The game's target frame rate, as App.setTargetFrameRate set it (0 = as fast as the display goes). The loop already
     *  holds it through framePacer(); this is for telling the OS (Android's frame-rate hint), which only a platform can. */
    virtual void setTargetFrameRate(float /*fps*/) {}
    virtual ~Platform() = default;

    /** A packaged, project-relative file — the APK's `assets/` on Android, the
     *  app bundle on iOS. Empty when missing. Backs NativeBridge.readFile. */
    virtual std::vector<esengine::u8> readAsset(const char* path) = 0;

    /**
     * The same file as a filesystem PATH, or empty where the assets are not
     * files (an APK's are not). For the one thing bytes cannot serve: a library
     * the OS loader opens by name, which is how a desktop build reaches its
     * compiled systems.
     */
    virtual std::string assetPath(const char*) { return {}; }

    /**
     * Writable private directory for things the host can REGENERATE — the SDK
     * bytecode cache, downloaded hot-update content. Empty disables it.
     *
     * The platform is free to delete this whenever it wants the space back, and
     * iOS does. Nothing a player would notice losing belongs here; that is
     * {@link dataDir}, and the split exists because the two were once one
     * directory whose durability quietly differed per platform.
     */
    virtual std::string cacheDir() = 0;

    /**
     * Writable private directory that SURVIVES — saves, settings, progress.
     *
     * Distinct from {@link cacheDir} in exactly one way that matters: the
     * platform will not reclaim it, and it is included in the device backup a
     * player restores a new phone from. Empty means this platform cannot promise
     * that, and storage falls back to lasting only for the session.
     */
    virtual std::string dataDir() = 0;

    /**
     * Writable directory a PLAYER can reach — where the boot record goes.
     *
     * Distinct from {@link cacheDir}, which is private to the app and reachable
     * only over adb or a rooted phone. When a packaged game fails on someone
     * else's device, the only evidence that can travel back is a file they can
     * find: `Android/data/<pkg>/files` on Android, Documents on iOS. Empty turns
     * the record off, and a platform that returns empty is choosing to make its
     * failures unreportable.
     */
    virtual std::string logDir() = 0;

    /** This device, in one line: model, OS version, ABI. The first thing asked
     *  about a failure that happens on someone else's phone and not on yours. */
    virtual std::string describe() = 0;

    /**
     * The language the player set their device to, as the OS spells it
     * ('zh-Hans-CN', 'en-US', 'zh_CN').
     *
     * Nothing else can answer this: a native script has no `navigator`, and the
     * JS engine's own `Intl` reports the locale it was built with, not the
     * phone's. Raw on purpose — the SDK reduces it to the language-region form a
     * browser reports, in one place for every host. Empty when the platform
     * cannot say, and the SDK then falls back to 'en'.
     */
    virtual std::string language() { return {}; }

    /**
     * The directory the executable is in, with a trailing separator — the only
     * place a shipped app's sibling libraries are looked for.
     *
     * A leaf name will not find them: `dlopen` does not search it. Empty on a
     * phone, whose loaders then report unavailable.
     */
    virtual std::string executableDir() { return {}; }

    /**
     * Open a window this big, in design pixels.
     *
     * A window exists before any JS does and the host parses no JSON, so the
     * project's design resolution arrives from the SDK once. Ignored where the app
     * is given a screen rather than owning a window.
     */
    virtual void setWindowSize(int /*width*/, int /*height*/) {}

    /**
     * Directories a PLAYER can browse to, best first — where a crash record is
     * copied so it can be sent.
     *
     * {@link logDir} is not one of them on Android: since Android 11 an app's
     * `Android/data` is closed to file managers and to the system Files app, so
     * the record a developer pulls over adb is one a player cannot reach at all.
     * Empty means this platform has nowhere better, and the copy is skipped.
     */
    virtual std::vector<std::string> publicDirs() { return {}; }

    /** The backend Dawn must pick: Vulkan on Android, Metal on iOS. */
    virtual WGPUBackendType backend() const = 0;

    /** The live window (`ANativeWindow*` / `CAMetalLayer*`) and its pixel size. */
    virtual esengine::WebGPUDevice::NativeSurface surface() = 0;
    virtual void surfaceSize(esengine::u32& width, esengine::u32& height) = 0;

    /** Content must stay inside these live margins, in surface pixels. */
    struct SafeInsets { float top = 0; float bottom = 0; float left = 0; float right = 0; };
    virtual SafeInsets safeAreaInsets() const { return {}; }

    virtual void log(bool error, const char* message) = 0;

    /** The face for @p family that covers @p codepoint, with @p style's bold/italic
     *  bits (see GLYPH_BOLD / GLYPH_ITALIC) applied to the match. Empty `path`
     *  when the platform has nothing — the glyph then simply does not draw.
     *
     *  This is the ONLY per-OS part of text: which face. Android asks its font
     *  matcher (which handles CJK fallback), Apple Core Text, Linux fontconfig,
     *  Windows DirectWrite; reading the file, the rasterization and the SDF
     *  conversion are shared (see media/glyph_raster.hpp). Called per glyph, so it
     *  must not touch the file. */
    virtual FontMatch matchFont(const std::string& family, esengine::u32 codepoint, int style) = 0;

    /**
     * Coverage the platform drew itself, padded and supersampled as the shared
     * path builds it — everything after (the engine's SDF, the downsample, the
     * tile) stays one implementation. See {@link Platform::drawGlyph}.
     */
    struct GlyphCoverage {
        std::vector<esengine::u8> alpha;  ///< `width * height`, 255 = full ink.
        int width = 0;                    ///< Supersampled px, padding included.
        int height = 0;
        esengine::f32 advance = 0.0f;     ///< Px at the asked size, not supersampled.
        esengine::f32 bearingX = 0.0f;    ///< Tile's top-left in pen space, y UP, at the asked size.
        esengine::f32 bearingY = 0.0f;
        bool blank = false;               ///< Whitespace: an advance and no tile.
    };

    /**
     * Draw @p codepoint with the platform's OWN rasterizer, for a system whose
     * font files the shared parser cannot read — Apple and Android ship CFF2 outlines
     * and stb_truetype has no CFF2. Reached only where the shared path could not, so
     * the default false keeps stb_truetype and costs a platform nothing.
     */
    virtual bool drawGlyph(const std::string& /*family*/, esengine::u32 /*codepoint*/,
                           int /*style*/, esengine::f32 /*pixelSize*/, int /*supersample*/,
                           int /*padding*/, GlyphCoverage& /*out*/) {
        return false;
    }

    /** Perform an HTTP request off the main thread (NSURLSession / a JNI
     *  HttpURLConnection), then hand the reply back through {@link deliverFetch}
     *  with the same `req.id`. The OS owns the TLS stack, so this is where native
     *  networking necessarily differs between iOS and Android. */
    virtual void startFetch(const FetchRequest& req) = 0;

    /**
     * The OS text-editing surface: a soft keyboard with its IME. A platform that
     * has one overrides these and reports what the user did through
     * {@link deliverTextEditorState} / Submit / Cancel; one that does not leaves
     * the defaults, `hasTextEditor()` stays false, the es_textEditor_* entry
     * points are never bound, and the SDK sees a realm where fields render but
     * cannot be typed into.
     *
     * The surface OWNS the value and the selection while a field is focused —
     * an IME composes into it, and the app's own edits go through `write`.
     */
    /**
     * The gamepads this platform can see, appended to @p out.
     *
     * POLLED, matching navigator.getGamepads(): a pad has no events, only a state
     * each frame. The default answers none — a phone's honest report.
     */
    virtual void pollGamepads(std::vector<GamepadState>& out) { out.clear(); }

    virtual bool hasTextEditor() const { return false; }
    virtual void textEditorFocus(const std::string& /*value*/, int /*selectionStart*/,
                                 int /*selectionEnd*/, bool /*multiline*/,
                                 int /*maxLength*/, bool /*password*/) {}
    virtual void textEditorBlur() {}
    virtual void textEditorWrite(const std::string& /*value*/, int /*selectionStart*/,
                                 int /*selectionEnd*/) {}

    /**
     * The app's own native code, by name: what a game's Java or Objective-C
     * registered to answer (an ad SDK, a store, a sign-in). A platform with such
     * a registry overrides both; the default has none.
     *
     * `nativeHas` is asked while the script decides what it can offer (whether
     * there are ads to show), so it must answer at once and from the frame loop.
     */
    virtual bool nativeHas(const std::string& /*method*/) { return false; }
    /**
     * Start the call and answer true, or answer false when nobody is registered
     * under @p method. The answer comes later through {@link deliverNativeReply}
     * with the same @p id, from any thread. @p args is JSON.
     */
    virtual bool nativeCall(int /*id*/, const std::string& /*method*/, const std::string& /*args*/) {
        return false;
    }
};

/** Deliver an HTTP reply for a {@link Platform::startFetch}. Thread-safe: the
 *  platform calls it from whatever thread its completion runs on; the result is
 *  queued and the JS callback runs on the next frame, on the JS thread. */
void deliverFetch(FetchResult result);

/** The editing surface's whole state, after the user (or its IME) changed it.
 *  Thread-safe, like {@link deliverFetch}: the platform calls it from its UI
 *  thread and the JS side is told on the next frame. `composing` is true while an
 *  IME preedit sits inside `value`. */
void deliverTextEditorState(std::string value, int selectionStart, int selectionEnd, bool composing);
/** The keyboard's done/go key on a single-line field. Thread-safe. */
void deliverTextEditorSubmit();
/** The keyboard was dismissed without committing (back gesture, done). Thread-safe. */
void deliverTextEditorCancel();

/** The answer to a {@link Platform::nativeCall}: @p payload is JSON when @p ok,
 *  otherwise the reason, which the script's promise rejects with. Thread-safe;
 *  the script hears it on the next frame. */
void deliverNativeReply(int id, bool ok, std::string payload);
/** Something native code raises on its own (a purchase finished in the
 *  background, a push arrived): every script listener of @p name receives the
 *  JSON @p payload on the next frame. Thread-safe. */
void deliverNativeEvent(std::string name, std::string payload);

/** How a C++ handler answers; callable once, from any thread. */
using NativeReply = std::function<void(bool ok, std::string payload)>;
/** A method answered in C++ rather than by the platform's registry. Runs on the
 *  frame-loop thread, inside the script's call. */
using NativeHandler = std::function<void(const std::string& args, NativeReply reply)>;
/** Answer @p method from C++; an empty handler removes it. The platform's own
 *  registry is asked first. Thread-safe. */
void registerNativeHandler(std::string method, NativeHandler handler);

/** @brief Boots Dawn, EstellaContext, the JS engine, the SDK bundle and the packaged
 *         project. Call once, when a window first exists; @p platform must
 *         outlive the host.
 *  @return false if any stage failed (the reason is already logged). */
bool boot(Platform& platform);

/** @brief (Re)binds the swapchain to Platform::surface(). Needed on first boot and
 *         again whenever the window is recreated — an Android screen-off/on
 *         destroys it, an iOS layer resize invalidates its size. */
bool bindSurface();

/** @brief The window is gone (backgrounded / screen off); stop presenting until
 *         the next bindSurface(). The engine and the JS World stay alive. */
void surfaceLost();

/** @brief Runs the game's update + one rendered, presented frame. No-op until
 *         boot() has succeeded and a surface is bound.
 *
 *  @param vsyncNanos The vsync this frame is for, on the steady clock's timeline,
 *         when a display callback hands one over, or 0 to measure the wall clock.
 *         A host whose loop is paced by its present (FramePacer.hpp) passes 0. */
void frame(long long vsyncNanos = 0);

/** @brief The pacer every native host's loop shares (FramePacer.hpp): the cap
 *         App.setTargetFrameRate set, and the floor that keeps a loop from
 *         spinning. Exists before boot, so a host can set its default cap. */
FramePacer& framePacer();

/** @brief How long until the next frame is due (zero: now). A looping host waits
 *         this long, serving input meanwhile, before it calls frame(); one stepped
 *         by a display callback passes @p floor false and skips the vsyncs the
 *         cap falls between. */
std::chrono::steady_clock::duration untilFrameDue(bool floor = true);

/** @brief Feeds one touch to the game. @p type: 0 start / 1 move / 2 end / 3 cancel.
 *         Coordinates are in surface pixels, top-left origin (as on the web). */
void touch(int type, int id, float x, float y);

/** @brief Feeds one mouse/pen event. @p type: 0 down / 1 move / 2 up; @p button
 *         in the DOM order (0 left, 1 middle, 2 right); coordinates as for touch.
 *
 *         Distinct from {@link touch} because it is distinct on the web: a touch
 *         synthesizes the primary pointer, a mouse IS one and carries a button. */
void pointer(int type, int button, float x, float y);

/** @brief Feeds one wheel event, in PIXELS — the DOM `deltaMode: 0` contract, and
 *         positive-down like it, so a game scrolls the same way everywhere. */
void wheel(float dx, float dy);

/** @brief Feeds one key transition. @p code is the DOM `KeyboardEvent.code` (the
 *         physical key: "KeyW", "Space", "ArrowLeft"), which is what the SDK's
 *         input maps are written against. */
void key(bool down, const char* code);

/** @brief The app went to background (@p visible false) or returned to foreground.
 *         Suspends/resumes the audio device natively and pushes the signal to JS,
 *         where the Lifecycle plugin auto-pauses the game. No-op before boot. */
void setVisible(bool visible);

/** @brief The OS reported memory pressure; asks the SDK's residency caches to
 *         drop evictable entries (the audio buffer cache). No-op before boot. */
void memoryWarning();

bool booted();

/** @brief Whether the host has asked its event loop to stop. Set by a capture run
 *         (`ESTELLA_SHOT_QUIT`, see Shot.hpp) and by nothing else; a platform
 *         whose OS owns the app's lifetime may ignore it. */
bool quitRequested();

/** Whether a surface is currently bound — false while the window is gone, which is
 *  when an event loop should block for events instead of spinning on frames. */
bool surfaceBound();

}  // namespace eshost