Estella 0.113.0
A fast 2D and 3D game engine powered by WebAssembly and ECS
Loading...
Searching...
No Matches
RendererBindings.cpp
Go to the documentation of this file.
1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
3
4#include <cmath>
5#include "UIBindings.hpp"
8
9#include <limits>
11#include "ActiveContext.hpp"
12#include "BoundarySpan.hpp"
15#ifdef ES_ENABLE_GPU_PARTICLES
18#endif
31#include "../ecs/Registry.hpp"
33#include "../core/World.hpp"
44#include "../core/Log.hpp"
45// Core, not particles: the seed binding below is unconditional.
47#ifdef ES_ENABLE_PARTICLES
49#endif
52#include "../ui/UISystem.hpp"
58
59#ifdef __EMSCRIPTEN__
60#include <emscripten/val.h>
61#ifdef ES_RENDER_THREADS
62#include <emscripten/emscripten.h>
63#endif
64#endif
65#include <glm/glm.hpp>
66#include <glm/gtc/matrix_transform.hpp>
67#include <glm/gtc/type_ptr.hpp>
68#include <cstring>
69#include <utility>
70
71namespace esengine {
72
73static EstellaContext& ctx() { return activeCtx(); }
74
75#define g_device (ctx().tryGet<GfxDevice>())
76#define g_initialized (ctx().state().initialized)
77#define g_renderFrame (ctx().tryGet<RenderFrame>())
78#define g_transformSystem (ctx().tryGet<ecs::TransformSystem>())
79#define g_glErrorCheckEnabled (ctx().state().gl_error_check_enabled)
80#define g_viewportWidth (ctx().state().viewport_width)
81#define g_viewportHeight (ctx().state().viewport_height)
82#ifdef ES_ENABLE_PARTICLES
83#define g_particleSystem (ctx().tryGet<particle::ParticleSystem>())
84#endif
85#define g_trailSystem (ctx().tryGet<trail::TrailSystem>())
86#define g_springBoneSystem (ctx().tryGet<springbone::SpringBoneSystem>())
87
88namespace {
89// The channels the engine's own mesh uploads use, named by semantic so a change
90// to the vocabulary moves them rather than leaving two literal 1s behind.
91// Byte offsets follow the packed {x,y,z,u,v,rgba8} vertex both callers build.
92constexpr GfxVertexAttribute kStandardMeshChannels[3] = {
93 {static_cast<u32>(MeshChannel::Position), 3, GfxDataType::Float, false, 0, 0},
94 {static_cast<u32>(MeshChannel::Color), 4, GfxDataType::UnsignedByte, true, 20, 0},
95 {static_cast<u32>(MeshChannel::TexCoord0), 2, GfxDataType::Float, false, 12, 0},
96};
97} // namespace
98
99static u32 checkGLErrors(const char* context) {
100 if (!g_glErrorCheckEnabled) return 0;
101 u32 errorCount = 0;
102 u32 err;
103 while ((err = g_device->getError()) != 0) {
104 ES_LOG_ERROR("[GL Error] 0x{:04X} at: {}", err, context);
105 errorCount++;
106 }
107 return errorCount;
108}
109
110// Geometry posed by a skeletal runtime — Spine and DragonBones both come through
111// here. Ungated on purpose: the core links neither, so neither runtime's build
112// option may decide whether this door exists.
114 ecs::Registry& registry,
115 uintptr_t verticesPtr, i32 vertexCount,
116 uintptr_t indicesPtr, i32 indexCount,
117 u32 textureId, i32 blendMode,
118 u32 entity, f32 skelScale, bool flipX, bool flipY,
119 i32 layer, f32 depth, u32 materialId
120) {
121 renderer_submitSkeletalBatchByEntityEx(registry, verticesPtr, vertexCount, indicesPtr, indexCount, textureId, blendMode, entity, skelScale, flipX, flipY, layer, depth, materialId, blendMode == 4 || blendMode == 5);
122}
123
125 ecs::Registry& registry,
126 uintptr_t verticesPtr, i32 vertexCount,
127 uintptr_t indicesPtr, i32 indexCount,
128 u32 textureId, i32 blendMode,
129 u32 entity, f32 skelScale, bool flipX, bool flipY,
130 i32 layer, f32 depth, u32 materialId, bool premultipliedColor
131) {
132 if (!g_initialized || !g_renderFrame) return;
133 const Entity ent = Entity::fromRaw(entity);
134 if (!registry.isEntityActive(ent) || !registry.has<ecs::Transform>(ent)) return;
135
136 auto& t = registry.get<ecs::Transform>(ent);
138
139 glm::vec3 s = t.worldScale;
140 s.x *= skelScale;
141 s.y *= skelScale;
142 if (flipX) s.x = -s.x;
143 if (flipY) s.y = -s.y;
144
145 glm::mat4 model = glm::translate(glm::mat4(1.0f), t.worldPosition)
146 * glm::mat4_cast(t.worldRotation)
147 * glm::scale(glm::mat4(1.0f), s);
148
149 if (vertexCount < 0 || indexCount < 0) return;
150 // Skeletal vertex format is x,y,u,v,r,g,b,a (8 floats per vertex).
151 auto* vertices = boundarySpan<f32>(verticesPtr, static_cast<u64>(vertexCount) * 8, "renderer_submitSkeletalBatchByEntity.vertices");
152 auto* indices = boundarySpan<u16>(indicesPtr, static_cast<u64>(indexCount), "renderer_submitSkeletalBatchByEntity.indices");
153 if (!vertices || !indices) return;
154 // A skeleton a Canvas holds takes what the UI tree above it says, as a control does: the
155 // opacity of the nearest UINode (itself included, which already carries every ancestor's)
156 // and the culling bit of the Canvas that holds it.
157 f32 treeAlpha = 1.0f;
158 u32 cullBit = 0;
159 if (g_renderFrame->uiTreeHolds(ent)) {
160 bool alphaFound = false;
161 Entity at = ent;
162 for (u32 guard = 0; registry.valid(at) && guard < 4096; ++guard) {
163 if (!alphaFound) {
164 if (const auto* node = registry.tryGet<ecs::UINode>(at)) {
165 treeAlpha = node->alpha_in_tree_;
166 alphaFound = true;
167 }
168 }
169 if (const auto* canvas = registry.tryGet<ecs::Canvas>(at)) {
170 cullBit = (canvas->layer < 0 || canvas->layer >= 32) ? 0u : (1u << canvas->layer);
171 break;
172 }
173 const auto* parent = registry.tryGet<ecs::Parent>(at);
174 if (!parent) break;
175 at = parent->entity;
176 }
177 }
178 g_renderFrame->submitSkeletalBatch(
179 vertices, vertexCount, indices, indexCount,
180 textureId, blendMode, &model[0][0], ent, layer, depth, materialId, premultipliedColor,
181 treeAlpha, cullBit);
182}
183
191 ecs::Registry& registry, u32 entity, i32 layer,
192 f32 minX, f32 minY, f32 maxX, f32 maxY, uintptr_t outVisiblePtr
193) {
194 auto* out = reinterpret_cast<i32*>(outVisiblePtr);
195 if (!out) return;
196 *out = 1;
197 if (!g_initialized || !g_renderFrame) return;
198 // The screen overlay has no camera to be outside of: what it draws is on the screen by
199 // construction (RenderCollectContext::visible), and the frustum still in hand is the last
200 // camera's, which would cull a skeleton in a screen Canvas by its pixel coordinates.
201 if (g_renderFrame->screenOverlayOpen()) return;
202 const Entity ent = Entity::fromRaw(entity);
203 if (!registry.has<ecs::Transform>(ent)) return;
204
205 auto& t = registry.get<ecs::Transform>(ent);
207 const glm::mat4 model = glm::translate(glm::mat4(1.0f), t.worldPosition)
208 * glm::mat4_cast(t.worldRotation)
209 * glm::scale(glm::mat4(1.0f), t.worldScale);
210
211 const glm::vec2 corners[4] = {
212 { minX, minY }, { maxX, minY }, { maxX, maxY }, { minX, maxY },
213 };
214 glm::vec3 lo{std::numeric_limits<f32>::max()};
215 glm::vec3 hi{-std::numeric_limits<f32>::max()};
216 for (const glm::vec2& corner : corners) {
217 const glm::vec4 world = model * glm::vec4(corner.x, corner.y, 0.0f, 1.0f);
218 lo = glm::min(lo, glm::vec3(world));
219 hi = glm::max(hi, glm::vec3(world));
220 }
221 *out = g_renderFrame->visibleToCamera(layer, (lo + hi) * 0.5f, (hi - lo) * 0.5f) ? 1 : 0;
222}
223
224// TS lays out glyph quads against the dynamic SDF atlas and
225// submits them here (ungated — text is core, unlike spine).
227 uintptr_t verticesPtr, i32 vertexCount,
228 uintptr_t indicesPtr, i32 indexCount,
229 u32 textureId, uintptr_t transformPtr,
230 u32 entity, i32 layer, f32 depth, i32 glyphMode, u32 cullBit
231) {
232 if (!g_initialized || !g_renderFrame) return;
233 if (vertexCount < 0 || indexCount < 0) return;
234 auto* vertices = boundarySpan<f32>(verticesPtr, static_cast<u64>(vertexCount) * TEXT_VERTEX_FLOATS, "renderer_submitTextBatch.vertices");
235 auto* indices = boundarySpan<u16>(indicesPtr, static_cast<u64>(indexCount), "renderer_submitTextBatch.indices");
236 auto* transform = boundarySpan<f32>(transformPtr, 16, "renderer_submitTextBatch.transform");
237 if (!vertices || !indices || !transform) return;
238 g_renderFrame->submitTextBatch(
239 vertices, vertexCount, indices, indexCount,
240 textureId, transform, Entity::fromRaw(entity), layer, depth, textGlyphModeFromRaw(glyphMode), cullBit);
241}
242
244 u32 entity, i32 sdf, i32 screen, i32 hasBox, i32 layer, f32 boxWidth, f32 boxHeight, i32 autoKind
245) {
246 if (!g_initialized || !g_renderFrame) return;
247 g_renderFrame->retainedText().begin(entity, sdf != 0, screen != 0, hasBox != 0, layer, boxWidth, boxHeight, autoKind != 0);
248}
249
251 u32 entity, uintptr_t verticesPtr, i32 vertexCount,
252 uintptr_t indicesPtr, i32 indexCount, u32 pageId, i32 glyphMode
253) {
254 if (!g_initialized || !g_renderFrame) return;
255 if (vertexCount < 0 || indexCount < 0) return;
256 auto* vertices = boundarySpan<f32>(verticesPtr, static_cast<u64>(vertexCount) * TEXT_VERTEX_FLOATS, "renderer_retainedTextBatch.vertices");
257 auto* indices = boundarySpan<u16>(indicesPtr, static_cast<u64>(indexCount), "renderer_retainedTextBatch.indices");
258 if (!vertices || !indices) return;
259 g_renderFrame->retainedText().add(entity, vertices, vertexCount, indices, indexCount, pageId, textGlyphModeFromRaw(glyphMode));
260}
261
263 if (!g_initialized || !g_renderFrame) return;
264 g_renderFrame->retainedText().clear(entity);
265}
266
267i32 renderer_retainedTextStale(ecs::Registry& registry, uintptr_t outPtr, i32 capacity) {
268 if (!g_initialized || !g_renderFrame || capacity <= 0) return 0;
269 auto* out = boundarySpanMut<u32>(outPtr, static_cast<u64>(capacity), "renderer_retainedTextStale.out");
270 if (!out) return 0;
271 auto* ui = ctx().tryGet<ecs::UISystem>();
272 auto& entries = g_renderFrame->retainedText().entries();
273 i32 written = 0;
274 for (auto it = entries.begin(); it != entries.end();) {
275 const Entity entity = Entity::fromRaw(it->first);
276 if (!registry.valid(entity)) {
277 it = entries.erase(it);
278 continue;
279 }
280 const RetainedText& text = it->second;
281 const auto* node = registry.tryGet<ecs::UINode>(entity);
282 const f32 width = node ? node->computed_size_.x : 0.0f;
283 const f32 height = node ? node->computed_size_.y : 0.0f;
284 const bool screen = ui && ui->isScreenDomain(registry, it->first);
285 bool stale = width != text.boxWidth || height != text.boxHeight || screen != text.screen;
286 if (!stale && text.autoKind) {
287 // The pipeline was chosen from the world scale: the script no longer reads the transform every frame to see whether it moved.
288 if (auto* transform = registry.tryGet<ecs::Transform>(entity)) {
289 transform->ensureDecomposed();
290 stale = retainedTextAutoIsSdf(transform->worldScale.x) != text.sdf;
291 }
292 }
293 if (stale && written < capacity) out[written++] = it->first;
294 ++it;
295 }
296 return written;
297}
298
299void renderer_retainedTextSubmit(ecs::Registry& registry, i32 screen, uintptr_t projectionPtr) {
300 // A frame that draws the labels in its own collect has them already: submitting them again would draw them twice.
301 if (!g_initialized || !g_renderFrame || g_renderFrame->retainedTextCollected()) return;
302 const f32* projection = projectionPtr ? boundarySpan<f32>(projectionPtr, 16, "renderer_retainedTextSubmit.projection") : nullptr;
303 g_renderFrame->submitRetainedText(registry, screen != 0, projection);
304}
305
307 if (g_renderFrame) g_renderFrame->setRetainedTextCollected(collected);
308}
309
310// MeshRenderer geometry upload: interleaved f32 [x,y,u,v] per vertex, optional RGBA8
311// colors (null = all white), u32 triangle-list indices. Validated here — the single
312// upload entry — so the render path can trust the payload: out-of-range indices or a
313// non-triangle count reject the whole upload instead of feeding the GPU garbage.
315 uintptr_t posUvPtr, u32 vertexCount,
316 uintptr_t colorsPtr,
317 uintptr_t indicesPtr, u32 indexCount) {
318 const Entity ent = Entity::fromRaw(entity);
319 auto* mesh = registry.tryGet<ecs::MeshRenderer>(ent);
320 if (!mesh) {
321 ES_LOG_WARN("meshRenderer_setGeometry: entity {} has no MeshRenderer component", entity);
322 return;
323 }
324
325 // Empty upload = clear the geometry (a valid state: the mesh renders nothing).
326 if (posUvPtr == 0 || indicesPtr == 0 || vertexCount == 0 || indexCount == 0) {
327 mesh->vertices.clear();
328 mesh->indices.clear();
329 mesh->localMin = mesh->localMax = glm::vec2(0.0f);
330 return;
331 }
332 if (indexCount % 3 != 0) {
333 ES_LOG_WARN("meshRenderer_setGeometry: indexCount {} is not a triangle list; rejected", indexCount);
334 return;
335 }
336
337 const f32* posUv = boundarySpan<f32>(posUvPtr, static_cast<u64>(vertexCount) * 4, "meshRenderer_setGeometry.posUv");
338 const u32* colors = colorsPtr ? boundarySpan<u32>(colorsPtr, vertexCount, "meshRenderer_setGeometry.colors") : nullptr;
339 const u32* indices = boundarySpan<u32>(indicesPtr, indexCount, "meshRenderer_setGeometry.indices");
340 if (!posUv || !indices || (colorsPtr && !colors)) return;
341
342 for (u32 i = 0; i < indexCount; ++i) {
343 if (indices[i] >= vertexCount) {
344 ES_LOG_WARN("meshRenderer_setGeometry: index {} out of range (vertexCount {}); rejected",
345 indices[i], vertexCount);
346 return;
347 }
348 }
349
350 mesh->vertices.resize(vertexCount);
351 glm::vec2 mn(posUv[0], posUv[1]);
352 glm::vec2 mx = mn;
353 for (u32 v = 0; v < vertexCount; ++v) {
354 auto& out = mesh->vertices[v];
355 out.position = { posUv[v * 4 + 0], posUv[v * 4 + 1] };
356 out.uv = { posUv[v * 4 + 2], posUv[v * 4 + 3] };
357 out.color = colors ? colors[v] : 0xFFFFFFFFu;
358 mn = glm::min(mn, out.position);
359 mx = glm::max(mx, out.position);
360 }
361 mesh->indices.assign(indices, indices + indexCount);
362 mesh->localMin = mn;
363 mesh->localMax = mx;
364}
365
366// The placements of a MeshInstances, copied in and measured: the corners of where the instances stand and the
367// greatest scale among them, which with the mesh's reach is what bounds the set. The collect trusts the count.
368void meshInstances_set(ecs::Registry& registry, u32 entity, uintptr_t dataPtr, u32 count) {
369 const Entity ent = Entity::fromRaw(entity);
370 auto* set = registry.tryGet<ecs::MeshInstances>(ent);
371 if (!set) {
372 ES_LOG_WARN("meshInstances_set: entity {} has no MeshInstances component", entity);
373 return;
374 }
375 constexpr u32 kFloats = 16;
376 registry.markChanged<ecs::MeshInstances>(ent);
377 if (dataPtr == 0 || count == 0) {
378 set->transforms.clear();
379 set->originMin = set->originMax = glm::vec3(0.0f);
380 set->maxScale = 1.0f;
381 return;
382 }
383 const f32* data = boundarySpan<f32>(dataPtr, static_cast<u64>(count) * kFloats, "meshInstances_set.transforms");
384 if (!data) return;
385 set->transforms.assign(data, data + static_cast<usize>(count) * kFloats);
386 glm::vec3 mn(data[3], data[7], data[11]);
387 glm::vec3 mx = mn;
388 f32 scale = 0.0f;
389 for (u32 i = 0; i < count; ++i) {
390 const f32* r = data + static_cast<usize>(i) * kFloats;
391 const glm::vec3 at(r[3], r[7], r[11]);
392 mn = glm::min(mn, at);
393 mx = glm::max(mx, at);
394 scale = std::max(scale, placement_bounds::stretchSquared(r));
395 }
396 set->originMin = mn;
397 set->originMax = mx;
398 set->maxScale = std::sqrt(scale);
399}
400
401// Geometry that STAYS on the GPU: interleaved f32 [x,y,z,u,v] plus optional RGBA8
402// colors, validated exactly as the inline path is. createMesh appends the
403// per-object transform, so nothing here knows how a mesh reaches the shader.
404// Geometry from an .esmesh. The channel table arrives in the file's own layout
405// (8 bytes each), so the asset layer owns the FORMAT and the engine owns the
406// vertex layout it becomes. A channel's semantic is its attribute location.
407namespace {
408
410struct MeshUpload {
411 GfxVertexAttribute channels[MAX_VERTEX_ATTRIBUTES];
412 u32 channelCount = 0;
413 u32 vertexStride = 0;
414 const u8* verts = nullptr;
415 u32 vertexBytes = 0;
416 const u32* indices = nullptr;
417 u32 indexCount = 0;
418 const f32* bind = nullptr;
419 u32 bindFloats = 0;
420 MeshMorphSource morph;
421 glm::vec3 localMin{0.0f};
422 glm::vec3 localMax{0.0f};
423
424 ConstSpan<u8> vertexSpan() const { return ConstSpan<u8>(verts, vertexBytes); }
425 ConstSpan<u32> indexSpan() const { return ConstSpan<u32>(indices, indexCount); }
426 ConstSpan<GfxVertexAttribute> channelSpan() const {
427 return ConstSpan<GfxVertexAttribute>(channels, channelCount);
428 }
429 ConstSpan<f32> bindSpan() const {
430 return bind ? ConstSpan<f32>(bind, bindFloats) : ConstSpan<f32>();
431 }
432};
433
434// Shared by the mint and the rebuild so a mesh cannot be validated one way when
435// it arrives and another way when it comes back.
436bool marshalMeshChannels(MeshUpload& out, const char* who,
437 uintptr_t channelsPtr, u32 channelCount, u32 vertexStride,
438 uintptr_t vertexPtr, u32 vertexBytes,
439 uintptr_t indexPtr, u32 indexCount,
440 f32 minX, f32 minY, f32 minZ,
441 f32 maxX, f32 maxY, f32 maxZ,
442 uintptr_t bindPtr, u32 bindFloats,
443 uintptr_t morphPtr, u32 morphFloats,
444 u32 morphTargets, u32 morphNormals) {
445 if (channelCount == 0 || channelCount > MAX_VERTEX_ATTRIBUTES) return false;
446 if (vertexStride == 0 || vertexBytes == 0 || indexCount == 0) return false;
447 if (indexCount % 3 != 0) {
448 ES_LOG_WARN("{}: indexCount {} is not a triangle list", who, indexCount);
449 return false;
450 }
451
452 const u8* table = boundarySpan<u8>(channelsPtr, static_cast<u64>(channelCount) * 8, who);
453 const u8* verts = boundarySpan<u8>(vertexPtr, vertexBytes, who);
454 const u32* indices = boundarySpan<u32>(indexPtr, indexCount, who);
455 if (!table || !verts || !indices) return false;
456
457 const u32 vertexCount = vertexBytes / vertexStride;
458 for (u32 i = 0; i < indexCount; ++i) {
459 if (indices[i] >= vertexCount) {
460 ES_LOG_WARN("{}: index {} out of range ({} vertices)", who, indices[i], vertexCount);
461 return false;
462 }
463 }
464
465 // The file's channel type, which is the asset layer's vocabulary, into the
466 // device's — the boundary the format crosses as bytes.
467 auto channelType = [](u8 code) {
468 switch (static_cast<MeshChannelType>(code)) {
473 default: return GfxDataType::Float;
474 }
475 };
476 for (u32 i = 0; i < channelCount; ++i) {
477 const u8* c = table + i * 8;
478 out.channels[i] = GfxVertexAttribute{
479 .location = c[0],
480 .components = c[1],
481 .type = channelType(c[2]),
482 .normalized = c[3] != 0,
483 .offset = static_cast<u32>(c[4]) | (static_cast<u32>(c[5]) << 8)
484 | (static_cast<u32>(c[6]) << 16) | (static_cast<u32>(c[7]) << 24),
485 .bufferSlot = 0,
486 };
487 }
488
489 // The bind pose rides beside the vertices because the Joints channel indexes
490 // it; a mesh with joints and no matrices is drawn static rather than wrong.
491 out.bind = bindFloats > 0 ? boundarySpan<f32>(bindPtr, bindFloats, who) : nullptr;
492 out.bindFloats = bindFloats;
493 // The shapes ride with the vertices for the reason the bind pose does: a
494 // delta is addressed BY a vertex index, so the two are one statement.
495 if (morphTargets > 0 && morphFloats > 0) {
496 if (const f32* deltas = boundarySpan<f32>(morphPtr, morphFloats, who)) {
497 out.morph = {ConstSpan<f32>(deltas, morphFloats), morphTargets, morphNormals != 0};
498 }
499 }
500 out.channelCount = channelCount;
501 out.vertexStride = vertexStride;
502 out.verts = verts;
503 out.vertexBytes = vertexBytes;
504 out.indices = indices;
505 out.indexCount = indexCount;
506 out.localMin = glm::vec3(minX, minY, minZ);
507 out.localMax = glm::vec3(maxX, maxY, maxZ);
508 return true;
509}
510
511} // namespace
512
513// Geometry from an .esmesh. The channel table arrives in the file's own layout
514// (8 bytes each), so the asset layer owns the FORMAT and the engine owns the
515// vertex layout it becomes. A channel's semantic is its attribute location.
516u32 mesh_createFromChannels(uintptr_t channelsPtr, u32 channelCount, u32 vertexStride,
517 uintptr_t vertexPtr, u32 vertexBytes,
518 uintptr_t indexPtr, u32 indexCount,
519 f32 minX, f32 minY, f32 minZ,
520 f32 maxX, f32 maxY, f32 maxZ,
521 uintptr_t bindPtr, u32 bindFloats,
522 uintptr_t morphPtr, u32 morphFloats,
523 u32 morphTargets, u32 morphNormals) {
524 auto* rm = ctx().tryGet<resource::ResourceManager>();
525 MeshUpload up;
526 if (!rm || !marshalMeshChannels(up, "mesh_createFromChannels",
527 channelsPtr, channelCount, vertexStride,
528 vertexPtr, vertexBytes, indexPtr, indexCount,
529 minX, minY, minZ, maxX, maxY, maxZ, bindPtr, bindFloats,
530 morphPtr, morphFloats, morphTargets, morphNormals)) {
531 return 0;
532 }
533 auto handle = rm->createMesh(up.vertexSpan(), up.indexSpan(), up.channelSpan(), up.vertexStride,
534 up.localMin, up.localMax,
535 MeshRecovery::SourceReplayable, up.bindSpan(), up.morph);
536 return handle.id();
537}
538
539// The same geometry arriving for a SECOND time, behind a handle that already
540// exists: a device generation ended and the asset layer is replaying the source.
541// Minting here instead would leave every component pointing at the dead mesh.
543 uintptr_t channelsPtr, u32 channelCount, u32 vertexStride,
544 uintptr_t vertexPtr, u32 vertexBytes,
545 uintptr_t indexPtr, u32 indexCount,
546 f32 minX, f32 minY, f32 minZ,
547 f32 maxX, f32 maxY, f32 maxZ,
548 uintptr_t bindPtr, u32 bindFloats,
549 uintptr_t morphPtr, u32 morphFloats,
550 u32 morphTargets, u32 morphNormals) {
551 auto* rm = ctx().tryGet<resource::ResourceManager>();
552 MeshUpload up;
553 if (!rm || targetHandle == 0
554 || !marshalMeshChannels(up, "mesh_rematerializeFromChannels",
555 channelsPtr, channelCount, vertexStride,
556 vertexPtr, vertexBytes, indexPtr, indexCount,
557 minX, minY, minZ, maxX, maxY, maxZ, bindPtr, bindFloats,
558 morphPtr, morphFloats, morphTargets, morphNormals)) {
559 return 0;
560 }
561 return rm->rematerializeMesh(resource::MeshHandle(targetHandle),
562 up.vertexSpan(), up.indexSpan(), up.channelSpan(),
563 up.vertexStride, up.localMin, up.localMax, up.bindSpan(),
564 up.morph)
565 ? targetHandle : 0;
566}
567
568u32 mesh_setSkinChunks(u32 meshHandle, uintptr_t chunksPtr, u32 chunkCount, uintptr_t bonesPtr, u32 boneCount) {
569 auto* rm = ctx().tryGet<resource::ResourceManager>();
570 if (!rm || chunkCount == 0 || boneCount == 0) return 0;
571 const u32* records = boundarySpan<u32>(chunksPtr, static_cast<u64>(chunkCount) * 3, "mesh_setSkinChunks");
572 const u16* bones = boundarySpan<u16>(bonesPtr, boneCount, "mesh_setSkinChunks");
573 if (!records || !bones) return 0;
574 std::vector<MeshSkinChunk> chunks(chunkCount);
575 u32 boneOffset = 0;
576 for (u32 c = 0; c < chunkCount; ++c) {
577 chunks[c] = MeshSkinChunk{records[c * 3], records[c * 3 + 1], boneOffset, records[c * 3 + 2]};
578 boneOffset += records[c * 3 + 2];
579 }
580 return rm->setMeshSkinChunks(resource::MeshHandle(meshHandle), std::move(chunks),
581 std::vector<u16>(bones, bones + boneCount)) ? 1 : 0;
582}
583
585u32 mesh_setClusters(u32 meshHandle, uintptr_t clustersPtr, u32 clusterCount, uintptr_t indexPtr, u32 indexCount) {
586 auto* rm = ctx().tryGet<resource::ResourceManager>();
587 if (!rm || clusterCount == 0 || indexCount == 0) return 0;
588 const u8* records = boundarySpan<u8>(clustersPtr, static_cast<u64>(clusterCount) * sizeof(lod::Cluster), "mesh_setClusters");
589 const u32* indices = boundarySpan<u32>(indexPtr, indexCount, "mesh_setClusters");
590 if (!records || !indices) return 0;
591 lod::ClusterHierarchy hierarchy;
592 hierarchy.clusters.resize(clusterCount);
593 std::memcpy(hierarchy.clusters.data(), records, static_cast<usize>(clusterCount) * sizeof(lod::Cluster));
594 hierarchy.indices.assign(indices, indices + indexCount);
595 return rm->setMeshClusters(resource::MeshHandle(meshHandle), std::move(hierarchy)) ? 1 : 0;
596}
597
598void mesh_release(u32 meshHandle) {
599 if (auto* rm = ctx().tryGet<resource::ResourceManager>()) {
600 rm->releaseMesh(resource::MeshHandle(meshHandle));
601 }
602}
603
610u32 environment_create(uintptr_t shPtr, u32 specularHandle, f32 faceSize, u32 mipCount,
611 f32 maxRange, u32 columns) {
612 auto* rm = ctx().tryGet<resource::ResourceManager>();
613 if (!rm) return 0;
614 const f32* sh = boundarySpan<f32>(shPtr, 27, "environment_create.irradiance");
615 if (!sh) return 0;
616 return rm->createEnvironment(ConstSpan<f32>(sh, 27),
617 resource::TextureHandle(specularHandle),
618 faceSize, mipCount, maxRange, columns).id();
619}
620
621void renderer_setSkyEnvironment(u32 environmentHandle) {
622 if (!g_renderFrame) return;
623 g_renderFrame->setSkyEnvironment(resource::EnvironmentHandle(environmentHandle));
624}
625
627void environment_setSky(u32 environmentHandle, u32 skyHandle) {
628 auto* rm = ctx().tryGet<resource::ResourceManager>();
629 if (!rm) return;
630 if (Environment* environment = rm->getEnvironment(resource::EnvironmentHandle(environmentHandle))) {
631 environment->sky = resource::TextureHandle(skyHandle);
632 }
633}
634
641void environment_setSun(u32 environmentHandle, uintptr_t skyShPtr, f32 dx, f32 dy, f32 dz,
642 f32 r, f32 g, f32 b) {
643 auto* rm = ctx().tryGet<resource::ResourceManager>();
644 if (!rm) return;
645 const f32* sh = boundarySpan<f32>(skyShPtr, 27, "environment_setSun.skyIrradiance");
646 if (!sh) return;
647 Environment* environment = rm->getEnvironment(resource::EnvironmentHandle(environmentHandle));
648 if (!environment) return;
649 const glm::vec3 toward(dx, dy, dz);
650 const f32 length = glm::length(toward);
651 if (!(length > 0.0f)) return;
652 for (usize i = 0; i < 9; ++i) {
653 environment->skyIrradiance[i] = glm::vec3(sh[i * 3], sh[i * 3 + 1], sh[i * 3 + 2]);
654 }
655 environment->sunDirection = toward / length;
656 environment->sunColor = glm::max(glm::vec3(r, g, b), glm::vec3(0.0f));
657 environment->hasSun = true;
658}
659
661void environment_release(u32 environmentHandle) {
662 if (auto* rm = ctx().tryGet<resource::ResourceManager>()) {
663 rm->releaseEnvironment(resource::EnvironmentHandle(environmentHandle));
664 }
665}
666
672u32 probe_volume_create(i32 resX, i32 resY, i32 resZ, uintptr_t shPtr) {
673 auto* rm = ctx().tryGet<resource::ResourceManager>();
674 if (!rm) return 0;
675 if (resX <= 0 || resY <= 0 || resZ <= 0) return 0;
676 const u64 want = static_cast<u64>(resX) * static_cast<u64>(resY)
677 * static_cast<u64>(resZ) * 27u;
678 const f32* sh = boundarySpan<f32>(shPtr, want, "probe_volume_create.irradiance");
679 if (!sh) return 0;
680 return rm->createProbeVolume({resX, resY, resZ},
681 ConstSpan<f32>(sh, static_cast<usize>(want))).id();
682}
683
684u32 probe_volume_createBricks(i32 resX, i32 resY, i32 resZ, i32 brickCount, uintptr_t bricksPtr, uintptr_t shPtr) {
685 auto* rm = ctx().tryGet<resource::ResourceManager>();
686 if (!rm) return 0;
687 if (resX <= 0 || resY <= 0 || resZ <= 0 || brickCount <= 0) return 0;
688 const u64 ints = static_cast<u64>(brickCount) * 4u;
689 const u64 want = static_cast<u64>(brickCount) * static_cast<u64>(ProbeVolume::kBrickProbes) * 27u;
690 const i32* bricks = boundarySpan<i32>(bricksPtr, ints, "probe_volume_createBricks.bricks");
691 const f32* sh = boundarySpan<f32>(shPtr, want, "probe_volume_createBricks.irradiance");
692 if (!bricks || !sh) return 0;
693 return rm->createProbeVolumeBricks({resX, resY, resZ}, ConstSpan<i32>(bricks, static_cast<usize>(ints)),
694 ConstSpan<f32>(sh, static_cast<usize>(want))).id();
695}
696
698void probe_volume_setSkyVisibility(u32 volumeHandle, uintptr_t visibilityPtr) {
699 auto* rm = ctx().tryGet<resource::ResourceManager>();
700 if (!rm) return;
701 ProbeVolume* grid = rm->getProbeVolume(resource::ProbeVolumeHandle(volumeHandle));
702 if (!grid || !grid->isValid()) return;
703 const u32 want = grid->probeCount() * 9;
704 const f32* v = boundarySpan<f32>(visibilityPtr, want, "probe_volume_setSkyVisibility.visibility");
705 if (!v) return;
706 grid->skyVisibility.assign(v, v + want);
708}
709
710bool probe_volume_getResolution(u32 volumeHandle, uintptr_t outPtr) {
711 auto* rm = ctx().tryGet<resource::ResourceManager>();
712 const ProbeVolume* grid = rm ? rm->getProbeVolume(resource::ProbeVolumeHandle(volumeHandle)) : nullptr;
713 if (!grid || !grid->isValid()) return false;
714 i32* out = boundarySpanMut<i32>(outPtr, 3, "probe_volume_getResolution.out");
715 if (!out) return false;
716 out[0] = grid->resolution.x;
717 out[1] = grid->resolution.y;
718 out[2] = grid->resolution.z;
719 return true;
720}
721
722i32 probe_volume_getBricks(u32 volumeHandle, uintptr_t outPtr, i32 maxBricks) {
723 auto* rm = ctx().tryGet<resource::ResourceManager>();
724 const ProbeVolume* grid = rm ? rm->getProbeVolume(resource::ProbeVolumeHandle(volumeHandle)) : nullptr;
725 if (!grid || !grid->isValid() || !grid->sparse()) return 0;
726 const i32 count = static_cast<i32>(grid->bricks.size());
727 const i32 take = std::min(count, std::max(maxBricks, 0));
728 if (take > 0) {
729 i32* out = boundarySpanMut<i32>(outPtr, static_cast<u64>(take) * 4u, "probe_volume_getBricks.out");
730 if (!out) return 0;
731 for (i32 b = 0; b < take; ++b) {
732 const glm::ivec4 k = grid->bricks[static_cast<usize>(b)];
733 out[b * 4] = k.x; out[b * 4 + 1] = k.y; out[b * 4 + 2] = k.z; out[b * 4 + 3] = k.w;
734 }
735 }
736 return count;
737}
738
739void probe_volume_release(u32 volumeHandle) {
740 if (auto* rm = ctx().tryGet<resource::ResourceManager>()) {
741 rm->releaseProbeVolume(resource::ProbeVolumeHandle(volumeHandle));
742 }
743}
744
745namespace {
746// Freezes a MeshRenderer's inline geometry onto the GPU: the same vertices, uploaded
747// once and drawn with a per-object transform. The inline payload is cleared, so
748// the two can never disagree.
749u32 freezeMeshGeometry(ecs::MeshRenderer* mesh) {
750 auto* rm = ctx().tryGet<resource::ResourceManager>();
751 if (!mesh || !rm || mesh->vertices.empty() || mesh->indices.empty()) return 0;
752
753 struct MeshVertex { f32 x, y, z, u, v; u32 color; };
754 std::vector<MeshVertex> verts(mesh->vertices.size());
755 for (usize i = 0; i < mesh->vertices.size(); ++i) {
756 const auto& in = mesh->vertices[i];
757 verts[i] = { in.position.x, in.position.y, 0.0f, in.uv.x, in.uv.y, in.color };
758 }
759
760 // HostOnly: the payload below is cleared on the way out, so this geometry
761 // exists in no file and a device generation ends it for good.
762 auto handle = rm->createMesh(
763 ConstSpan<u8>(reinterpret_cast<const u8*>(verts.data()), verts.size() * sizeof(MeshVertex)),
764 ConstSpan<u32>(mesh->indices.data(), mesh->indices.size()),
765 ConstSpan<GfxVertexAttribute>(kStandardMeshChannels, 3), sizeof(MeshVertex),
766 glm::vec3(mesh->localMin, 0.0f), glm::vec3(mesh->localMax, 0.0f),
768 if (!handle.isValid()) return 0;
769
770 mesh->mesh = handle;
771 mesh->vertices.clear();
772 mesh->indices.clear();
773 return handle.id();
774}
775} // namespace
776
778 u32 pointed = 0;
779 for (auto entity : registry.view<ecs::MeshRenderer>()) {
780 auto* mesh = registry.tryGet<ecs::MeshRenderer>(entity);
781 if (!mesh) continue;
782 mesh->mesh = resource::MeshHandle(meshHandle);
783 // Cleared: an entity carrying both draws the resident geometry, so a
784 // leftover payload would hide a mesh that never arrived.
785 mesh->vertices.clear();
786 mesh->indices.clear();
787 ++pointed;
788 }
789 return pointed;
790}
791
793 u32 pointed = 0;
794 for (auto entity : registry.view<ecs::MeshRenderer>()) {
795 if (auto* mesh = registry.tryGet<ecs::MeshRenderer>(entity)) {
796 mesh->material = materialId;
797 ++pointed;
798 }
799 }
800 return pointed;
801}
802
804 u32 frozen = 0;
805 for (auto entity : registry.view<ecs::MeshRenderer>()) {
806 if (freezeMeshGeometry(registry.tryGet<ecs::MeshRenderer>(entity)) != 0) ++frozen;
807 }
808 return frozen;
809}
810
812void renderer_init(u32 width, u32 height) {
813 if (!g_renderFrame) return;
814 ctx().state().viewport_width = width;
815 ctx().state().viewport_height = height;
816 g_renderFrame->resize(width, height);
817}
818
819void renderer_resize(u32 width, u32 height) {
820 if (!g_renderFrame) return;
821 ctx().state().viewport_width = width;
822 ctx().state().viewport_height = height;
823 g_renderFrame->resize(width, height);
824}
825
828 setRenderOrigin(glm::dvec3(x, y, z));
829}
830
833void renderer_setParallaxAnchor(bool set, f64 x, f64 y) {
834 parallaxAnchor() = ParallaxAnchor{set, glm::dvec2(x, y)};
835}
836
838
839f64 renderThread_fence() { return static_cast<f64>(ctx().renderThread().fence()); }
840
842 if (!std::isfinite(fence) || fence < 0 || fence > 9007199254740991.0 || std::floor(fence) != fence) return false;
843 return ctx().renderThread().complete(static_cast<RenderThread::Fence>(fence));
844}
845
847
848void renderer_beginFrame(f32 elapsedSec) {
849 // A render frame is not a mutation: composition is invalidated by the
850 // producers that write transform inputs. A server has no frames, and one
851 // frame may run several fixed steps.
852
853 if (auto* rc = ctx().tryGet<RenderContext>()) {
854 rc->setFrameTime(elapsedSec, g_viewportWidth, g_viewportHeight);
855 }
856 // The frame's own opening, which begin() is not: it runs once per camera.
857 if (g_renderFrame) { g_renderFrame->setPlanarTime(elapsedSec); g_renderFrame->beginFrame(); }
858}
859
860// The pass's load-op rides begin: clearFlags bit0 = color, bit1 = depth; the color
861// value and an optional region (w == 0 = full target) come with it, so no sticky
862// clear state exists anywhere between TS and the device.
863void renderer_begin(uintptr_t matrixPtr, u32 targetHandle, i32 clearFlags,
864 f32 r, f32 g, f32 b, f32 a,
865 i32 clearX, i32 clearY, u32 clearW, u32 clearH) {
866 if (!g_renderFrame) return;
867
868 const f32* matrixData = boundarySpan<f32>(matrixPtr, 16, "renderer_begin.matrix");
869 if (!matrixData) return;
870 glm::mat4 viewProjection = glm::make_mat4(matrixData);
871
872 g_renderFrame->begin(viewProjection, targetHandle,
873 RenderFrame::PassClear{(clearFlags & 1) != 0, (clearFlags & 2) != 0,
874 glm::vec4(r, g, b, a),
875 clearX, clearY, clearW, clearH});
876}
877
879 if (!g_renderFrame) return;
880 g_renderFrame->flush();
881 checkGLErrors("renderer_flush");
882}
883
885 if (!g_renderFrame) return;
886 g_renderFrame->end();
887 checkGLErrors("renderer_end");
888}
889
891 if (!g_renderFrame) return;
892 g_renderFrame->endFrame();
893#if defined(__EMSCRIPTEN__) && defined(ES_RENDER_THREADS)
894 EM_ASM({ if (Module['estellaGLPresent']) Module['estellaGLPresent'](); });
895#endif
896}
897
901 if (g_transformSystem) g_transformSystem->ensureComposed(registry);
902}
903
904#ifdef ES_ENABLE_BITMAP_TEXT
905#endif
906
907
908#ifdef ES_ENABLE_PARTICLES
909#endif
910
914
915// Painter order within a sorting layer is the order the render plugins iterate
916// the ECS pools, which is storage order — so a scene draws in its authored entity
917// order only because loading it spawns in that order. This is the entry point that
918// re-establishes the order on an ALREADY populated registry (the editor moving a
919// row in the outliner, a game bringing a card to the front): the same picture a
920// reload would produce, without respawning anything.
921void renderer_setEntityDrawOrder(ecs::Registry& registry, uintptr_t entitiesPtr, u32 count) {
922 if (entitiesPtr == 0 || count == 0) return;
923 const u32* raw = boundarySpan<u32>(entitiesPtr, count, "renderer_setEntityDrawOrder.entities");
924 if (!raw) return;
925 std::vector<Entity> order;
926 order.reserve(count);
927 for (u32 i = 0; i < count; ++i) order.push_back(Entity::fromRaw(raw[i]));
928 ecs::applySceneEntityOrder(registry, order.data(), order.size());
929}
930
934static const std::unordered_set<u32>* screenDomain() {
935 auto* ui = ctx().tryGet<ecs::UISystem>();
936 return ui ? &ui->screenDomain() : nullptr;
937}
938
939void renderer_beginScreenOverlay(uintptr_t projectionPtr, i32 vpX, i32 vpY, u32 vpW, u32 vpH) {
940 if (!g_renderFrame) return;
941 const f32* matrixData = boundarySpan<f32>(projectionPtr, 16, "renderer_beginScreenOverlay.matrix");
942 if (!matrixData) return;
943 g_renderFrame->beginScreenOverlay(glm::make_mat4(matrixData), vpX, vpY, vpW, vpH);
944}
945
947 if (!g_renderFrame) return;
948 ensureTransformsUpdated(registry);
949 g_renderFrame->setScreenDomain(screenDomain());
950 g_renderFrame->setUITreeLayers(uiTreeLayers());
951 g_renderFrame->submitScreenOverlay(registry);
952}
953
954bool renderer_keepScreenOverlay(ecs::Registry& registry, bool hostStill) {
955 if (!g_renderFrame) return false;
956 // Composed first, as a collect would: a composition that moves a world matrix stamps it, and that is a change to see.
957 ensureTransformsUpdated(registry);
958 g_renderFrame->setScreenDomain(screenDomain());
959 g_renderFrame->setUITreeLayers(uiTreeLayers());
960 if (auto* ui = ctx().tryGet<ecs::UISystem>()) g_renderFrame->setScreenRoots(&ui->screenRoots(), &ui->screenRootByIndex());
961 else g_renderFrame->setScreenRoots(nullptr, nullptr);
962 return g_renderFrame->keepScreenOverlay(registry, hostStill);
963}
964
966 if (g_renderFrame) g_renderFrame->setScreenOverlayEffect(material);
967}
968
969void renderer_endScreenOverlay(u32 targetHandle) {
970 if (!g_renderFrame) return;
971 g_renderFrame->endScreenOverlay(targetHandle);
972 checkGLErrors("renderer_endScreenOverlay");
973}
974
975void renderer_drawOverScreen(i32 vpX, i32 vpY, u32 vpW, u32 vpH, u32 targetHandle) {
976 if (!g_renderFrame) return;
977 g_renderFrame->drawOverScreen(vpX, vpY, vpW, vpH, targetHandle);
978 checkGLErrors("renderer_drawOverScreen");
979}
980
981void renderer_submitAll(ecs::Registry& registry, i32 vpX, i32 vpY, i32 vpW, i32 vpH) {
982 // A frame refused for a lost device draws nothing, so nothing is collected for it.
983 if (!g_renderFrame || !g_renderFrame->inFrame()) return;
984 ensureTransformsUpdated(registry);
985 // What this camera must NOT draw. Set on every collect rather than once a
986 // frame: the set is rebuilt by each layout pass, and a camera holding the
987 // previous one would draw a just-reparented element in the wrong domain.
988 g_renderFrame->setScreenDomain(screenDomain());
989 g_renderFrame->setUITreeLayers(uiTreeLayers());
990 g_renderFrame->processMasks(registry, vpX, vpY, vpW, vpH);
991
992 g_renderFrame->collectAll(registry);
993}
994
995#ifdef ES_ENABLE_PARTICLES
996void particle_update(ecs::Registry& registry, f32 dt) {
997 if (!g_particleSystem) return;
998 ensureTransformsUpdated(registry);
999 g_particleSystem->update(registry, dt);
1000}
1001
1002u32 particle_collisionQueryCount() { return g_particleSystem ? static_cast<u32>(g_particleSystem->collisionQueries().size()) : 0; }
1003uintptr_t particle_collisionQueries() { return g_particleSystem ? reinterpret_cast<uintptr_t>(g_particleSystem->collisionQueries().data()) : 0; }
1004u32 particle_collisionEventCount() { return g_particleSystem ? static_cast<u32>(g_particleSystem->collisionEvents().size()) : 0; }
1005uintptr_t particle_collisionEvents() { return g_particleSystem ? reinterpret_cast<uintptr_t>(g_particleSystem->collisionEvents().data()) : 0; }
1006u32 particle_collisionStatsCount() { return g_particleSystem ? static_cast<u32>(g_particleSystem->collisionStats().size()) : 0; }
1007uintptr_t particle_collisionStats() { return g_particleSystem ? reinterpret_cast<uintptr_t>(g_particleSystem->collisionStats().data()) : 0; }
1008void particle_collisionSetBudget(u32 queries, u32 events, bool debug) { if (g_particleSystem) g_particleSystem->setCollisionBudget(queries,events,debug); }
1009void particle_collisionResolve(ecs::Registry& registry, uintptr_t ptr, u32 count) {
1010 if (!g_particleSystem) return;
1011 const u32 expected = static_cast<u32>(g_particleSystem->collisionQueries().size());
1012 const auto* replies = count == expected && count <= 65536 ? boundarySpan<particle::CollisionReply>(ptr,count,"particle_collisionResolve") : nullptr;
1013 g_particleSystem->resolveCollisions(registry,replies,replies ? count : 0);
1014}
1015
1016// The entity crosses the wasm boundary as a raw u32 (Embind has no registered
1017// binding for esengine::Entity — calling with it throws "unbound types"). Rebuild
1018// the Entity C++-side, matching particle_set_color_lut/set_size_lut below.
1019void particle_play(ecs::Registry& registry, u32 entity) {
1020 if (!g_particleSystem) return;
1021 (void)registry;
1022 g_particleSystem->play(Entity::fromRaw(entity));
1023}
1024
1025void particle_stop(ecs::Registry& registry, u32 entity) {
1026 if (!g_particleSystem) return;
1027 (void)registry;
1028 g_particleSystem->stop(Entity::fromRaw(entity));
1029}
1030
1031void particle_reset(ecs::Registry& registry, u32 entity) {
1032 if (!g_particleSystem) return;
1033 (void)registry;
1034 g_particleSystem->reset(Entity::fromRaw(entity));
1035}
1036
1037u32 particle_emitAt(ecs::Registry& registry, u32 entity, u32 count, f32 px, f32 py, f32 pz,
1038 f32 nx, f32 ny, f32 nz, f32 vx, f32 vy, f32 vz) {
1039 if (!g_particleSystem) return 0;
1040 return g_particleSystem->emitAt(registry, Entity::fromRaw(entity), count, glm::vec3(px, py, pz),
1041 glm::vec3(nx, ny, nz), glm::vec3(vx, vy, vz));
1042}
1043
1044u32 particle_getAliveCount(u32 entity) {
1045 if (!g_particleSystem) return 0;
1046 return g_particleSystem->aliveCount(Entity::fromRaw(entity));
1047}
1048
1049void particle_set_color_lut(u32 entity, uintptr_t ptr, i32 count) {
1050 if (!g_particleSystem) return;
1051 g_particleSystem->setColorLut(Entity::fromRaw(entity), reinterpret_cast<const f32*>(ptr), count);
1052}
1053
1054void particle_set_size_lut(u32 entity, uintptr_t ptr, i32 count) {
1055 if (!g_particleSystem) return;
1056 g_particleSystem->setSizeLut(Entity::fromRaw(entity), reinterpret_cast<const f32*>(ptr), count);
1057}
1058
1059void particle_set_speed_lut(u32 entity, uintptr_t ptr, i32 count) {
1060 if (!g_particleSystem) return;
1061 g_particleSystem->setSpeedLut(Entity::fromRaw(entity), reinterpret_cast<const f32*>(ptr), count);
1062}
1063
1064void particle_set_bursts(u32 entity, uintptr_t ptr, i32 count) {
1065 if (!g_particleSystem) return;
1066 g_particleSystem->setBursts(Entity::fromRaw(entity), reinterpret_cast<const f32*>(ptr), count);
1067}
1068#endif
1069
1070void trail_update(ecs::Registry& registry, f32 dt) {
1071 if (!g_trailSystem) return;
1072 g_trailSystem->update(registry, dt);
1073}
1074
1075// The entity crosses the wasm boundary as a raw u32 (Embind has no Entity binding);
1076// rebuild it C++-side, matching particle_play/stop above.
1077void trail_clear(ecs::Registry& registry, u32 entity) {
1078 if (!g_trailSystem) return;
1079 (void)registry;
1080 g_trailSystem->clear(Entity::fromRaw(entity));
1081}
1082
1084 if (!g_springBoneSystem) return;
1085 g_springBoneSystem->update(registry, g_transformSystem, dt);
1086}
1087
1088void springbone_reset(ecs::Registry& registry, u32 entity) {
1089 if (!g_springBoneSystem) return;
1090 (void)registry;
1091 g_springBoneSystem->reset(Entity::fromRaw(entity));
1092}
1093
1094void springbone_release(ecs::Registry& registry, u32 entity) {
1095 if (!g_springBoneSystem) return;
1096 g_springBoneSystem->release(registry, Entity::fromRaw(entity));
1097}
1098
1099static std::vector<f32>& springBoneSnapshot() {
1100 static std::vector<f32> data;
1101 return data;
1102}
1103
1105 (void)registry;
1106 auto& data = springBoneSnapshot();
1107 if (!g_springBoneSystem) { data.clear(); return 0; }
1108 g_springBoneSystem->snapshot(Entity::fromRaw(entity), data);
1109 return static_cast<u32>(data.size() / 7);
1110}
1111
1113 return static_cast<u32>(springBoneSnapshot().size() / 7);
1114}
1115
1117 return reinterpret_cast<uintptr_t>(springBoneSnapshot().data());
1118}
1119
1121 if (!g_renderFrame) return;
1122 g_renderFrame->setStage(static_cast<RenderStage>(stage));
1123}
1124
1125u32 renderer_createTarget(u32 width, u32 height, i32 flags) {
1126 if (!g_renderFrame) return 0;
1127 bool depth = (flags & 1) != 0;
1128 bool linear = (flags & 2) != 0;
1129 // 4 once asked for the texture as drawn rather than a copy turned bottom-up; every target is read as drawn now.
1130 return g_renderFrame->targetManager().create(width, height, depth, linear, (flags & 8) != 0);
1131}
1132
1134 if (!g_renderFrame) return 0;
1135 auto* target = g_renderFrame->targetManager().get(handle);
1136 return target ? static_cast<u32>(target->getDepthTexture()) : 0;
1137}
1138
1140 if (!g_renderFrame) return;
1141 g_renderFrame->cancelMaterialBakesFor(handle);
1142 g_renderFrame->targetManager().release(handle);
1143}
1144
1146 if (!g_renderFrame) return 0;
1147 auto* target = g_renderFrame->targetManager().get(handle);
1148 return target ? static_cast<u32>(target->getColorTexture()) : 0;
1149}
1150
1151u32 renderer_queueMaterialBake(u32 material, u32 shader, u32 target, u32 x, u32 y, u32 w, u32 h,
1152 f32 a0, f32 a1, f32 a2, f32 a3, f32 b0, f32 b1, f32 b2, f32 b3) {
1153 if (!g_renderFrame) return 0;
1154 return g_renderFrame->queueMaterialBake(material, shader, target, x, y, w, h, glm::vec4(a0, a1, a2, a3), glm::vec4(b0, b1, b2, b3));
1155}
1156
1157bool renderer_projectMaterialBake(u32 ticket, u32 material, u32 target, u32 instances) {
1158 return g_renderFrame && g_renderFrame->projectMaterialBake(ticket, material, target, instances);
1159}
1160
1162 if (!g_renderFrame) return -1;
1163 return g_renderFrame->materialBakeState(ticket);
1164}
1165
1167 if (!g_renderFrame) return 0;
1168 return g_renderFrame->stats().draw_calls;
1169}
1170
1172 auto* device = g_device;
1173 return device ? device->pendingProgramLabels() : std::string();
1174}
1175
1177 if (!g_renderFrame) return 0;
1178 return g_renderFrame->stats().waiting_for_program;
1179}
1180
1182 if (!g_renderFrame) return 0;
1183 return g_renderFrame->stats().gpu_draws;
1184}
1185
1186#ifdef __EMSCRIPTEN__
1193emscripten::val meshRenderer_localBounds(ecs::Registry& registry, u32 entity) {
1194 const Entity ent = Entity::fromRaw(entity);
1195 const auto* mesh = registry.tryGet<ecs::MeshRenderer>(ent);
1196 if (!mesh) return emscripten::val::null();
1197
1198 // The inline payload is authored as 2D positions and has no third dimension;
1199 // resident geometry carries the one it was imported with.
1200 glm::vec3 mn(mesh->localMin, 0.0f);
1201 glm::vec3 mx(mesh->localMax, 0.0f);
1202 if (mesh->mesh.isValid()) {
1203 if (auto* rm = ctx().tryGet<resource::ResourceManager>()) {
1204 if (const Mesh* res = rm->getMesh(mesh->mesh)) {
1205 mn = res->localMin;
1206 mx = res->localMax;
1207 }
1208 }
1209 }
1210 if (!(mx.x > mn.x) && !(mx.y > mn.y) && !(mx.z > mn.z)) return emscripten::val::null();
1211
1212 auto out = emscripten::val::object();
1213 out.set("minX", mn.x);
1214 out.set("minY", mn.y);
1215 out.set("minZ", mn.z);
1216 out.set("maxX", mx.x);
1217 out.set("maxY", mx.y);
1218 out.set("maxZ", mx.z);
1219 return out;
1220}
1221
1222emscripten::val renderer_getLiveObjects() {
1223 auto* device = g_device;
1224 // Null rather than zeros: with no device there is nothing to report, and a
1225 // census that recorded 0 live textures would read as "everything was freed".
1226 if (!device) return emscripten::val::null();
1227 const GfxLiveObjects live = device->liveObjects();
1228 auto out = emscripten::val::object();
1229 out.set("buffers", static_cast<f64>(live.buffers));
1230 out.set("textures", static_cast<f64>(live.textures));
1231 out.set("programs", static_cast<f64>(live.programs));
1232 out.set("layouts", static_cast<f64>(live.layouts));
1233 out.set("pipelines", static_cast<f64>(live.pipelines));
1234 out.set("renderTargets", static_cast<f64>(live.renderTargets));
1235 out.set("readbacks", static_cast<f64>(live.readbacks));
1236 return out;
1237}
1238#endif // __EMSCRIPTEN__
1239
1241 if (!g_renderFrame) return 0;
1242 return g_renderFrame->stats().triangles;
1243}
1244
1246 if (!g_renderFrame) return 0;
1247 return g_renderFrame->stats().sprites;
1248}
1249
1251 if (!g_renderFrame) return 0;
1252 return g_renderFrame->stats().skeletal;
1253}
1254
1256 if (!g_renderFrame) return 0;
1257 return g_renderFrame->stats().text;
1258}
1259
1261 if (!g_renderFrame) return 0;
1262 return g_renderFrame->stats().meshes;
1263}
1264
1266 if (!g_renderFrame) return 0;
1267 return g_renderFrame->stats().culled;
1268}
1269
1271 if (!g_renderFrame) return -1.0f;
1272 return g_renderFrame->stats().gpu_time_ms;
1273}
1274
1277}
1278
1280 // Valid pre-init, and it has to be: the SDK sets this beside the colour
1281 // space, before the context has registered anything. Remembered here, and
1282 // adopted by EstellaContext when it creates the source.
1284 if (auto* source = ctx().tryGet<RandomSource>()) {
1285 source->reseed(seed);
1286 // Consumers derive a generator once, so each is re-derived here. One
1287 // today; this list is where a second one announces itself.
1288#ifdef ES_ENABLE_PARTICLES
1289 if (auto* particles = g_particleSystem) particles->reseedFrom(*source);
1290#endif
1291 }
1292}
1293
1294std::string engine_getCpuScopes() {
1295 return FrameProfiler::get().lastJson();
1296}
1297
1298void engine_prepareMeshPrograms(u32 rowsPtr, u32 count, u32 outPtr) {
1299 auto* out = reinterpret_cast<u32*>(static_cast<uintptr_t>(outPtr));
1300 for (u32 i = 0; i < 11; ++i) out[i] = 0;
1301 if (!g_initialized || !g_renderFrame || !g_device) return;
1302 const auto* rc = ctx().tryGet<RenderContext>();
1303 if (!rc) return;
1304
1305 // Bracketed: a generation or epoch that moved underneath means neither
1306 // reading describes the live renderer, so no claim is produced rather than
1307 // one assembled out of two different worlds.
1308 const u64 generationBefore = g_device->deviceGeneration();
1309 const u64 epochBefore = rc->programEpoch();
1310
1311 const auto* rows = reinterpret_cast<const MeshDocumentRecord*>(static_cast<uintptr_t>(rowsPtr));
1312 const RenderPrewarmResult r = g_renderFrame->prewarmDocument(rows, count);
1313
1314 const u64 generationAfter = g_device->deviceGeneration();
1315 const u64 epochAfter = rc->programEpoch();
1316
1317 out[0] = (generationBefore == generationAfter && epochBefore == epochAfter) ? 1u : 0u;
1318 out[1] = r.asks;
1319 out[2] = r.compiles;
1320 out[3] = r.materialAsks;
1321 out[4] = r.materialCompiles;
1322 const u64 digest = r.requirementDigest();
1323 out[5] = static_cast<u32>(digest & 0xFFFFFFFFull);
1324 out[6] = static_cast<u32>(digest >> 32);
1325 out[7] = static_cast<u32>(epochAfter & 0xFFFFFFFFull);
1326 out[8] = static_cast<u32>(epochAfter >> 32);
1327 out[9] = static_cast<u32>(generationAfter & 0xFFFFFFFFull);
1328 out[10] = static_cast<u32>(generationAfter >> 32);
1329}
1330
1331#ifdef ES_ENABLE_TEST_PROBES
1336static void writePrewarm(u32* out, const RenderPrewarmResult& r) {
1337 out[0] = r.asks;
1338 out[1] = r.compiles;
1339 out[2] = r.uniqueKeys;
1340 out[3] = r.materialAsks;
1341 out[4] = r.materialCompiles;
1342 for (u32 w = 0; w < 2; ++w) {
1343 out[5 + w * 2] = static_cast<u32>(r.keys[w] & 0xFFFFFFFFull);
1344 out[6 + w * 2] = static_cast<u32>(r.keys[w] >> 32);
1345 }
1346 const u64 digest = r.requirementDigest();
1347 out[9] = static_cast<u32>(digest & 0xFFFFFFFFull);
1348 out[10] = static_cast<u32>(digest >> 32);
1349 const auto* rc = ctx().tryGet<RenderContext>();
1350 const u64 epoch = rc ? rc->programEpoch() : 0;
1351 out[11] = static_cast<u32>(epoch & 0xFFFFFFFFull);
1352 out[12] = static_cast<u32>(epoch >> 32);
1353 // Not a third truth in the stamp: the guard that says the two above were
1354 // read on one device. A generation that moved mid-derivation invalidates the
1355 // whole readying rather than being recorded alongside it.
1356 const u64 generation = g_device ? g_device->deviceGeneration() : 0;
1357 out[13] = static_cast<u32>(generation & 0xFFFFFFFFull);
1358 out[14] = static_cast<u32>(generation >> 32);
1359}
1360
1361void engine_prewarmMeshVariants(ecs::Registry& registry, u32 entitiesPtr, u32 count, u32 outPtr) {
1362 auto* out = reinterpret_cast<u32*>(static_cast<uintptr_t>(outPtr));
1363 for (u32 i = 0; i < 13; ++i) out[i] = 0;
1364 if (!g_initialized || !g_renderFrame) return;
1365 const auto* entities = reinterpret_cast<const Entity*>(static_cast<uintptr_t>(entitiesPtr));
1366 writePrewarm(out, g_renderFrame->prewarmPrograms(registry, entities, count));
1367}
1368
1369#endif
1370
1371std::string engine_getCounters() {
1373}
1374
1375std::string engine_getGpuScopes() {
1377}
1378
1380 if (auto* rm = ctx().tryGet<resource::ResourceManager>()) {
1381 return static_cast<f64>(rm->getStats().textureBytes);
1382 }
1383 return 0.0;
1384}
1385
1387 return g_device ? static_cast<f64>(g_device->estimatedGpuBytes()) : 0.0;
1388}
1389
1390// f64 rather than u32: the epoch is a counter nothing resets, and a session that
1391// outlives 4 billion invalidations should not wrap into a stamp that matches.
1393 if (auto* rc = ctx().tryGet<RenderContext>()) {
1394 return static_cast<f64>(rc->programEpoch());
1395 }
1396 return 0.0;
1397}
1398
1400 return g_device ? static_cast<f64>(g_device->deviceGeneration()) : 0.0;
1401}
1402
1404 ctx().state().clear_color = glm::vec4(r, g, b, a);
1405}
1406
1408 g_device->setViewport(x, y, static_cast<u32>(w), static_cast<u32>(h));
1409}
1410
1412 if (g_device) g_device->setAsyncComputeEnabled(enabled);
1413}
1414
1416 return g_device && g_device->asyncComputeEnabled();
1417}
1418
1420 return g_device && g_device->supportsAsyncCompute();
1421}
1422
1423void renderer_setSkinCache(i32 enabled, i32 behavior, f32 maxMegabytes) {
1424 auto* frame = g_renderFrame;
1425 if (!frame || !frame->skinCache()) return;
1426 SkinCacheSettings settings;
1427 settings.enabled = enabled != 0;
1429 settings.maxMegabytes = std::max(0.0f, maxMegabytes);
1430 frame->skinCache()->setSettings(settings);
1431}
1432
1434 auto* frame = g_renderFrame;
1435 SkinCache* cache = frame ? frame->skinCache() : nullptr;
1436 if (!cache) return 0.0;
1437 switch (which) {
1438 case 0: return cache->active() ? 1.0 : 0.0;
1439 case 1: return static_cast<f64>(cache->entryCount());
1440 case 2: return static_cast<f64>(cache->bytesUsed());
1441 case 3: return static_cast<f64>(cache->refusedThisFrame());
1442 case 4: return static_cast<f64>(cache->scheduledThisFrame());
1443 case 5: return static_cast<f64>(cache->drawsThisFrame());
1444 default: return 0.0;
1445 }
1446}
1447
1449 if (auto* frame = g_renderFrame) frame->setYSortLayers(mask);
1450}
1451
1453 if (auto* frame = g_renderFrame) frame->setTreeSortLayers(mask);
1454}
1455
1456// The 2.5D opt-in, per sorting layer. Same shape as setYSortLayers because it is
1457// the same kind of declaration: how a layer resolves the draws inside it.
1458void renderer_setQualityBudgets(u32 atlasSize, u32 cellSize, u32 cascades, u32 particleLimit) {
1459 if (g_renderFrame) g_renderFrame->setShadowBudget(atlasSize, cellSize, cascades);
1460#ifdef ES_ENABLE_PARTICLES
1461 if (g_particleSystem) g_particleSystem->setParticleLimit(particleLimit);
1462#endif
1463}
1464
1466 if (auto* frame = g_renderFrame) frame->setDepthLayers(mask);
1467}
1468
1469void renderer_setViewLighting(u32 mode, f32 rotationDegrees, f32 keyIntensity, f32 fillIntensity,
1470 f32 skyIntensity, bool showSky) {
1471 if (!g_renderFrame) return;
1473 lighting.studio = mode == 1;
1474 lighting.rotation = std::isfinite(rotationDegrees) ? rotationDegrees : 0.0f;
1475 lighting.keyIntensity = std::isfinite(keyIntensity) ? std::max(keyIntensity, 0.0f) : 0.0f;
1476 lighting.fillIntensity = std::isfinite(fillIntensity) ? std::max(fillIntensity, 0.0f) : 0.0f;
1477 lighting.skyIntensity = std::isfinite(skyIntensity) ? std::max(skyIntensity, 0.0f) : 0.0f;
1478 lighting.showSky = showSky;
1479 g_renderFrame->setViewLighting(lighting);
1480}
1481
1482void renderer_setPlanarReflectionQuality(f32 scale, u32 maxSize, f32 updatesPerSecond, bool capAuthored) {
1483 if (g_renderFrame) g_renderFrame->setPlanarQuality(scale, maxSize, updatesPerSecond, capAuthored);
1484}
1485
1487#ifdef ES_ENABLE_GPU_PARTICLES
1488 if (g_renderFrame) {
1489 if (GpuParticles* gpu = g_renderFrame->gpuParticles()) gpu->setDepthGridMax(texels);
1490 }
1491#else
1492 (void)texels;
1493#endif
1494}
1495
1497 if (auto* context = ctx().tryGet<RenderContext>()) context->setQualityConstants(glm::vec4(x, y, z, w));
1498}
1499
1500std::string renderer_getPlanarReflectionStatus(u32 view, u32 entity) {
1501 return g_renderFrame ? g_renderFrame->planarStatus(view, entity) : "{\"state\":\"unavailable\"}";
1502}
1503
1505 if (g_renderFrame) g_renderFrame->setShadowDistance(distance);
1506}
1507
1509 if (g_renderFrame) g_renderFrame->setShadow2DSoftSamples(samples);
1510}
1511
1512bool renderer_setQualityValue(const std::string& name, f32 value) {
1513 return g_renderFrame && g_renderFrame->setQualityValue(name, value);
1514}
1515
1517 if (g_renderFrame) g_renderFrame->setLightingDirect(on);
1518}
1519
1521 if (g_renderFrame) g_renderFrame->setDepthPrepass(on);
1522}
1523
1525 if (g_renderFrame) g_renderFrame->setProbesPerPixel(on);
1526}
1527
1529 const auto* rc = ctx().tryGet<RenderContext>();
1530 if (!rc) return 0.0;
1531 const ProbeStore& probes = rc->probes();
1532 return probes.atlasTexture() != 0 ? static_cast<f64>(probes.atlasBytes()) : 0.0;
1533}
1534
1536 const auto* rc = ctx().tryGet<RenderContext>();
1537 if (!rc) return 0;
1538 const ProbeStore& probes = rc->probes();
1539 return perPixel ? probes.perPixelDraws() : probes.perObjectDraws();
1540}
1541
1543 if (g_renderFrame) g_renderFrame->setLodDistanceScale(scale);
1544}
1545
1547 if (g_renderFrame) g_renderFrame->setOcclusionGridSize(size);
1548}
1549
1551 if (g_renderFrame) g_renderFrame->setTargetPoolIdleBudget(static_cast<u64>(megabytes) * 1024 * 1024);
1552}
1553
1555 if (auto* device = g_device) device->setSkipPendingPrograms(on);
1556}
1557
1559 auto* device = g_device;
1560 return device ? device->pendingProgramCount() : 0u;
1561}
1562
1563// Which layers the NEXT collect draws. Set per camera, before renderer_submitAll.
1565 if (auto* frame = g_renderFrame) frame->setCullingMask(mask);
1566}
1567
1568// A camera's own identity, which is what makes a LOD level the VIEW's answer and
1569// not the entity's: two cameras looking at one object may settle on two levels.
1571 if (auto* frame = g_renderFrame) frame->setViewId(view);
1572}
1573
1575 return g_device && g_device->framePending() ? 1 : 0;
1576}
1577
1578i32 renderer_clusterInspect(u32 entity, uintptr_t outPtr) {
1579 auto* out = boundarySpanMut<u32>(outPtr, 2, "renderer_clusterInspect.out");
1580 if (!out) return 0;
1581 out[0] = out[1] = 0;
1582 if (!g_renderFrame) return 0;
1583 return g_renderFrame->clusterInspect(Entity::fromRaw(entity), out[0], out[1]) ? 1 : 0;
1584}
1585
1586i32 renderer_lodInspect(u32 view, u32 entity, uintptr_t outPtr) {
1587 auto* out = boundarySpanMut<f32>(outPtr, 4, "renderer_lodInspect.out");
1588 if (!out) return 0;
1589 out[0] = out[1] = out[2] = out[3] = 0.0f;
1590 if (!g_renderFrame) return 0;
1591 u8 level = 0, unbiased = 0, levels = 0;
1592 f32 size = 0.0f;
1593 if (!g_renderFrame->lodInspect(view, Entity::fromRaw(entity), level, unbiased, levels, size)) {
1594 return 0;
1595 }
1596 // Culled is a level nothing draws, not a big number: handed over as -1 so a
1597 // reader that forgets to check it gets an impossible level rather than 255.
1598 out[0] = level == lod::kCulled ? -1.0f : static_cast<f32>(level);
1599 out[1] = unbiased == lod::kCulled ? -1.0f : static_cast<f32>(unbiased);
1600 out[2] = static_cast<f32>(levels);
1601 out[3] = size;
1602 return 1;
1603}
1604
1606 if (!g_renderFrame) return {};
1607 return g_renderFrame->takeTextureWants();
1608}
1609
1610void renderer_setImpostorAtlas(u32 entity, u32 texture, u32 frames) {
1611 if (!g_renderFrame) return;
1612 g_renderFrame->setImpostorAtlas(Entity::fromRaw(entity), texture, frames);
1613}
1614
1615void renderer_setLodPreview(u32 view, u32 entity, i32 level) {
1616 if (!g_renderFrame) return;
1617 const u8 held = level < 0 ? lod::kNoPreview : static_cast<u8>(level);
1618 g_renderFrame->setLodPreview(view, Entity::fromRaw(entity), held);
1619}
1620
1622 if (g_renderFrame) g_renderFrame->requestProbeCapture({x, y, z}, face);
1623}
1624
1626 return g_renderFrame ? g_renderFrame->pollProbeCapture() : 2;
1627}
1628
1629bool renderer_takeProbeCapture(uintptr_t dst, u32 bytes) {
1630 if (!g_renderFrame || dst == 0) return false;
1631 const std::vector<u8>& px = g_renderFrame->probeCapturePixels();
1632 if (px.empty() || px.size() > bytes) return false;
1633 std::memcpy(reinterpret_cast<void*>(dst), px.data(), px.size());
1634 return true;
1635}
1636
1637void renderer_setProbeVolumeReflection(u32 entity, u32 environmentHandle, u32 slot) {
1638 if (g_renderFrame) g_renderFrame->setProbeVolumeReflection(entity, environmentHandle, slot);
1639}
1640
1641void renderer_setProbeVolumeOverride(u32 entity, u32 volumeHandle) {
1642 if (g_renderFrame) g_renderFrame->setProbeVolumeOverride(entity, resource::ProbeVolumeHandle(volumeHandle));
1643}
1644
1646 if (g_renderFrame) g_renderFrame->setWorldUnitsPerMeter(units);
1647}
1648
1650 if (!g_renderFrame) return;
1651 // An unknown mode is the authored look, not a crash: a newer editor may ask for
1652 // a mode this engine does not have.
1653 const ShadingMode known = (mode > 0 && mode < static_cast<i32>(kShadingModeCount))
1654 ? static_cast<ShadingMode>(mode) : ShadingMode::Shaded;
1655 g_renderFrame->setViewShading(view, known);
1656}
1657
1658void renderer_setViewSelection(u32 view, uintptr_t idsPtr, u32 count) {
1659 if (!g_renderFrame) return;
1660 const u32* ids = count > 0 ? boundarySpan<u32>(idsPtr, count, "renderer_setViewSelection.ids") : nullptr;
1661 g_renderFrame->setViewSelection(view, ids, ids ? count : 0);
1662}
1663
1664void renderer_setViewSkinWeights(u32 view, u32 entity, i32 joint) {
1665 if (!g_renderFrame) return;
1666 g_renderFrame->setViewSkinWeights(view, joint < 0 ? INVALID_ENTITY : Entity::fromRaw(entity),
1667 joint < 0 ? 0u : static_cast<u32>(joint));
1668}
1669
1671 if (auto* resources = ctx().tryGet<resource::ResourceManager>()) resources->setMeshEdgeBuffers(enabled);
1672}
1673
1674i32 renderer_lightStatus(u32 entity, uintptr_t outPtr) {
1675 auto* out = boundarySpanMut<f32>(outPtr, 9, "renderer_lightStatus.out");
1676 if (!out) return 0;
1677 for (u32 i = 0; i < 9; ++i) out[i] = 0.0f;
1678 if (!g_renderFrame) return 0;
1679 const LightCapReport& cap = g_renderFrame->lightCap();
1680 if (cap.limit == 0) return 0; // no frame has decided anything yet
1681 const LightRefusal why = cap.refusalFor(Entity::fromRaw(entity));
1682 out[0] = why == LightRefusal::None ? 1.0f : 0.0f;
1683 out[1] = static_cast<f32>(static_cast<u8>(why));
1684 out[2] = static_cast<f32>(cap.limit);
1685 out[3] = static_cast<f32>(cap.requested);
1686 out[4] = static_cast<f32>(cap.refused.size());
1687 out[5] = cap.environmentSun ? 1.0f : 0.0f;
1688 out[6] = cap.environmentSunAim.x;
1689 out[7] = cap.environmentSunAim.y;
1690 out[8] = cap.environmentSunAim.z;
1691 return 1;
1692}
1693
1694i32 renderer_shadowStatus(u32 entity, uintptr_t outPtr) {
1695 auto* out = boundarySpanMut<f32>(outPtr, 5, "renderer_shadowStatus.out");
1696 if (!out) return 0;
1697 for (u32 i = 0; i < 5; ++i) out[i] = 0.0f;
1698 if (!g_renderFrame) return 0;
1699 const ShadowPlanReport& plan = g_renderFrame->shadowPlan();
1700 const ShadowGrant* grant = plan.grantFor(Entity::fromRaw(entity));
1701 if (!grant) return 0;
1702 out[0] = static_cast<f32>(grant->requested);
1703 out[1] = static_cast<f32>(grant->granted);
1704 out[2] = static_cast<f32>(static_cast<u8>(grant->refusal));
1705 out[3] = static_cast<f32>(plan.deniedCasters());
1706 out[4] = static_cast<f32>(plan.reducedCasters());
1707 return 1;
1708}
1709
1711 // Valid pre-init: the global reaches every later shader compile, and
1712 // RenderFrame::init adopts it. A live frame applies immediately (editor
1713 // realms reset it per session, mirroring renderer_setYSortLayers).
1715 if (auto* frame = g_renderFrame) frame->setColorSpace(linear != 0);
1716}
1717
1719 if (!g_initialized) {
1720 ES_LOG_ERROR("[Diagnose] Renderer not initialized");
1721 return;
1722 }
1723
1724 ES_LOG_INFO("[Diagnose] GL Version: {}", g_device->getString(GfxStringName::Version));
1725 ES_LOG_INFO("[Diagnose] GL Renderer: {}", g_device->getString(GfxStringName::Renderer));
1726 ES_LOG_INFO("[Diagnose] GL Vendor: {}", g_device->getString(GfxStringName::Vendor));
1727 ES_LOG_INFO("[Diagnose] GLSL Version: {}", g_device->getString(GfxStringName::ShadingLanguageVersion));
1728 ES_LOG_INFO("[Diagnose] Stored viewport: {}x{}", g_viewportWidth, g_viewportHeight);
1729 ES_LOG_INFO("[Diagnose] Max texture units: {}", g_device->getInt(GfxIntParam::MaxTextureImageUnits));
1730 ES_LOG_INFO("[Diagnose] Max vertex attribs: {}", g_device->getInt(GfxIntParam::MaxVertexAttribs));
1731
1732 while (g_device->getError() != 0) {}
1733 ES_LOG_INFO("[Diagnose] No pending GL errors (cleared)");
1734}
1735
1736void gl_enableErrorCheck(bool enabled) {
1737 ctx().state().gl_error_check_enabled = enabled;
1738 if (enabled) {
1739 while (g_device->getError() != 0) {}
1740 ES_LOG_INFO("[GL] Error checking enabled");
1741 }
1742}
1743
1744u32 gl_checkErrors(const std::string& context) {
1745 bool prev = g_glErrorCheckEnabled;
1746 ctx().state().gl_error_check_enabled = true;
1747 u32 count = checkGLErrors(context.c_str());
1748 ctx().state().gl_error_check_enabled = prev;
1749 if (count == 0 && prev) {
1750 ES_LOG_INFO("[GL] No errors at: {}", context);
1751 }
1752 return count;
1753}
1754
1756 auto view = registry.activeView<ecs::Canvas>();
1757 for (auto entity : view) {
1758 return static_cast<i32>(entity.id());
1759 }
1760 return -1;
1761}
1762
1763#ifdef __EMSCRIPTEN__
1764// Every Canvas, so the caller can pick one that belongs to a RUNNING scene. Scene
1765// membership (SceneOwner) is an SDK component the engine cannot see, which is why
1766// this reports rather than decides — the camera query has the same shape.
1767emscripten::val registry_getCanvasEntities(ecs::Registry& registry) {
1768 auto view = registry.activeView<ecs::Canvas>();
1769 auto result = emscripten::val::array();
1770 u32 idx = 0;
1771 for (auto entity : view) {
1772 result.set(idx++, entity.id());
1773 }
1774 return result;
1775}
1776#endif
1777
1778#ifdef __EMSCRIPTEN__
1779emscripten::val registry_getCameraEntities(ecs::Registry& registry) {
1780 auto cameraView = registry.activeView<ecs::Camera, ecs::Transform>();
1781 auto result = emscripten::val::array();
1782 u32 idx = 0;
1783 for (auto entity : cameraView) {
1784 auto& camera = registry.get<ecs::Camera>(entity);
1785 if (camera.isActive) {
1786 result.set(idx++, entity.id());
1787 }
1788 }
1789 return result;
1790}
1791
1792emscripten::val getChildEntities(ecs::Registry& registry, u32 entity) {
1793 auto result = emscripten::val::array();
1794 if (!registry.has<ecs::Children>(Entity::fromRaw(entity))) {
1795 return result;
1796 }
1797 const auto& children = registry.get<ecs::Children>(Entity::fromRaw(entity));
1798 u32 idx = 0;
1799 for (auto child : children.entities) {
1800 result.set(idx++, child.id());
1801 }
1802 return result;
1803}
1804#endif
1805
1807 return Entity::fromRaw(entity).generation();
1808}
1809
1811void registry_unwatchEntityChanges(ecs::Registry& registry, u32 reader) { registry.unwatchEntityChanges(reader); }
1814double registry_componentMutationRevision(ecs::Registry& registry, u32 component, bool topology) {
1815 return registry.componentMutationRevision(component, topology);
1816}
1817int registry_readEntityChanges(ecs::Registry& registry, double after, uintptr_t outputPtr, int capacity) {
1818 if (capacity < 0 || capacity > static_cast<int>(ecs::ENTITY_CHANGE_CAPACITY)
1819 || outputPtr % alignof(ecs::EntityChangeRow)) return -1;
1820 if (capacity == 0) return registry.readEntityChanges(after, {});
1821 auto* rows = boundarySpanMut<ecs::EntityChangeRow>(outputPtr, static_cast<u64>(capacity), "registry_readEntityChanges");
1822 return rows ? registry.readEntityChanges(after, {rows, static_cast<usize>(capacity)}) : -1;
1823}
1824
1825int registry_readWorldPoses2D(ecs::Registry& registry, uintptr_t entitiesPtr, int count, uintptr_t outputPtr) {
1826 if (count <= 0 || entitiesPtr % alignof(u32) || outputPtr % alignof(EntityPose2D)) return 0;
1827 const auto* ids = boundarySpan<u32>(entitiesPtr, static_cast<u64>(count), "registry_readWorldPoses2D.entities");
1828 auto* output = boundarySpanMut<EntityPose2D>(outputPtr, static_cast<u64>(count), "registry_readWorldPoses2D.output");
1829 if (!ids || !output) return 0;
1830 int written = 0;
1831 for (int i = 0; i < count; ++i) {
1832 const auto entity = Entity::fromRaw(ids[i]);
1833 if (!registry.valid(entity) || !registry.isEntityActive(entity) || !registry.has<ecs::Transform>(entity)) continue;
1834 auto& tf = registry.get<ecs::Transform>(entity);
1835 tf.ensureDecomposed();
1836 const auto& q = tf.worldRotation;
1837 const f32 angle = std::atan2(2.0f * (q.w * q.z + q.x * q.y), 1.0f - 2.0f * (q.y * q.y + q.z * q.z));
1838 output[written++] = {entity.id(), tf.worldPosition.x, tf.worldPosition.y, angle};
1839 }
1840 return written;
1841}
1842
1843void registry_batchSyncPhysicsTransforms(ecs::Registry& registry, uintptr_t bufferPtr, int count, float ppu) {
1844 // Physics is a producer of transform INPUTS. The composed world fields are
1845 // TransformSystem's, and writing them here made this a second author of them.
1847 if (count < 0) return;
1848 const float* buffer = boundarySpan<f32>(bufferPtr, static_cast<u64>(count) * 4, "registry_batchSyncPhysicsTransforms");
1849 if (!buffer) return;
1850 for (int i = 0; i < count; i++) {
1851 const int offset = i * 4;
1852 uint32_t entityId;
1853 std::memcpy(&entityId, buffer + offset, sizeof(uint32_t));
1854 auto entity = Entity::fromRaw(entityId);
1855 if (!registry.valid(entity)) continue;
1856 if (!registry.has<ecs::Transform>(entity)) continue;
1857
1858 auto& transform = registry.get<ecs::Transform>(entity);
1859 float px = buffer[offset + 1] * ppu;
1860 float py = buffer[offset + 2] * ppu;
1861 float angle = buffer[offset + 3];
1862 float half = angle * 0.5f;
1863 glm::quat rot(std::cos(half), 0.0f, 0.0f, std::sin(half));
1864
1865 // Only a body that moved is written, and stamped: a sleeping body rewritten with its own pose every step would read as
1866 // changed to every consumer of changes (the renderer), every frame.
1867 if (transform.position.x == px && transform.position.y == py && transform.rotation == rot) continue;
1868 transform.position.x = px;
1869 transform.position.y = py;
1870 transform.rotation = rot;
1871 registry.markChanged<ecs::Transform>(entity);
1872 }
1873}
1874
1875void registry_markComponentsChanged(ecs::Registry& registry, uintptr_t pairsPtr, int count) {
1876 if (count <= 0 || pairsPtr % alignof(u32)) return;
1877 const u32* pairs = boundarySpan<u32>(pairsPtr, static_cast<u64>(count) * 2, "registry_markComponentsChanged");
1878 if (!pairs) return;
1879 for (int i = 0; i < count; ++i) registry.markChangedById(pairs[i * 2], Entity::fromRaw(pairs[i * 2 + 1]));
1880}
1881
1883 if (g_renderFrame) {
1884 g_renderFrame->frameCapture().requestCapture();
1885 }
1886}
1887
1889 if (!g_renderFrame) return 0;
1890 return g_renderFrame->frameCapture().getRecordCount();
1891}
1892
1894 if (!g_renderFrame) return 0;
1895 return reinterpret_cast<uintptr_t>(g_renderFrame->frameCapture().getRecords());
1896}
1897
1899 if (!g_renderFrame) return 0;
1900 return reinterpret_cast<uintptr_t>(g_renderFrame->frameCapture().getEntities());
1901}
1902
1904 if (!g_renderFrame) return 0;
1905 return g_renderFrame->frameCapture().getEntityCount();
1906}
1907
1909 if (!g_renderFrame) return 0;
1910 return reinterpret_cast<uintptr_t>(g_renderFrame->frameCapture().getTextures());
1911}
1912
1914 if (!g_renderFrame) return 0;
1915 return g_renderFrame->frameCapture().getTextureCount();
1916}
1917
1919 if (!g_renderFrame) return 0;
1920 return g_renderFrame->frameCapture().getPassCount();
1921}
1922
1924 if (!g_renderFrame) return false;
1925 return g_renderFrame->frameCapture().hasCapturedData();
1926}
1927
1928void renderer_replayToDrawCall(i32 drawCallIndex) {
1929 if (!g_renderFrame) return;
1930 g_renderFrame->replayToDrawCall(drawCallIndex);
1931}
1932
1933// Lands the snapshot's async readback: 0 = pending (poll again after yielding
1934// to the event loop), 1 = getSnapshot* serve the pixels, 2 = none/failed.
1936 return g_renderFrame && g_renderFrame->snapshotMatchesCapture();
1937}
1938
1940 return g_renderFrame ? g_renderFrame->pollSnapshotReadback() : 2;
1941}
1942
1943namespace {
1944bool copyOut(const void* src, usize bytes, uintptr_t dest, u32 destSize) {
1945 if (!src || !dest || bytes == 0 || destSize < bytes) return false;
1946 std::memcpy(reinterpret_cast<void*>(dest), src, bytes);
1947 return true;
1948}
1949} // namespace
1950
1951bool renderer_copyCapturedRecords(uintptr_t dest, u32 destSize) {
1952 if (!g_renderFrame) return false;
1953 const auto& c = g_renderFrame->frameCapture();
1954 return copyOut(c.getRecords(), usize(c.getRecordCount()) * sizeof(DrawCallRecord), dest, destSize);
1955}
1956
1957bool renderer_copyCapturedEntities(uintptr_t dest, u32 destSize) {
1958 if (!g_renderFrame) return false;
1959 const auto& c = g_renderFrame->frameCapture();
1960 return copyOut(c.getEntities(), usize(c.getEntityCount()) * sizeof(Entity), dest, destSize);
1961}
1962
1963bool renderer_copyCapturedTextures(uintptr_t dest, u32 destSize) {
1964 if (!g_renderFrame) return false;
1965 const auto& c = g_renderFrame->frameCapture();
1966 return copyOut(c.getTextures(), usize(c.getTextureCount()) * sizeof(u32), dest, destSize);
1967}
1968
1969bool renderer_copySnapshot(uintptr_t dest, u32 destSize) {
1970 if (!g_renderFrame) return false;
1971 return copyOut(g_renderFrame->getSnapshotPixels(), g_renderFrame->getSnapshotSize(), dest, destSize);
1972}
1973
1975 if (!g_renderFrame) return 0;
1976 return reinterpret_cast<uintptr_t>(g_renderFrame->getSnapshotPixels());
1977}
1978
1980 if (!g_renderFrame) return 0;
1981 return g_renderFrame->getSnapshotSize();
1982}
1983
1985 if (!g_renderFrame) return 0;
1986 return g_renderFrame->getSnapshotWidth();
1987}
1988
1990 if (!g_renderFrame) return 0;
1991 return g_renderFrame->getSnapshotHeight();
1992}
1993
1994// =============================================================================
1995// Frame readback (what was drawn, from the backend that drew it)
1996// =============================================================================
1997
2004 auto* device = g_device;
2005 if (!device) return 0;
2006 return static_cast<u32>(device->captureNextFrame(w, h));
2007}
2008
2010 auto* device = g_device;
2011 if (!device || !g_renderFrame || w == 0 || h == 0) return 0;
2012 auto* rt = g_renderFrame->targetManager().get(target);
2013 if (!rt) return 0;
2014 return static_cast<u32>(device->requestReadback(rt->getFramebuffer(), w, h));
2015}
2016
2017bool renderer_takeTargetCapture(u32 handle, uintptr_t dest, u32 destSize) {
2018 auto* device = g_device;
2019 if (!device || !handle || !dest) return false;
2020 // A target is the engine's own RGBA, never a surface's BGRA: no swap, unlike a frame capture.
2021 return device->takeReadback(static_cast<ReadbackHandle>(handle), reinterpret_cast<void*>(dest), static_cast<usize>(destSize));
2022}
2023
2026 auto* device = g_device;
2027 if (!device || !handle) return 2;
2028 switch (device->pollReadback(static_cast<ReadbackHandle>(handle))) {
2029 case GfxReadbackStatus::Pending: return 0;
2030 case GfxReadbackStatus::Ready: return 1;
2031 default: return 2;
2032 }
2033}
2034
2042bool renderer_takeFrameCapture(u32 handle, uintptr_t dest, u32 destSize) {
2043 auto* device = g_device;
2044 if (!device || !handle || !dest) return false;
2045 if (!device->takeReadback(static_cast<ReadbackHandle>(handle),
2046 reinterpret_cast<void*>(dest), static_cast<usize>(destSize))) {
2047 return false;
2048 }
2049 if (device->frameCaptureIsBGRA()) {
2050 auto* px = reinterpret_cast<u8*>(dest);
2051 for (u32 i = 0; i + 3 < destSize; i += 4) std::swap(px[i], px[i + 2]);
2052 }
2053 return true;
2054}
2055
2057 if (!g_renderFrame || w <= 0 || h <= 0) return 0;
2058 return static_cast<u32>(g_renderFrame->createSkeletalPreview(
2059 static_cast<u32>(w), static_cast<u32>(h)));
2060}
2061
2063 u32 preview,
2064 uintptr_t verticesPtr, i32 vertexCount,
2065 uintptr_t indicesPtr, i32 indexCount,
2066 u32 textureId, i32 blendMode, uintptr_t transformPtr,
2067 i32 layer, f32 depth, u32 materialId
2068) {
2069 return renderer_submitSkeletalPreviewBatchEx(preview, verticesPtr, vertexCount, indicesPtr, indexCount, textureId, blendMode, transformPtr, layer, depth, materialId, blendMode == 4 || blendMode == 5);
2070}
2071
2073 u32 preview,
2074 uintptr_t verticesPtr, i32 vertexCount,
2075 uintptr_t indicesPtr, i32 indexCount,
2076 u32 textureId, i32 blendMode, uintptr_t transformPtr,
2077 i32 layer, f32 depth, u32 materialId, bool premultipliedColor
2078) {
2079 if (!g_renderFrame || vertexCount < 0 || indexCount < 0) return 0;
2080 // Skeletal vertex format is x,y,u,v,r,g,b,a (8 floats per vertex).
2081 auto* vertices = boundarySpan<f32>(verticesPtr, static_cast<u64>(vertexCount) * 8,
2082 "renderer_submitSkeletalPreviewBatch.vertices");
2083 auto* indices = boundarySpan<u16>(indicesPtr, static_cast<u64>(indexCount),
2084 "renderer_submitSkeletalPreviewBatch.indices");
2085 auto* transform = boundarySpan<f32>(transformPtr, 16,
2086 "renderer_submitSkeletalPreviewBatch.transform");
2087 if (!vertices || !indices || !transform) return 0;
2088 return g_renderFrame->submitSkeletalPreviewBatch(
2089 preview, vertices, vertexCount, indices, indexCount,
2090 textureId, blendMode, transform, layer, depth, materialId, premultipliedColor) ? 1 : 0;
2091}
2092
2093i32 renderer_renderSkeletalPreview(u32 preview, uintptr_t viewProjectionPtr) {
2094 if (!g_renderFrame) return 0;
2095 auto* vp = boundarySpan<f32>(viewProjectionPtr, 16, "renderer_renderSkeletalPreview.vp");
2096 if (!vp) return 0;
2097 glm::mat4 viewProjection{1.0f};
2098 std::memcpy(&viewProjection[0][0], vp, sizeof(f32) * 16);
2099 return g_renderFrame->renderSkeletalPreview(preview, viewProjection) ? 1 : 0;
2100}
2101
2103 return g_renderFrame ? g_renderFrame->pollSkeletalPreview(preview) : 2;
2104}
2105
2107 return g_renderFrame
2108 ? reinterpret_cast<uintptr_t>(g_renderFrame->skeletalPreviewPixels(preview)) : 0;
2109}
2110
2112 return g_renderFrame ? g_renderFrame->skeletalPreviewSize(preview) : 0;
2113}
2114
2116 return g_renderFrame ? g_renderFrame->skeletalPreviewWidth(preview) : 0;
2117}
2118
2120 return g_renderFrame ? g_renderFrame->skeletalPreviewHeight(preview) : 0;
2121}
2122
2124 if (g_renderFrame) g_renderFrame->destroySkeletalPreview(preview);
2125}
2126
2127namespace {
2128// The angle previews are seen from: off-axis, above and to the right, unless an inspector is turning one. Degrees.
2129f32 g_previewYaw = 30.96f;
2130f32 g_previewPitch = 21.10f;
2131glm::vec3 previewEyeDirection() {
2132 const f32 yaw = glm::radians(g_previewYaw), pitch = glm::radians(glm::clamp(g_previewPitch, -89.0f, 89.0f));
2133 return glm::vec3(std::sin(yaw) * std::cos(pitch), std::sin(pitch), std::cos(yaw) * std::cos(pitch));
2134}
2135
2136// A preview is one picture, read back once: a program still compiling in the background would leave it empty, and the
2137// next one asks for a freshly loaded material whose program is compiling again. So a preview waits for its programs.
2138struct WaitForPrograms {
2139 GfxDevice* device;
2140 bool was;
2141 WaitForPrograms() : device(g_device), was(g_device && g_device->skipPendingPrograms()) {
2142 if (device) device->setSkipPendingPrograms(false);
2143 }
2144 ~WaitForPrograms() { if (device) device->setSkipPendingPrograms(was); }
2145 WaitForPrograms(const WaitForPrograms&) = delete;
2146 WaitForPrograms& operator=(const WaitForPrograms&) = delete;
2147};
2148} // namespace
2149
2150void renderer_setPreviewOrbit(f32 yawDegrees, f32 pitchDegrees) {
2151 g_previewYaw = std::isfinite(yawDegrees) ? yawDegrees : 30.96f;
2152 g_previewPitch = std::isfinite(pitchDegrees) ? pitchDegrees : 21.10f;
2153}
2154
2155void renderer_renderMaterialPreview(u32 materialId, i32 w, i32 h, u32 meshId, u32 textureId) {
2156 if (!g_renderFrame || w <= 0 || h <= 0) return;
2157 const WaitForPrograms wait;
2158
2159 ecs::Registry reg;
2160 auto light = reg.create();
2161 reg.emplace<ecs::Transform>(light);
2162 reg.emplace<ecs::Light>(light).type = static_cast<i32>(ecs::LightType::Directional);
2163 // A shape of the caller's choosing: the material on a mesh, seen off-axis and framed to the
2164 // mesh's own bounds (a ball seen from one side is a disc), lit by one directional light.
2165 auto* rm = meshId != 0 ? ctx().tryGet<resource::ResourceManager>() : nullptr;
2166 const Mesh* res = rm ? rm->getMesh(resource::MeshHandle{meshId}) : nullptr;
2167 if (res) {
2168 auto entity = reg.create();
2169 reg.emplace<ecs::Transform>(entity);
2170 auto& mesh = reg.emplace<ecs::MeshRenderer>(entity);
2171 mesh.mesh = resource::MeshHandle{meshId};
2172 mesh.material = materialId;
2173 mesh.lit = true;
2174 mesh.opaque = true;
2175 // By id, not through a reference held across the emplace above: it can have moved.
2176 reg.get<ecs::Transform>(light).position = glm::vec3(0.0f, 0.0f, 1.0f);
2177
2178 if (g_transformSystem) {
2179 esengine::World world{reg, ctx().services(), 0.0f};
2180 g_transformSystem->update(world);
2181 }
2182
2183 const glm::vec3 centre = (res->localMin + res->localMax) * 0.5f;
2184 const f32 radius = std::max(glm::length(res->localMax - res->localMin) * 0.5f, 1e-4f);
2185 const glm::vec3 eye = centre + previewEyeDirection() * (radius * 4.0f);
2186 const glm::mat4 view = glm::lookAt(eye, centre, glm::vec3(0.0f, 1.0f, 0.0f));
2187 f32 half = 1e-4f;
2188 for (i32 corner = 0; corner < 8; ++corner) {
2189 const glm::vec3 world{
2190 (corner & 1) ? res->localMax.x : res->localMin.x,
2191 (corner & 2) ? res->localMax.y : res->localMin.y,
2192 (corner & 4) ? res->localMax.z : res->localMin.z,
2193 };
2194 const glm::vec3 v = glm::vec3(view * glm::vec4(world, 1.0f));
2195 half = std::max({half, std::abs(v.x), std::abs(v.y)});
2196 }
2197 half *= 1.08f;
2198 const glm::mat4 proj = math::ortho(-half, half, -half, half, 0.01f, radius * 8.0f);
2199 g_renderFrame->renderToTarget(reg, proj * view, static_cast<u32>(w), static_cast<u32>(h));
2200 return;
2201 }
2202
2203 // Otherwise a 2×2 quad filling the ortho [-1,1] with the material — a sprite, so a sprite shader
2204 // gets the picture it samples (`textureId`, 0 = none).
2205 auto quad = reg.create();
2206 reg.emplace<ecs::Transform>(quad);
2207 auto& sprite = reg.emplace<ecs::Sprite>(quad);
2208 sprite.material = materialId;
2209 sprite.size = glm::vec2(2.0f, 2.0f);
2210 if (textureId != 0) sprite.texture = resource::TextureHandle{textureId};
2211
2212 if (g_transformSystem) {
2213 esengine::World world{reg, ctx().services(), 0.0f};
2214 g_transformSystem->update(world);
2215 }
2216
2217 const glm::mat4 vp = math::ortho(-1.0f, 1.0f, -1.0f, 1.0f, -1.0f, 1.0f);
2218 g_renderFrame->renderToTarget(reg, vp, static_cast<u32>(w), static_cast<u32>(h));
2219}
2220
2228 if (!g_renderFrame || w <= 0 || h <= 0) return;
2229 const WaitForPrograms wait;
2230 auto* rm = ctx().tryGet<resource::ResourceManager>();
2231 const Mesh* res = rm ? rm->getMesh(resource::MeshHandle{meshId}) : nullptr;
2232 if (!res) return;
2233
2234 ecs::Registry reg;
2235 auto entity = reg.create();
2236 reg.emplace<ecs::Transform>(entity);
2237 auto& mesh = reg.emplace<ecs::MeshRenderer>(entity);
2238 mesh.mesh = resource::MeshHandle{meshId};
2239 mesh.lit = true;
2240 mesh.opaque = true;
2241
2242 auto light = reg.create();
2243 auto& lightTransform = reg.emplace<ecs::Transform>(light);
2244 lightTransform.position = glm::vec3(0.0f, 0.0f, 1.0f);
2245 reg.emplace<ecs::Light>(light).type = static_cast<i32>(ecs::LightType::Directional);
2246
2247 if (g_transformSystem) {
2248 esengine::World world{reg, ctx().services(), 0.0f};
2249 g_transformSystem->update(world);
2250 }
2251
2252 // Frame the mesh's own bounds: an .esmesh is authored at whatever scale its
2253 // source used, so a fixed box would show one model whole and another as a dot.
2254 const glm::vec3 centre = (res->localMin + res->localMax) * 0.5f;
2255 const f32 radius = std::max(glm::length(res->localMax - res->localMin) * 0.5f, 1e-4f);
2256 const glm::vec3 eye = centre + previewEyeDirection() * (radius * 4.0f);
2257 const glm::mat4 view = glm::lookAt(eye, centre, glm::vec3(0.0f, 1.0f, 0.0f));
2258
2259 // The box is measured AFTER the turn: a flat model seen off-axis is much
2260 // smaller than its diagonal, and framing by the diagonal draws it as a stamp
2261 // in the middle of an empty thumbnail.
2262 f32 half = 1e-4f;
2263 for (i32 corner = 0; corner < 8; ++corner) {
2264 const glm::vec3 world{
2265 (corner & 1) ? res->localMax.x : res->localMin.x,
2266 (corner & 2) ? res->localMax.y : res->localMin.y,
2267 (corner & 4) ? res->localMax.z : res->localMin.z,
2268 };
2269 const glm::vec3 v = glm::vec3(view * glm::vec4(world, 1.0f));
2270 half = std::max({half, std::abs(v.x), std::abs(v.y)});
2271 }
2272 half *= 1.08f;
2273 const glm::mat4 proj = math::ortho(-half, half, -half, half, 0.01f, radius * 8.0f);
2274 g_renderFrame->renderToTarget(reg, proj * view, static_cast<u32>(w), static_cast<u32>(h));
2275}
2276
2277// Same 0/1/2 contract as renderer_pollSnapshotReadback, for the material preview.
2279 return g_renderFrame ? g_renderFrame->pollPreviewReadback() : 2;
2280}
2281
2283 return g_renderFrame ? reinterpret_cast<uintptr_t>(g_renderFrame->getPreviewPixels()) : 0;
2284}
2285
2287 return g_renderFrame ? g_renderFrame->getPreviewSize() : 0;
2288}
2289
2291 return g_renderFrame ? g_renderFrame->getPreviewWidth() : 0;
2292}
2293
2295 return g_renderFrame ? g_renderFrame->getPreviewHeight() : 0;
2296}
2297
2298void renderer_setTextureParams(u32 textureId, i32 minFilter, i32 magFilter, i32 wrapS, i32 wrapT) {
2299 auto* device = g_device;
2300 if (!device) return;
2301 device->setTextureParams(
2302 TextureHandle{textureId},
2303 static_cast<TextureFilter>(minFilter),
2304 static_cast<TextureFilter>(magFilter),
2305 static_cast<TextureWrap>(wrapS),
2306 static_cast<TextureWrap>(wrapT)
2307 );
2308}
2309
2310} // namespace esengine
2311
Always-on validation for JS-supplied pointer+length pairs at the WASM boundary.
Camera component for rendering viewpoints.
Canvas component for 2D game resolution management.
Custom geometry for user-defined mesh rendering.
Per-frame CPU scope timing (ES_PROFILE_SCOPE) read by the editor profiler.
#define g_initialized
#define g_device
Abstract graphics device interface.
Particles simulated by a compute kernel, drawn from the buffer the kernel wrote (WebGPU).
Hierarchy components for parent-child relationships.
#define g_viewportWidth
#define g_viewportHeight
Immediate mode 2D drawing API.
Which lights reached the frame, and who was turned away.
2D light source component for the Lit material domain.
Which representation an object's size on screen asks for.
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
Arbitrary-geometry 2D mesh renderable (deformed sprites, polygons, water surfaces,...
Conservative mesh reach and affine stretch for native placements.
The engine's randomness, and the only place its seed lives.
Central ECS registry for entity and component management.
Rendering context containing all renderer state.
Frame resources and the shared scene rendering contract.
#define g_transformSystem
#define g_trailSystem
#define g_glErrorCheckEnabled
#define g_renderFrame
#define g_springBoneSystem
Central resource management system.
Glyph geometry the engine keeps between frames, and the clipping of it against a view.
Parser for unified .esshader file format.
What each caster asked the shadow atlas for, and what it got.
Skinned meshes posed once a frame by a compute shader, into vertices every pass then draws as they ar...
Per-App secondary motion: runs every SpringBone chain after the animation has posed the skeleton and ...
2D sprite rendering component
Adapters that exist only to let a driver run an experiment.
Per-App motion-trail simulation: records each TrailRenderer entity's world position over time into a ...
System for computing hierarchical world transforms.
Unified Transform component with local and world-space data.
The UI entry points the SDK drives: the Yoga layout pass, hit testing, draw order,...
UI subsystem owning layout tree and hit-test state.
Unified context passed to all ECS systems.
The two halves of an image-based light, as the importer baked them.
bool hasSun
The sun the importer found in the panorama: the one compact source a directional light can stand in f...
std::array< glm::vec3, 9 > skyIrradiance
ServiceRegistry & services()
RenderThread & renderThread()
std::string lastGpuJson() const
std::string lastJson() const
std::string lastCountersJson() const
static FrameProfiler & get()
Buffers, the layout that describes them, and the bounds culling reads.
Definition Mesh.hpp:85
glm::vec3 localMin
Definition Mesh.hpp:143
glm::vec3 localMax
Definition Mesh.hpp:144
The frame's probe volumes, and the trilinear read through them.
u32 atlasTexture() const
u32 perObjectDraws() const
u64 atlasBytes() const
What the atlas takes on the GPU: four half floats a texel, no mips. What a sparse grid saves is here.
u32 perPixelDraws() const
Irradiance at a grid of points — an Environment sampled, not held.
u64 revision
Changes whenever the coefficients do (a new grid, its sky visibility set): what the frame's probe atl...
static u64 nextRevision()
u32 probeCount() const
The probes the coefficients hold: the grid's for a dense one, kBrickProbes a brick for a sparse one.
std::vector< f32 > skyVisibility
How much of the sky each probe sees: nine coefficients per probe, cosine-convolved like the irradianc...
static constexpr i32 kBrickProbes
bool complete(Fence value) const
u32 drawsThisFrame() const
Definition SkinCache.hpp:96
u32 refusedThisFrame() const
Definition SkinCache.hpp:91
bool active() const
u32 entryCount() const
Definition SkinCache.hpp:89
u64 bytesUsed() const
Definition SkinCache.hpp:88
u32 scheduledThisFrame() const
Definition SkinCache.hpp:93
Central container for all entities and components.
Definition Registry.hpp:73
bool isEntityActive(Entity e) const
Definition Registry.hpp:115
double entityChangeResetEpoch() const
Definition Registry.hpp:131
double entityChangeSequence() const
Definition Registry.hpp:130
void unwatchEntityChanges(u32 reader)
Definition Registry.hpp:129
T & get(Entity entity)
Gets a component from an entity (must exist).
Definition Registry.hpp:649
bool has(Entity entity) const
Checks if an entity has a specific component.
Definition Registry.hpp:711
double componentMutationRevision(u32 component, bool topology) const
Definition Registry.hpp:134
void markChangedById(u32 typeId, Entity entity)
markChanged by a component type id (componentTypeId): for a writer that names the type at run time,...
Definition Registry.hpp:201
void markChanged(Entity entity)
Says entity's T was written, through a reference held from before.
Definition Registry.hpp:196
bool valid(Entity entity) const
Checks if an entity is currently valid.
Definition Registry.hpp:518
i32 readEntityChanges(double after, std::span< EntityChangeRow > output) const
Definition Registry.hpp:137
Entity create()
Creates a new entity.
Definition Registry.hpp:371
T * tryGet(Entity entity)
Tries to get a component from an entity.
Definition Registry.hpp:670
T & emplace(Entity entity, Args &&... args)
Adds a component to an entity with in-place construction.
Definition Registry.hpp:576
View< Components... > view()
Creates a view for iterating entities with specific components.
Definition Registry.hpp:761
UI subsystem: owns layout tree + hit-test state.
Definition UISystem.hpp:56
const std::unordered_set< u32 > & screenDomain() const
Every entity that belongs to the SCREEN, as opposed to the world.
Definition UISystem.hpp:135
IdType id() const
Gets the packed identifier (index + generation).
Definition Handle.hpp:85
Central manager for GPU resources.
MeshHandle createMesh(ConstSpan< u8 > vertexBytes, ConstSpan< u32 > indices, ConstSpan< GfxVertexAttribute > channels, u32 vertexStride, const glm::vec3 &localMin, const glm::vec3 &localMax, MeshRecovery recovery, ConstSpan< f32 > inverseBind={}, const MeshMorphSource &morph={})
bool rematerializeMesh(MeshHandle target, ConstSpan< u8 > vertexBytes, ConstSpan< u32 > indices, ConstSpan< GfxVertexAttribute > channels, u32 vertexStride, const glm::vec3 &localMin, const glm::vec3 &localMax, ConstSpan< f32 > inverseBind={}, const MeshMorphSource &morph={})
Puts new geometry behind an EXISTING mesh handle.
static void setLinearColorSpace(bool linear)
Process-global color-space mode. When linear, every assembled stage compiles with ES_LINEAR defined (...
static constexpr u32 ENTITY_CHANGE_CAPACITY
void applySceneEntityOrder(Registry &registry, const Entity *order, usize count)
Applies a scene's authored entity order to the whole world.
void invalidateTransformComposition()
Say that composed world transforms are stale.
constexpr u8 kCulled
The level of an object small enough that nothing is drawn for it.
glm::mat4 ortho(float left, float right, float bottom, float top, float nearPlane, float farPlane)
Creates an orthographic projection matrix.
Definition Math.hpp:201
f32 stretchSquared(const f32 *rows)
Handle< esengine::Environment > EnvironmentHandle
Handle to a baked environment (irradiance + prefiltered reflection).
Definition Handle.hpp:229
Handle< esengine::Texture > TextureHandle
Handle to a texture resource.
Definition Handle.hpp:217
Handle< esengine::ProbeVolume > ProbeVolumeHandle
Handle to a grid of baked irradiance.
Definition Handle.hpp:232
Handle< esengine::Mesh > MeshHandle
Handle to GPU-resident geometry.
Definition Handle.hpp:226
u32 renderer_queueMaterialBake(u32 material, u32 shader, u32 target, u32 x, u32 y, u32 w, u32 h, f32 a0, f32 a1, f32 a2, f32 a3, f32 b0, f32 b1, f32 b2, f32 b3)
void renderer_setImpostorAtlas(u32 entity, u32 texture, u32 frames)
Hand entity's Impostor the atlas it draws from: texture holds frames x frames pictures.
void renderThread_flush()
void renderer_releaseTarget(u32 handle)
u32 renderer_getPreviewSize()
u32 renderer_getSkeletalPreviewSize(u32 preview)
const T * boundarySpan(uintptr_t ptr, u64 count, const char *what)
Validates a JS-supplied pointer to count elements of T and returns it typed.
void engine_setRandomSeed(u32 seed)
TextGlyphMode textGlyphModeFromRaw(i32 raw)
The mode a raw script-side value names; anything out of range is Color, the draw that cannot be wrong...
f32 renderer_getGpuTimeMs()
u32 mesh_createFromChannels(uintptr_t channelsPtr, u32 channelCount, u32 vertexStride, uintptr_t vertexPtr, u32 vertexBytes, uintptr_t indexPtr, u32 indexCount, f32 minX, f32 minY, f32 minZ, f32 maxX, f32 maxY, f32 maxZ, uintptr_t bindPtr, u32 bindFloats, uintptr_t morphPtr, u32 morphFloats, u32 morphTargets, u32 morphNormals)
Geometry from an .esmesh channel table; returns its handle, 0 on failure.
void renderer_setTargetPoolIdleBudget(u32 megabytes)
void renderer_setViewId(u32 view)
void renderer_setAsyncComputeEnabled(bool enabled)
static const std::unordered_set< u32 > * screenDomain()
void meshInstances_set(ecs::Registry &registry, u32 entity, uintptr_t dataPtr, u32 count)
The placements of a MeshInstances: sixteen f32 an instance (see the component). Empty clears the set.
std::int32_t i32
Signed 32-bit integer.
Definition Types.hpp:54
void renderer_setProbeVolumeOverride(u32 entity, u32 volumeHandle)
void renderer_setDepthPrepass(bool on)
i32 renderer_retainedTextStale(ecs::Registry &registry, uintptr_t outPtr, i32 capacity)
The entities whose retained text no longer matches the world, written to outPtr as u32s.
u32 renderer_getSkeletal()
u32 renderer_getSnapshotHeight()
u32 gl_checkErrors(const std::string &context)
static void ensureTransformsUpdated(ecs::Registry &registry)
std::string renderer_getPendingProgramLabels()
What each program still compiling in the background is, one per line: its id and what it was made for...
bool renderer_takeFrameCapture(u32 handle, uintptr_t dest, u32 destSize)
void renderer_setOcclusionGridSize(u32 size)
u32 renderer_getCapturedEntityCount()
u32 probe_volume_create(i32 resX, i32 resY, i32 resZ, uintptr_t shPtr)
Registers a grid of baked irradiance — an environment sampled at points.
void springbone_release(ecs::Registry &registry, u32 entity)
bool renderer_takeProbeCapture(uintptr_t dst, u32 bytes)
uintptr_t renderer_getSnapshotPtr()
void renderer_setRetainedTextCollected(bool collected)
The frame draws the retained labels in its own collects from now on, and renderer_retainedTextSubmit ...
bool renderer_snapshotMatchesCapture()
void environment_setSun(u32 environmentHandle, uintptr_t skyShPtr, f32 dx, f32 dy, f32 dz, f32 r, f32 g, f32 b)
Gives an environment the sun its importer separated from the sky.
f64 renderer_getSkinCacheStat(i32 which)
The skin cache's state: 0 active, 1 meshes held, 2 bytes held, 3 refused this frame by the budget,...
void renderer_setProbesPerPixel(bool on)
Whether meshes read their probe volume per pixel (true, the default) or per object,...
std::uint64_t u64
Unsigned 64-bit integer.
Definition Types.hpp:47
void renderer_setPlanarReflectionQuality(f32 scale, u32 maxSize, f32 updatesPerSecond, bool capAuthored)
uintptr_t renderer_getCapturedFrameData()
i32 renderer_materialBakeState(u32 ticket)
0 waiting, 1 drawn, -1 not drawable; a drawn or failed ticket is forgotten once asked.
i32 renderer_submitSkeletalPreviewBatch(u32 preview, uintptr_t verticesPtr, i32 vertexCount, uintptr_t indicesPtr, i32 indexCount, u32 textureId, i32 blendMode, uintptr_t transformPtr, i32 layer, f32 depth, u32 materialId)
i32 renderer_pollFrameCapture(u32 handle)
u32 renderer_getGpuDrawCalls()
Every draw the GPU was asked for in the last frame, every pass included (shadows, prepass,...
bool renderer_setQualityValue(const std::string &name, f32 value)
void renderer_endScreenOverlay(u32 targetHandle)
u32 springbone_snapshot(ecs::Registry &registry, u32 entity)
i32 renderer_pollPreviewReadback()
void renderer_begin(uintptr_t matrixPtr, u32 targetHandle, i32 clearFlags, f32 r, f32 g, f32 b, f32 a, i32 clearX, i32 clearY, u32 clearW, u32 clearH)
void trail_update(ecs::Registry &registry, f32 dt)
void registry_markComponentsChanged(ecs::Registry &registry, uintptr_t pairsPtr, int count)
bool renderThread_complete(f64 fence)
void renderer_setTextureParams(u32 textureId, i32 minFilter, i32 magFilter, i32 wrapS, i32 wrapT)
void renderer_renderMaterialPreview(u32 materialId, i32 w, i32 h, u32 meshId, u32 textureId)
std::string renderer_takeTextureWants()
What size each texture was asked for since the last call, as handle:side pairs joined by commas,...
constexpr i32 TEXT_VERTEX_FLOATS
void renderer_submitScreenOverlay(ecs::Registry &registry)
void renderer_setParticleDepthGrid(u32 texels)
bool probe_volume_getResolution(u32 volumeHandle, uintptr_t outPtr)
The finest grid's probes along x, y and z, as three ints at outPtr. False for no such volume.
u32 renderer_getPreviewWidth()
void renderer_setLodPreview(u32 view, u32 entity, i32 level)
Draw level for entity in view instead of the chosen one; a negative level goes back to the view's own...
void renderer_renderMeshPreview(u32 meshId, i32 w, i32 h)
u32 renderer_createSkeletalPreview(i32 w, i32 h)
bool renderer_hasCapturedData()
u32 mesh_setSkinChunks(u32 meshHandle, uintptr_t chunksPtr, u32 chunkCount, uintptr_t bonesPtr, u32 boneCount)
Gives a skinned mesh the chunks it is drawn in: chunkCount records of three u32 (first index,...
void registry_unwatchEntityChanges(ecs::Registry &registry, u32 reader)
std::size_t usize
Size type for indexing and sizes.
Definition Types.hpp:64
u32 renderer_getTriangles()
u32 meshRenderer_setMaterialAll(ecs::Registry &registry, u32 materialId)
Points every MeshRenderer at one material; returns how many.
void renderer_setViewShading(u32 view, i32 mode)
Shade a view's meshes as authored (0), as neutral clay (1), as flat albedo (2), as wireframe (3),...
void renderer_submitSkeletalBatchByEntityEx(ecs::Registry &registry, uintptr_t verticesPtr, i32 vertexCount, uintptr_t indicesPtr, i32 indexCount, u32 textureId, i32 blendMode, u32 entity, f32 skelScale, bool flipX, bool flipY, i32 layer, f32 depth, u32 materialId, bool premultipliedColor)
i32 renderer_pollProbeCapture()
@ SourceReplayable
Replayable from an asset the loader can load again.
Definition Mesh.hpp:29
@ HostOnly
Built in this process; the device keeps its bytes.
Definition Mesh.hpp:30
constexpr Entity INVALID_ENTITY
Invalid entity sentinel value.
Definition Types.hpp:174
u32 renderer_createTarget(u32 width, u32 height, i32 flags)
void springbone_reset(ecs::Registry &registry, u32 entity)
void renderer_setTreeSortLayers(u32 mask)
void renderer_beginFrame(f32 elapsedSec)
u32 renderer_getSprites()
void renderer_setShadowDistance(f32 distance)
T * boundarySpanMut(uintptr_t ptr, u64 count, const char *what)
Mutable variant of boundarySpan, for entry points that WRITE into a JS buffer.
void meshRenderer_setGeometry(ecs::Registry &registry, u32 entity, uintptr_t posUvPtr, u32 vertexCount, uintptr_t colorsPtr, uintptr_t indicesPtr, u32 indexCount)
void renderer_setLightingDirect(bool on)
u32 renderer_getDrawsWaitingForProgram()
Scene draws the last frame left out because a program they use was still compiling in the background.
void renderer_setLodDistanceScale(f32 scale)
void environment_release(u32 environmentHandle)
Releases an environment. Its atlas is an ordinary texture and outlives it.
u32 renderer_captureTarget(u32 target, u32 w, u32 h)
void renderer_retainedTextBatch(u32 entity, uintptr_t verticesPtr, i32 vertexCount, uintptr_t indicesPtr, i32 indexCount, u32 pageId, i32 glyphMode)
bool renderer_getAsyncComputeEnabled()
u32 renderer_getPreviewHeight()
void springbone_update(ecs::Registry &registry, f32 dt)
bool renderer_takeTargetCapture(u32 handle, uintptr_t dest, u32 destSize)
std::string engine_getGpuScopes()
bool renderer_projectMaterialBake(u32 ticket, u32 material, u32 target, u32 instances)
Attach an additive, instanced projection to the just-queued material bake. Both run before the scene.
i32 renderer_renderSkeletalPreview(u32 preview, uintptr_t viewProjectionPtr)
void renderer_requestProbeCapture(f32 x, f32 y, f32 z, u32 face)
void renderer_setShadow2DSoftSamples(u32 samples)
static constexpr u32 MAX_VERTEX_ATTRIBUTES
Definition GfxEnums.hpp:217
void renderer_retainedTextClear(u32 entity)
Forgets an entity's retained text.
LightRefusal
Why a light did not reach the frame.
Definition LightPlan.hpp:25
void renderer_endFrame()
u32 renderer_getSnapshotWidth()
void probe_volume_release(u32 volumeHandle)
Releases a probe volume.
void renderer_setColorSpace(u32 linear)
u32 meshRenderer_setMeshAll(ecs::Registry &registry, u32 meshHandle)
Points every MeshRenderer at one resident mesh; returns how many.
ParallaxAnchor & parallaxAnchor()
bool renderThread_enabled()
i32 renderer_lodInspect(u32 view, u32 entity, uintptr_t outPtr)
What view decided about entity's LOD, into four floats at outPtr: level, the level the bare threshold...
void renderer_setClearColor(f32 r, f32 g, f32 b, f32 a)
int registry_readWorldPoses2D(ecs::Registry &registry, uintptr_t entitiesPtr, int count, uintptr_t outputPtr)
bool renderer_copyCapturedEntities(uintptr_t dest, u32 destSize)
i32 renderer_pollSnapshotReadback()
u32 renderer_getSkeletalPreviewWidth(u32 preview)
uintptr_t renderer_getPreviewPtr()
u32 renderer_getCapturedFrameSize()
u32 mesh_rematerializeFromChannels(u32 targetHandle, uintptr_t channelsPtr, u32 channelCount, u32 vertexStride, uintptr_t vertexPtr, u32 vertexBytes, uintptr_t indexPtr, u32 indexCount, f32 minX, f32 minY, f32 minZ, f32 maxX, f32 maxY, f32 maxZ, uintptr_t bindPtr, u32 bindFloats, uintptr_t morphPtr, u32 morphFloats, u32 morphTargets, u32 morphNormals)
Releases a mesh and the buffers it owns.
void renderer_replayToDrawCall(i32 drawCallIndex)
u32 renderer_getTargetDepthTexture(u32 handle)
uintptr_t renderer_getCapturedTextures()
void renderer_setCullingMask(u32 mask)
void renderer_setViewport(i32 x, i32 y, i32 w, i32 h)
void setRenderOrigin(const glm::dvec3 &origin)
u32 environment_create(uintptr_t shPtr, u32 specularHandle, f32 faceSize, u32 mipCount, f32 maxRange, u32 columns)
Registers a baked environment: nine irradiance coefficients and the prefiltered reflection an ambient...
u32 renderer_getSnapshotSize()
i32 renderer_pollSkeletalPreview(u32 preview)
void renderer_init(u32 width, u32 height)
Points a MeshRenderer at resident geometry; 0 returns it to its inline payload.
void renderer_setViewSkinWeights(u32 view, u32 entity, i32 joint)
Colour one skinned entity in a view by how much a joint moves each vertex.
std::span< const T > ConstSpan
Definition Types.hpp:242
void renderer_setScreenOverlayEffect(u32 material)
f64 renderer_getEstimatedGpuBytes()
f64 renderThread_fence()
void renderer_setAsyncShaderCompile(bool on)
i32 renderer_framePending()
1 while the GPU is still working on the frame last ended (GfxDevice::framePending); asks without wait...
MeshChannelType
How a channel's components are stored, as the file spells it.
Definition GfxEnums.hpp:188
@ UNorm16
Skin weights at high precision.
Definition GfxEnums.hpp:195
@ UInt8
Joint indices of a skin or chunk of at most 256 bones: a byte each.
Definition GfxEnums.hpp:193
void renderer_resize(u32 width, u32 height)
uintptr_t springbone_snapshotData()
void renderer_submitSkeletalBatchByEntity(ecs::Registry &registry, uintptr_t verticesPtr, i32 vertexCount, uintptr_t indicesPtr, i32 indexCount, u32 textureId, i32 blendMode, u32 entity, f32 skelScale, bool flipX, bool flipY, i32 layer, f32 depth, u32 materialId)
void renderer_drawOverScreen(i32 vpX, i32 vpY, u32 vpW, u32 vpH, u32 targetHandle)
const std::unordered_map< u32, i32 > * uiTreeLayers()
uintptr_t renderer_getSkeletalPreviewPtr(u32 preview)
void mesh_release(u32 meshHandle)
static std::vector< f32 > & springBoneSnapshot()
void renderer_setQualityBudgets(u32 atlasSize, u32 cellSize, u32 cascades, u32 particleLimit)
bool retainedTextAutoIsSdf(f32 worldScaleX)
void renderer_beginScreenOverlay(uintptr_t projectionPtr, i32 vpX, i32 vpY, u32 vpW, u32 vpH)
uintptr_t renderer_getCapturedEntities()
u32 springbone_snapshotCount()
u32 probe_volume_createBricks(i32 resX, i32 resY, i32 resZ, i32 brickCount, uintptr_t bricksPtr, uintptr_t shPtr)
Registers a sparse grid of baked irradiance: brickCount bricks of four ints (first finest-brick cell ...
std::uint32_t u32
Unsigned 32-bit integer.
Definition Types.hpp:45
void renderer_flush()
void renderer_submitAll(ecs::Registry &registry, i32 vpX, i32 vpY, i32 vpW, i32 vpH)
bool renderer_supportsAsyncCompute()
void renderer_diagnose()
u32 renderer_getProbeDraws(bool perPixel)
Draws that read a probe volume last frame: per pixel when perPixel, else per object.
i32 renderer_submitSkeletalPreviewBatchEx(u32 preview, uintptr_t verticesPtr, i32 vertexCount, uintptr_t indicesPtr, i32 indexCount, u32 textureId, i32 blendMode, uintptr_t transformPtr, i32 layer, f32 depth, u32 materialId, bool premultipliedColor)
void registry_batchSyncPhysicsTransforms(ecs::Registry &registry, uintptr_t bufferPtr, int count, float ppu)
double registry_entityChangeSequence(ecs::Registry &registry)
i32 renderer_shadowStatus(u32 entity, uintptr_t outPtr)
What the shadow atlas gave entity last frame, into five floats at outPtr: requested,...
std::uint8_t u8
Unsigned 8-bit integer.
Definition Types.hpp:41
void renderer_retainedTextSubmit(ecs::Registry &registry, i32 screen, uintptr_t projectionPtr)
void renderer_setViewSelection(u32 view, uintptr_t idsPtr, u32 count)
The editor's selection in view, outlined on screen: count entity ids at idsPtr; zero clears it.
bool renderer_copySnapshot(uintptr_t dest, u32 destSize)
ShadingMode
What a mesh is drawn WITH in a view, whatever its own material says.
@ Shaded
Each mesh as authored: its material, its textures, its light.
void renderer_setPreviewOrbit(f32 yawDegrees, f32 pitchDegrees)
The angle the next mesh or material preview is seen from, degrees: yaw about up, pitch above the hori...
std::uint16_t u16
Unsigned 16-bit integer.
Definition Types.hpp:43
void renderer_submitTextBatch(uintptr_t verticesPtr, i32 vertexCount, uintptr_t indicesPtr, i32 indexCount, u32 textureId, uintptr_t transformPtr, u32 entity, i32 layer, f32 depth, i32 glyphMode, u32 cullBit)
void renderer_destroySkeletalPreview(u32 preview)
bool renderer_copyCapturedRecords(uintptr_t dest, u32 destSize)
void renderer_captureNextFrame()
std::string engine_getCounters()
void engine_prepareMeshPrograms(u32 rowsPtr, u32 count, u32 outPtr)
Readies the mesh programs a prepared cell requires, and reports what a readiness claim must record (l...
void renderer_setMeshEdgeBuffers(bool enabled)
Give meshes realized from now on an edge buffer, for a wireframe view.
u32 renderer_getCapturedTextureCount()
void renderer_setViewLighting(u32 mode, f32 rotationDegrees, f32 keyIntensity, f32 fillIntensity, f32 skyIntensity, bool showSky)
double f64
64-bit floating point
Definition Types.hpp:61
void renderer_setSkinCache(i32 enabled, i32 behavior, f32 maxMegabytes)
The project's skin cache: on or off, which meshes go through it when their MeshSkin says Auto (0 ever...
u32 renderer_captureFrame(u32 w, u32 h)
void renderer_setDepthLayers(u32 mask)
void engine_setCpuProfiling(bool on)
void renderer_setOrigin(f64 x, f64 y, f64 z)
The point the next frames are drawn relative to (RenderOrigin.hpp); the view-projection they are begu...
void renderer_retainedTextBegin(u32 entity, i32 sdf, i32 screen, i32 hasBox, i32 layer, f32 boxWidth, f32 boxHeight, i32 autoKind)
i32 renderer_clusterInspect(u32 entity, uintptr_t outPtr)
What the last frames drew of entity's Cluster LOD mesh: triangles and clusters, two u32 at outPtr; 0 ...
u32 renderer_getCapturedPassCount()
double registry_entityChangeResetEpoch(ecs::Registry &registry)
void gl_enableErrorCheck(bool enabled)
f64 renderer_getTextureBytes()
u32 renderer_getPendingShaders()
void renderer_setStage(i32 stage)
void renderer_setQualityConstants(f32 x, f32 y, f32 z, f32 w)
i32 renderer_lightStatus(u32 entity, uintptr_t outPtr)
What the light cap did to entity last frame, into nine floats at outPtr: accepted,...
u32 mesh_setClusters(u32 meshHandle, uintptr_t clustersPtr, u32 clusterCount, uintptr_t indexPtr, u32 indexCount)
Releases a mesh and the buffers it owns.
f64 renderer_programEpoch()
The renderer's current program-readiness epoch. A readiness record stamped with an older one names pr...
void setPendingRandomSeed(u32 seed)
f64 renderer_getProbeAtlasBytes()
What the frame's probe atlas takes on the GPU, in bytes (0 while nothing reads per pixel).
u32 renderer_getTargetTexture(u32 handle)
constexpr u8 kShadingModeCount
void renderer_setEntityDrawOrder(ecs::Registry &registry, uintptr_t entitiesPtr, u32 count)
static EstellaContext & ctx()
EstellaContext & activeCtx()
The engine context every binding routes through — single source of truth.
void renderer_setParallaxAnchor(bool set, f64 x, f64 y)
void renderer_updateTransforms(ecs::Registry &registry)
f64 renderer_deviceGeneration()
Which generation of the GPU device is current. Not part of a readiness claim — the guard that says th...
void trail_clear(ecs::Registry &registry, u32 entity)
void renderer_setWorldUnitsPerMeter(f32 units)
double registry_componentMutationRevision(ecs::Registry &registry, u32 component, bool topology)
u32 renderer_getSkeletalPreviewHeight(u32 preview)
u32 registry_getGeneration(ecs::Registry &registry, u32 entity)
bool renderer_keepScreenOverlay(ecs::Registry &registry, bool hostStill)
bool renderer_copyCapturedTextures(uintptr_t dest, u32 destSize)
i32 registry_getCanvasEntity(ecs::Registry &registry)
int registry_readEntityChanges(ecs::Registry &registry, double after, uintptr_t outputPtr, int capacity)
u32 renderer_getDrawCalls()
void renderer_setSkyEnvironment(u32 environmentHandle)
The environment the sky lights the scene with, 0 for none: an Ambient light that names no environment...
void renderer_entityVisibleToCamera(ecs::Registry &registry, u32 entity, i32 layer, f32 minX, f32 minY, f32 maxX, f32 maxY, uintptr_t outVisiblePtr)
i32 probe_volume_getBricks(u32 volumeHandle, uintptr_t outPtr, i32 maxBricks)
A sparse volume's bricks, four ints each (first finest-brick cell x, y, z and span),...
ReadbackHandle
An in-flight framebuffer readback (GfxDevice::requestReadback).
Definition GfxEnums.hpp:43
u32 registry_watchEntityChanges(ecs::Registry &registry)
float f32
32-bit floating point
Definition Types.hpp:59
void probe_volume_setSkyVisibility(u32 volumeHandle, uintptr_t visibilityPtr)
Releases a probe volume.
void environment_setSky(u32 environmentHandle, u32 skyHandle)
Gives an environment the panorama its sky is drawn from.
void renderer_setYSortLayers(u32 mask)
void renderer_setProbeVolumeReflection(u32 entity, u32 environmentHandle, u32 slot)
std::string renderer_getPlanarReflectionStatus(u32 view, u32 entity)
u32 meshRenderer_makeAllResident(ecs::Registry &registry)
Freezes every MeshRenderer in the world; returns how many were frozen.
std::string engine_getCpuScopes()
static u32 checkGLErrors(const char *context)
Entity identifier with packed index + generation.
Definition Types.hpp:135
static constexpr Entity fromRaw(u32 v)
Reconstructs an Entity from a raw packed value.
Definition Types.hpp:162
constexpr u32 generation() const
Gets the generation number.
Definition Types.hpp:153
GPU objects the device has created and not yet destroyed.
Definition GfxDevice.hpp:57
What the frame's light cap came to.
Definition LightPlan.hpp:57
LightRefusal refusalFor(Entity entity) const
What entity was told, or None when it was not refused.
Definition LightPlan.hpp:82
u32 requested
Lights that asked. Equal to accepted when nothing was turned away.
Definition LightPlan.hpp:61
std::vector< LightGrant > refused
Definition LightPlan.hpp:66
u32 limit
The shader's array bound — what accepted can never exceed.
Definition LightPlan.hpp:59
What a renderable's program key is made of, with no say in where the facts came from — a live entity'...
One piece a skinned mesh is drawn in, when its bones are more than one draw can carry.
Definition Mesh.hpp:68
Where parallax is measured from, when it is not the camera drawing the frame.
The frame's main-pass load-op: which attachments to clear, the color, and an optional region (w == 0 ...
The editor view's own lighting, in place of the scene's.
bool showSky
Draw the scene's environment as the background while studio-lit.
f32 skyIntensity
Scales the neutral sky's light; the scene's own Ambient is not consulted.
f32 rotation
Degrees about +Y that the key and fill turn together.
What readying a set of renderables' programs found. Counts, not JSON: this crosses no boundary and pa...
u64 requirementDigest() const
A stable name for the SET of program requirements described here.
One caster's claim on the atlas: what it wanted, what it kept, and why the difference.
u32 requested
Tiles asked for: a sun's cascade set, a cube's six faces, or one.
u32 granted
Tiles kept. 0 means this light casts no shadow at all this frame.
The frame's whole shadow allocation, as numbers something outside it can check.
const ShadowGrant * grantFor(Entity entity) const
What entity asked for and kept, or null when it asked nothing.
The project's skin cache settings.
Definition SkinCache.hpp:46
SkinCacheBehavior behavior
Definition SkinCache.hpp:48
Context passed to every System::update call.
Definition World.hpp:40
Camera component for rendering viewpoints.
Definition Camera.hpp:70
Canvas component for 2D game resolution management.
Definition Canvas.hpp:71
Children list component.
Definition Hierarchy.hpp:66
A 2D light contributing to Lit-shaded materials.
Definition Light.hpp:54
Many placements of the one mesh a MeshRenderer draws, as ONE renderable.
resource::MeshHandle mesh
Geometry from an .esmesh, drawn INSTEAD of the inline vertices.
Parent reference component.
Definition Hierarchy.hpp:46
Unified transform component.
Definition Transform.hpp:45
UINode — the CSS box-model layout input (the CSS/Flex primary layout model).
Definition UINode.hpp:79
A mesh's clusters and the indices they name, every level together.
One cluster: its run of the hierarchy's indices, its own bounds and its group's.