Estella 0.113.0
A fast 2D and 3D game engine powered by WebAssembly and ECS
Loading...
Searching...
No Matches
RenderFrameWater.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#include "RenderFrame.hpp"
4#ifdef ES_ENABLE_POSTPROCESS
5#include "../RenderOrigin.hpp"
7#include "../../core/Hash.hpp"
8#include <cmath>
9
10namespace esengine {
11
12RenderFrame::ReceiverMaps RenderFrame::declareCausticReceivers(ecs::Registry& registry, const MaterialBake& bake,
13 const glm::vec4& sun, usize index) {
14 // A light-space height map. A flat refracted ray keeps the same xy at every depth;
15 // the actual bent rays only travel their difference across this map.
16 const glm::dvec4 window(bake.a), levels(bake.b);
17 const double span = window.z, level = levels.z, reach = levels.w;
18 ReceiverMaps maps;
19 if (span <= 0.0 || reach <= 0.0) return maps;
20 // A guard band and a snapped origin keep the opaque map valid as the wave window follows the lens.
21 const double block = span / 4.0, extent = span + block;
22 const auto corner = [span, block, extent](double x) {
23 return std::floor((x + span * 0.5) / block + 0.5) * block - extent * 0.5;
24 };
25 const double x = corner(window.x), z = corner(window.y);
26 maps.window = glm::vec4((window.x - x) / extent, (window.y - z) / extent, span / extent, 0);
27 const double top = std::max(levels.x + levels.y, level) + 0.01 * reach;
28 const double height = top - level + reach;
29 const glm::dvec3 ray = -glm::refract(-glm::dvec3(sun), glm::dvec3(0, 1, 0), 1.0 / 1.333);
30 const glm::dvec2 slope(ray.x / ray.y, ray.z / ray.y);
31 const glm::dvec3 origin = renderOrigin();
32 glm::dmat4 matrix(1.0);
33 matrix[0][0] = 2.0 / extent;
34 matrix[1][0] = -2.0 * slope.x / extent;
35 matrix[3][0] = 2.0 * (origin.x - x + slope.x * (level - origin.y)) / extent - 1.0;
36 matrix[1][1] = 2.0 * slope.y / extent;
37 matrix[2][1] = -2.0 / extent;
38 matrix[3][1] = 1.0 - 2.0 * (origin.z - z + slope.y * (level - origin.y)) / extent;
39 matrix[1][2] = -1.0 / height;
40 matrix[2][2] = 0.0;
41 matrix[3][2] = (top - origin.y) / height;
42 const glm::mat4 projection(matrix);
43
44 Frustum frustum;
45 frustum.extractFromMatrix(projection);
46 auto frame = makeContext();
47 frame.view_projection = projection;
48 frame.purpose = RenderPurpose::ShadowDepth;
49 frame.causticReceivers = true;
50 // Reuse the renderer's mobility tracking. The fixed map is independently keyed
51 // by its draw records so even the first move out of a resting pose is caught.
52 for (auto& plugin : plugins_) {
53 u64 unused = 0;
54 if (plugin->castsShadows()) plugin->castInputs(frame, registry, unused);
55 }
56 const u32 side = bake.w + bake.w / 4;
57 for (u32 group = 0; group < 2; ++group) {
58 const bool moving = group == 1;
59 const usize slot = index * 2 + group;
60 if (slot >= receiver_captures_.size()) receiver_captures_.resize(slot + 1);
61 if (!receiver_captures_[slot]) {
62 auto record = makeUnique<ReceiverCapture>(device_);
63 record->pool.init();
64 receiver_captures_[slot] = std::move(record);
65 }
66 auto& capture = *receiver_captures_[slot];
67 capture.bakeTarget = bake.receiver;
68 capture.pool.beginFrame();
69 capture.draws.clear();
70 RenderCollectContext collect{registry, frustum, clip_state_, capture.pool, capture.draws, frame, computeCameraView(projection)};
71 collect.screen_ui = screen_domain_;
72 collect.ui_tree_layers = ui_tree_layers_;
73 collect.lod = {view_id_, &lod_view_state_, nullptr, true};
74 collect.casters = moving ? CasterSplit::Movers : CasterSplit::Held;
75 for (auto& plugin : plugins_) if (plugin->castsShadows()) plugin->collect(collect);
76 capture.draws.finalize(capture.pool);
77 if (!capture.draws.commandCount()) { capture.valid = false; continue; }
78
79 if (!capture.target || capture.target->getWidth() != side) {
80 FramebufferSpec spec;
81 spec.width = spec.height = side;
82 spec.linearFilter = false;
83 spec.depthStencil = true;
84 capture.target = Framebuffer::create(device_, spec);
85 capture.valid = false;
86 }
87 if (!capture.target) continue;
88 const auto depth = graph_.importTarget(capture.target->handle(), side, side, false, capture.target->getColorAttachment());
89 if (moving) { maps.moving = depth; maps.window.w = 1; }
90 else maps.fixed = depth;
91
92 bool trusted = !moving;
93 u64 key = hash::combineWords(hash::kFnv64Offset, &projection, sizeof(projection));
94 key = hash::combine(key, device_.geometryWrites());
95 key = hash::combine(key, device_.deviceGeneration());
96 key = hash::combine(key, resource_manager_.meshesRevision());
97 if (trusted) key = capture.draws.contentHashOfRecords(key, capture.pool, trusted);
98 const auto trackTexture = [&](TextureHandle texture) {
99 const u64 revision = device_.trackedTextureRevision(texture);
100 trusted &= revision != 0;
101 key = hash::combine(key, revision);
102 };
103 const MaterialStore& materials = context_.materials();
104 for (u32 i = 0; trusted && i < capture.draws.commandCount(); ++i) {
105 const DrawCommand& draw = capture.draws.command(i);
106 if (!draw.material_id) continue;
107 const auto* material = materials.find(draw.material_id);
108 const auto* layout = material ? materials.layoutFor(material->shaderRef) : nullptr;
109 if (!layout) { trusted = false; break; }
110 key = hash::combineWords(key, material->uboBytes.data(), material->uboBytes.size());
111 if (materials.castsCutoutShadow(draw.material_id) && draw.texture_count) {
112 trackTexture(TextureHandle{draw.texture_ids[0]});
113 }
114 for (const auto& binding : material->textures) {
115 if (static_cast<i32>(binding.unit) != layout->depthInputUnit) continue;
116 const auto* texture = resource_manager_.getTexture(binding.texture);
117 if (texture) trackTexture(texture->handle());
118 else trusted = false;
119 }
120 }
121 if (trusted && capture.valid && capture.key == key) continue;
122 if (capture.constants == BufferHandle::Invalid) {
123 capture.constants = device_.createBuffer({GfxBufferUsage::Uniform, RenderContext::frameConstantsSize(), true},
124 GfxContent::transient(), nullptr);
125 }
126 if (capture.constants == BufferHandle::Invalid) continue;
127 capture.pool.upload();
128 context_.prepareFrameConstants(capture.constants, projection);
129 rg::PassDesc pass;
130 pass.name = moving ? "water-caustic-moving-receivers" : "water-caustic-fixed-receivers";
131 pass.write = depth;
132 pass.clear = pass.clearDepth = true;
133 pass.clearColor[3] = 0.0f;
134 pass.discardDepth = true;
135 pass.execute = [this, &capture, trusted, key](const rg::PassContext&) {
136 ES_PROFILE_SCOPE("render.water.causticReceivers");
137 context_.bindFrameConstants(capture.constants);
138 context_.lights().uploadAndBind();
139 capture.draws.execute(device_, capture.pool, context_.materials(), context_.getWhiteTextureId(),
140 nullptr, context_.perDrawBlocks());
141 context_.bindFrameConstants(context_.frameUbo());
142 device_.invalidatePipelineCache();
143 capture.valid = trusted && capture.draws.skippedForProgram() == 0;
144 capture.key = key;
145 };
146 graph_.addPass(std::move(pass));
147 }
148 return maps;
149}
150} // namespace esengine
151#endif
Per-frame CPU scope timing (ES_PROFILE_SCOPE) read by the editor profiler.
#define ES_PROFILE_SCOPE(name)
Frame resources and the shared scene rendering contract.
The point the frame is drawn relative to: a world far from zero loses precision in single floats,...
static Unique< Framebuffer > create(GfxDevice &device, const FramebufferSpec &spec)
Creates a framebuffer from specification.
static constexpr GfxContent transient()
static u32 frameConstantsSize()
Bytes a buffer passed to useFrameConstants must hold.
Central container for all entities and components.
Definition Registry.hpp:73
constexpr u64 combine(u64 h, u64 v)
Definition Hash.hpp:33
constexpr u64 kFnv64Offset
Definition Hash.hpp:12
u64 combineWords(u64 h, const void *data, usize bytes)
Definition Hash.hpp:37
constexpr Unique< T > makeUnique(Args &&... args)
Creates a Unique pointer with the given arguments.
Definition Types.hpp:99
std::int32_t i32
Signed 32-bit integer.
Definition Types.hpp:54
std::uint64_t u64
Unsigned 64-bit integer.
Definition Types.hpp:47
std::size_t usize
Size type for indexing and sizes.
Definition Types.hpp:64
std::uint32_t u32
Unsigned 32-bit integer.
Definition Types.hpp:45
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)