15#ifdef ES_ENABLE_GPU_PARTICLES
47#ifdef ES_ENABLE_PARTICLES
60#include <emscripten/val.h>
61#ifdef ES_RENDER_THREADS
62#include <emscripten/emscripten.h>
66#include <glm/gtc/matrix_transform.hpp>
67#include <glm/gtc/type_ptr.hpp>
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>())
85#define g_trailSystem (ctx().tryGet<trail::TrailSystem>())
86#define g_springBoneSystem (ctx().tryGet<springbone::SpringBoneSystem>())
92constexpr GfxVertexAttribute kStandardMeshChannels[3] = {
103 while ((err =
g_device->getError()) != 0) {
104 ES_LOG_ERROR(
"[GL Error] 0x{:04X} at: {}", err, context);
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,
121 renderer_submitSkeletalBatchByEntityEx(registry, verticesPtr, vertexCount, indicesPtr, indexCount, textureId, blendMode, entity, skelScale, flipX, flipY, layer, depth, materialId, blendMode == 4 || blendMode == 5);
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
139 glm::vec3 s = t.worldScale;
142 if (flipX) s.x = -s.x;
143 if (flipY) s.y = -s.y;
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);
149 if (vertexCount < 0 || indexCount < 0)
return;
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;
157 f32 treeAlpha = 1.0f;
160 bool alphaFound =
false;
162 for (
u32 guard = 0; registry.
valid(at) && guard < 4096; ++guard) {
165 treeAlpha = node->alpha_in_tree_;
170 cullBit = (canvas->layer < 0 || canvas->layer >= 32) ? 0u : (1u << canvas->layer);
179 vertices, vertexCount, indices, indexCount,
180 textureId, blendMode, &model[0][0], ent, layer, depth, materialId, premultipliedColor,
192 f32 minX,
f32 minY,
f32 maxX,
f32 maxY, uintptr_t outVisiblePtr
194 auto* out =
reinterpret_cast<i32*
>(outVisiblePtr);
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);
211 const glm::vec2 corners[4] = {
212 { minX, minY }, { maxX, minY }, { maxX, maxY }, { minX, maxY },
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));
221 *out =
g_renderFrame->visibleToCamera(layer, (lo + hi) * 0.5f, (hi - lo) * 0.5f) ? 1 : 0;
227 uintptr_t verticesPtr,
i32 vertexCount,
228 uintptr_t indicesPtr,
i32 indexCount,
229 u32 textureId, uintptr_t transformPtr,
233 if (vertexCount < 0 || indexCount < 0)
return;
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;
239 vertices, vertexCount, indices, indexCount,
247 g_renderFrame->retainedText().begin(entity, sdf != 0, screen != 0, hasBox != 0, layer, boxWidth, boxHeight, autoKind != 0);
251 u32 entity, uintptr_t verticesPtr,
i32 vertexCount,
252 uintptr_t indicesPtr,
i32 indexCount,
u32 pageId,
i32 glyphMode
255 if (vertexCount < 0 || indexCount < 0)
return;
257 auto* indices =
boundarySpan<u16>(indicesPtr,
static_cast<u64>(indexCount),
"renderer_retainedTextBatch.indices");
258 if (!vertices || !indices)
return;
274 for (
auto it = entries.begin(); it != entries.end();) {
276 if (!registry.
valid(entity)) {
277 it = entries.erase(it);
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) {
289 transform->ensureDecomposed();
293 if (stale && written < capacity) out[written++] = it->first;
302 const f32* projection = projectionPtr ?
boundarySpan<f32>(projectionPtr, 16,
"renderer_retainedTextSubmit.projection") :
nullptr;
303 g_renderFrame->submitRetainedText(registry, screen != 0, projection);
315 uintptr_t posUvPtr,
u32 vertexCount,
317 uintptr_t indicesPtr,
u32 indexCount) {
321 ES_LOG_WARN(
"meshRenderer_setGeometry: entity {} has no MeshRenderer component", entity);
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);
332 if (indexCount % 3 != 0) {
333 ES_LOG_WARN(
"meshRenderer_setGeometry: indexCount {} is not a triangle list; rejected", indexCount);
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;
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);
350 mesh->vertices.resize(vertexCount);
351 glm::vec2 mn(posUv[0], posUv[1]);
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);
361 mesh->indices.assign(indices, indices + indexCount);
372 ES_LOG_WARN(
"meshInstances_set: entity {} has no MeshInstances component", entity);
375 constexpr u32 kFloats = 16;
377 if (dataPtr == 0 || count == 0) {
378 set->transforms.clear();
379 set->originMin = set->originMax = glm::vec3(0.0f);
380 set->maxScale = 1.0f;
383 const f32* data =
boundarySpan<f32>(dataPtr,
static_cast<u64>(count) * kFloats,
"meshInstances_set.transforms");
385 set->transforms.assign(data, data +
static_cast<usize>(count) * kFloats);
386 glm::vec3 mn(data[3], data[7], data[11]);
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);
398 set->maxScale = std::sqrt(scale);
412 u32 channelCount = 0;
413 u32 vertexStride = 0;
414 const u8* verts =
nullptr;
416 const u32* indices =
nullptr;
418 const f32* bind =
nullptr;
420 MeshMorphSource morph;
421 glm::vec3 localMin{0.0f};
422 glm::vec3 localMax{0.0f};
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,
442 uintptr_t bindPtr,
u32 bindFloats,
443 uintptr_t morphPtr,
u32 morphFloats,
444 u32 morphTargets,
u32 morphNormals) {
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);
455 if (!table || !verts || !indices)
return false;
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);
467 auto channelType = [](
u8 code) {
476 for (
u32 i = 0; i < channelCount; ++i) {
477 const u8* c = table + i * 8;
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),
491 out.bind = bindFloats > 0 ?
boundarySpan<f32>(bindPtr, bindFloats, who) : nullptr;
492 out.bindFloats = bindFloats;
495 if (morphTargets > 0 && morphFloats > 0) {
497 out.morph = {
ConstSpan<f32>(deltas, morphFloats), morphTargets, morphNormals != 0};
500 out.channelCount = channelCount;
501 out.vertexStride = vertexStride;
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);
517 uintptr_t vertexPtr,
u32 vertexBytes,
518 uintptr_t indexPtr,
u32 indexCount,
521 uintptr_t bindPtr,
u32 bindFloats,
522 uintptr_t morphPtr,
u32 morphFloats,
523 u32 morphTargets,
u32 morphNormals) {
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)) {
533 auto handle = rm->
createMesh(up.vertexSpan(), up.indexSpan(), up.channelSpan(), up.vertexStride,
534 up.localMin, up.localMax,
543 uintptr_t channelsPtr,
u32 channelCount,
u32 vertexStride,
544 uintptr_t vertexPtr,
u32 vertexBytes,
545 uintptr_t indexPtr,
u32 indexCount,
548 uintptr_t bindPtr,
u32 bindFloats,
549 uintptr_t morphPtr,
u32 morphFloats,
550 u32 morphTargets,
u32 morphNormals) {
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)) {
562 up.vertexSpan(), up.indexSpan(), up.channelSpan(),
563 up.vertexStride, up.localMin, up.localMax, up.bindSpan(),
570 if (!rm || chunkCount == 0 || boneCount == 0)
return 0;
573 if (!records || !bones)
return 0;
574 std::vector<MeshSkinChunk> chunks(chunkCount);
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];
581 std::vector<u16>(bones, bones + boneCount)) ? 1 : 0;
587 if (!rm || clusterCount == 0 || indexCount == 0)
return 0;
590 if (!records || !indices)
return 0;
592 hierarchy.
clusters.resize(clusterCount);
594 hierarchy.
indices.assign(indices, indices + indexCount);
599 if (
auto* rm =
ctx().tryGet<resource::ResourceManager>()) {
611 f32 maxRange,
u32 columns) {
618 faceSize, mipCount, maxRange, columns).id();
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]);
656 environment->
sunColor = glm::max(glm::vec3(r, g, b), glm::vec3(0.0f));
657 environment->
hasSun =
true;
662 if (
auto* rm =
ctx().tryGet<resource::ResourceManager>()) {
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;
680 return rm->createProbeVolume({resX, resY, resZ},
687 if (resX <= 0 || resY <= 0 || resZ <= 0 || brickCount <= 0)
return 0;
688 const u64 ints =
static_cast<u64>(brickCount) * 4u;
692 if (!bricks || !sh)
return 0;
693 return rm->createProbeVolumeBricks({resX, resY, resZ},
ConstSpan<i32>(bricks,
static_cast<usize>(ints)),
702 if (!grid || !grid->
isValid())
return;
704 const f32* v =
boundarySpan<f32>(visibilityPtr, want,
"probe_volume_setSkyVisibility.visibility");
713 if (!grid || !grid->isValid())
return false;
715 if (!out)
return false;
716 out[0] = grid->resolution.x;
717 out[1] = grid->resolution.y;
718 out[2] = grid->resolution.z;
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));
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;
740 if (
auto* rm =
ctx().tryGet<resource::ResourceManager>()) {
749u32 freezeMeshGeometry(ecs::MeshRenderer* mesh) {
750 auto* rm =
ctx().
tryGet<resource::ResourceManager>();
751 if (!mesh || !rm || mesh->vertices.empty() || mesh->indices.empty())
return 0;
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 };
762 auto handle = rm->createMesh(
763 ConstSpan<u8>(
reinterpret_cast<const u8*
>(verts.data()), verts.size() *
sizeof(MeshVertex)),
766 glm::vec3(mesh->localMin, 0.0f), glm::vec3(mesh->localMax, 0.0f),
768 if (!handle.isValid())
return 0;
771 mesh->vertices.clear();
772 mesh->indices.clear();
785 mesh->vertices.clear();
786 mesh->indices.clear();
796 mesh->material = materialId;
842 if (!std::isfinite(fence) || fence < 0 || fence > 9007199254740991.0 || std::floor(fence) != fence)
return false;
853 if (
auto* rc =
ctx().tryGet<RenderContext>()) {
869 if (!matrixData)
return;
870 glm::mat4 viewProjection = glm::make_mat4(matrixData);
874 glm::vec4(r, g, b, a),
875 clearX, clearY, clearW, clearH});
893#if defined(__EMSCRIPTEN__) && defined(ES_RENDER_THREADS)
894 EM_ASM({
if (Module[
'estellaGLPresent']) Module[
'estellaGLPresent'](); });
904#ifdef ES_ENABLE_BITMAP_TEXT
908#ifdef ES_ENABLE_PARTICLES
922 if (entitiesPtr == 0 || count == 0)
return;
925 std::vector<Entity> order;
926 order.reserve(count);
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);
960 if (
auto* ui =
ctx().tryGet<ecs::UISystem>())
g_renderFrame->setScreenRoots(&ui->screenRoots(), &ui->screenRootByIndex());
962 return g_renderFrame->keepScreenOverlay(registry, hostStill);
977 g_renderFrame->drawOverScreen(vpX, vpY, vpW, vpH, targetHandle);
995#ifdef ES_ENABLE_PARTICLES
996void particle_update(ecs::Registry& registry,
f32 dt) {
997 if (!g_particleSystem)
return;
999 g_particleSystem->update(registry, dt);
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);
1020 if (!g_particleSystem)
return;
1026 if (!g_particleSystem)
return;
1032 if (!g_particleSystem)
return;
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));
1044u32 particle_getAliveCount(
u32 entity) {
1045 if (!g_particleSystem)
return 0;
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);
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);
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);
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);
1100 static std::vector<f32> data;
1109 return static_cast<u32>(data.size() / 7);
1127 bool depth = (flags & 1) != 0;
1128 bool linear = (flags & 2) != 0;
1130 return g_renderFrame->targetManager().create(width, height, depth, linear, (flags & 8) != 0);
1136 return target ?
static_cast<u32>(target->getDepthTexture()) : 0;
1148 return target ?
static_cast<u32>(target->getColorTexture()) : 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));
1173 return device ? device->pendingProgramLabels() : std::string();
1186#ifdef __EMSCRIPTEN__
1193emscripten::val meshRenderer_localBounds(ecs::Registry& registry,
u32 entity) {
1195 const auto* mesh = registry.tryGet<ecs::MeshRenderer>(ent);
1196 if (!mesh)
return emscripten::val::null();
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)) {
1210 if (!(mx.x > mn.x) && !(mx.y > mn.y) && !(mx.z > mn.z))
return emscripten::val::null();
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);
1222emscripten::val renderer_getLiveObjects() {
1226 if (!device)
return emscripten::val::null();
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));
1284 if (
auto* source =
ctx().tryGet<RandomSource>()) {
1285 source->reseed(seed);
1288#ifdef ES_ENABLE_PARTICLES
1289 if (
auto* particles = g_particleSystem) particles->reseedFrom(*source);
1299 auto* out =
reinterpret_cast<u32*
>(
static_cast<uintptr_t
>(outPtr));
1300 for (
u32 i = 0; i < 11; ++i) out[i] = 0;
1308 const u64 generationBefore =
g_device->deviceGeneration();
1309 const u64 epochBefore = rc->programEpoch();
1311 const auto* rows =
reinterpret_cast<const MeshDocumentRecord*
>(
static_cast<uintptr_t
>(rowsPtr));
1314 const u64 generationAfter =
g_device->deviceGeneration();
1315 const u64 epochAfter = rc->programEpoch();
1317 out[0] = (generationBefore == generationAfter && epochBefore == epochAfter) ? 1u : 0u;
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);
1331#ifdef ES_ENABLE_TEST_PROBES
1336static void writePrewarm(
u32* out,
const RenderPrewarmResult& r) {
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);
1346 const u64 digest = r.requirementDigest();
1347 out[9] =
static_cast<u32>(digest & 0xFFFFFFFFull);
1348 out[10] =
static_cast<u32>(digest >> 32);
1350 const u64 epoch = rc ? rc->programEpoch() : 0;
1351 out[11] =
static_cast<u32>(epoch & 0xFFFFFFFFull);
1352 out[12] =
static_cast<u32>(epoch >> 32);
1357 out[13] =
static_cast<u32>(generation & 0xFFFFFFFFull);
1358 out[14] =
static_cast<u32>(generation >> 32);
1362 auto* out =
reinterpret_cast<u32*
>(
static_cast<uintptr_t
>(outPtr));
1363 for (
u32 i = 0; i < 13; ++i) out[i] = 0;
1365 const auto* entities =
reinterpret_cast<const Entity*
>(
static_cast<uintptr_t
>(entitiesPtr));
1366 writePrewarm(out,
g_renderFrame->prewarmPrograms(registry, entities, count));
1380 if (
auto* rm =
ctx().tryGet<resource::ResourceManager>()) {
1381 return static_cast<f64>(rm->getStats().textureBytes);
1393 if (
auto* rc =
ctx().tryGet<RenderContext>()) {
1394 return static_cast<f64>(rc->programEpoch());
1408 g_device->setViewport(x, y,
static_cast<u32>(w),
static_cast<u32>(h));
1425 if (!frame || !frame->skinCache())
return;
1427 settings.
enabled = enabled != 0;
1430 frame->skinCache()->setSettings(settings);
1435 SkinCache* cache = frame ? frame->skinCache() :
nullptr;
1436 if (!cache)
return 0.0;
1438 case 0:
return cache->
active() ? 1.0 : 0.0;
1444 default:
return 0.0;
1449 if (
auto* frame =
g_renderFrame) frame->setYSortLayers(mask);
1453 if (
auto* frame =
g_renderFrame) frame->setTreeSortLayers(mask);
1460#ifdef ES_ENABLE_PARTICLES
1461 if (g_particleSystem) g_particleSystem->setParticleLimit(particleLimit);
1466 if (
auto* frame =
g_renderFrame) frame->setDepthLayers(mask);
1470 f32 skyIntensity,
bool showSky) {
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;
1487#ifdef ES_ENABLE_GPU_PARTICLES
1497 if (
auto* context =
ctx().tryGet<RenderContext>()) context->setQualityConstants(glm::vec4(x, y, z, w));
1530 if (!rc)
return 0.0;
1555 if (
auto* device =
g_device) device->setSkipPendingPrograms(on);
1560 return device ? device->pendingProgramCount() : 0u;
1565 if (
auto* frame =
g_renderFrame) frame->setCullingMask(mask);
1581 out[0] = out[1] = 0;
1589 out[0] = out[1] = out[2] = out[3] = 0.0f;
1591 u8 level = 0, unbiased = 0, levels = 0;
1599 out[1] = unbiased ==
lod::kCulled ? -1.0f :
static_cast<f32>(unbiased);
1600 out[2] =
static_cast<f32>(levels);
1617 const u8 held = level < 0 ? lod::kNoPreview : static_cast<u8>(level);
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());
1660 const u32* ids = count > 0 ?
boundarySpan<u32>(idsPtr, count,
"renderer_setViewSelection.ids") :
nullptr;
1661 g_renderFrame->setViewSelection(view, ids, ids ? count : 0);
1667 joint < 0 ? 0u :
static_cast<u32>(joint));
1671 if (
auto* resources =
ctx().tryGet<resource::ResourceManager>()) resources->setMeshEdgeBuffers(enabled);
1677 for (
u32 i = 0; i < 9; ++i) out[i] = 0.0f;
1680 if (cap.
limit == 0)
return 0;
1683 out[1] =
static_cast<f32>(
static_cast<u8>(why));
1684 out[2] =
static_cast<f32>(cap.
limit);
1686 out[4] =
static_cast<f32>(cap.
refused.size());
1697 for (
u32 i = 0; i < 5; ++i) out[i] = 0.0f;
1701 if (!grant)
return 0;
1704 out[2] =
static_cast<f32>(
static_cast<u8>(grant->
refusal));
1715 if (
auto* frame =
g_renderFrame) frame->setColorSpace(linear != 0);
1732 while (
g_device->getError() != 0) {}
1733 ES_LOG_INFO(
"[Diagnose] No pending GL errors (cleared)");
1739 while (
g_device->getError() != 0) {}
1749 if (count == 0 && prev) {
1757 for (
auto entity : view) {
1758 return static_cast<i32>(entity.id());
1763#ifdef __EMSCRIPTEN__
1767emscripten::val registry_getCanvasEntities(ecs::Registry& registry) {
1768 auto view = registry.activeView<ecs::Canvas>();
1769 auto result = emscripten::val::array();
1771 for (
auto entity : view) {
1772 result.set(idx++, entity.id());
1778#ifdef __EMSCRIPTEN__
1779emscripten::val registry_getCameraEntities(
ecs::Registry& registry) {
1781 auto result = emscripten::val::array();
1783 for (
auto entity : cameraView) {
1785 if (camera.isActive) {
1786 result.set(idx++, entity.id());
1793 auto result = emscripten::val::array();
1799 for (
auto child : children.entities) {
1800 result.set(idx++, child.id());
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");
1829 if (!ids || !output)
return 0;
1831 for (
int i = 0; i < count; ++i) {
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};
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;
1853 std::memcpy(&entityId, buffer + offset,
sizeof(uint32_t));
1855 if (!registry.
valid(entity))
continue;
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));
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;
1876 if (count <= 0 || pairsPtr %
alignof(
u32))
return;
1877 const u32* pairs =
boundarySpan<u32>(pairsPtr,
static_cast<u64>(count) * 2,
"registry_markComponentsChanged");
1895 return reinterpret_cast<uintptr_t
>(
g_renderFrame->frameCapture().getRecords());
1900 return reinterpret_cast<uintptr_t
>(
g_renderFrame->frameCapture().getEntities());
1910 return reinterpret_cast<uintptr_t
>(
g_renderFrame->frameCapture().getTextures());
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);
1954 return copyOut(c.getRecords(),
usize(c.getRecordCount()) *
sizeof(
DrawCallRecord), dest, destSize);
1960 return copyOut(c.getEntities(),
usize(c.getEntityCount()) *
sizeof(
Entity), dest, destSize);
1966 return copyOut(c.getTextures(),
usize(c.getTextureCount()) *
sizeof(
u32), dest, destSize);
1976 return reinterpret_cast<uintptr_t
>(
g_renderFrame->getSnapshotPixels());
2005 if (!device)
return 0;
2006 return static_cast<u32>(device->captureNextFrame(w, h));
2011 if (!device || !
g_renderFrame || w == 0 || h == 0)
return 0;
2014 return static_cast<u32>(device->requestReadback(rt->getFramebuffer(), w, h));
2019 if (!device || !handle || !dest)
return false;
2021 return device->takeReadback(
static_cast<ReadbackHandle>(handle),
reinterpret_cast<void*
>(dest),
static_cast<usize>(destSize));
2027 if (!device || !handle)
return 2;
2028 switch (device->pollReadback(
static_cast<ReadbackHandle>(handle))) {
2044 if (!device || !handle || !dest)
return false;
2046 reinterpret_cast<void*
>(dest),
static_cast<usize>(destSize))) {
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]);
2059 static_cast<u32>(w),
static_cast<u32>(h)));
2064 uintptr_t verticesPtr,
i32 vertexCount,
2065 uintptr_t indicesPtr,
i32 indexCount,
2066 u32 textureId,
i32 blendMode, uintptr_t transformPtr,
2069 return renderer_submitSkeletalPreviewBatchEx(preview, verticesPtr, vertexCount, indicesPtr, indexCount, textureId, blendMode, transformPtr, layer, depth, materialId, blendMode == 4 || blendMode == 5);
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
2079 if (!
g_renderFrame || vertexCount < 0 || indexCount < 0)
return 0;
2082 "renderer_submitSkeletalPreviewBatch.vertices");
2084 "renderer_submitSkeletalPreviewBatch.indices");
2086 "renderer_submitSkeletalPreviewBatch.transform");
2087 if (!vertices || !indices || !transform)
return 0;
2089 preview, vertices, vertexCount, indices, indexCount,
2090 textureId, blendMode, transform, layer, depth, materialId, premultipliedColor) ? 1 : 0;
2095 auto* vp =
boundarySpan<f32>(viewProjectionPtr, 16,
"renderer_renderSkeletalPreview.vp");
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;
2108 ?
reinterpret_cast<uintptr_t
>(
g_renderFrame->skeletalPreviewPixels(preview)) : 0;
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));
2138struct WaitForPrograms {
2142 if (device) device->setSkipPendingPrograms(
false);
2144 ~WaitForPrograms() {
if (device) device->setSkipPendingPrograms(was); }
2145 WaitForPrograms(
const WaitForPrograms&) =
delete;
2146 WaitForPrograms& operator=(
const WaitForPrograms&) =
delete;
2151 g_previewYaw = std::isfinite(yawDegrees) ? yawDegrees : 30.96f;
2152 g_previewPitch = std::isfinite(pitchDegrees) ? pitchDegrees : 21.10f;
2157 const WaitForPrograms wait;
2160 auto light = reg.
create();
2168 auto entity = reg.
create();
2172 mesh.material = materialId;
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));
2188 for (
i32 corner = 0; corner < 8; ++corner) {
2189 const glm::vec3 world{
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)});
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));
2205 auto quad = reg.
create();
2208 sprite.material = materialId;
2209 sprite.size = glm::vec2(2.0f, 2.0f);
2217 const glm::mat4 vp =
math::ortho(-1.0f, 1.0f, -1.0f, 1.0f, -1.0f, 1.0f);
2229 const WaitForPrograms wait;
2235 auto entity = reg.
create();
2242 auto light = reg.
create();
2244 lightTransform.
position = glm::vec3(0.0f, 0.0f, 1.0f);
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));
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,
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)});
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));
2300 if (!device)
return;
2301 device->setTextureParams(
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.
Abstract graphics device interface.
Particles simulated by a compute kernel, drawn from the buffer the kernel wrote (WebGPU).
Hierarchy components for parent-child relationships.
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.
#define ES_LOG_ERROR(...)
Logs an error message.
#define ES_LOG_INFO(...)
Logs an info message.
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_glErrorCheckEnabled
#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 ...
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.
The frame's probe volumes, and the trilinear read through them.
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
u32 refusedThisFrame() const
u32 scheduledThisFrame() const
Central container for all entities and components.
bool isEntityActive(Entity e) const
double entityChangeResetEpoch() const
double entityChangeSequence() const
void unwatchEntityChanges(u32 reader)
T & get(Entity entity)
Gets a component from an entity (must exist).
bool has(Entity entity) const
Checks if an entity has a specific component.
double componentMutationRevision(u32 component, bool topology) const
void markChangedById(u32 typeId, Entity entity)
markChanged by a component type id (componentTypeId): for a writer that names the type at run time,...
void markChanged(Entity entity)
Says entity's T was written, through a reference held from before.
bool valid(Entity entity) const
Checks if an entity is currently valid.
i32 readEntityChanges(double after, std::span< EntityChangeRow > output) const
Entity create()
Creates a new entity.
T * tryGet(Entity entity)
Tries to get a component from an entity.
T & emplace(Entity entity, Args &&... args)
Adds a component to an entity with in-place construction.
View< Components... > view()
Creates a view for iterating entities with specific components.
UI subsystem: owns layout tree + hit-test state.
const std::unordered_set< u32 > & screenDomain() const
Every entity that belongs to the SCREEN, as opposed to the world.
IdType id() const
Gets the packed identifier (index + generation).
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 ®istry, 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.
f32 stretchSquared(const f32 *rows)
Handle< esengine::Environment > EnvironmentHandle
Handle to a baked environment (irradiance + prefiltered reflection).
Handle< esengine::Texture > TextureHandle
Handle to a texture resource.
Handle< esengine::ProbeVolume > ProbeVolumeHandle
Handle to a grid of baked irradiance.
Handle< esengine::Mesh > MeshHandle
Handle to GPU-resident geometry.
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 ®istry, 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.
void renderer_setProbeVolumeOverride(u32 entity, u32 volumeHandle)
void renderer_setDepthPrepass(bool on)
i32 renderer_retainedTextStale(ecs::Registry ®istry, 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 ®istry)
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 ®istry, 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.
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 ®istry, 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 ®istry, f32 dt)
void registry_markComponentsChanged(ecs::Registry ®istry, 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 ®istry)
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 ®istry, u32 reader)
std::size_t usize
Size type for indexing and sizes.
u32 renderer_getTriangles()
u32 meshRenderer_setMaterialAll(ecs::Registry ®istry, 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 ®istry, 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.
@ HostOnly
Built in this process; the device keeps its bytes.
constexpr Entity INVALID_ENTITY
Invalid entity sentinel value.
u32 renderer_createTarget(u32 width, u32 height, i32 flags)
void springbone_reset(ecs::Registry ®istry, 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 ®istry, 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 ®istry, 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
void renderer_retainedTextClear(u32 entity)
Forgets an entity's retained text.
LightRefusal
Why a light did not reach the frame.
u32 renderer_getSnapshotWidth()
void probe_volume_release(u32 volumeHandle)
Releases a probe volume.
void renderer_setColorSpace(u32 linear)
u32 meshRenderer_setMeshAll(ecs::Registry ®istry, 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 ®istry, 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
void renderer_setScreenOverlayEffect(u32 material)
f64 renderer_getEstimatedGpuBytes()
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.
@ UNorm16
Skin weights at high precision.
@ UInt8
Joint indices of a skin or chunk of at most 256 bones: a byte each.
void renderer_resize(u32 width, u32 height)
uintptr_t springbone_snapshotData()
void renderer_submitSkeletalBatchByEntity(ecs::Registry ®istry, 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.
void renderer_submitAll(ecs::Registry ®istry, i32 vpX, i32 vpY, i32 vpW, i32 vpH)
bool renderer_supportsAsyncCompute()
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 ®istry, uintptr_t bufferPtr, int count, float ppu)
double registry_entityChangeSequence(ecs::Registry ®istry)
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.
void renderer_retainedTextSubmit(ecs::Registry ®istry, 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.
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
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 ®istry)
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 ®istry, 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 ®istry)
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 ®istry, u32 entity)
void renderer_setWorldUnitsPerMeter(f32 units)
double registry_componentMutationRevision(ecs::Registry ®istry, u32 component, bool topology)
u32 renderer_getSkeletalPreviewHeight(u32 preview)
u32 registry_getGeneration(ecs::Registry ®istry, u32 entity)
bool renderer_keepScreenOverlay(ecs::Registry ®istry, bool hostStill)
bool renderer_copyCapturedTextures(uintptr_t dest, u32 destSize)
i32 registry_getCanvasEntity(ecs::Registry ®istry)
int registry_readEntityChanges(ecs::Registry ®istry, 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 ®istry, 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).
u32 registry_watchEntityChanges(ecs::Registry ®istry)
float f32
32-bit floating point
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 ®istry)
Freezes every MeshRenderer in the world; returns how many were frozen.
std::string engine_getCpuScopes()
static u32 checkGLErrors(const char *context)
bool gl_error_check_enabled
Entity identifier with packed index + generation.
static constexpr Entity fromRaw(u32 v)
Reconstructs an Entity from a raw packed value.
constexpr u32 generation() const
Gets the generation number.
GPU objects the device has created and not yet destroyed.
What the frame's light cap came to.
glm::vec3 environmentSunAim
LightRefusal refusalFor(Entity entity) const
What entity was told, or None when it was not refused.
u32 requested
Lights that asked. Equal to accepted when nothing was turned away.
std::vector< LightGrant > refused
u32 limit
The shader's array bound — what accepted can never exceed.
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.
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.
u32 reducedCasters() const
u32 deniedCasters() const
The project's skin cache settings.
SkinCacheBehavior behavior
Context passed to every System::update call.
Camera component for rendering viewpoints.
Canvas component for 2D game resolution management.
A 2D light contributing to Lit-shaded materials.
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.
UINode — the CSS box-model layout input (the CSS/Flex primary layout model).
A mesh's clusters and the indices they name, every level together.
std::vector< u32 > indices
std::vector< Cluster > clusters
One cluster: its run of the hierarchy's indices, its own bounds and its group's.