Estella 0.113.0
A fast 2D and 3D game engine powered by WebAssembly and ECS
Loading...
Searching...
No Matches
RenderTypePlugin.hpp
Go to the documentation of this file.
1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
3#pragma once
4
5#include "../core/Types.hpp"
6#include "../core/Hash.hpp"
7#include "./RenderOrigin.hpp"
9#include "./frame/Frustum.hpp"
15#include "./draw/RenderItem.hpp"
17#include <unordered_set>
18#include "./draw/DrawList.hpp"
19#include "./draw/ClipState.hpp"
21#include "../ecs/Registry.hpp"
24
25#include <glm/glm.hpp>
26#include <glm/gtc/matrix_access.hpp>
27#include <glm/gtc/quaternion.hpp>
28
29#include <cmath>
30#include <algorithm>
31#include <array>
32#include <unordered_map>
33#include <unordered_set>
34#include <vector>
35
36namespace esengine {
37
38class RenderContext;
39class MaterialStore;
40class RenderFrame;
41class SkinCache;
42
62
105
111 f32 left = 0.0f, bottom = 0.0f, right = 0.0f, top = 0.0f;
112 glm::vec2 center{0.0f};
115 glm::vec2 parallaxCenter{0.0f};
116
120 glm::vec4 eye{0.0f, 0.0f, 1.0f, 0.0f};
121
128 f32 viewDepth(const glm::vec3& worldPos) const {
129 if (eye.w < 0.5f) return glm::dot(worldPos, glm::vec3(eye));
130 return -glm::length(worldPos - glm::vec3(eye));
131 }
132};
133
143 bool set = false;
144 glm::dvec2 at{0.0};
145};
146
148 static ParallaxAnchor anchor;
149 return anchor;
150}
151
152inline CameraView computeCameraView(const glm::mat4& viewProjection) {
153 glm::mat4 invVP = glm::inverse(viewProjection);
154 glm::vec4 bl = invVP * glm::vec4(-1.0f, -1.0f, 0.0f, 1.0f);
155 glm::vec4 tr = invVP * glm::vec4( 1.0f, 1.0f, 0.0f, 1.0f);
156 CameraView view;
157 view.left = bl.x / bl.w;
158 view.bottom = bl.y / bl.w;
159 view.right = tr.x / tr.w;
160 view.top = tr.y / tr.w;
161 view.center = { (view.left + view.right) * 0.5f, (view.bottom + view.top) * 0.5f };
162 // The centre above is from the render origin, as the view-projection is; the anchor is a world point.
163 const ParallaxAnchor& anchor = parallaxAnchor();
164 view.parallaxCenter = anchor.set
165 ? glm::vec2(anchor.at - glm::dvec2(renderOrigin()))
166 : view.center;
167 view.eye = cameraFromViewProjection(viewProjection);
168 return view;
169}
170
188
190 bool hasNormals = false;
191 bool lit = false;
193 bool skinned = false;
197 bool lightmapped = false;
199 bool tangents = false;
201 bool opaque = true;
203};
204
216 std::array<u64, MESH_VARIANTS / 64> keys{};
217
219 bool addKey(u32 variant) {
220 u64& word = keys[variant / 64];
221 const u64 bit = 1ull << (variant % 64);
222 if (word & bit) return false;
223 word |= bit;
224 return true;
225 }
226
229 std::vector<u64> materialKeys;
230
232 static u64 materialKey(u32 materialId, bool normals, bool skinned, bool envMapped,
233 bool lightmapped, bool tangents = false) {
234 return (static_cast<u64>(materialId) << 5) | (tangents ? 16u : 0u) | (lightmapped ? 8u : 0u) | (normals ? 4u : 0u)
235 | (skinned ? 2u : 0u) | (envMapped ? 1u : 0u);
236 }
237
238 void addMaterialKey(u64 key) {
239 if (std::find(materialKeys.begin(), materialKeys.end(), key) == materialKeys.end()) {
240 materialKeys.push_back(key);
241 }
242 }
243
253 std::vector<u64> sorted(materialKeys);
254 std::sort(sorted.begin(), sorted.end());
256 auto mix = [&h](u64 v) { h = hash::fnv1aBytes(h, &v, sizeof(v)); };
257 for (u64 word : keys) mix(word);
258 for (u64 k : sorted) mix(k);
259 return h;
260 }
261
263 asks += other.asks;
264 compiles += other.compiles;
265 uniqueKeys += other.uniqueKeys;
266 materialAsks += other.materialAsks;
268 for (usize w = 0; w < keys.size(); ++w) keys[w] |= other.keys[w];
269 // A union, so combining two plugins' answers cannot depend on the order
270 // they ran in — the digest above rests on that.
271 for (u64 k : other.materialKeys) addMaterialKey(k);
272 return *this;
273 }
274};
275
276enum class CasterSplit : u8 { All, Held, Movers };
277
286
294 const std::unordered_set<u32>* screen_ui = nullptr;
296 const std::vector<u32>* screen_root_by_index = nullptr;
299
301 const std::unordered_map<u32, i32>* ui_tree_layers = nullptr;
302
307 i32 treeLayer(Entity entity, i32 authored) const {
308 if (authored != 0 || !ui_tree_layers) return authored;
309 const auto it = ui_tree_layers->find(entity.id());
310 return it == ui_tree_layers->end() ? authored : it->second;
311 }
312
318 const OcclusionView* occlusion = nullptr;
325 const std::unordered_set<u32>* selection = nullptr;
327
334 const Frustum* shadowReceivers = nullptr;
335 glm::vec3 shadowRay{0.0f, -1.0f, 0.0f};
340
342 bool castsIntoView(const glm::vec3& centre, f32 radius) {
343 if (!shadowReceivers) return true;
344 f32 length = shadowReachCap;
345 if (shadowRay.y < -1e-3f) length = std::min(length, std::max(centre.y - shadowFloor + radius, 0.0f) / -shadowRay.y);
346 if (shadowReceivers->intersectsSweptSphere(centre, centre + shadowRay * length, radius)) return true;
347 ++shadowCulled;
348 return false;
349 }
350
352 bool isOverlay() const { return frame_context.purpose == RenderPurpose::ScreenOverlay; }
353
361 bool accepts(Entity entity) const {
362 if (entity == excluded) return false;
363 const bool screen = screen_ui && screen_ui->count(entity.id()) != 0;
364 if (isOverlay() != screen) return false;
365 if (!screen || only_root == 0 || !screen_root_by_index) return true;
366 const u32 index = entity.index();
367 return index < screen_root_by_index->size() && (*screen_root_by_index)[index] == only_root;
368 }
369
378 bool visible(const glm::vec3& centre, const glm::vec3& halfExtents, bool depthTested) {
379 // A screen element is on the screen by construction, with no camera to be
380 // outside of — a frustum test would ask about wherever one is looking.
381 if (isOverlay()) return true;
382 if (!frustum.intersectsAABB(centre, halfExtents)) return false;
383 if (depthTested && occlusion && occlusion->hidden(centre, halfExtents)) {
384 ++occluded;
385 return false;
386 }
387 return true;
388 }
389
397 f32 sortDepth(const glm::vec3& worldPos) const {
398 return isOverlay() ? 0.0f : camera.viewDepth(worldPos);
399 }
400
410
420
427
436 struct LodView {
442 bool follow = false;
443 };
445
452
455};
456
465inline glm::vec3 towardViewer(const glm::vec3& worldPos, const CameraView& camera) {
466 return camera.eye.w < 0.5f ? glm::vec3(camera.eye) : glm::vec3(camera.eye) - worldPos;
467}
468
476inline glm::vec3 ribbonSide(const glm::vec3& tangent, const glm::vec3& worldPos,
477 const CameraView& camera, const glm::vec3& lastSide) {
478 const glm::vec3 side = glm::cross(towardViewer(worldPos, camera), tangent);
479 const f32 len2 = glm::dot(side, side);
480 return len2 > 1e-12f ? side / std::sqrt(len2) : lastSide;
481}
482
483inline glm::vec3 parallaxedWorldPosition(ecs::Transform& transform, const glm::vec2& parallax,
484 const CameraView& camera) {
485 transform.ensureDecomposed();
486 glm::vec3 position = rebased(transform.worldPosition);
487 position.x += camera.parallaxCenter.x * (1.0f - parallax.x);
488 position.y += camera.parallaxCenter.y * (1.0f - parallax.y);
489 return position;
490}
491
496inline glm::vec2 flatTurnZ(const glm::quat& rotation) {
497 const f32 n = rotation.w * rotation.w + rotation.z * rotation.z;
498 if (n <= 1e-12f) return {1.0f, 0.0f};
499 return {(rotation.w * rotation.w - rotation.z * rotation.z) / n,
500 2.0f * rotation.w * rotation.z / n};
501}
502
511inline void orientedWorldAabb(const glm::vec3& position, const glm::quat& rotation,
512 const glm::vec3& scale, const glm::vec3& localMin,
513 const glm::vec3& localMax, glm::vec3& outCentre,
514 glm::vec3& outHalf) {
515 const glm::mat3 basis = glm::mat3_cast(rotation);
516 const glm::vec3 scaledHalf = glm::abs((localMax - localMin) * 0.5f * scale);
517 outCentre = position + basis * ((localMin + localMax) * 0.5f * scale);
518 outHalf = {
519 glm::dot(glm::abs(glm::row(basis, 0)), scaledHalf),
520 glm::dot(glm::abs(glm::row(basis, 1)), scaledHalf),
521 glm::dot(glm::abs(glm::row(basis, 2)), scaledHalf),
522 };
523}
524
530inline glm::vec3 flatHalfExtents(const glm::vec2& turn, const glm::vec3& half) {
531 const f32 c = std::abs(turn.x), s = std::abs(turn.y);
532 const glm::vec3 extent = glm::abs(half);
533 return {c * extent.x + s * extent.y, s * extent.x + c * extent.y, extent.z};
534}
535
537public:
538 virtual ~RenderTypePlugin() = default;
539
540 virtual void init(RenderFrameContext& ctx) { (void)ctx; }
541 virtual void shutdown() {}
542
551 virtual bool castsShadows() const { return false; }
559 virtual bool castInputs(RenderFrameContext& /*ctx*/, ecs::Registry& /*registry*/, u64& /*key*/) { return false; }
560 virtual bool castHeldInputs(u64& /*key*/) const { return false; }
561 virtual u32 castMoverCount() const { return 0; }
564 virtual bool drawsMotion() const { return false; }
565
573 virtual bool drawsScreenUI() const { return false; }
574
575 virtual void collect(RenderCollectContext& ctx) = 0;
576
589 virtual void scheduleSkins(RenderFrameContext& ctx, ecs::Registry& registry, SkinCache& cache) {
590 (void)ctx; (void)registry; (void)cache;
591 }
592
594 const Entity* entities, u32 count, bool shadowPasses) {
595 (void)ctx; (void)registry; (void)entities; (void)count; (void)shadowPasses;
596 return {};
597 }
598
607 const MeshDocumentRecord* rows, u32 count,
608 bool shadowPasses) {
609 (void)ctx; (void)rows; (void)count; (void)shadowPasses;
610 return {};
611 }
612
620 virtual const char* collectScope() const { return "render.collect.other"; }
621
629 virtual bool clusterInspect(u32 /*entityId*/, u32& /*triangles*/, u32& /*clusters*/) const { return false; }
630};
631
632} // namespace esengine
Per-frame shader constants shared via a single Uniform Buffer Object.
The six planes a projection bounds, and the box test against them.
Which representation an object's size on screen asks for.
What a view knows about an object's level: what it chose, why, and whether something is being held up...
What this view already has something solid in front of.
Central ECS registry for entity and component management.
The point the frame is drawn relative to: a world far from zero loses precision in single floats,...
Central resource management system.
Unified Transform component with local and world-space data.
Core type definitions and utilities for ESEngine.
How a view shades the meshes it draws: as authored, clay, flat albedo, wireframe, or one part of the ...
Maps a material handle to its resolved record. Owned by RenderContext so it is reachable from both th...
The depths this view is blocked at, and the test a bound asks it.
virtual ~RenderTypePlugin()=default
virtual bool castsShadows() const
Whether what this plugin draws belongs in a shadow map.
virtual const char * collectScope() const
What this plugin's collect is called in a frame profile.
virtual bool drawsScreenUI() const
Whether this plugin can draw an entity that lives in a UI tree.
virtual void collect(RenderCollectContext &ctx)=0
virtual u32 castMoverCount() const
virtual bool castHeldInputs(u64 &) const
virtual void init(RenderFrameContext &ctx)
virtual bool drawsMotion() const
virtual bool castInputs(RenderFrameContext &, ecs::Registry &, u64 &)
For a plugin that casts: one number for everything its depth collect reads apart from the shadow view...
virtual RenderPrewarmResult prewarmDocument(RenderFrameContext &ctx, const MeshDocumentRecord *rows, u32 count, bool shadowPasses)
The same readiness, asked of a PREPARED cell's own description.
virtual RenderPrewarmResult prewarm(RenderFrameContext &ctx, ecs::Registry &registry, const Entity *entities, u32 count, bool shadowPasses)
virtual bool clusterInspect(u32, u32 &, u32 &) const
What the last frames drew of the Cluster LOD mesh of the entity entityId.
virtual void scheduleSkins(RenderFrameContext &ctx, ecs::Registry &registry, SkinCache &cache)
Make ready the programs entities will be asked for, drawing none.
Central container for all entities and components.
Definition Registry.hpp:73
Levels remembered per (view, entity) pair.
Central manager for GPU resources.
u64 fnv1aBytes(u64 h, const void *data, usize bytes)
Definition Hash.hpp:21
constexpr u64 kFnv64Offset
Definition Hash.hpp:12
RenderPurpose
What a collect is FOR — the phase, not a feature the geometry has.
std::int32_t i32
Signed 32-bit integer.
Definition Types.hpp:54
std::uint64_t u64
Unsigned 64-bit integer.
Definition Types.hpp:47
glm::vec3 flatHalfExtents(const glm::vec2 &turn, const glm::vec3 &half)
World AABB half-extents of a flat box turned by turn (from flatTurnZ). |R| * half,...
std::size_t usize
Size type for indexing and sizes.
Definition Types.hpp:64
constexpr Entity INVALID_ENTITY
Invalid entity sentinel value.
Definition Types.hpp:174
glm::vec3 parallaxedWorldPosition(ecs::Transform &transform, const glm::vec2 &parallax, const CameraView &camera)
ParallaxAnchor & parallaxAnchor()
glm::vec3 towardViewer(const glm::vec3 &worldPos, const CameraView &camera)
Decomposes transform and returns its world position shifted toward the camera by (1 - parallax); fact...
std::uint32_t u32
Unsigned 32-bit integer.
Definition Types.hpp:45
glm::vec3 rebased(const glm::vec3 &world)
A world position as the frame draws it: from the origin.
std::uint8_t u8
Unsigned 8-bit integer.
Definition Types.hpp:41
static constexpr u32 MESH_VARIANTS
Definition GfxEnums.hpp:150
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.
glm::dvec3 & renderOrigin()
The origin, in world units. A double, as the world positions it is taken from are far from zero.
CameraView computeCameraView(const glm::mat4 &viewProjection)
glm::vec2 flatTurnZ(const glm::quat &rotation)
The cos/sin of the turn a plane renderable draws with: its entity's rotation about Z,...
void orientedWorldAabb(const glm::vec3 &position, const glm::quat &rotation, const glm::vec3 &scale, const glm::vec3 &localMin, const glm::vec3 &localMax, glm::vec3 &outCentre, glm::vec3 &outHalf)
The world AABB of a turned box: its centre and half-extents, from a local box and the position,...
static EstellaContext & ctx()
glm::vec3 ribbonSide(const glm::vec3 &tangent, const glm::vec3 &worldPos, const CameraView &camera, const glm::vec3 &lastSide)
The side vector a ribbon widens along: perpendicular to both its path and the viewer,...
glm::vec4 cameraFromViewProjection(const glm::mat4 &viewProjection)
Where the frame is seen from, read out of the matrix that projects it.
float f32
32-bit floating point
Definition Types.hpp:59
What every plugin needs to know about the camera, derived once per collect from the inverse view-proj...
f32 viewDepth(const glm::vec3 &worldPos) const
How near worldPos is to the viewer, larger = nearer — the order the sort key wants,...
Entity identifier with packed index + generation.
Definition Types.hpp:135
constexpr u32 id() const
Returns the raw packed value for FFI serialization.
Definition Types.hpp:159
constexpr u32 index() const
Gets the entity index.
Definition Types.hpp:150
What a renderable's program key is made of, with no say in where the facts came from — a live entity'...
Where parallax is measured from, when it is not the camera drawing the frame.
Which view is looking, where its level choices are kept, and where the selections it makes are counte...
bool follow
Read the level view settled on instead of choosing one: what a shadow cast for that view's picture is...
u32 only_root
Nonzero: this collect is one screen root's, and an entity of the domain under any other root is not i...
u32 culled
How many renderables this collect's frustum rejected.
WeightTarget weights
The one skinned draw this view colours by a joint's weights, if any.
u32 occluded
How many of those culled an OCCLUDER refused.
const OcclusionView * occlusion
What this view is already blocked by, or null for a collect that must not ask — a shadow face looks f...
f32 sortDepth(const glm::vec3 &worldPos) const
The sort depth of a draw anchored at worldPos.
ShadingMode shading
How the meshes of THIS collect are shaded. Shaded unless the view asked for another mode; a collect t...
bool accepts(Entity entity) const
Whether entity belongs to THIS collect.
const std::vector< u32 > * screen_root_by_index
With only_root: by entity index, the screen root each entity of the domain draws under (ecs::UISystem...
const std::unordered_map< u32, i32 > * ui_tree_layers
The layer of each emitter and plain Sprite a Canvas holds, by entity id, or null.
bool castsIntoView(const glm::vec3 &centre, f32 radius)
Whether a caster bounded by a sphere can shade anything the camera sees. True where this collect asks...
i32 treeLayer(Entity entity, i32 authored) const
The layer entity draws at: its place in a Canvas's tree, unless its author named one.
const Frustum * shadowReceivers
A sun's shadow map only: the camera's frustum, which is what its shadows are worth drawing for,...
bool visible(const glm::vec3 &centre, const glm::vec3 &halfExtents, bool depthTested)
Whether a renderable bounded by centre / halfExtents is drawn.
bool isOverlay() const
Whether this collect is the frame's screen overlay.
u32 lightsSpared
Light slots the lit quads of this collect were spared: per quad, the loop lights that cannot reach it...
u32 shadowCulled
How many casters that left out.
const std::unordered_set< u32 > * selection
A motion collect that draws the editor's selection mask instead (RenderFrame::collectSelection): only...
const std::unordered_set< u32 > * screen_ui
The entities the SCREEN owns (UISystem::screenDomain), or null.
const MaterialStore * materials
u32 environment_texture_id
The frame environment's prefiltered reflection atlas (0 = none this frame).
resource::ResourceManager & resources
u32 shadow_texture_id
The map that pass produced, handed to the meshes that receive it (0 = none).
bool causticReceivers
Opaque geometry seen by refracted sunlight, including objects with shadow casting disabled.
RenderFrame * frame
The owning frame, for lazily-compiled batch variants (RenderFrame::batchProgram).
What readying a set of renderables' programs found. Counts, not JSON: this crosses no boundary and pa...
bool addKey(u32 variant)
Whether this key is already in the set; adds it if not.
std::array< u64, MESH_VARIANTS/64 > keys
static u64 materialKey(u32 materialId, bool normals, bool skinned, bool envMapped, bool lightmapped, bool tangents=false)
What a material program is asked for, as one comparable value.
u64 requirementDigest() const
A stable name for the SET of program requirements described here.
RenderPrewarmResult & operator+=(const RenderPrewarmResult &other)
The one skinned entity a view colours by a joint's weights, and which joint.
Unified transform component.
Definition Transform.hpp:45
What a frame's selections came to, counted where each one is made.