Skip to content

A fast 2D and 3D game engine — TypeScript SDK, C++/WebAssembly core, visual editor. Ship one project to web, desktop, WeChat MiniGames, playable ads, and native Android / iOS.

fix(render): the antialiasing was never the engine's, and a post chain walked away from it

esenginede90837181e7
diff --git a/fixtures/scenes/aa-edge-post.esscene b/fixtures/scenes/aa-edge-post.esscene
new file mode 100644
index 000000000..5c0fc6d48
--- /dev/null
+++ b/fixtures/scenes/aa-edge-post.esscene
@@ -0,0 +1,99 @@
+{
+ "version": 4,
+ "name": "AaEdgePost",
+ "entities": [
+ {
+ "id": 0,
+ "name": "Camera",
+ "parent": null,
+ "children": [],
+ "visible": true,
+ "components": [
+ {
+ "type": "Transform",
+ "data": {
+ "position": {
+ "x": 0,
+ "y": 0,
+ "z": 300
+ }
+ }
+ },
+ {
+ "type": "Camera",
+ "data": {
+ "projectionType": 1,
+ "orthoSize": 100,
+ "nearPlane": 1,
+ "farPlane": 1000,
+ "isActive": true,
+ "priority": 0
+ }
+ },
+ {
+ "type": "PostProcessVolume",
+ "data": {
+ "isGlobal": true,
+ "priority": 0,
+ "weight": 1,
+ "effects": [
+ {
+ "type": "pixelate",
+ "enabled": true,
+ "uniforms": {
+ "u_pixelSize": 1
+ }
+ }
+ ]
+ }
+ }
+ ]
+ },
+ {
+ "id": 1,
+ "name": "Blade",
+ "parent": null,
+ "children": [],
+ "visible": true,
+ "components": [
+ {
+ "type": "Transform",
+ "data": {
+ "position": {
+ "x": 0,
+ "y": 0,
+ "z": 0
+ },
+ "rotation": {
+ "x": 0,
+ "y": 0,
+ "z": 0.1736,
+ "w": 0.9848
+ },
+ "scale": {
+ "x": 1.4,
+ "y": 0.35,
+ "z": 1
+ }
+ }
+ },
+ {
+ "type": "MeshRenderer",
+ "data": {
+ "mesh": "builtin:quad",
+ "color": {
+ "r": 1,
+ "g": 1,
+ "b": 1,
+ "a": 1
+ },
+ "lit": false,
+ "opaque": true,
+ "cullBackfaces": false,
+ "enabled": true
+ }
+ }
+ ]
+ }
+ ]
+}
diff --git a/fixtures/scenes/aa-edge.esscene b/fixtures/scenes/aa-edge.esscene
new file mode 100644
index 000000000..941d60766
--- /dev/null
+++ b/fixtures/scenes/aa-edge.esscene
@@ -0,0 +1,82 @@
+{
+ "version": 4,
+ "name": "AaEdge",
+ "entities": [
+ {
+ "id": 0,
+ "name": "Camera",
+ "parent": null,
+ "children": [],
+ "visible": true,
+ "components": [
+ {
+ "type": "Transform",
+ "data": {
+ "position": {
+ "x": 0,
+ "y": 0,
+ "z": 300
+ }
+ }
+ },
+ {
+ "type": "Camera",
+ "data": {
+ "projectionType": 1,
+ "orthoSize": 100,
+ "nearPlane": 1,
+ "farPlane": 1000,
+ "isActive": true,
+ "priority": 0
+ }
+ }
+ ]
+ },
+ {
+ "id": 1,
+ "name": "Blade",
+ "parent": null,
+ "children": [],
+ "visible": true,
+ "components": [
+ {
+ "type": "Transform",
+ "data": {
+ "position": {
+ "x": 0,
+ "y": 0,
+ "z": 0
+ },
+ "rotation": {
+ "x": 0,
+ "y": 0,
+ "z": 0.1736,
+ "w": 0.9848
+ },
+ "scale": {
+ "x": 1.4,
+ "y": 0.35,
+ "z": 1
+ }
+ }
+ },
+ {
+ "type": "MeshRenderer",
+ "data": {
+ "mesh": "builtin:quad",
+ "color": {
+ "r": 1,
+ "g": 1,
+ "b": 1,
+ "a": 1
+ },
+ "lit": false,
+ "opaque": true,
+ "cullBackfaces": false,
+ "enabled": true
+ }
+ }
+ ]
+ }
+ ]
+}
diff --git a/src/esengine/renderer/frame/PostProcessPipeline.cpp b/src/esengine/renderer/frame/PostProcessPipeline.cpp
index ac4bba7cc..e0ddddb44 100644
--- a/src/esengine/renderer/frame/PostProcessPipeline.cpp
+++ b/src/esengine/renderer/frame/PostProcessPipeline.cpp
@@ -63,6 +63,10 @@ void PostProcessPipeline::init(u32 width, u32 height) {
return;
}
+ // Capped at 4: what a browser offers a drawing buffer, past which a sample
+ // buys less than its bandwidth. A backend with no MSAA answers 1.
+ scene_samples_ = std::min(4u, device_.maxSamples());
+
initialized_ = true;
}
@@ -359,8 +363,13 @@ void PostProcessPipeline::begin(const f32* clearColor) {
// With no pass to run, the blit samples the scene target itself, so the
// present's filter is the one that applies to it.
const bool sceneIsBlitSource = bypass_ || passes_.empty();
- sceneResource_ = graph_->createExternalTarget(
- sceneIsBlitSource ? blitSourceTarget(scene_needs_depth_) : chainTarget(scene_needs_depth_));
+ rg::TargetDesc sceneDesc =
+ sceneIsBlitSource ? blitSourceTarget(scene_needs_depth_) : chainTarget(scene_needs_depth_);
+ // The only target geometry is rasterised into, so the only one with edges.
+ // Every other target in the chain is a fullscreen pass and stays at one
+ // sample. Gate: check-postfx-aa.
+ sceneDesc.samples = scene_samples_;
+ sceneResource_ = graph_->createExternalTarget(sceneDesc);
if (sceneResource_ == rg::kNoResource) {
ES_LOG_ERROR("PostProcessPipeline: no scene target this frame");
return;
diff --git a/src/esengine/renderer/frame/PostProcessPipeline.hpp b/src/esengine/renderer/frame/PostProcessPipeline.hpp
index 8361d32ae..0d9a248a3 100644
--- a/src/esengine/renderer/frame/PostProcessPipeline.hpp
+++ b/src/esengine/renderer/frame/PostProcessPipeline.hpp
@@ -402,6 +402,8 @@ private:
bool bypass_ = false;
bool linear_output_ = false;
bool scene_needs_depth_ = false;
+ /// Samples the scene target rasterises with; the backend's ceiling, capped.
+ u32 scene_samples_ = 1;
OutputTransform output_transform_ = OutputTransform::None;
/// The graph resource the scene is drawn into, live between begin() and end().
rg::ResourceId sceneResource_ = rg::kNoResource;
diff --git a/src/esengine/renderer/graph/RenderGraph.cpp b/src/esengine/renderer/graph/RenderGraph.cpp
index 53fde7e1b..5d108b279 100644
--- a/src/esengine/renderer/graph/RenderGraph.cpp
+++ b/src/esengine/renderer/graph/RenderGraph.cpp
@@ -139,6 +139,7 @@ TargetHandle RenderGraph::acquire(const Resource& res) {
shape.format = res.desc.format;
shape.linearFilter = res.desc.linearFilter;
shape.depthStencil = res.desc.depthStencil;
+ shape.samples = res.desc.samples;
const TargetHandle handle = pool_.acquire(shape);
if (handle != kNoTarget) borrowed_.push_back(handle);
return handle;
diff --git a/src/esengine/renderer/graph/RenderGraph.hpp b/src/esengine/renderer/graph/RenderGraph.hpp
index 869ad0a63..5e8990d0b 100644
--- a/src/esengine/renderer/graph/RenderGraph.hpp
+++ b/src/esengine/renderer/graph/RenderGraph.hpp
@@ -61,6 +61,9 @@ struct TargetDesc {
GfxPixelFormat format = GfxPixelFormat::RGBA8;
bool linearFilter = true;
bool depthStencil = false;
+ /// Samples to DRAW with. What the target hands back to be sampled stays
+ /// single-sample either way — the resolve is the target's own business.
+ u32 samples = 1;
};
/** What a pass's execute() is told: where it is drawing and what it may read. */
diff --git a/src/esengine/renderer/graph/TargetPool.cpp b/src/esengine/renderer/graph/TargetPool.cpp
index 1204d0002..0a46f5e74 100644
--- a/src/esengine/renderer/graph/TargetPool.cpp
+++ b/src/esengine/renderer/graph/TargetPool.cpp
@@ -22,12 +22,17 @@ u64 texelBytes(const TargetShape& shape) {
// Depth24Stencil8 is what a depth-stencil attachment costs; the colour above
// is separate storage, not a second view of it.
if (shape.depthStencil) bytes += 4u;
+ // A multisampled target is that many times over, PLUS the single-sample
+ // attachments it resolves into — it is two targets in one object, and a
+ // budget that counted only the shape would under-report it fivefold.
+ if (shape.samples > 1) bytes *= (shape.samples + 1);
return bytes;
}
bool sameShape(const TargetShape& a, const TargetShape& b) {
return a.width == b.width && a.height == b.height && a.format == b.format
- && a.linearFilter == b.linearFilter && a.depthStencil == b.depthStencil;
+ && a.linearFilter == b.linearFilter && a.depthStencil == b.depthStencil
+ && a.samples == b.samples;
}
} // namespace
@@ -68,6 +73,7 @@ TargetHandle TargetPool::acquire(const TargetShape& shape) {
spec.depthStencil = shape.depthStencil;
spec.linearFilter = shape.linearFilter;
spec.colorFormat = shape.format;
+ spec.samples = shape.samples;
auto fbo = Framebuffer::create(device_, spec);
if (!fbo) {
ES_LOG_ERROR("TargetPool: failed to create a {}x{} target", shape.width, shape.height);
diff --git a/src/esengine/renderer/graph/TargetPool.hpp b/src/esengine/renderer/graph/TargetPool.hpp
index 119e5b5e5..7e046d442 100644
--- a/src/esengine/renderer/graph/TargetPool.hpp
+++ b/src/esengine/renderer/graph/TargetPool.hpp
@@ -52,6 +52,9 @@ struct TargetShape {
GfxPixelFormat format = GfxPixelFormat::RGBA8;
bool linearFilter = true;
bool depthStencil = false;
+ /// Samples the target is DRAWN into with; what it hands back to be sampled
+ /// is always single-sample, because the target resolves itself.
+ u32 samples = 1;
};
class TargetPool {
diff --git a/src/esengine/renderer/rhi/Framebuffer.cpp b/src/esengine/renderer/rhi/Framebuffer.cpp
index 6680054d7..566f31353 100644
--- a/src/esengine/renderer/rhi/Framebuffer.cpp
+++ b/src/esengine/renderer/rhi/Framebuffer.cpp
@@ -17,6 +17,8 @@
#include "./GfxDevice.hpp"
#include "../../core/Log.hpp"
+#include <algorithm>
+
namespace esengine {
// =============================================================================
@@ -32,10 +34,14 @@ Framebuffer::Framebuffer(Framebuffer&& other) noexcept
spec_(other.spec_),
handle_(other.handle_),
colorAttachment_(other.colorAttachment_),
- depthAttachment_(other.depthAttachment_) {
+ depthAttachment_(other.depthAttachment_),
+ resolveColor_(other.resolveColor_),
+ resolveDepth_(other.resolveDepth_) {
other.handle_ = FramebufferHandle::Default;
other.colorAttachment_ = TextureHandle::Invalid;
other.depthAttachment_ = TextureHandle::Invalid;
+ other.resolveColor_ = TextureHandle::Invalid;
+ other.resolveDepth_ = TextureHandle::Invalid;
}
Framebuffer& Framebuffer::operator=(Framebuffer&& other) noexcept {
@@ -46,9 +52,13 @@ Framebuffer& Framebuffer::operator=(Framebuffer&& other) noexcept {
handle_ = other.handle_;
colorAttachment_ = other.colorAttachment_;
depthAttachment_ = other.depthAttachment_;
+ resolveColor_ = other.resolveColor_;
+ resolveDepth_ = other.resolveDepth_;
other.handle_ = FramebufferHandle::Default;
other.colorAttachment_ = TextureHandle::Invalid;
other.depthAttachment_ = TextureHandle::Invalid;
+ other.resolveColor_ = TextureHandle::Invalid;
+ other.resolveDepth_ = TextureHandle::Invalid;
}
return *this;
}
@@ -103,6 +113,9 @@ void Framebuffer::resize(u32 width, u32 height) {
bool Framebuffer::initialize() {
const TextureFilter filter = spec_.linearFilter ? TextureFilter::Linear : TextureFilter::Nearest;
+ // The backend's ceiling, not the caller's wish: asking a backend with no MSAA
+ // for samples would leave a resolve reading an attachment nothing multisampled.
+ const u32 samples = std::min(std::max(spec_.samples, 1u), device_->maxSamples());
TextureDesc colorDesc;
colorDesc.width = spec_.width;
@@ -110,19 +123,35 @@ bool Framebuffer::initialize() {
colorDesc.format = spec_.colorFormat;
colorDesc.minFilter = filter;
colorDesc.magFilter = filter;
+ colorDesc.samples = samples;
colorAttachment_ = device_->createTexture(colorDesc, nullptr);
+ TextureDesc depthDesc;
+ depthDesc.width = spec_.width;
+ depthDesc.height = spec_.height;
+ depthDesc.format = GfxPixelFormat::Depth24Stencil8;
+ depthDesc.minFilter = TextureFilter::Nearest;
+ depthDesc.magFilter = TextureFilter::Nearest;
if (spec_.depthStencil) {
- TextureDesc depthDesc;
- depthDesc.width = spec_.width;
- depthDesc.height = spec_.height;
- depthDesc.format = GfxPixelFormat::Depth24Stencil8;
- depthDesc.minFilter = TextureFilter::Nearest;
- depthDesc.magFilter = TextureFilter::Nearest;
+ depthDesc.samples = samples;
depthAttachment_ = device_->createTexture(depthDesc, nullptr);
}
- handle_ = device_->createFramebuffer({colorAttachment_, depthAttachment_});
+ // The single-sample twins the multisampled attachments resolve into. They
+ // belong to this target: it is what makes a multisampled target sampleable,
+ // and no pass or effect has to know it happened.
+ if (samples > 1) {
+ colorDesc.samples = 1;
+ resolveColor_ = device_->createTexture(colorDesc, nullptr);
+ if (spec_.depthStencil) {
+ depthDesc.samples = 1;
+ resolveDepth_ = device_->createTexture(depthDesc, nullptr);
+ }
+ }
+
+ handle_ = device_->createFramebuffer({colorAttachment_, depthAttachment_,
+ resolveColor_, resolveDepth_,
+ spec_.width, spec_.height});
if (handle_ == FramebufferHandle::Default) {
ES_LOG_ERROR("Framebuffer is incomplete! (size: {}x{}, GL error 0x{:X})",
spec_.width, spec_.height, device_->getError());
@@ -135,6 +164,14 @@ bool Framebuffer::initialize() {
void Framebuffer::cleanup() {
if (!device_) return;
+ if (resolveColor_ != TextureHandle::Invalid) {
+ device_->deleteTexture(resolveColor_);
+ resolveColor_ = TextureHandle::Invalid;
+ }
+ if (resolveDepth_ != TextureHandle::Invalid) {
+ device_->deleteTexture(resolveDepth_);
+ resolveDepth_ = TextureHandle::Invalid;
+ }
if (colorAttachment_ != TextureHandle::Invalid) {
device_->deleteTexture(colorAttachment_);
colorAttachment_ = TextureHandle::Invalid;
diff --git a/src/esengine/renderer/rhi/Framebuffer.hpp b/src/esengine/renderer/rhi/Framebuffer.hpp
index dafb28872..7249252bb 100644
--- a/src/esengine/renderer/rhi/Framebuffer.hpp
+++ b/src/esengine/renderer/rhi/Framebuffer.hpp
@@ -143,10 +143,17 @@ public:
// =========================================================================
/** @brief Gets the color attachment texture */
- TextureHandle getColorAttachment() const { return colorAttachment_; }
+ /// What a shader samples. On a multisampled target this is the RESOLVED
+ /// attachment, not the one drawn into — the caller never handles the
+ /// multisampled side, which cannot be sampled at all.
+ TextureHandle getColorAttachment() const {
+ return resolveColor_ != TextureHandle::Invalid ? resolveColor_ : colorAttachment_;
+ }
/** @brief Gets the depth attachment texture (Invalid if none) */
- TextureHandle getDepthAttachment() const { return depthAttachment_; }
+ TextureHandle getDepthAttachment() const {
+ return resolveDepth_ != TextureHandle::Invalid ? resolveDepth_ : depthAttachment_;
+ }
/** @brief Gets the framebuffer width in pixels */
u32 getWidth() const { return spec_.width; }
@@ -177,6 +184,9 @@ private:
FramebufferHandle handle_ = FramebufferHandle::Default;
TextureHandle colorAttachment_ = TextureHandle::Invalid;
TextureHandle depthAttachment_ = TextureHandle::Invalid;
+ /// Single-sample twins, non-Invalid only when spec_.samples > 1.
+ TextureHandle resolveColor_ = TextureHandle::Invalid;
+ TextureHandle resolveDepth_ = TextureHandle::Invalid;
};
} // namespace esengine
diff --git a/src/esengine/renderer/rhi/GLDevice.cpp b/src/esengine/renderer/rhi/GLDevice.cpp
index 17e8e5808..f39981193 100644
--- a/src/esengine/renderer/rhi/GLDevice.cpp
+++ b/src/esengine/renderer/rhi/GLDevice.cpp
@@ -91,6 +91,14 @@ namespace esengine {
namespace {
+// A multisampled attachment is a RENDERBUFFER in WebGL2, and renderbuffer ids
+// live in their own namespace where id 3 and texture 3 both exist — hence a tag
+// bit rather than a lookup that would confuse the two.
+constexpr u32 kRenderbufferTag = 0x80000000u;
+inline bool isRenderbuffer(u32 handle) { return (handle & kRenderbufferTag) != 0; }
+inline GLuint rbId(u32 handle) { return static_cast<GLuint>(handle & ~kRenderbufferTag); }
+
+
GLenum toGLFilter(TextureFilter filter) {
switch (filter) {
case TextureFilter::Nearest: return GL_NEAREST;
@@ -1061,6 +1069,24 @@ void GLDevice::evictSamplerBinding(u32 textureId) {
TextureHandle GLDevice::createTexture(const TextureDesc& desc, const void* pixels) {
if (!isDeviceUsable()) return TextureHandle::Invalid;
+
+ // Multisampled: a renderbuffer, never sampled, only drawn into and resolved
+ // from. It takes no filter or wrap because nothing reads it through a sampler.
+ if (desc.samples > 1) {
+ GLuint rb = 0;
+ glGenRenderbuffers(1, &rb);
+ glBindRenderbuffer(GL_RENDERBUFFER, rb);
+ auto glfmt = toGLPixelFormat(desc.format);
+ glRenderbufferStorageMultisample(GL_RENDERBUFFER, static_cast<GLsizei>(desc.samples),
+ glfmt.internalFormat,
+ static_cast<GLsizei>(desc.width),
+ static_cast<GLsizei>(desc.height));
+ glBindRenderbuffer(GL_RENDERBUFFER, 0);
+ if (rb == 0) return TextureHandle::Invalid;
+ texture_formats_[rb | kRenderbufferTag] = desc.format;
+ return TextureHandle{rb | kRenderbufferTag};
+ }
+
GLuint id = 0;
glGenTextures(1, &id);
texture_formats_[id] = desc.format;
@@ -1128,9 +1154,15 @@ TextureHandle GLDevice::importExternalTexture(u32 nativeId, const TextureDesc& d
}
void GLDevice::deleteTexture(TextureHandle texture) {
- GLuint id = static_cast<GLuint>(texture);
- glDeleteTextures(1, &id);
- texture_formats_.erase(static_cast<u32>(texture));
+ const u32 handle = static_cast<u32>(texture);
+ if (isRenderbuffer(handle)) {
+ GLuint rb = rbId(handle);
+ glDeleteRenderbuffers(1, &rb);
+ } else {
+ GLuint id = static_cast<GLuint>(texture);
+ glDeleteTextures(1, &id);
+ }
+ texture_formats_.erase(handle);
}
void GLDevice::updateTexture(TextureHandle texture, i32 x, i32 y, u32 width, u32 height,
@@ -1171,18 +1203,31 @@ FramebufferHandle GLDevice::createFramebuffer(const FramebufferDesc& desc) {
glGenFramebuffers(1, &id);
glBindFramebuffer(GL_FRAMEBUFFER, id);
+ auto attachDepth = [&](u32 handle) {
+ auto it = texture_formats_.find(handle);
+ const bool depthOnly = it != texture_formats_.end()
+ && it->second == GfxPixelFormat::DepthComponent24;
+ const GLenum point = depthOnly ? GL_DEPTH_ATTACHMENT : GL_DEPTH_STENCIL_ATTACHMENT;
+ if (isRenderbuffer(handle)) {
+ glFramebufferRenderbuffer(GL_FRAMEBUFFER, point, GL_RENDERBUFFER, rbId(handle));
+ } else {
+ glFramebufferTexture2D(GL_FRAMEBUFFER, point, GL_TEXTURE_2D,
+ static_cast<GLuint>(handle), 0);
+ }
+ };
+
if (desc.color0 != TextureHandle::Invalid) {
- glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D,
- static_cast<GLuint>(desc.color0), 0);
+ const u32 c = static_cast<u32>(desc.color0);
+ if (isRenderbuffer(c)) {
+ glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_RENDERBUFFER, rbId(c));
+ } else {
+ glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D,
+ static_cast<GLuint>(c), 0);
+ }
}
if (desc.depthStencil != TextureHandle::Invalid) {
// Attach point follows the texture's pixel format (depth-only vs packed depth+stencil).
- auto it = texture_formats_.find(static_cast<u32>(desc.depthStencil));
- const bool depthOnly = it != texture_formats_.end()
- && it->second == GfxPixelFormat::DepthComponent24;
- glFramebufferTexture2D(GL_FRAMEBUFFER,
- depthOnly ? GL_DEPTH_ATTACHMENT : GL_DEPTH_STENCIL_ATTACHMENT,
- GL_TEXTURE_2D, static_cast<GLuint>(desc.depthStencil), 0);
+ attachDepth(static_cast<u32>(desc.depthStencil));
}
const bool complete = glCheckFramebufferStatus(GL_FRAMEBUFFER) == GL_FRAMEBUFFER_COMPLETE;
@@ -1191,12 +1236,61 @@ FramebufferHandle GLDevice::createFramebuffer(const FramebufferDesc& desc) {
glDeleteFramebuffers(1, &id);
return FramebufferHandle::Default;
}
+ // A multisampled target keeps a second, single-sample framebuffer of its own
+ // to resolve into. It is the target's, not a pass's: whoever leaves the
+ // target gets the resolve for free and never has to ask for it.
+ if (desc.resolveColor0 != TextureHandle::Invalid) {
+ GLuint dst = 0;
+ glGenFramebuffers(1, &dst);
+ glBindFramebuffer(GL_FRAMEBUFFER, dst);
+ glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D,
+ static_cast<GLuint>(desc.resolveColor0), 0);
+ if (desc.resolveDepthStencil != TextureHandle::Invalid) {
+ attachDepth(static_cast<u32>(desc.resolveDepthStencil));
+ }
+ const bool ok = glCheckFramebufferStatus(GL_FRAMEBUFFER) == GL_FRAMEBUFFER_COMPLETE;
+ glBindFramebuffer(GL_FRAMEBUFFER, 0);
+ if (ok) {
+ framebuffer_resolve_[id] = {dst, desc.width, desc.height,
+ desc.resolveDepthStencil != TextureHandle::Invalid};
+ } else {
+ glDeleteFramebuffers(1, &dst);
+ ES_LOG_ERROR("GLDevice: multisample resolve target incomplete");
+ }
+ }
framebuffer_textures_[id] = {static_cast<u32>(desc.color0), static_cast<u32>(desc.depthStencil)};
return FramebufferHandle{id};
}
+/**
+ * Blits a multisampled target into the single-sample one it owns. Depth rides
+ * along because a post-process effect reads the scene's depth and a
+ * multisampled depth attachment cannot be sampled — GL_NEAREST is the only
+ * filter a depth blit accepts.
+ */
+void GLDevice::resolveFramebuffer(u32 fbo) {
+ auto it = framebuffer_resolve_.find(fbo);
+ if (it == framebuffer_resolve_.end() || it->second.destFbo == 0) return;
+ const auto& r = it->second;
+ if (r.width == 0 || r.height == 0) return;
+ glBindFramebuffer(GL_READ_FRAMEBUFFER, fbo);
+ glBindFramebuffer(GL_DRAW_FRAMEBUFFER, r.destFbo);
+ const GLsizei w = static_cast<GLsizei>(r.width), h = static_cast<GLsizei>(r.height);
+ glBlitFramebuffer(0, 0, w, h, 0, 0, w, h, GL_COLOR_BUFFER_BIT, GL_LINEAR);
+ if (r.depth) {
+ // A separate blit: depth and colour cannot share one when the filter
+ // differs, and depth refuses anything but NEAREST.
+ glBlitFramebuffer(0, 0, w, h, 0, 0, w, h, GL_DEPTH_BUFFER_BIT, GL_NEAREST);
+ }
+ glBindFramebuffer(GL_FRAMEBUFFER, static_cast<GLuint>(current_fbo_));
+}
+
void GLDevice::deleteFramebuffer(FramebufferHandle framebuffer) {
GLuint id = static_cast<GLuint>(framebuffer);
+ if (auto it = framebuffer_resolve_.find(id); it != framebuffer_resolve_.end()) {
+ if (it->second.destFbo != 0) glDeleteFramebuffers(1, &it->second.destFbo);
+ framebuffer_resolve_.erase(it);
+ }
if (id != 0) glDeleteFramebuffers(1, &id);
framebuffer_textures_.erase(id);
}
@@ -1208,6 +1302,11 @@ void GLDevice::clearStencil(i32 value) {
void GLDevice::beginRenderPass(const RenderPassDesc& desc) {
const GLuint target = static_cast<GLuint>(desc.target);
+ // Retargeting LEAVES the previous target, and the model has no explicit pass
+ // object to hang the resolve on — so leaving is the event, whether it comes
+ // from endRenderPass or from being retargeted out from under.
+ if (current_fbo_ != target) resolveFramebuffer(current_fbo_);
+ current_fbo_ = target;
glBindFramebuffer(GL_FRAMEBUFFER, target);
// Feedback-loop guard: a render target's own attachment must not remain bound to
@@ -1251,9 +1350,19 @@ void GLDevice::beginRenderPass(const RenderPassDesc& desc) {
}
void GLDevice::endRenderPass() {
+ resolveFramebuffer(current_fbo_);
+ current_fbo_ = 0;
glBindFramebuffer(GL_FRAMEBUFFER, 0);
}
+u32 GLDevice::maxSamples() {
+ if (max_samples_ != 0) return max_samples_;
+ GLint n = 0;
+ glGetIntegerv(GL_MAX_SAMPLES, &n);
+ max_samples_ = n > 1 ? static_cast<u32>(n) : 1u;
+ return max_samples_;
+}
+
// =============================================================================
// Readback (async seam; GL resolves at request time)
// =============================================================================
diff --git a/src/esengine/renderer/rhi/GLDevice.hpp b/src/esengine/renderer/rhi/GLDevice.hpp
index aeb10fad6..33993dc23 100644
--- a/src/esengine/renderer/rhi/GLDevice.hpp
+++ b/src/esengine/renderer/rhi/GLDevice.hpp
@@ -80,6 +80,7 @@ public:
void bindTexture(u32 slot, TextureHandle texture) override;
bool supportsCompressedFormat(GfxCompressedFormat format) override;
bool supportsFloatTargets() override;
+ u32 maxSamples() override;
bool supportsShaderLanguage(GfxShaderLanguage language) const override {
return language == GfxShaderLanguage::GLSL_ES300;
@@ -239,6 +240,24 @@ private:
};
std::unordered_map<u32, FramebufferTextures> framebuffer_textures_;
+ // Where a multisampled framebuffer resolves to, and how big. The blit runs
+ // whenever the target is left, which is the only reason anything above the
+ // RHI can sample a target it drew into multisampled.
+ struct ResolvePair {
+ u32 destFbo = 0;
+ u32 width = 0;
+ u32 height = 0;
+ bool depth = false;
+ };
+ std::unordered_map<u32, ResolvePair> framebuffer_resolve_;
+ /// Blit a multisampled target into the single-sample one it owns; no-op for
+ /// a target that owns none. Called whenever a target is left.
+ void resolveFramebuffer(u32 fbo);
+ /// The target a pass is currently drawing into, so leaving it can resolve it.
+ u32 current_fbo_ = 0;
+ /// 0 = unprobed; otherwise GL_MAX_SAMPLES, floored at 1.
+ u32 max_samples_ = 0;
+
// Completed readbacks parked until taken: GL reads synchronously at request
// time, so the async contract resolves on the caller's first poll.
std::unordered_map<u32, std::vector<u8>> readbacks_;
diff --git a/src/esengine/renderer/rhi/GfxDevice.hpp b/src/esengine/renderer/rhi/GfxDevice.hpp
index 9473c089b..258b6054c 100644
--- a/src/esengine/renderer/rhi/GfxDevice.hpp
+++ b/src/esengine/renderer/rhi/GfxDevice.hpp
@@ -382,6 +382,15 @@ public:
*/
virtual bool supportsFloatTargets() = 0;
+ /**
+ * @brief Most samples an offscreen colour attachment may carry; 1 = none.
+ * @details The engine owns its own multisampling: a target the scene draws
+ * into is created with this many samples and resolves itself. Ask
+ * before requesting samples — a backend answering 1 has no MSAA to
+ * give, and a target that asks anyway would resolve from nothing.
+ */
+ virtual u32 maxSamples() = 0;
+
// =========================================================================
// Shader Programs
// =========================================================================
diff --git a/src/esengine/renderer/rhi/GfxEnums.hpp b/src/esengine/renderer/rhi/GfxEnums.hpp
index e3babc980..88a0d4043 100644
--- a/src/esengine/renderer/rhi/GfxEnums.hpp
+++ b/src/esengine/renderer/rhi/GfxEnums.hpp
@@ -355,6 +355,10 @@ struct BufferDesc {
struct TextureDesc {
u32 width = 1;
u32 height = 1;
+ /// Samples per pixel. Above 1 the attachment is MULTISAMPLED and cannot be
+ /// sampled by a shader — it is only ever drawn into and resolved from. Ask
+ /// GfxDevice::maxSamples() first; a backend that answers 1 wants 1.
+ u32 samples = 1;
GfxPixelFormat format = GfxPixelFormat::RGBA8;
TextureFilter minFilter = TextureFilter::Linear;
TextureFilter magFilter = TextureFilter::Linear;
@@ -371,6 +375,15 @@ struct TextureDesc {
struct FramebufferDesc {
TextureHandle color0 = TextureHandle::Invalid;
TextureHandle depthStencil = TextureHandle::Invalid;
+ /// Single-sample attachments a multisampled target resolves into. Set them
+ /// and the device resolves whenever the target is left, so nothing above the
+ /// RHI learns the target was multisampled.
+ TextureHandle resolveColor0 = TextureHandle::Invalid;
+ TextureHandle resolveDepthStencil = TextureHandle::Invalid;
+ /// Pixel size, required only when resolving: a blit needs a rectangle and an
+ /// attachment handle carries no dimensions.
+ u32 width = 0;
+ u32 height = 0;
};
/**
diff --git a/src/esengine/renderer/webgpu/WebGPUDevice.cpp b/src/esengine/renderer/webgpu/WebGPUDevice.cpp
index dc76952fa..0de0bba5d 100644
--- a/src/esengine/renderer/webgpu/WebGPUDevice.cpp
+++ b/src/esengine/renderer/webgpu/WebGPUDevice.cpp
@@ -73,6 +73,11 @@ WebGPUDevice::~WebGPUDevice() {
shutdown();
}
+// MSAA is not wired on this backend yet: its targets are all sampleCount 1 and
+// its pipelines multisample.count 1, so a caller must not ask for more — a
+// target that did would resolve out of an attachment that was never multisampled.
+u32 WebGPUDevice::maxSamples() { return 1; }
+
void WebGPUDevice::init() {
captureDeviceIdentity();
}
diff --git a/src/esengine/renderer/webgpu/WebGPUDevice.hpp b/src/esengine/renderer/webgpu/WebGPUDevice.hpp
index 533d8234c..40b71af62 100644
--- a/src/esengine/renderer/webgpu/WebGPUDevice.hpp
+++ b/src/esengine/renderer/webgpu/WebGPUDevice.hpp
@@ -143,6 +143,7 @@ public:
bool supportsCompressedFormat(GfxCompressedFormat format) override;
// Float-target rendering is a WebGPU core capability.
bool supportsFloatTargets() override { return true; }
+ u32 maxSamples() override;
bool supportsShaderLanguage(GfxShaderLanguage language) const override {
return language == GfxShaderLanguage::WGSL;
diff --git a/tests/renderer/MockGfxDevice.hpp b/tests/renderer/MockGfxDevice.hpp
index 5792e248f..89bf11f1d 100644
--- a/tests/renderer/MockGfxDevice.hpp
+++ b/tests/renderer/MockGfxDevice.hpp
@@ -182,6 +182,8 @@ struct MockGfxDevice final : GfxDevice {
}
bool supportsCompressedFormat(GfxCompressedFormat) override { return compressedSupported; }
bool supportsFloatTargets() override { return true; }
+ // No multisampling: these tests exercise the device seam, not a resolve.
+ u32 maxSamples() override { return 1; }
bool supportsShaderLanguage(GfxShaderLanguage language) const override {
return language == GfxShaderLanguage::GLSL_ES300 || (wgslSupported && language == GfxShaderLanguage::WGSL);
diff --git a/tools/check-postfx-aa.mjs b/tools/check-postfx-aa.mjs
new file mode 100644
index 000000000..b3b694917
--- /dev/null
+++ b/tools/check-postfx-aa.mjs
@@ -0,0 +1,73 @@
+#!/usr/bin/env node
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file check-postfx-aa.mjs — a post-process chain must not cost the frame its
+ * antialiasing.
+ *
+ * A WebGL2 canvas gives the default framebuffer 4x multisampling. A chain draws
+ * the scene into a target the engine made instead, so THAT target has to carry
+ * the sample count and resolve itself — or an effect that changes no colour at
+ * all still flattens every edge in the frame, which is what it did.
+ *
+ * The pixel criteria (aa-edge / aa-edge-post) say the coverage is there. They
+ * cannot say where it came from, because a screen-space filter smeared along the
+ * edges reproduces the same greys. So the ownership is asserted here instead.
+ *
+ * Run: node tools/check-postfx-aa.mjs (exit 1 on a violation)
+ */
+import { readFileSync } from 'node:fs';
+import path from 'node:path';
+import { fileURLToPath } from 'node:url';
+
+const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
+const PIPE_CPP = 'src/esengine/renderer/frame/PostProcessPipeline.cpp';
+const FB_CPP = 'src/esengine/renderer/rhi/Framebuffer.cpp';
+
+const read = (rel) => readFileSync(path.join(ROOT, rel), 'utf8');
+const findings = [];
+
+const pipe = read(PIPE_CPP);
+
+// 1. The scene target — the one target geometry is rasterised into — takes its
+// sample count from the member, never from a literal.
+const assign = /sceneDesc\.samples\s*=\s*([^;]+);/.exec(pipe);
+if (!assign) {
+ findings.push(`${PIPE_CPP}: the scene target sets no sample count — a post chain would `
+ + 'draw the scene single-sampled and the frame would lose its edges.');
+} else if (assign[1].trim() !== 'scene_samples_') {
+ findings.push(`${PIPE_CPP}: the scene target's sample count is \`${assign[1].trim()}\`, not `
+ + 'scene_samples_. A literal here is how the chain silently drops antialiasing; '
+ + 'the count belongs to the target and comes from the device.');
+}
+
+// 2. scene_samples_ is the DEVICE's answer, not a constant somebody picked.
+const derived = /scene_samples_\s*=\s*([^;]+);/.exec(pipe);
+if (!derived) {
+ findings.push(`${PIPE_CPP}: scene_samples_ is never assigned.`);
+} else if (!/maxSamples\s*\(\s*\)/.test(derived[1])) {
+ findings.push(`${PIPE_CPP}: scene_samples_ is \`${derived[1].trim()}\`, which never asks the `
+ + 'device. A backend with no multisampling must be able to answer 1, and one with '
+ + 'multisampling must not be capped by a guess.');
+}
+
+// 3. A multisampled target resolves ITSELF. Without the resolve attachments a
+// sampler reads the multisampled side, which cannot be sampled at all.
+const fb = read(FB_CPP);
+if (!/resolveColor_\s*=\s*device_->createTexture/.test(fb)) {
+ findings.push(`${FB_CPP}: a multisampled target no longer creates the single-sample `
+ + 'attachment it resolves into. Resolve is the target\'s own business — a pass or an '
+ + 'effect must never have to ask for it.');
+}
+if (!/createFramebuffer\(\{[^}]*resolveColor_/s.test(fb)) {
+ findings.push(`${FB_CPP}: the resolve attachments are created but not handed to `
+ + 'createFramebuffer, so the device has nothing to resolve into.');
+}
+
+if (findings.length) {
+ console.error('check-postfx-aa: the chain may cost the frame its antialiasing.\n');
+ for (const f of findings) console.error(` - ${f}`);
+ console.error('\nSee tools/check-postfx-aa.mjs for why this is a gate.');
+ process.exit(1);
+}
+console.log('check-postfx-aa: the scene target owns its sample count and resolves itself.');
diff --git a/tools/gates.mjs b/tools/gates.mjs
index 82be0db3e..aa2146364 100644
--- a/tools/gates.mjs
+++ b/tools/gates.mjs
@@ -46,6 +46,7 @@ export const GATES = [
{ id: 'gl-boundary', run: 'node tools/check-gl-boundary.mjs' },
{ id: 'draw-command-boundary', run: 'node tools/check-draw-command-boundary.mjs' },
{ id: 'shadow-pass', run: 'node tools/check-shadow-pass.mjs' },
+ { id: 'postfx-aa', run: 'node tools/check-postfx-aa.mjs' },
{ id: 'sidemodule-gates', run: 'node tools/check-sidemodule-gates.mjs' },
{ id: 'engine-exports', run: 'node tools/check-engine-exports.mjs' },
{ id: 'fixture-scenes', run: 'node tools/check-fixture-scenes.mjs' },
diff --git a/tools/renderScenes.mjs b/tools/renderScenes.mjs
index a18149472..b7d6c1a5f 100644
--- a/tools/renderScenes.mjs
+++ b/tools/renderScenes.mjs
@@ -450,6 +450,12 @@ export const SCENES = [
// SSAO: one unlit grey floor read at seven places. Contact, corner and
// step come back darker than the open floor they are made of, the floating
// box does not, and the wall behind a silhouette keeps its colour.
+ // A quad turned 20 degrees on black, read twice: the SAME values with and
+ // without a post chain is the claim. WebGPU has no MSAA yet, so both its
+ // halves read the hard step — still the claim, that the chain changes nothing.
+ { id: "aa-edge", tier: "pr", webgpu: { ESTELLA_VERIFY_EXPECT: "[{\"x\":0.2353,\"y\":0.502,\"rgb\":[0,0,0],\"tol\":6},{\"x\":0.2392,\"y\":0.502,\"rgb\":[255,255,255],\"tol\":6},{\"x\":0.749,\"y\":0.502,\"rgb\":[255,255,255],\"tol\":6},{\"x\":0.7529,\"y\":0.502,\"rgb\":[0,0,0],\"tol\":6},{\"x\":0.502,\"y\":0.502,\"rgb\":[255,255,255],\"tol\":6},{\"x\":0.0784,\"y\":0.0784,\"rgb\":[0,0,0],\"tol\":6}]" }, env: { ESTELLA_VERIFY_SCENE: "/scenes/aa-edge.esscene", ESTELLA_VERIFY_W: "256", ESTELLA_VERIFY_H: "256", ESTELLA_VERIFY_STEPS: "2", ESTELLA_VERIFY_EXPECT: "[{\"x\":0.2353,\"y\":0.502,\"rgb\":[128,128,128],\"tol\":64},{\"x\":0.2392,\"y\":0.502,\"rgb\":[128,128,128],\"tol\":64},{\"x\":0.749,\"y\":0.502,\"rgb\":[128,128,128],\"tol\":64},{\"x\":0.7529,\"y\":0.502,\"rgb\":[128,128,128],\"tol\":64},{\"x\":0.502,\"y\":0.502,\"rgb\":[255,255,255],\"tol\":6},{\"x\":0.0784,\"y\":0.0784,\"rgb\":[0,0,0],\"tol\":6}]" } },
+ // The other half: the same edges, read through an identity post chain.
+ { id: "aa-edge-post", tier: "pr", webgpu: { ESTELLA_VERIFY_EXPECT: "[{\"x\":0.2353,\"y\":0.502,\"rgb\":[0,0,0],\"tol\":6},{\"x\":0.2392,\"y\":0.502,\"rgb\":[255,255,255],\"tol\":6},{\"x\":0.749,\"y\":0.502,\"rgb\":[255,255,255],\"tol\":6},{\"x\":0.7529,\"y\":0.502,\"rgb\":[0,0,0],\"tol\":6},{\"x\":0.502,\"y\":0.502,\"rgb\":[255,255,255],\"tol\":6},{\"x\":0.0784,\"y\":0.0784,\"rgb\":[0,0,0],\"tol\":6}]" }, env: { ESTELLA_VERIFY_SCENE: "/scenes/aa-edge-post.esscene", ESTELLA_VERIFY_W: "256", ESTELLA_VERIFY_H: "256", ESTELLA_VERIFY_STEPS: "2", ESTELLA_VERIFY_EXPECT: "[{\"x\":0.2353,\"y\":0.502,\"rgb\":[128,128,128],\"tol\":64},{\"x\":0.2392,\"y\":0.502,\"rgb\":[128,128,128],\"tol\":64},{\"x\":0.749,\"y\":0.502,\"rgb\":[128,128,128],\"tol\":64},{\"x\":0.7529,\"y\":0.502,\"rgb\":[128,128,128],\"tol\":64},{\"x\":0.502,\"y\":0.502,\"rgb\":[255,255,255],\"tol\":6},{\"x\":0.0784,\"y\":0.0784,\"rgb\":[0,0,0],\"tol\":6}]" } },
{ id: "ssao", tier: "pr", webgpu: true, env: { ESTELLA_VERIFY_SCENE: "/scenes/ssao.esscene", ESTELLA_VERIFY_W: "320", ESTELLA_VERIFY_H: "240", ESTELLA_VERIFY_STEPS: "4", ESTELLA_VERIFY_EXPECT: "[{\"x\":0.5016,\"y\":0.8996,\"rgb\":[191,191,191],\"tol\":6},{\"x\":0.3762,\"y\":0.4937,\"rgb\":[144,144,144],\"tol\":9},{\"x\":0.627,\"y\":0.4812,\"rgb\":[172,172,172],\"tol\":9},{\"x\":0.8527,\"y\":0.4686,\"rgb\":[147,147,147],\"tol\":9},{\"x\":0.1881,\"y\":0.5272,\"rgb\":[123,141,113],\"tol\":9},{\"x\":0.1285,\"y\":0.1967,\"rgb\":[133,136,148],\"tol\":9},{\"x\":0.627,\"y\":0.2008,\"rgb\":[179,184,199],\"tol\":5}]" } },
{ id: "depth-outline-flat", tier: "pr", webgpu: true, env: { ESTELLA_VERIFY_SCENE: "/scenes/depth-outline-flat.esscene", ESTELLA_VERIFY_W: "256", ESTELLA_VERIFY_H: "256", ESTELLA_VERIFY_STEPS: "2", ESTELLA_VERIFY_EXPECT: "[{\"x\":0.5,\"y\":0.5,\"rgb\":[230,102,26],\"tol\":20}]" } },
{ id: "mesh-opaque", tier: "pr", webgpu: true, env: { ESTELLA_VERIFY_SCENE: "/scenes/mesh-depth.esscene", ESTELLA_VERIFY_MANIFEST: "/scenes/mesh-depth.textures.json", ESTELLA_VERIFY_W: "256", ESTELLA_VERIFY_H: "256", ESTELLA_VERIFY_STEPS: "4", ESTELLA_VERIFY_EXPECT: "[{\"x\":0.42,\"y\":0.5,\"rgb\":[0,255,0],\"tol\":40},{\"x\":0.58,\"y\":0.5,\"rgb\":[255,0,0],\"tol\":40}]" } },