42 , resourceManager_(resourceManager)
44 , frameGraph_(&graph) {
52 , resourceManager_(resourceManager) {
62 if (initialized_)
return;
67 blitShader_ = compileBlit({});
68 if (!blitShader_.isValid()) {
69 ES_LOG_ERROR(
"PostProcessPipeline: Failed to create blit shader");
94 if (handle.isValid()) {
100 for (
const auto& p : parsed.properties) {
101 if (p.fromParam && p.name ==
"u_displayLut" && p.textureUnit >= 0) compiled->setUniform(p.name,
static_cast<i32>(p.textureUnit));
110 view_exposure_ = std::isfinite(ev) ? std::clamp(ev, -10.0f, 10.0f) : 0.0f;
111 context_.setViewExposure(view_exposure_);
119 const u32 key = (upscale ? 1u : 0u) | (
static_cast<u32>(transform) << 1) | (lut ? 8u : 0u);
120 if (key == 0)
return blitShader_;
121 if (
const auto it = blitVariants_.find(key); it != blitVariants_.end())
return it->second;
122 std::vector<std::string> features;
123 if (upscale) features.push_back(
"ES_UPSCALE");
126 if (lut) features.push_back(
"ES_DISPLAY_LUT");
128 if (!handle.
isValid())
ES_LOG_ERROR(
"PostProcessPipeline: the last pass would not compile with upscale={} curve={} lut={}", upscale,
static_cast<u32>(transform), lut);
129 blitVariants_[key] = handle;
138 const struct {
bool upscale;
OutputTransform transform;
bool lut; } wants[] = {
139 {upscale, output_transform_, lut},
140 {upscale, output_transform_,
false},
141 {
false, output_transform_,
false},
144 for (
const auto& w : wants) {
146 if (handle.isValid())
return handle;
157 return frame_format_.effective;
161void PostProcessPipeline::commitFormat() {
162 frame_format_ =
decideHdrFormat(linear_output_, device_.supportsFloatTargets());
165void PostProcessPipeline::ensureGraph() {
170 graph_ = ownedGraph_.get();
172 if (linear_output_) {
175 :
"SRGB8_ALPHA8 (LDR linear)");
186rg::TargetDesc PostProcessPipeline::chainTarget(
bool withDepth)
const {
188 desc.
format = interFormat();
189 desc.linearFilter =
true;
190 desc.depthStencil = withDepth;
200rg::TargetDesc PostProcessPipeline::blitSourceTarget(
bool withDepth)
const {
201 rg::TargetDesc desc = chainTarget(withDepth);
207 if (!initialized_)
return;
209 for (
auto& pass : passes_) releasePassResources(pass);
210 for (
auto& pass : screenPasses_) releasePassResources(pass);
211 releasePassResources(sky_capture_.copy);
212 releasePassResources(cloud_shadow_copy_);
213 dropSpareParamUbos();
214 sky_capture_.target.reset();
215 sky_capture_.state = SkyCapture::State::Idle;
216 for (
auto& [source, program] : compute_cache_) device_.deleteCompute(program);
217 compute_cache_.clear();
219 dynamic_gis_.clear();
221 device_.deleteBuffer(compute_view_ubo_);
225 screenPasses_.clear();
229 auto* device = &device_;
231 device->deleteBuffer(projected_triangle_indices_);
235 device->deleteBuffer(screen_quad_vbo_);
239 device->deleteVertexLayout(screen_quad_layout_);
246 graph_ = frameGraph_;
249 screenCaptureActive_ =
false;
250 screenFBOCreated_ =
false;
253 if (blitShader_.isValid()) {
254 resourceManager_.releaseShader(blitShader_);
256 if (copyShader_.isValid()) {
257 resourceManager_.releaseShader(copyShader_);
260 if (exactCopyShader_.isValid()) {
261 resourceManager_.releaseShader(exactCopyShader_);
264 if (rgbmShader_.isValid()) {
265 resourceManager_.releaseShader(rgbmShader_);
268 if (copyDepthShader_.isValid()) {
269 resourceManager_.releaseShader(copyDepthShader_);
272 for (
auto* outline : {&outlineShader_, &outlineGroundShader_}) {
273 if (outline->isValid()) resourceManager_.releaseShader(*outline);
276 for (
auto& [key, shader] : blitVariants_) {
277 if (shader.isValid()) resourceManager_.releaseShader(shader);
279 blitVariants_.clear();
281 device_.deleteBuffer(blitParamUbo_);
283 blitParamAmount_ = -1.0f;
286 initialized_ =
false;
291 if (!initialized_)
return;
292 if (width == width_ && height == height_)
return;
299 if (graph_) graph_->releasePool();
307 if (screenFBOCreated_) {
309 screenFBOCreated_ =
false;
320 passes_.push_back(pass);
321 return static_cast<u32>(passes_.size() - 1);
331bool PostProcessPipeline::programPending(
const PostProcessPass& pass)
const {
332 if (!device_.
skipPendingPrograms() || !pass.nativeKind.empty() || pass.isCompute)
return false;
334 return shader && !device_.
programReady(shader->handle());
342 passes_.push_back(pass);
343 return static_cast<u32>(passes_.size() - 1);
347 const std::vector<std::string>& params,
u32 workgroupX,
u32 workgroupY) {
356 if (device_.supportsCompute()) {
357 auto cached = compute_cache_.find(wgsl);
358 if (cached == compute_cache_.end()) {
362 ES_LOG_ERROR(
"PostProcessPipeline: compute pass '{}' did not compile: {}", name, log);
365 cached = compute_cache_.emplace(wgsl, program).first;
369 passes_.push_back(pass);
370 return static_cast<u32>(passes_.size() - 1);
379void PostProcessPipeline::applySampleRequest() {
380 scene_samples_ = std::clamp(requested_samples_, 1u, device_.
maxSamples());
387 requested_samples_ = samples < 1u ? 1u : samples;
388 if (initialized_) applySampleRequest();
392 if (
auto* pass = findPass(passName)) {
395 pass->scale = std::clamp(scale, 0.01f, 1.0f);
400 if (
auto* pass = findPass(passName)) pass->continuesEffect =
true;
403bool PostProcessPipeline::passHasTexture(
const PostProcessPass& pass,
const char* name) {
405 if (!layout)
return false;
406 for (
const auto& slot : layout->
textures) {
407 if (slot.name == name)
return true;
413 const MaterialUniformLayout* layout = context_.materials().layoutFor(pass.shader);
418 return passHasTexture(pass,
"u_history");
421u64 PostProcessPipeline::feedbackKey(
const std::string& passName)
const {
422 return temporalKey_ * 1000003ull + std::hash<std::string>{}(passName);
425bool PostProcessPipeline::passesWantGBuffer() {
426 if (bypass_)
return false;
427 for (
const auto& pass : passes_) {
428 if (!pass.enabled)
continue;
430 if (!pass.nativeKind.empty()) {
432 if (
const auto skip = pass.floatUniforms.find(
"u_skip"); skip != pass.floatUniforms.end() && (
static_cast<u32>(skip->second) & 32u))
continue;
433 if (device_.supportsCompute())
return true;
436 const MaterialUniformLayout* layout = context_.materials().layoutFor(pass.shader);
437 if (layout && layout->usesGBuffer)
return true;
443 if (!initialized_ || bypass_)
return false;
444 for (
const auto& pass : passes_) {
445 if (pass.enabled && passIsTemporal(pass))
return true;
451 if (!initialized_ || bypass_)
return false;
452 for (
const auto& pass : passes_) {
453 if (!pass.enabled || !pass.nativeKind.empty() || passIsTemporal(pass))
continue;
455 if (layout && layout->
find(
"u_prevViewProjection0"))
return true;
461 TemporalState& state = temporal_[key];
464 state.current = viewProjection;
470 if (!initialized_ || bypass_)
return false;
471 for (
const auto& pass : passes_) {
472 if (!pass.enabled || !pass.nativeKind.empty())
continue;
474 if (!layout || !layout->
find(
"u_sceneCoverage"))
continue;
475 if (
const auto it = pass.floatUniforms.find(
"u_panorama"); it != pass.floatUniforms.end() && it->second > 0.001f)
continue;
482 if (!initialized_ || bypass_ || !device_.supportsFloatTargets())
return false;
483 for (
const auto& pass : passes_) {
484 if (pass.enabled && passHasTexture(pass,
"u_velocity"))
return true;
492 f32 f = 1.0f, r = 0.0f;
494 f /=
static_cast<f32>(base);
495 r += f *
static_cast<f32>(index % base);
502constexpr u32 kJitterPhases = 8;
506 TemporalState& state = temporal_[key];
509 else state.previous = viewProjection;
510 state.current = viewProjection;
515 if (state.writtenFrame + 1 != state.frame) state.valid =
false;
516 const u32 phase = (state.frame % kJitterPhases) + 1;
517 const f32 jx = halton(phase, 2) - 0.5f;
518 const f32 jy = halton(phase, 3) - 0.5f;
519 const f32 w =
static_cast<f32>(std::max(width_, 1u));
520 const f32 h =
static_cast<f32>(std::max(height_, 1u));
521 state.jitter = {jx * 2.0f / w, jy * 2.0f / h};
527 const auto it = temporal_.find(key);
528 const u32 frame = it == temporal_.end() ? 0u : it->second.frame;
532 const u32 phase = ((frame + 1) % kJitterPhases) + 1;
533 const f32 w =
static_cast<f32>(std::max(width_, 1u));
534 const f32 h =
static_cast<f32>(std::max(height_, 1u));
535 view.
jitter = {(halton(phase, 2) - 0.5f) * 2.0f / w, (halton(phase, 3) - 0.5f) * 2.0f / h};
537 const u32 before = (frame % kJitterPhases) + 1;
538 view.
previousJitter = {(halton(before, 2) - 0.5f) * 2.0f / w, (halton(before, 3) - 0.5f) * 2.0f / h};
546 if (!passHasTexture(pass,
"u_rainCover"))
return false;
548 return layout && layout->
find(
"u_shelterRange");
552 if (!initialized_ || bypass_)
return false;
553 for (
const auto& pass : passes_) {
554 if (pass.
enabled && passDrawsCover(pass))
return true;
560 for (
const auto& pass : passes_) {
561 if (!pass.
enabled || !passDrawsCover(pass))
continue;
563 return std::max(it->second, 10.0f);
570 for (
const auto& pass : passes_) {
571 if (!pass.
enabled || !passDrawsCover(pass))
continue;
579 cover_active_ =
false;
581 if (!cover_fbo_ || cover_fbo_->getWidth() != size) {
590 ES_LOG_ERROR(
"PostProcessPipeline: Failed to create the rain cover target");
593 static u32 nextCoverSerial = 0;
594 cover_serial_ = ++nextCoverSerial;
596 cover_resource_ = graph_->importTarget(cover_fbo_->handle(), size, size,
false,
597 cover_fbo_->getColorAttachment());
598 cover_active_ =
true;
599 return cover_resource_;
603 velocity_active_ =
false;
604 if (!graph_ || !device_.supportsFloatTargets())
return rg::kNoResource;
605 const u32 w = std::max(width_, 1u);
606 const u32 h = std::max(height_, 1u);
607 if (!velocity_fbo_ || velocity_fbo_->getWidth() != w || velocity_fbo_->getHeight() != h) {
615 if (!velocity_fbo_) {
616 ES_LOG_ERROR(
"PostProcessPipeline: Failed to create the motion target");
620 velocity_resource_ = graph_->importTarget(velocity_fbo_->handle(), w, h,
false,
621 velocity_fbo_->getColorAttachment());
622 velocity_active_ =
true;
623 return velocity_resource_;
626bool PostProcessPipeline::passIsHighPrecision(
const PostProcessPass& pass) {
631PostProcessPipeline::TemporalState* PostProcessPipeline::prepareHistory(TemporalState& state,
636 if (state.history[0] && state.width == w && state.height == h
637 && state.format == format) {
640 for (
auto& fbo : state.history) {
641 FramebufferSpec spec;
642 spec.colorFormat = format;
645 spec.depthStencil =
false;
647 spec.linearFilter =
true;
650 ES_LOG_ERROR(
"PostProcessPipeline: Failed to create a temporal history target");
651 state.history[0].reset();
652 state.history[1].reset();
658 state.format = format;
664 if (!rgbmShader_.isValid()) {
665 rgbmShader_ = compileBlit({
"ES_RGBM"});
666 if (!rgbmShader_.isValid()) {
ES_LOG_ERROR(
"PostProcessPipeline: the RGBM pack would not compile");
return; }
668 Shader* shader = resourceManager_.getShader(rgbmShader_);
670 applyPassPipeline(*shader);
673 bindBlitInputs(rgbmShader_);
678 sky_capture_.pass = passName;
679 sky_capture_.width = std::clamp(width, 4u, 512u);
680 sky_capture_.height = std::clamp(height, 2u, 256u);
681 sky_capture_.state = SkyCapture::State::Requested;
686 SkyCapture& c = sky_capture_;
688 case SkyCapture::State::Idle:
return 2;
689 case SkyCapture::State::Requested:
return 0;
690 case SkyCapture::State::Drawn:
691 c.readback = c.target ? device_.requestReadback(c.target->handle(), c.width, c.height) :
ReadbackHandle::Invalid;
693 c.state = SkyCapture::State::Reading;
695 case SkyCapture::State::Reading: {
698 c.state = SkyCapture::State::Idle;
700 c.pixels.resize(
static_cast<usize>(c.width) * c.height * 4);
701 return device_.takeReadback(c.readback, c.pixels.data(), c.pixels.size()) ? 1 : 2;
708 SkyCapture& c = sky_capture_;
709 if (!c.target || c.target->getSpecification().width != c.width || c.target->getSpecification().height != c.height) {
712 spec.
width = c.width;
718 ES_LOG_ERROR(
"PostProcessPipeline: could not make the sky capture target");
719 c.state = SkyCapture::State::Idle;
727 c.copy.name = pass.
name +
"_skyCapture";
728 c.copy.temporal =
false;
729 c.copy.feedback =
false;
730 c.copy.earlierInputs.clear();
731 c.copy.floatUniforms[
"u_skyCapture"] = 1.0f;
732 c.copy.paramDirty =
true;
735 node.name = c.copy.name;
736 node.reads = {input, effectInput};
738 node.write = graph_->importTarget(c.target->handle(), c.width, c.height,
false, c.target->getColorAttachment());
739 node.execute = [
this](
const rg::PassContext&
ctx) {
740 renderPass(sky_capture_.copy,
ctx);
741 sky_capture_.state = SkyCapture::State::Drawn;
743 graph_->addPass(std::move(node));
749 if (!pass.
enabled || programPending(pass))
continue;
751 if (!layout || !layout->
find(
"u_cloudShadowPass"))
continue;
753 const auto value = [&](
const char* name,
f32 fallback) {
758 if (value(
"u_castCloudShadows", 0.0f) < 0.5f)
continue;
759 if (layout->
find(
"u_cloudShadow") && value(
"u_cloudShadow", 0.0f) <= 0.001f)
continue;
760 extentKm = std::max(value(
"u_cloudShadowExtentKm", 16.0f), 0.1f);
761 unitsPerKm = layout->
find(
"u_unitsPerKm") ? std::max(value(
"u_unitsPerKm", 0.0f), 0.0f) : 0.0f;
768 f32 extentKm = 0.0f, unitsPerKm = 0.0f;
773 cloud_shadow_copy_ = *caster;
775 cloud_shadow_copy_.name = caster->
name +
"_cloudShadow";
776 cloud_shadow_copy_.temporal =
false;
777 cloud_shadow_copy_.feedback =
false;
778 cloud_shadow_copy_.earlierInputs.clear();
779 cloud_shadow_copy_.floatUniforms[
"u_cloudShadowPass"] = 1.0f;
780 for (
int c = 0; c < 4; ++c) {
781 cloud_shadow_copy_.vec4Uniforms[
"u_cloudShadowInv" + std::to_string(c)] = glm::vec4(inverse[c]);
783 cloud_shadow_copy_.vec4Uniforms[
"u_cloudShadowRect"] = rect;
784 cloud_shadow_copy_.paramDirty =
true;
785 drawing_cloud_shadow_ =
true;
789 renderPass(cloud_shadow_copy_,
ctx);
790 drawing_cloud_shadow_ =
false;
794 const std::vector<std::pair<std::string, glm::vec4>>& overrides,
u32 scratch) {
796 Shader* program = resourceManager_.getShader(handle);
797 if (!program)
return false;
798 applyPassPipeline(*program);
804 if (!context_.materials().bindThrough(material, handle, overrides, scratch))
return false;
811 Shader* program = handle.
isValid() ? resourceManager_.getShader(handle) :
nullptr;
812 return program && context_.materials().layoutFor(handle) && device_.programReady(program->
handle());
817 Shader* program = handle.
isValid() ? resourceManager_.getShader(handle) :
nullptr;
818 if (!program)
return false;
819 applyPassPipeline(*program,
true);
826 context_.materials().bindForDraw(material);
839BufferHandle PostProcessPipeline::takeParamUbo(
u32 bytes,
const void* data) {
840 for (
usize i = 0; i < spare_param_ubos_.size(); ++i) {
841 if (spare_param_ubos_[i].bytes != bytes)
continue;
842 const BufferHandle handle = spare_param_ubos_[i].handle;
843 spare_param_ubos_[i] = spare_param_ubos_.back();
844 spare_param_ubos_.pop_back();
845 device_.updateBuffer(handle, 0, data, bytes);
851void PostProcessPipeline::dropSpareParamUbos() {
852 for (
const SpareParamUbo& spare : spare_param_ubos_) device_.deleteBuffer(spare.handle);
853 spare_param_ubos_.clear();
857 const std::string& uniform,
f32 value) {
858 if (
auto* pass = findPass(passName)) {
865 const std::string& uniform,
u32 glTextureId) {
866 auto* pass = findPass(passName);
869 if (name == uniform) {
id = glTextureId;
return; }
875 const std::string& uniform,
876 const glm::vec4& value) {
877 if (
auto* pass = findPass(passName)) {
884 if (index >= passes_.size())
return nullptr;
885 return &passes_[index];
889 for (
const auto& pass : passes_) {
890 if (pass.
name == name) {
897PostProcessPass* PostProcessPipeline::findPass(
const std::string& name) {
898 for (
auto& pass : passes_) {
899 if (pass.
name == name) {
906void PostProcessPipeline::ensureScreenQuad() {
911 -1.0f, -1.0f, 0.0f, 0.0f,
912 3.0f, -1.0f, 2.0f, 0.0f,
913 -1.0f, 3.0f, 0.0f, 2.0f,
915 screen_quad_vbo_ = device_.createBuffer(
919 VertexLayoutDesc desc;
920 desc.attributeCount = 2;
921 desc.strides[0] = 4 *
sizeof(
f32);
924 screen_quad_layout_ = device_.createVertexLayout(desc);
927void PostProcessPipeline::drawScreenQuad() {
928 device_.setVertexBuffer(0, screen_quad_vbo_, 0);
930 device_.drawArrays(0, 3);
936 for (
const auto& light : context_.lights().data().lights) {
937 if (light.posDir.z > 0.5f && light.posDir.z < 1.5f && light.color.a > 0.0f) {
938 sun = glm::vec4(-glm::normalize(glm::vec3(light.posDir.x, light.posDir.y, light.posDir.w)), 1.0f);
947 const auto ref = context_.materials().shaderOf(material);
948 Shader* shader = resourceManager_.getShader(ref);
949 const auto* layout = context_.materials().layoutFor(ref);
950 if (!shader || !layout)
return false;
951 if (layout->
findTexture(
"u_bakeReceiverDepth") && sun.y <= 0.0f)
return true;
953 const u16 triangle[] = {0, 1, 2};
958 applyPassPipeline(*shader,
false,
true);
959 if (!context_.materials().bindThrough(material, ref, {{
"u_bakeSun", sun}, {
"u_bakeReceiverWindow", receiverWindow}}, scratch))
return false;
960 device_.setVertexBuffer(0, screen_quad_vbo_, 0);
962 if (
const auto* slot = layout->
findTexture(
"u_bakeReceiverDepth")) device_.bindTexture(slot->unit, receiverDepth);
965 if (
const auto* slot = layout->
findTexture(
"u_bakeMovingDepth")) device_.bindTexture(slot->unit, movingDepth);
967 device_.setIndexBuffer(projected_triangle_indices_);
972void PostProcessPipeline::applyPassPipeline(
const Shader& shader,
bool over,
bool additive) {
978 desc.program = shader.handle();
979 desc.vertexLayout = screen_quad_layout_;
980 desc.blendEnabled = over || additive;
981 if (additive) desc.blend = BlendMode::PmaAdditive;
982 else if (over) desc.blend = BlendMode::PremultipliedAlpha;
983 desc.depthTest =
false;
984 desc.depthWrite =
false;
985 device_.setPipeline(device_.createPipeline(desc));
989 if (screenCaptureActive_ && screenFBOCreated_)
return screenFBO_->handle();
990 if (inFrame_ && graph_)
return graph_->framebufferOf(sceneResource_);
1007 graph_->begin(width_, height_);
1010 const bool sceneIsBlitSource = bypass_ || passes_.empty();
1012 sceneIsBlitSource ? blitSourceTarget(scene_needs_depth_) : chainTarget(scene_needs_depth_);
1016 sceneDesc.
samples = scene_samples_;
1019 scene_gbuffer_ = scene_needs_depth_ && passesWantGBuffer();
1020 sceneDesc.
gbuffer = scene_gbuffer_;
1021 sceneResource_ = graph_->createExternalTarget(sceneDesc);
1023 ES_LOG_ERROR(
"PostProcessPipeline: no scene target this frame");
1031 if (linear_output_) {
1033 for (
int i = 0; i < 3; ++i) {
1036 v <= 0.04045f ? v / 12.92f : std::pow((v + 0.055f) / 1.055f, 2.4f);
1040 device_.beginRenderPass(pass);
1041 device_.setViewport(0, 0, width_, height_);
1049 if (!initialized_ || !inFrame_)
return;
1053 sceneTexture_ = graph_->textureOf(sceneResource_);
1056 device_.endRenderPass();
1058 runChain(passes_, sceneResource_);
1062 velocity_active_ =
false;
1063 cover_active_ =
false;
1064 background_sky_ =
false;
1065 if (!initialized_ || !inFrame_)
return;
1066 device_.invalidatePipelineCache();
1069 present_over_ =
false;
1072 present_required_ =
false;
1076 Shader* shader = resourceManager_.getShader(pass.
shader);
1077 if (!shader)
return;
1079 auto* device = &device_;
1080 applyPassPipeline(*shader);
1092 shader->
setUniform(
"u_gbuffer",
static_cast<i32
>(kGBufferUnit));
1095 shader->
setUniform(
"u_shadowMap",
static_cast<i32>(SHADOW_MAP_TEXTURE_UNIT));
1103 const MaterialUniformLayout* layout = context_.materials().layoutFor(pass.
shader);
1104 TemporalState* temporal =
nullptr;
1106 if (
auto it = temporal_.find(temporalKey_); it != temporal_.end()) temporal = &it->second;
1108 if (
auto it = feedback_.find(pass.
historyKey); it != feedback_.end()) temporal = &it->second;
1110 if (layout && layout->find(
"u_backgroundSky")) {
1111 const f32 behind = background_sky_ ? 1.0f : 0.0f;
1112 const auto [held, added] = pass.
floatUniforms.try_emplace(
"u_backgroundSky", behind);
1113 if (added || held->second != behind) {
1114 held->second = behind;
1121 if (layout && layout->find(
"u_coverMatrix0")) {
1122 for (
int c = 0; c < 4; ++c) {
1123 pass.
vec4Uniforms[
"u_coverMatrix" + std::to_string(c)] = glm::vec4(cover_matrix_[c]);
1125 pass.
floatUniforms[
"u_coverActive"] = cover_active_ ? 1.0f : 0.0f;
1128 if (layout->find(
"u_coverRange")) pass.
floatUniforms[
"u_coverRange"] = coverRange();
1129 if (layout->find(
"u_coverBias")) pass.
floatUniforms[
"u_coverBias"] = coverBias();
1132 if (layout && layout->usesLights) {
1135 context_.lights().uploadAndBind();
1137 if (drawing_cloud_shadow_) {
1138 device->bindTexture(SHADOW_MAP_TEXTURE_UNIT, context_.materials().builtinDefault(MaterialDefaultTexture::White));
1139 }
else if (shadow_texture_ != 0) {
1140 device->bindTexture(SHADOW_MAP_TEXTURE_UNIT, TextureHandle{shadow_texture_});
1143 if (layout && layout->find(
"u_envParams")) {
1144 const LightConstants& lights = context_.lights().data();
1153 for (
int c = 0; c < 4; ++c) {
1154 pass.
vec4Uniforms[
"u_prevViewProjection" + std::to_string(c)] =
1155 glm::vec4(temporal->previous[c]);
1157 pass.
floatUniforms[
"u_historyValid"] = temporal->valid ? 1.0f : 0.0f;
1158 pass.
vec4Uniforms[
"u_jitter"] = glm::vec4(temporal->jitter, 0.0f, 0.0f);
1160 }
else if (temporal) {
1161 pass.
floatUniforms[
"u_historyValid"] = temporal->valid ? 1.0f : 0.0f;
1166 if (!pass.
temporal && layout && layout->find(
"u_prevViewProjection0")) {
1167 if (
auto it = temporal_.find(temporalKey_); it != temporal_.end()) {
1168 for (
int c = 0; c < 4; ++c) {
1169 pass.
vec4Uniforms[
"u_prevViewProjection" + std::to_string(c)] = glm::vec4(it->second.previous[c]);
1175 if (layout->blockSize > 0) {
1180 pass.
paramBytes.assign(layout->blockSize, 0);
1181 for (
const auto& p : layout->params) {
1182 std::memcpy(pass.
paramBytes.data() + p.offset, p.defaults,
1183 p.arity *
sizeof(f32));
1185 std::memcpy(pass.
paramBytes.data() + p.offset, &fit->second,
sizeof(f32));
1188 std::memcpy(pass.
paramBytes.data() + p.offset, &vit->second.x,
1189 std::min(p.arity, 4u) *
sizeof(f32));
1193 if (pass.
paramUbo == BufferHandle::Invalid) {
1201 if (pass.
paramUbo != BufferHandle::Invalid) {
1202 device->setUniformBuffer(MATERIAL_CONSTANTS_BINDING, pass.
paramUbo);
1212 const bool scene = graph_ && !drawing_cloud_shadow_;
1213 device->bindTexture(kSceneDepthUnit, scene ? graph_->depthTextureOf(sceneResource_) : TextureHandle::Invalid);
1215 device->bindTexture(kGBufferUnit, scene && scene_gbuffer_ ? graph_->gbufferTextureOf(sceneResource_)
1216 : TextureHandle::Invalid);
1220 for (
const auto& slot : layout->textures) {
1221 TextureHandle gpu = context_.materials().builtinDefault(slot);
1222 if (temporal && (slot.name ==
"u_history" || slot.name ==
"u_feedback")
1223 && temporal->history[temporal->readIndex]) {
1224 gpu = temporal->history[temporal->readIndex]->getColorAttachment();
1226 if (slot.name ==
"u_environment" && environment_texture_ != 0) {
1229 if (slot.name ==
"u_velocity" && velocity_active_ && velocity_fbo_) {
1230 gpu = velocity_fbo_->getColorAttachment();
1233 if (slot.name ==
"u_sceneAlbedo" && graph_ && scene_gbuffer_ && !drawing_cloud_shadow_) {
1234 const TextureHandle albedo = graph_->albedoTextureOf(sceneResource_);
1235 if (albedo != TextureHandle::Invalid) gpu = albedo;
1237 if (slot.name ==
"u_rainCover" && cover_active_ && cover_fbo_) {
1238 gpu = cover_fbo_->getColorAttachment();
1241 if (name == slot.name && glId != 0) { gpu =
TextureHandle{glId};
break; }
1244 if (name != slot.name || !graph_)
continue;
1246 if (earlier != TextureHandle::Invalid) gpu = earlier;
1249 if (gpu != TextureHandle::Invalid) device->bindTexture(slot.unit, gpu);
1258 shader->
setUniform(
"u_resolution", glm::vec2(
static_cast<f32>(
ctx.width),
static_cast<f32>(
ctx.height)));
1264 if (extraUnit >= kGBufferUnit)
break;
1266 device->bindTexture(extraUnit, TextureHandle{glId});
1283void PostProcessPipeline::computePass(PostProcessPass& pass,
const rg::PassContext& ctx) {
1284 if (pass.compute == ComputeHandle::Invalid ||
ctx.output == TextureHandle::Invalid)
return;
1286 if (input == TextureHandle::Invalid)
return;
1290 const usize floats = std::max<usize>(4, (pass.computeParams.size() + 3) / 4 * 4);
1291 std::vector<f32> values(floats, 0.0f);
1292 for (usize i = 0; i < pass.computeParams.size(); ++i) {
1293 if (
auto it = pass.floatUniforms.find(pass.computeParams[i]); it != pass.floatUniforms.end()) values[i] = it->second;
1295 const u32 paramBytes =
static_cast<u32>(values.size() *
sizeof(f32));
1296 if (pass.paramUbo == BufferHandle::Invalid) {
1297 pass.paramUbo = takeParamUbo(paramBytes, values.data());
1298 pass.paramUboBytes = paramBytes;
1300 device_.updateBuffer(pass.paramUbo, 0, values.data(), paramBytes);
1303 const f32 w =
static_cast<f32>(std::max(
ctx.width, 1u));
1304 const f32 h =
static_cast<f32>(std::max(
ctx.height, 1u));
1305 const f32 view[4] = {w, h, 1.0f / w, 1.0f / h};
1306 if (compute_view_ubo_ == BufferHandle::Invalid) {
1307 compute_view_ubo_ = device_.createBuffer({GfxBufferUsage::Uniform,
sizeof(view),
true},
1308 GfxContent::retained(), view);
1310 device_.updateBuffer(compute_view_ubo_, 0, view,
sizeof(view));
1314 const TextureHandle depth = (pass.usesComputeDepth && graph_ && sceneResource_ != rg::kNoResource) ? graph_->depthTextureOf(sceneResource_)
1315 : TextureHandle::Invalid;
1316 const GfxComputeBinding bindings[6] = {
1317 GfxComputeBinding::sampled(0, input),
1318 GfxComputeBinding::storageTexture(1,
ctx.output),
1319 GfxComputeBinding::uniform(2, pass.paramUbo),
1320 GfxComputeBinding::uniform(3, compute_view_ubo_),
1321 GfxComputeBinding::depth(4, depth),
1322 GfxComputeBinding::sampler(5, TextureFilter::Linear),
1324 const u32 groupsX = (
ctx.width + pass.workgroupX - 1) / pass.workgroupX;
1325 const u32 groupsY = (
ctx.height + pass.workgroupY - 1) / pass.workgroupY;
1326 device_.dispatchCompute(pass.compute, bindings, 6, groupsX, groupsY, 1);
1331 constexpr u32 kSpareClears = 8;
1332 for (
usize i = 0; i < spare_param_ubos_.size();) {
1333 if (++spare_param_ubos_[i].clears <= kSpareClears) { ++i;
continue; }
1334 device_.deleteBuffer(spare_param_ubos_[i].handle);
1335 spare_param_ubos_[i] = spare_param_ubos_.back();
1336 spare_param_ubos_.pop_back();
1338 for (
auto& pass : passes_) {
1340 if (pass.paramUboBytes > 0) spare_param_ubos_.push_back({pass.paramUbo, pass.paramUboBytes, 0});
1341 else device_.deleteBuffer(pass.paramUbo);
1343 pass.paramUboBytes = 0;
1347 display_lut_texture_ = 0;
1348 display_lut_amount_ = 0.0f;
1352 output_target_fbo_ = target;
1365 handle = compileBlit({marked ?
"ES_COPY" :
"ES_COPY_EXACT"});
1367 ES_LOG_ERROR(
"PostProcessPipeline: no copy shader; a refractive surface sees nothing behind it");
1371 Shader* shader = resourceManager_.getShader(handle);
1372 if (!shader)
return;
1373 applyPassPipeline(*shader);
1376 bindBlitInputs(handle);
1381 return device_.supportsFloatTargets();
1387constexpr u32 kSelectionMaskUnit = 15;
1392 if (!outlineShader_.isValid()) {
1393 outlineShader_ = compileBlit({
"ES_SELECTION_OUTLINE"});
1394 if (!outlineShader_.isValid())
return;
1396 Shader* shader = resourceManager_.getShader(outlineShader_);
1397 if (!shader)
return;
1398 applyPassPipeline(*shader,
true);
1399 if (shader->
hasUniform(
"u_selectionMask")) shader->
setUniform(
"u_selectionMask",
static_cast<i32>(kSelectionMaskUnit));
1402 bindBlitInputs(outlineShader_);
1403 device_.bindTexture(kSelectionMaskUnit, mask);
1410 if (!outlineGroundShader_.isValid()) {
1411 outlineGroundShader_ = compileBlit({
"ES_SELECTION_SCENE_DEPTH"});
1412 if (!outlineGroundShader_.isValid())
return;
1414 Shader* shader = resourceManager_.getShader(outlineGroundShader_);
1415 if (!shader)
return;
1416 applyPassPipeline(*shader);
1419 bindBlitInputs(outlineGroundShader_);
1426 if (!copyDepthShader_.isValid()) {
1427 copyDepthShader_ = compileBlit({
"ES_COPY_DEPTH"});
1428 if (!copyDepthShader_.isValid()) {
1429 ES_LOG_ERROR(
"PostProcessPipeline: no depth copy shader; water sees no depth behind it");
1433 Shader* shader = resourceManager_.getShader(copyDepthShader_);
1434 if (!shader)
return;
1435 applyPassPipeline(*shader);
1440 bindBlitInputs(copyDepthShader_);
1444void PostProcessPipeline::blitPass() {
1446 Shader* shader = resourceManager_.getShader(outputHandle);
1447 if (!shader)
return;
1452 if (output_vp_w_ > 0 && output_vp_h_ > 0) {
1453 device_.setViewport(output_vp_x_, output_vp_y_, output_vp_w_, output_vp_h_);
1456 applyPassPipeline(*shader, present_over_);
1459 bindBlitInputs(outputHandle);
1464void PostProcessPipeline::bindBlitInputs(
const resource::ShaderHandle& handle) {
1465 const MaterialUniformLayout* layout = context_.materials().layoutFor(handle);
1466 if (!layout)
return;
1468 const bool lastPass = handle.id() != copyShader_.id() && handle.id() != exactCopyShader_.id() && handle.id() != copyDepthShader_.id();
1469 const f32 amount = lastPass && displayLutActive() ? display_lut_amount_ : 0.0f;
1470 if (layout->blockSize > 0) {
1471 if (blitParamUbo_ == BufferHandle::Invalid || blitParamAmount_ != amount) {
1472 std::vector<u8> bytes(layout->blockSize, 0);
1473 for (
const auto& p : layout->params) {
1474 if (p.name ==
"u_displayLutAmount") std::memcpy(bytes.data() + p.offset, &amount,
sizeof(f32));
1476 if (blitParamUbo_ == BufferHandle::Invalid) {
1477 blitParamUbo_ = device_.createBuffer({GfxBufferUsage::Uniform, layout->blockSize,
true},
1478 GfxContent::retained(), bytes.data());
1480 device_.updateBuffer(blitParamUbo_, 0, bytes.data(),
static_cast<u32>(bytes.size()));
1482 blitParamAmount_ = amount;
1484 device_.setUniformBuffer(MATERIAL_CONSTANTS_BINDING, blitParamUbo_);
1486 for (
const auto& slot : layout->textures) {
1487 TextureHandle gpu = context_.materials().builtinDefault(slot);
1488 if (slot.name ==
"u_displayLut" && lastPass && display_lut_texture_ != 0) gpu =
TextureHandle{display_lut_texture_};
1489 if (gpu != TextureHandle::Invalid) device_.bindTexture(slot.unit, gpu);
1493void PostProcessPipeline::runChain(std::vector<PostProcessPass>& passes, rg::ResourceId scene) {
1494 if (!graph_ || scene == rg::kNoResource)
return;
1499 const u32 outW = std::max(width_, output_vp_x_ + output_vp_w_);
1500 const u32 outH = std::max(height_, output_vp_y_ + output_vp_h_);
1501 const rg::ResourceId out = graph_->importTarget(output_target_fbo_, outW, outH);
1502 const rg::TargetDesc desc = chainTarget(
false);
1503 const rg::TargetDesc blitDesc = blitSourceTarget(
false);
1507 std::vector<char> live(passes.size());
1508 for (usize i = 0; i < passes.size(); ++i) live[i] = runnable(passes[i]) ? 1 : 0;
1509 if (device_.skipPendingPrograms()) {
1510 for (usize begin = 0; begin < passes.size();) {
1511 usize end = begin + 1;
1512 while (end < passes.size() && passes[end].continuesEffect) ++end;
1514 for (usize k = begin; k < end && ready; ++k) ready = !live[k] || !programPending(passes[k]);
1515 if (!ready) std::fill(live.begin() +
static_cast<std::ptrdiff_t
>(begin), live.begin() +
static_cast<std::ptrdiff_t
>(end), 0);
1521 usize lastEnabled = passes.size();
1522 for (usize i = passes.size(); i-- > 0;) {
1523 if (live[i]) { lastEnabled = i;
break; }
1526 rg::ResourceId input = scene;
1527 rg::ResourceId effectInput = scene;
1529 std::vector<std::pair<std::string, rg::ResourceId>> effectOutputs;
1530 for (usize i = 0; i < passes.size(); ++i) {
1531 auto& pass = passes[i];
1532 if (!live[i])
continue;
1533 if (!pass.continuesEffect) {
1534 effectInput = input;
1535 effectOutputs.clear();
1538 node.name = pass.name;
1539 pass.earlierInputs.clear();
1540 if (
const MaterialUniformLayout* layout = context_.materials().layoutFor(pass.shader)) {
1541 for (
const auto& slot : layout->textures) {
1542 if (slot.name ==
"u_sceneColor") {
1543 pass.earlierInputs.emplace_back(slot.name, scene);
1544 node.dependencies.push_back(scene);
1547 if (slot.name.rfind(
"u_pass_", 0) != 0)
continue;
1548 const std::string wanted = slot.name.substr(7);
1549 for (
const auto& [name,
id] : effectOutputs) {
1550 if (name != wanted)
continue;
1551 pass.earlierInputs.emplace_back(slot.name,
id);
1552 node.dependencies.push_back(
id);
1560 node.reads = {input, effectInput};
1565 if (scene_needs_depth_ || scene_gbuffer_) node.dependencies.push_back(scene);
1568 if (velocity_active_ && velocity_resource_ != rg::kNoResource && passHasTexture(pass,
"u_velocity")) {
1569 node.dependencies.push_back(velocity_resource_);
1571 if (cover_active_ && cover_resource_ != rg::kNoResource && passHasTexture(pass,
"u_rainCover")) {
1572 node.dependencies.push_back(cover_resource_);
1574 if (shadow_resource_ != rg::kNoResource && passUsesLights(pass)) {
1575 node.dependencies.push_back(shadow_resource_);
1579 rg::TargetDesc writeDesc = (i == lastEnabled) ? blitDesc : desc;
1580 if (i != lastEnabled) writeDesc.scale = pass.scale;
1581 if (passIsHighPrecision(pass)) writeDesc.format = GfxPixelFormat::RGBA16F;
1582 if (!pass.nativeKind.empty()) {
1584 if (pass.nativeKind ==
"dynamicGI" && &passes == &passes_ && (scene_needs_depth_ || scene_gbuffer_) && scene_gbuffer_) {
1585 const auto get = [&pass](
const char* name,
f32 fallback) {
1586 const auto it = pass.floatUniforms.find(name);
1587 return it != pass.floatUniforms.end() ? it->second : fallback;
1590 gi.intensity = get(
"u_intensity", gi.intensity);
1591 gi.blend = get(
"u_blend", gi.blend);
1592 gi.cardSlices =
static_cast<u32>(std::max(get(
"u_cardSlices",
static_cast<f32>(gi.cardSlices)), 1.0f));
1593 gi.probeStride =
static_cast<u32>(std::max(get(
"u_probeStride",
static_cast<f32>(gi.probeStride)), 1.0f));
1594 gi.skip =
static_cast<u32>(std::max(get(
"u_skip", 0.0f), 0.0f));
1595 gi.probeSpacing =
static_cast<u32>(std::max(get(
"u_probeSpacing", 0.0f), 0.0f));
1596 gi.halfRes = get(
"u_halfRes", 0.0f) > 0.5f;
1597 gi.probeDensity = get(
"u_probeDensity", 1.0f);
1598 gi.probeRows =
static_cast<u32>(std::max(get(
"u_probeRows",
static_cast<f32>(gi.probeRows)), 1.0f) + 0.5f);
1599 auto& cache = dynamic_gis_[temporalKey_];
1601 if (dynamic_gis_.size() > 4) {
1602 for (
auto it = dynamic_gis_.begin(); it != dynamic_gis_.end(); ++it) {
1603 if (it->first != temporalKey_) { dynamic_gis_.erase(it);
break; }
1606 dynamic_gis_[temporalKey_] = makeUnique<DynamicGI>(device_, context_);
1608 input = dynamic_gis_[temporalKey_]->declare(*graph_, input, scene, gi, width_, height_);
1610 if (pass.nativeKind ==
"voxelGI" && &passes == &passes_ && (scene_needs_depth_ || scene_gbuffer_) && scene_gbuffer_) {
1611 const auto get = [&pass](
const char* name,
f32 fallback) {
1612 const auto it = pass.floatUniforms.find(name);
1613 return it != pass.floatUniforms.end() ? it->second : fallback;
1616 gi.intensity = get(
"u_intensity", gi.intensity);
1617 gi.rays =
static_cast<u32>(std::max(get(
"u_rays",
static_cast<f32>(gi.rays)), 1.0f));
1618 gi.voxelSize = get(
"u_voxelSize", gi.voxelSize);
1619 gi.range = get(
"u_range", gi.range);
1620 gi.maxBounce = get(
"u_maxBounce", gi.maxBounce);
1621 gi.decay = get(
"u_decay", gi.decay);
1622 gi.bias = get(
"u_bias", gi.bias);
1623 gi.divisor =
static_cast<u32>(std::max(get(
"u_divisor",
static_cast<f32>(gi.divisor)), 1.0f));
1624 gi.debug = get(
"u_debug", gi.debug);
1625 gi.blend = get(
"u_blend", gi.blend);
1626 gi.sunAlbedo = get(
"u_sunAlbedo", gi.sunAlbedo);
1627 gi.bounceFeedback = get(
"u_bounceFeedback", gi.bounceFeedback);
1628 gi.gridSize =
static_cast<u32>(std::max(get(
"u_gridSize",
static_cast<f32>(gi.gridSize)), 1.0f) + 0.5f);
1629 gi.sunSamples =
static_cast<u32>(std::max(get(
"u_sunSamples",
static_cast<f32>(gi.sunSamples)), 1.0f) + 0.5f);
1630 auto& cache = voxel_gis_[temporalKey_];
1633 if (voxel_gis_.size() > 4) {
1634 for (
auto it = voxel_gis_.begin(); it != voxel_gis_.end(); ++it) {
1635 if (it->first != temporalKey_) { voxel_gis_.erase(it);
break; }
1638 voxel_gis_[temporalKey_] = makeUnique<VoxelGI>(device_, context_);
1640 input = voxel_gis_[temporalKey_]->declare(*graph_, input, scene, gi, width_, height_,
1641 TextureHandle{shadow_texture_}, shadow_resource_);
1645 if (pass.isCompute) {
1648 writeDesc.format = GfxPixelFormat::RGBA16F;
1649 writeDesc.storage =
true;
1650 writeDesc.linearFilter =
true;
1651 pass.temporal =
false;
1652 pass.feedback =
false;
1653 node.compute =
true;
1654 node.asyncCompute =
true;
1655 node.reads = {input};
1656 if (pass.usesComputeDepth) node.dependencies = {scene};
1657 node.write = graph_->createTarget(writeDesc);
1658 node.execute = [
this, &pass](
const rg::PassContext&
ctx) { computePass(pass, ctx); };
1660 effectOutputs.emplace_back(pass.name, input);
1661 graph_->addPass(std::move(node));
1664 if (sky_capture_.state == SkyCapture::State::Requested && pass.name == sky_capture_.pass && &passes == &passes_) {
1665 declareSkyCapture(pass, input, effectInput);
1669 TemporalState* temporal =
nullptr;
1670 pass.temporal =
false;
1671 pass.feedback =
false;
1672 if (&passes == &passes_) {
1673 if (passIsTemporal(pass)) {
1675 if (
auto it = temporal_.find(temporalKey_); it != temporal_.end() && it->second.frame > 0) {
1676 temporal = prepareHistory(it->second, width_, height_, interFormat());
1677 pass.temporal = temporal !=
nullptr;
1679 }
else if (passHasTexture(pass,
"u_feedback")) {
1681 pass.historyKey = feedbackKey(pass.name);
1682 u32 fw =
static_cast<u32>(
static_cast<f32>(width_) * pass.scale);
1683 u32 fh =
static_cast<u32>(
static_cast<f32>(height_) * pass.scale);
1685 const auto sized = [&pass](
const char* name,
u32 fallback) {
1686 const auto it = pass.floatUniforms.find(name);
1687 return it != pass.floatUniforms.end() && it->second >= 1.0f ? std::min(
static_cast<u32>(it->second), 4096u) : fallback;
1689 fw = sized(
"u_feedbackWidth", fw);
1690 fh = sized(
"u_feedbackHeight", fh);
1692 temporal = prepareHistory(feedback_[pass.historyKey], fw, fh,
1693 passIsHighPrecision(pass) ? GfxPixelFormat::RGBA16F : interFormat());
1694 pass.feedback = temporal !=
nullptr;
1698 const u32 write = temporal->readIndex ^ 1u;
1699 Framebuffer& target = *temporal->history[write];
1700 node.write = graph_->importTarget(target.handle(), temporal->width, temporal->height,
1701 false, target.getColorAttachment());
1702 node.execute = [
this, &pass, temporal, write](
const rg::PassContext&
ctx) {
1703 renderPass(pass, ctx);
1704 temporal->readIndex = write;
1705 temporal->valid =
true;
1706 temporal->writtenFrame = temporal->frame;
1709 node.write = graph_->createTarget(writeDesc);
1710 node.execute = [
this, &pass](
const rg::PassContext&
ctx) { renderPass(pass, ctx); };
1713 effectOutputs.emplace_back(pass.name, input);
1714 graph_->addPass(std::move(node));
1719 blit.reads = {input};
1721 blit.execute = [
this](
const rg::PassContext&) { blitPass(); };
1722 graph_->addPass(std::move(blit));
1725 if (selectionMask_ != rg::kNoResource) {
1726 const rg::ResourceId mask = selectionMask_;
1727 rg::PassDesc outline;
1728 outline.name =
"selection-outline";
1729 outline.reads = {mask};
1730 outline.write = out;
1731 outline.execute = [
this, mask](
const rg::PassContext&) {
1732 if (output_vp_w_ > 0 && output_vp_h_ > 0) device_.setViewport(output_vp_x_, output_vp_y_, output_vp_w_, output_vp_h_);
1733 drawSelectionOutline(graph_->textureOf(mask));
1735 graph_->addPass(std::move(outline));
1737 selectionMask_ = rg::kNoResource;
1740void PostProcessPipeline::ensureScreenFBO() {
1744 if (screenFBOCreated_ && screenFBOFormat_ == interFormat())
return;
1746 screenFBOCreated_ =
false;
1748 FramebufferSpec spec;
1753 spec.width = width_;
1754 spec.height = height_;
1755 spec.depthStencil =
false;
1756 spec.linearFilter =
true;
1758 screenFBO_ = Framebuffer::create(device_, spec);
1760 ES_LOG_ERROR(
"PostProcessPipeline: Failed to create screen FBO");
1764 screenFBOFormat_ = spec.colorFormat;
1765 screenFBOCreated_ =
true;
1769 if (!initialized_ || screenCaptureActive_)
return;
1772 if (!screenFBOCreated_)
return;
1774 device_.beginRenderPass({screenFBO_->handle(),
true,
true});
1775 device_.setViewport(0, 0, width_, height_);
1777 screenCaptureActive_ =
true;
1781 if (!initialized_ || !screenCaptureActive_)
return;
1783 screenFBO_->unbind();
1784 screenCaptureActive_ =
false;
1788 if (!initialized_ || !screenFBOCreated_)
return;
1790 auto* device = &device_;
1791 device->invalidatePipelineCache();
1792 device->setScissorTest(
false);
1795 if (!graph_)
return;
1797 sceneTexture_ = screenFBO_->getColorAttachment();
1798 screenFBO_->unbind();
1803 graph_->begin(width_, height_);
1804 runChain(screenPasses_, graph_->importTexture(sceneTexture_, width_, height_));
1809 device->invalidatePipelineCache();
1818 screenPasses_.push_back(pass);
1819 return static_cast<u32>(screenPasses_.size() - 1);
1823 for (
auto& pass : screenPasses_) releasePassResources(pass);
1824 screenPasses_.clear();
1827PostProcessPass* PostProcessPipeline::findScreenPass(
const std::string& name) {
1828 for (
auto& pass : screenPasses_) {
1829 if (pass.name == name) {
1837 const std::string& uniform,
f32 value) {
1838 if (
auto* pass = findScreenPass(passName)) {
1839 pass->floatUniforms[uniform] = value;
1840 pass->paramDirty =
true;
1845 const std::string& uniform,
1846 const glm::vec4& value) {
1847 if (
auto* pass = findScreenPass(passName)) {
1848 pass->vec4Uniforms[uniform] = value;
1849 pass->paramDirty =
true;
Diffuse global illumination from the scene's distance field and surface cache, run as compute passes ...
Abstract graphics device interface.
Backend-agnostic graphics enumerations.
Per-frame 2D lighting constants — the third tier of the engine's constant-buffer layering (after per-...
Logging utilities for ESEngine.
#define ES_LOG_ERROR(...)
Logs an error message.
#define ES_LOG_INFO(...)
Logs an info message.
Binding points for per-material shader constants — the second tier of the engine's constant-buffer la...
Engine-side material registry — the resolved "how to draw" for a material handle.
Post-processing effects pipeline.
Rendering context containing all renderer state.
The point the frame is drawn relative to: a world far from zero loses precision in single floats,...
Central resource management system.
Parser for unified .esshader file format.
GPU shader program abstraction.
Diffuse global illumination from a world-space voxel cache, run as compute passes (WebGPU).
static Unique< Framebuffer > create(GfxDevice &device, const FramebufferSpec &spec)
Creates a framebuffer from specification.
static constexpr GfxContent retained()
Abstract graphics device interface.
bool programReady(ShaderHandle program)
Whether program can be drawn with now, without waiting: linked, or finished linking in the background...
virtual void setSurfaceSamples(u32 samples)
Asks for the backbuffer to be drawn with this many samples.
bool skipPendingPrograms() const
virtual u32 maxSamples()=0
Most samples an offscreen colour attachment may carry; 1 = none.
virtual bool supportsFloatTargets()=0
Whether RGBA16F color attachments are renderable.
void deleteBuffer(BufferHandle buffer)
Deletes a buffer.
virtual bool supportsCompute() const
Whether this device runs compute shaders.
void registerLayout(resource::ShaderHandle shader, MaterialUniformLayout layout)
const MaterialUniformLayout * layoutFor(resource::ShaderHandle shader) const
static MaterialUniformLayout layoutOf(const resource::ParsedShader &parsed)
void setPassContinuesEffect(const std::string &passName)
Mark passName as a later pass of the effect the pass before it began.
void setPassUniformVec4(const std::string &passName, const std::string &uniform, const glm::vec4 &value)
Sets a vec4 uniform for a pass.
bool displayLutActive() const
void executeScreenPasses()
Executes screen-level post-process passes on captured output.
bool velocityWanted()
Whether an enabled pass reads how far each moving surface travelled (u_velocity).
void resize(u32 width, u32 height)
Resizes the framebuffers.
void clearScreenPasses()
Clears all screen-level passes.
bool drawMaterialOver(u32 material)
f32 coverRange()
How far from the camera, in world units, that map reaches each way (the effect's u_shelterRange).
PostProcessPipeline(GfxDevice &device, RenderContext &context, resource::ResourceManager &resourceManager, rg::RenderGraph &graph)
Builds a pipeline that declares its chains onto the FRAME's graph.
u32 addComputePass(const std::string &name, const std::string &wgsl, const std::vector< std::string > ¶ms, u32 workgroupX, u32 workgroupY)
Adds a pass that is a compute shader over the picture instead of a draw.
void begin(const f32 *clearColor=nullptr)
Begins rendering to the pipeline.
u32 addNativePass(const std::string &name, const std::string &kind)
Adds a pass the engine implements itself: "voxelGI" (see VoxelGI). Its parameters are set like any pa...
const PostProcessPass * getPass(u32 index) const
Gets a pass by index.
bool isEngaged() const
Whether the scene goes through the graph or straight to the surface.
void grabScene(bool marked=true)
void setViewExposure(f32 ev)
void drawCloudShadow(const glm::mat4 &inverse, const glm::vec4 &rect, const rg::PassContext &ctx)
Draws the caster's cloud shadow into the tile at rect of the bound target: what of the sun is left in...
const PostProcessPass * cloudShadowCaster(f32 &extentKm, f32 &unitsPerKm) const
The sky that casts the sun's cloud shadow this frame, how far its map reaches each way in kilometres,...
bool temporalActive()
Whether this frame's chain holds a temporal effect.
glm::vec2 beginTemporalView(const glm::mat4 &viewProjection, u64 key)
Starts a frame of the temporal view key, and answers how far to shift it.
void setScreenPassUniformFloat(const std::string &passName, const std::string &uniform, f32 value)
Sets a float uniform for a screen-level pass.
bool coverWanted()
Whether an enabled pass reads what stands over each place (u_rainCover).
bool canDrawMaterialOver(u32 material)
rg::ResourceId declareCover(u32 size)
The map's target for this frame, declared in the graph (kNoResource when it cannot be made).
void setScreenPassUniformVec4(const std::string &passName, const std::string &uniform, const glm::vec4 &value)
Sets a vec4 uniform for a screen-level pass.
bool drawProjectedMaterial(u32 material, u32 instances, u32 scratch, const glm::vec4 &sun, const glm::vec4 &receiverWindow, TextureHandle receiverDepth, TextureHandle movingDepth)
FramebufferHandle currentSceneFBO() const
The surface the scene is currently rendering into: the screen-capture FBO when the screen stack is li...
void setOutputTarget(FramebufferHandle target)
Sets the output target for the final blit (Default = screen).
void clearPasses()
Checks if bypass mode is enabled.
TemporalView peekTemporalView(const glm::mat4 &viewProjection, u64 key) const
void setPassUniformFloat(const std::string &passName, const std::string &uniform, f32 value)
Sets a float uniform for a pass.
bool presentUpscales() const
Whether the present is a whole-multiple upscale of the chain.
void beginScreenCapture()
Begins screen-level capture (all camera output goes into screen FBO).
void drawSelectionOutline(TextureHandle mask)
The selection's outline over what the bound target holds, from its mask. Blended over; the caller set...
rg::ResourceId declareVelocity()
The motion pass's target for this frame, declared in the graph (kNoResource when it cannot be made).
void requestSkyCapture(const std::string &passName, u32 width, u32 height)
Draws pass passName once more, next frame, into a width x height RGBA8 target with its float param u_...
glm::vec4 bakeSun() const
void trackView(const glm::mat4 &viewProjection, u64 key)
Records this frame's camera as the view key's current one, and last frame's as its previous....
void setPassScale(const std::string &passName, f32 scale)
Draw passName at scale of the chain size (clamped to (0, 1]).
void shutdown()
Shuts down and releases resources.
bool drawMaterialThrough(u32 material, u32 shader, const std::vector< std::pair< std::string, glm::vec4 > > &overrides, u32 scratch)
u32 addPass(const std::string &name, resource::ShaderHandle shader)
Adds a post-processing pass.
bool sceneCoverageWanted()
Whether the scene is to be cleared to nothing (all four channels zero) so that its alpha says how muc...
u32 addScreenPass(const std::string &name, resource::ShaderHandle shader)
Adds a screen-level post-process pass.
void encodeRgbm()
Draws the texture on unit 0 into the bound target as RGBM over 8 (alpha 0 kept for nothing drawn): a ...
bool cameraMotionWanted()
Whether an enabled pass that keeps no history reads the previous camera (u_prevViewProjection0).
i32 pollSkyCapture()
0 = not yet, 1 = the pixels are ready (skyCapturePixels), 2 = none was asked for or it failed....
void setRequestedSamples(u32 samples)
The project's multisampling request; 1 = off. Clamped by the device.
bool supportsCompute() const
Whether passes added with addComputePass run on this device.
void setPassTexture(const std::string &passName, const std::string &uniform, u32 glTextureId)
Binds a texture to a pass's sampler uniform (unit 2 upward, in registration order)....
bool presentIsWholeMultiple() const
f32 coverBias()
The bias the drawing effect reads the map with (its u_shelterBias), for a pass that only borrows the ...
void init(u32 width, u32 height)
Initializes the pipeline with given dimensions.
void setOutputViewport(u32 x, u32 y, u32 w, u32 h)
Sets the output viewport for the final blit.
void drawSelectionGround(TextureHandle depth)
The selection mask's ground, into the bound mask target: the scene's depth in g, nothing covered.
void endScreenCapture()
Ends screen-level capture.
void grabDepth()
Draws, into the target being drawn, the distance to the opaque scene at every pixel (the scene's dept...
MaterialStore & materials()
The engine-side material registry (handle -> resolved render state).
GPU shader program for rendering.
void commitParams()
Uploads the shadow (when dirty) and binds this shader's params UBO at DRAW_PARAMS_BINDING.
GfxShaderLanguage language() const
The source language this program was compiled from.
void setUniform(const std::string &name, i32 value) const
Sets an integer uniform.
bool hasUniform(const std::string &name) const
True if the linked program declares this uniform.
ShaderHandle handle() const
Gets the device program handle.
bool isValid() const
Checks if the handle references a valid resource.
Central manager for GPU resources.
ShaderTargetLanguage preferredShaderTarget() const
preferredShaderLanguage() as a ShaderParser assembly target.
GfxShaderLanguage preferredShaderLanguage() const
The language embedded pipelines must author their sources in.
Shader * getShader(ShaderHandle handle)
Gets a shader by handle.
ShaderHandle createShader(const std::string &vertSrc, const std::string &fragSrc, bool rewriteLoose=true, GfxShaderLanguage language=GfxShaderLanguage::GLSL_ES300, bool deferLink=false)
static ParsedShader parse(const std::string &source)
Parses shader source into structured format (no include support).
static std::string assembleStage(const ParsedShader &parsed, ShaderStage stage, const std::string &platform="", const std::vector< std::string > &features={}, ShaderTargetLanguage target=ShaderTargetLanguage::GLSL_ES300)
Assembles final GLSL source for a specific stage.
constexpr const char * BLIT
Handle< esengine::Shader > ShaderHandle
Handle to a shader resource.
constexpr ResourceId kNoResource
FramebufferHandle
Handle 0 is the default framebuffer (backbuffer); it cannot be created or deleted.
constexpr Unique< T > makeUnique(Args &&... args)
Creates a Unique pointer with the given arguments.
std::int32_t i32
Signed 32-bit integer.
std::uint64_t u64
Unsigned 64-bit integer.
std::size_t usize
Size type for indexing and sizes.
OutputTransform
What the last pass of a chain does to scene values on the way out.
@ ACES
Narkowicz ACES filmic curve, for a scene that carries HDR radiance.
@ None
Encode only. Values above 1 clip, which is what LDR content means.
@ Neutral
Khronos PBR Neutral: hue and saturation survive, highlights roll off.
glm::mat4 viewProjectionFromOrigin(const glm::mat4 &viewProjection, const glm::dvec3 &origin)
A view-projection made for origin, for a point given from the origin now: the point from the old orig...
ComputeHandle
A compute program (GfxDevice::createCompute); only a device that supportsCompute() issues one.
constexpr u32 kGBufferUnit
The unit a PostProcess pass reads the scene's surface record at: what a surface IS — octahedral norma...
HdrFormatDecision decideHdrFormat(bool linearOutput, bool supportsFloatTargets)
What a linear project asks for, and what supportsFloatTargets grants.
constexpr u32 kSceneDepthUnit
The unit a PostProcess pass reads the scene's DEPTH at.
GfxReadbackStatus
State of an in-flight readback. GL completes at request time (first poll reports Ready); WebGPU resol...
std::uint32_t u32
Unsigned 32-bit integer.
std::uint16_t u16
Unsigned 16-bit integer.
glm::dvec3 & renderOrigin()
The origin, in world units. A double, as the world positions it is taken from are far from zero.
static EstellaContext & ctx()
float f32
32-bit floating point
Framebuffer creation parameters.
GfxPixelFormat colorFormat
Color attachment format. RGBA16F needs GfxDevice::supportsFloatTargets.
bool depthStencil
Whether to create depth/stencil attachment.
bool linearFilter
Texture filter mode: false=GL_NEAREST, true=GL_LINEAR.
u32 height
Framebuffer height in pixels.
u32 width
Framebuffer width in pixels.
A compute program's source. Compute is WGSL only: GLSL ES 3.00 has no compute stage.
One scalar/vector param's slot in a shader's std140 MaterialConstants block.
Post-processing pass configuration.
resource::ShaderHandle shader
std::unordered_map< std::string, f32 > floatUniforms
u32 paramUboBytes
The size paramUbo was made with: what lets the next chain's pass of the same size take it over.
std::vector< u8 > paramBytes
std::string nativeKind
A pass the engine implements itself, in compute passes of its own (see VoxelGI): its name,...
std::vector< std::pair< std::string, u32 > > textureUniforms
u64 historyKey
Which remembered state the pass uses, resolved when the chain is declared.
std::vector< std::pair< std::string, rg::ResourceId > > earlierInputs
std::vector< std::string > computeParams
std::unordered_map< std::string, glm::vec4 > vec4Uniforms
What a temporal view would be given by its NEXT begin: the sub-pixel shift and last frame's camera.
glm::vec2 previousJitter
The shift the previous frame was drawn with.
One render pass: a target, which attachments to clear on entry, and the clear values — full load-op s...
Shape of a target the graph allocates.
bool gbuffer
A second colour attachment for the surface's material, drawn beside the first.