Estella 0.113.0
A fast 2D and 3D game engine powered by WebAssembly and ECS
Loading...
Searching...
No Matches
EstellaContext.cpp
Go to the documentation of this file.
1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
10
11#include "EstellaContext.hpp"
12#include "Log.hpp"
13
14#ifdef ES_PLATFORM_WEB
15#include "../renderer/rhi/GLDevice.hpp" // WebGL2 backend — web platform only
16#endif
23#ifdef ES_ENABLE_BITMAP_TEXT
25#endif
28// The engine's one random stream, registered unconditionally below: a core type
29// that reached this file only through a particle header, so turning particles
30// off stopped the CORE from compiling.
31#include "RandomSource.hpp"
32#ifdef ES_ENABLE_PARTICLES
35#endif
39#ifdef ES_ENABLE_TILEMAP
42#endif
45#include "../ui/UISystem.hpp"
47
48#ifdef ES_PLATFORM_WEB
49#include <emscripten/html5.h>
50#endif
51
52namespace esengine {
53
55 // Logic systems must exist even for headless apps that never call init()
56 // (e.g. tooling / tests that drive UI layout without a GL context). Without
57 // this, the binding's require<UISystem>() returned a null reference and ran
58 // against wasm address 0 — silent memory corruption masked by the fact that
59 // address 0 is valid linear memory. See registerLogicSystems().
60 registerLogicSystems();
61}
62
63void EstellaContext::registerLogicSystems() {
64 // Idempotent: the constructor and initSubsystems both call this, and a
65 // shutdown()+init() cycle clears services_ and re-registers. UISystem is the
66 // membership sentinel for the whole logic-system set.
67 if (services_.getService<ecs::UISystem>()) return;
68 // Before the systems that draw from it: a consumer takes its stream at
69 // registration, so the seed has to be the engine's before anyone asks.
70 auto randomSource = makeUnique<RandomSource>();
71 // A seed the SDK set before this context existed (see setPendingRandomSeed).
72 if (u32 pending = 0; takePendingRandomSeed(pending)) randomSource->reseed(pending);
73 services_.registerOwned<RandomSource>(std::move(randomSource));
74#ifdef ES_ENABLE_PARTICLES
76 services_.getService<particle::ParticleSystem>()->reseedFrom(*services_.getService<RandomSource>());
77#endif
80
81
85#ifdef ES_ENABLE_TILEMAP
86 // Chunk data and tile queries do not need a renderer. Register here once so
87 // later renderer initialization also retains maps loaded by headless tooling.
89#endif
90}
91
93 shutdown();
94 render_thread_.stop();
95}
96
97#ifdef ES_PLATFORM_WEB
98// The WebGL2 entry: takes an emscripten context handle and drives the GLDevice
99// backend. A native build has no WebGL — it enters through init(Unique<GfxDevice>)
100// with an injected WebGPUDevice instead, so this overload compiles out entirely.
101bool EstellaContext::init(int webglContextHandle) {
102 return init(webglContextHandle, false);
103}
104
105bool EstellaContext::init(int webglContextHandle, bool ownsContext) {
106 if (state_.initialized) {
107 ES_LOG_WARN("EstellaContext already initialized");
108 return true;
109 }
110
111 EMSCRIPTEN_RESULT result = emscripten_webgl_make_context_current(
112 static_cast<EMSCRIPTEN_WEBGL_CONTEXT_HANDLE>(webglContextHandle));
113 if (result != EMSCRIPTEN_RESULT_SUCCESS) {
114 ES_LOG_ERROR("Failed to make WebGL context current: {}", result);
115 return false;
116 }
117
118 state_.webgl_context = webglContextHandle;
119 state_.owns_webgl_context = ownsContext;
120
121 initSubsystems(makeUnique<GLDevice>());
122 return true;
123}
124#endif // ES_PLATFORM_WEB
125
127 if (state_.initialized) {
128 ES_LOG_WARN("EstellaContext already initialized");
129 return true;
130 }
131 if (!device) {
132 ES_LOG_ERROR("EstellaContext::init: no device");
133 return false;
134 }
135 initSubsystems(std::move(device));
136 return true;
137}
138
139void EstellaContext::initSubsystems(Unique<GfxDevice> gfxDevice) {
140 // The device arrives first: ResourceManager (the GPU-resource factory) and
141 // every other renderer subsystem borrow this single device. Which backend
142 // it is was decided at the platform edge (init overloads).
143 auto* gfxDevicePtr = gfxDevice.get();
144
145 // The one place a device loss becomes visible. Logged whether or not
146 // anything above the engine is listening: a loss nobody recorded is the
147 // black screen with no explanation.
148 gfxDevicePtr->setDeviceLostHandler([](const GfxDeviceLostInfo& info) {
150 });
151
152 services_.registerOwned<GfxDevice>(std::move(gfxDevice));
153
154 auto resourceManager = makeUnique<resource::ResourceManager>();
155 resourceManager->init(*gfxDevicePtr);
156 services_.registerOwned<resource::ResourceManager>(std::move(resourceManager));
157
158 auto renderContext = makeUnique<RenderContext>(*gfxDevicePtr);
159 renderContext->init();
160 // Materials name their textures by resource handle and resolve them per draw,
161 // so the store needs the manager that owns the pool.
162 renderContext->materials().setResourceManager(services_.getService<resource::ResourceManager>());
163 services_.registerOwned<RenderContext>(std::move(renderContext));
164
165 // GPU state is owned by the device: pipelines (setPipeline) carry program/blend/depth/
166 // stencil/cull, so there is no separate per-App state tracker to wire up here.
167
168 // GPU-independent logic systems (Transform/UI/Tween/Tilemap) are registered here too
169 // for the shutdown()+init() re-init path; the constructor already registered
170 // them for the headless/first-use path. Idempotent, so this is a no-op when
171 // they are already present.
172 registerLogicSystems();
173
174 auto* rm = services_.getService<resource::ResourceManager>();
175 auto* rc = services_.getService<RenderContext>();
176 auto immediateDraw = makeUnique<ImmediateDraw>(*gfxDevicePtr, *rc, *rm);
177 immediateDraw->init();
178 auto* immediateDrawPtr = immediateDraw.get();
179 services_.registerOwned<ImmediateDraw>(std::move(immediateDraw));
180
181 services_.registerOwned<GeometryManager>(makeUnique<GeometryManager>());
182
183 auto renderFrame = makeUnique<RenderFrame>(*gfxDevicePtr, *rc, *rm);
184 renderFrame->setPresentedOverlayDraw(immediateDrawPtr);
185 renderFrame->addPlugin(std::make_unique<SpritePlugin>());
186 renderFrame->addPlugin(std::make_unique<UIElementPlugin>());
187#ifdef ES_ENABLE_BITMAP_TEXT
188 renderFrame->addPlugin(std::make_unique<TextPlugin>());
189#endif
190 renderFrame->addPlugin(std::make_unique<ShapePlugin>());
191 renderFrame->addPlugin(std::make_unique<MeshPlugin>());
192 {
193 auto trailPlugin = std::make_unique<TrailPlugin>();
194 trailPlugin->setTrailSystem(services_.getService<trail::TrailSystem>());
195 renderFrame->addPlugin(std::move(trailPlugin));
196 }
197
198#ifdef ES_ENABLE_TILEMAP
199 {
200 auto tilemapPlugin = std::make_unique<TilemapRenderPlugin>();
201 tilemapPlugin->setTilemapSystem(services_.getService<tilemap::TilemapSystem>());
202 renderFrame->addPlugin(std::move(tilemapPlugin));
203 }
204#endif
205#ifdef ES_ENABLE_PARTICLES
206 {
207 auto particlePlugin = std::make_unique<ParticlePlugin>();
208 particlePlugin->setParticleSystem(services_.getService<particle::ParticleSystem>());
209 renderFrame->addPlugin(std::move(particlePlugin));
210 }
211#endif
212
213 renderFrame->init(state_.viewport_width, state_.viewport_height);
214 services_.registerOwned<RenderFrame>(std::move(renderFrame));
215
216#ifdef ES_ENABLE_POSTPROCESS
217 // ONE PostProcessPipeline per App: the postprocess_* bindings and RenderFrame
218 // must consult the SAME instance. Registering RenderFrame's pipeline as the
219 // service (borrowed — RenderFrame owns it) stops the bindings from lazily
220 // creating a second one, whose captures RenderFrame::begin could not see.
221 if (auto* pp = services_.getService<RenderFrame>()->postProcess()) {
222 services_.registerService<PostProcessPipeline>(pp);
223 }
224#endif
225
226 state_.initialized = true;
227
228 // First-frame clear as a proper pass load-op (values in the desc, no sticky state).
229 RenderPassDesc initPass{};
230 initPass.clearColor = true;
231 initPass.clearDepth = true;
232 initPass.clearColorValue[0] = state_.clear_color.r;
233 initPass.clearColorValue[1] = state_.clear_color.g;
234 initPass.clearColorValue[2] = state_.clear_color.b;
235 initPass.clearColorValue[3] = state_.clear_color.a;
236 gfxDevicePtr->beginRenderPass(initPass);
237 gfxDevicePtr->endRenderPass(); // a pass never outlives its task (WebGPU submits here)
238 // ...and neither does the image it drew to. A browser expires the swapchain
239 // texture at the end of the task that acquired it, so a frame that found this
240 // one still held would reuse it and submit a destroyed texture.
241 gfxDevicePtr->endFrame();
242
243 ES_LOG_INFO("EstellaContext initialized");
244}
245
247 if (render_thread_.enabled() && !render_thread_.isOwner()) {
248 render_thread_.invoke([this] { shutdown(); });
249 render_thread_.stop();
250 return;
251 }
252 if (!state_.initialized) return;
253
254#ifdef ES_PLATFORM_WEB
255 const auto webglCtx = static_cast<EMSCRIPTEN_WEBGL_CONTEXT_HANDLE>(state_.webgl_context);
256 const bool ownsWebglContext = state_.owns_webgl_context;
257 const auto previousContext = emscripten_webgl_get_current_context();
258 // GL object deletion uses the current context, including subsystem destructors.
259 // Another engine instance may have made its own context current since our init.
260 if (webglCtx > 0 && previousContext != webglCtx) {
261 emscripten_webgl_make_context_current(webglCtx);
262 }
263#endif
264
265 if (auto* rf = tryGet<RenderFrame>()) rf->shutdown();
266 if (auto* id = tryGet<ImmediateDraw>()) id->shutdown();
267 if (auto* rc = tryGet<RenderContext>()) rc->shutdown();
268 if (auto* rm = tryGet<resource::ResourceManager>()) rm->shutdown();
269
270 services_.clear();
271 state_ = EngineState{};
272
273#ifdef ES_PLATFORM_WEB
274 if (webglCtx > 0 && ownsWebglContext) {
275 emscripten_webgl_destroy_context(webglCtx);
276 }
277 if (webglCtx > 0 && previousContext != webglCtx) {
278 emscripten_webgl_make_context_current(previousContext);
279 }
280#endif
281
282 ES_LOG_INFO("EstellaContext shutdown");
283}
284
285} // namespace esengine
Custom geometry for user-defined mesh rendering.
Instance-based engine context for estella renderer.
OpenGL ES / WebGL implementation of GfxDevice.
Immediate mode 2D drawing API.
Logging utilities for ESEngine.
#define ES_LOG_WARN(...)
Logs a warning message.
Definition Log.hpp:294
#define ES_LOG_ERROR(...)
Logs an error message.
Definition Log.hpp:296
#define ES_LOG_INFO(...)
Logs an info message.
Definition Log.hpp:292
The engine's randomness, and the only place its seed lives.
Rendering context containing all renderer state.
Frame resources and the shared scene rendering contract.
Central resource management system.
Per-App secondary motion: runs every SpringBone chain after the animation has posed the skeleton and ...
Per-App motion-trail simulation: records each TrailRenderer entity's world position over time into a ...
System for computing hierarchical world transforms.
UI subsystem owning layout tree and hit-test state.
bool init(int webglContextHandle)
Initialize with an existing WebGL context handle.
void shutdown()
Shut down all subsystems and release resources.
T * getService()
Gets a service by type.
void registerOwned(Unique< T > service)
Registers an owned service.
UI subsystem: owns layout tree + hit-test state.
Definition UISystem.hpp:56
constexpr Unique< T > makeUnique(Args &&... args)
Creates a Unique pointer with the given arguments.
Definition Types.hpp:99
bool takePendingRandomSeed(u32 &out)
std::unique_ptr< T > Unique
Unique ownership smart pointer.
Definition Types.hpp:75
std::uint32_t u32
Unsigned 32-bit integer.
Definition Types.hpp:45
std::string gfxFormatDeviceLost(const GfxDeviceLostInfo &info)
The whole report as one line, for a log or a crash report.
Definition GfxEnums.hpp:630