Estella 0.113.0
A fast 2D and 3D game engine powered by WebAssembly and ECS
Loading...
Searching...
No Matches
RenderBinding.hpp
Go to the documentation of this file.
1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
3#pragma once
4
5#ifdef ES_RENDER_THREADS
6#include "ActiveContext.hpp"
7#include <string_view>
8#include <tuple>
9#include <type_traits>
10
11#ifdef __EMSCRIPTEN__
12namespace emscripten { class val; }
13#endif
14
15namespace esengine {
16
17// Both script hosts cross exactly the same ownership boundary. The default is
18// a rendezvous: the caller may recycle its upload scratch or mutate its world
19// immediately afterwards. Only commands with explicitly owned inputs detach.
20template<unsigned N> struct BindingName {
21 char text[N];
22 constexpr BindingName(const char (&name)[N]) {
23 for (unsigned i = 0; i < N; ++i) text[i] = name[i];
24 }
25};
26
27template<BindingName Name, auto Function> struct RenderBinding;
28
29template<BindingName Name, class R, class... Args, R (*Function)(Args...)>
30struct RenderBinding<Name, Function> {
31 static R call(Args... args) {
32 constexpr std::string_view name(Name.text);
33 auto& queue = activeCtx().renderThread();
34 if (!queue.enabled() || queue.isOwner()) return Function(args...);
35#ifdef __EMSCRIPTEN__
36 // JS objects belong to the originating realm. These queries read CPU
37 // metadata only, once the render owner has stopped modifying it.
38 if constexpr (std::is_same_v<R, emscripten::val>) {
39 queue.flush();
40 return Function(args...);
41 } else
42#endif
43 if constexpr (name == "renderer_endFrame") {
44#ifdef __EMSCRIPTEN__
45 queue.finishFrame([] { Function(); });
46#else
47 // The native host places the frame fence after presenting its surface.
48 queue.enqueue([] { Function(); });
49#endif
50 } else if constexpr (name == "renderer_end" || name == "renderer_flush"
51 || name == "mesh_release" || name == "environment_release"
52 || name == "rm_releaseTexture" || name == "rm_releaseBitmapFont"
53 || name == "rm_releaseShader") {
54 // A resource-manager reference names a context-owned service. Other
55 // arguments in this list are handles. Shutdown drains before teardown.
56 queue.enqueue([values = std::tuple<Args...>(args...)] { std::apply(Function, values); });
57 } else {
58 return queue.invoke([&] { return Function(args...); });
59 }
60 }
61};
62
63} // namespace esengine
64
65#define ES_RENDER_BIND(name) (&::esengine::RenderBinding<#name, &::esengine::name>::call)
66#else
67#define ES_RENDER_BIND(name) (&::esengine::name)
68#endif
RenderThread & renderThread()
EstellaContext & activeCtx()
The engine context every binding routes through — single source of truth.