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.
TypeScript 2d-game-engine3d3d-game-engineandroidcppecsgame-editorgame-enginegamedeviostypescriptwebassemblywebglwebgpuwechat-minigame
fix(render): a device is asked what its clip volume is, not assumed to be GL
yhh86006d990606
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex cfb983bc3..ea2483697 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -16,26 +16,39 @@ published separately; it ships inside the editor.### Changed-- **The two backends disagree about what is behind an orthographic camera, and a- scene now says so.** `mat4.ts` builds every camera projection in the GL convention,- where clip z runs `[-1, 1]`; WebGPU clips everything below 0 of it. So an- orthographic camera's box is symmetric on WebGL2 and one-sided on WebGPU, and a- renderable between the camera plane and `+farPlane` draws on one backend and not- the other. `RenderFrame.cpp:954` already hand-builds the shadow projection to dodge- exactly this, "because this matrix is the one place the choice is free" — a camera's- is not, so it kept the divergence.-- Nothing caught it because no fixture had content there: the whole scene corpus- stands its cameras back, and the parity host puts every entity at z = 0.- `celestial-heights` does have content there — `spire.esscene` has `HealthBar_Fill`- at world z = +1 under a camera at z = 0 — which is a Dawn build drawing the game- without part of its HUD.-- Gate `ortho-clip-behind-camera` is that geometry, and it is **red on WebGPU on- purpose**: it holds the divergence open rather than describing it. Whichever way the- conventions are reconciled, that scene is what says they were. The fix is not in this- change — it moves a convention that `Frustum::extractFromMatrix`, `cameraFrustumCorners`- (@beta) and a numeric assertion in `mat4.test.ts` all depend on.+- **A device is asked what its clip volume is, instead of being assumed to be GL.**+ Every projection in the engine is built for clip z in `[-1, 1]` and was handed to+ both backends unchanged. WebGPU keeps `[0, 1]` and discards the rest, so an+ orthographic camera's box was symmetric on WebGL2 and one-sided on WebGPU: anything+ between the camera plane and `+farPlane` drew on one backend and vanished on the+ other. `RenderFrame.cpp` had hand-built the shadow projection around this years-old+ fact, "because this matrix is the one place the choice is free" — a camera's was not,+ so it kept the divergence.++ Nothing caught it because no fixture had content there: the corpus stands its cameras+ back and the parity host puts every entity at z = 0. `celestial-heights` does —+ `spire.esscene` has `HealthBar_Fill` at world z = +1 under a camera at z = 0 — so a+ Dawn build drew the game without that part of its HUD.++ `GfxDevice::clipDepthRange()` is that fact, declared by each backend rather than read+ off the display name in its identity, and pure so a backend added later cannot inherit+ someone else's convention in silence. `RenderContext::updateCameraConstants` is the+ one place a camera's projection is converted, and it converts only what it uploads:+ the engine keeps `[-1, 1]` everywhere else, so `Frustum::extractFromMatrix`, the+ published `cameraFrustumCorners`, `ImmediateDraw`'s own unprojection and every+ numeric assertion in `mat4.test.ts` are untouched, and a WebGL2 build is unchanged to+ the bit. No shader was edited; the eye in `FrameConstants` is invariant under the+ conversion, so nothing had to be ordered around it.++ The shadow cascades keep going through the unconverted path, and that is now stated+ rather than implied: their projection spans exactly the occluders it draws, so it+ already sits inside either clip volume, and converting it would move the depths it+ writes away from the copy of the matrix the receiving shader compares against — while+ a bias derived from the range it spans went on meaning the old one.++ Gate `ortho-clip-behind-camera` is that geometry. It was landed red on WebGPU on+ purpose one commit earlier, to hold the divergence open; it is green on both now, as+ is every other scene in the tier on both backends.- **A turned sprite is culled by a box that turned with it.** The same bound the meshpath just gained, for the three plane renderables that also draw a turned quad: adiff --git a/src/esengine/renderer/draw/ImmediateDraw.cpp b/src/esengine/renderer/draw/ImmediateDraw.cppindex 43cb01a70..a3ceb0d13 100644--- a/src/esengine/renderer/draw/ImmediateDraw.cpp+++ b/src/esengine/renderer/draw/ImmediateDraw.cpp@@ -128,8 +128,9 @@ void ImmediateDraw::begin(const glm::mat4& viewProjection) {if (!initialized_) return;// The batch shader reads u_projection from the shared FrameConstants UBO; update it- // for this pass rather than uploading a loose uniform per flush.- context_.updateFrameConstants(viewProjection);+ // for this pass rather than uploading a loose uniform per flush. A camera's, so it+ // is converted for the device — Draw.line3D places geometry in the world.+ context_.updateCameraConstants(viewProjection);// A prior phase may have left another pipeline bound; force our pipeline to re-apply.device_.invalidatePipelineCache();diff --git a/src/esengine/renderer/frame/RenderContext.cpp b/src/esengine/renderer/frame/RenderContext.cppindex cd628833a..c6985310c 100644--- a/src/esengine/renderer/frame/RenderContext.cpp+++ b/src/esengine/renderer/frame/RenderContext.cpp@@ -155,9 +155,30 @@ void RenderContext::initFrameUbo() {ES_LOG_DEBUG("FrameConstants UBO created (handle: {})", static_cast<u32>(frameUbo_));}+// The same projection with its clip z mapped from [-1, 1] onto [0, 1]: row 2+// becomes the average of rows 2 and 3, which is that map written as a matrix.+static glm::mat4 toZeroToOneDepth(const glm::mat4& p) {+ glm::mat4 out = p;+ for (int col = 0; col < 4; ++col) out[col][2] = (p[col][2] + p[col][3]) * 0.5f;+ return out;+}++void RenderContext::updateCameraConstants(const glm::mat4& viewProjection) {+ const bool zeroToOne = device_.clipDepthRange() == ClipDepthRange::ZeroToOne;+ uploadFrameConstants(zeroToOne ? toZeroToOneDepth(viewProjection) : viewProjection,+ viewProjection);+}+void RenderContext::updateFrameConstants(const glm::mat4& viewProjection) {- viewProjection_ = viewProjection;- const FrameConstants frame{viewProjection, cameraFromViewProjection(viewProjection)};+ uploadFrameConstants(viewProjection, viewProjection);+}++// `engine` is the projection in the engine's own convention, which is what the+// viewpoint is read from: the two agree on it, but only one of them is the answer+// to "where is the eye" that the rest of the engine also holds.+void RenderContext::uploadFrameConstants(const glm::mat4& upload, const glm::mat4& engine) {+ viewProjection_ = engine;+ const FrameConstants frame{upload, cameraFromViewProjection(engine)};device_.updateBuffer(frameUbo_, 0, &frame, sizeof(FrameConstants));// Re-arm the params fallback for this pass: a post-process or custom-draw// commit from the previous pass left its own (differently sized) buffer ondiff --git a/src/esengine/renderer/frame/RenderContext.hpp b/src/esengine/renderer/frame/RenderContext.hppindex 778da4ee9..15e671424 100644--- a/src/esengine/renderer/frame/RenderContext.hpp+++ b/src/esengine/renderer/frame/RenderContext.hpp@@ -158,6 +158,20 @@ public:* The camera's own placement rides along, recovered from the matrix — every* path in hands over exactly one view-projection and nothing else.*/+ /**+ * @brief Point the frame at what a CAMERA sees.+ * @details Keeps the projection in the engine's convention and uploads it in+ * the device's. This is the one place that conversion happens.+ */+ void updateCameraConstants(const glm::mat4& viewProjection);++ /**+ * @brief Point the frame at a pass whose projection already suits the device.+ * @details The shadow cascades: theirs spans exactly the occluders it draws,+ * so it lands inside either clip volume untouched, and converting it+ * would move the depths it writes away from the copy of the matrix+ * the receiving shader compares against.+ */void updateFrameConstants(const glm::mat4& viewProjection);/** @brief Uploads the frame clock + canvas size into the injected TimeConstants UBO. */@@ -186,6 +200,8 @@ private:TextureHandle make1x1Texture(u32 rgba);void initFrameUbo();+ void uploadFrameConstants(const glm::mat4& upload, const glm::mat4& engine);+glm::mat4 viewProjection_{1.0f};RenderContextStats stats_;diff --git a/src/esengine/renderer/frame/RenderFrame.cpp b/src/esengine/renderer/frame/RenderFrame.cppindex 85d0169b6..766ddaa5c 100644--- a/src/esengine/renderer/frame/RenderFrame.cpp+++ b/src/esengine/renderer/frame/RenderFrame.cpp@@ -340,7 +340,7 @@ void RenderFrame::flush() {pool_.upload();}- context_.updateFrameConstants(view_projection_);+ context_.updateCameraConstants(view_projection_);context_.lights().uploadAndBind();gpu_timer_.poll(device_);@@ -463,7 +463,7 @@ void RenderFrame::replayToDrawCall(i32 stopAtDrawCall) {frame_capture_.setReplayMode(stopAtDrawCall + 1);- context_.updateFrameConstants(view_projection_);+ context_.updateCameraConstants(view_projection_);context_.lights().uploadAndBind();draw_list_.execute(device_, pool_, context_.materials(), context_.getWhiteTextureId(),&frame_capture_, context_.skinUbo());@@ -519,7 +519,7 @@ void RenderFrame::renderToTarget(ecs::Registry& registry, const glm::mat4& viewPdraw_list_.finalize(pool_);pool_.upload();- context_.updateFrameConstants(viewProjection);+ context_.updateCameraConstants(viewProjection);context_.lights().uploadAndBind();draw_list_.execute(device_, pool_, context_.materials(), context_.getWhiteTextureId(),&frame_capture_, context_.skinUbo());@@ -995,6 +995,9 @@ void RenderFrame::renderShadowMap(ecs::Registry& registry) {draw_list_.finalize(pool_);pool_.upload();+ // Not a camera's: this projection spans exactly the occluders it draws, so+ // it sits inside either clip volume as built, and the depths it writes are+ // compared against the copy of it the receiving shader holds.context_.updateFrameConstants(matrices[c]);// The depth variant is still a Lit2D shader and still declares the light block,// and a draw whose declared UBO is unbound is undefined behaviour that drawsdiff --git a/src/esengine/renderer/rhi/GLDevice.hpp b/src/esengine/renderer/rhi/GLDevice.hppindex 1a1200882..aeb10fad6 100644--- a/src/esengine/renderer/rhi/GLDevice.hpp+++ b/src/esengine/renderer/rhi/GLDevice.hpp@@ -36,6 +36,8 @@ public:GLDevice() = default;~GLDevice() override = default;+ ClipDepthRange clipDepthRange() const override { return ClipDepthRange::MinusOneToOne; }+void init() override;void shutdown() override;diff --git a/src/esengine/renderer/rhi/GfxDevice.hpp b/src/esengine/renderer/rhi/GfxDevice.hppindex 98f35e683..9473c089b 100644--- a/src/esengine/renderer/rhi/GfxDevice.hpp+++ b/src/esengine/renderer/rhi/GfxDevice.hpp@@ -119,6 +119,15 @@ public:*/const GfxDeviceIdentity& deviceIdentity() const { return identity_; }+ /**+ * @brief The clip volume this device keeps along z.+ * @details Pure: a backend that does not state this is a backend whose+ * projections silently mean something else, which is the bug this+ * exists to make impossible. It is not read off `deviceIdentity`,+ * whose backend name is a label rather than a capability.+ */+ virtual ClipDepthRange clipDepthRange() const = 0;+/*** @brief Declares the device lost from outside the backend.* @details The host observes losses the backend cannot: a browser firingdiff --git a/src/esengine/renderer/rhi/GfxEnums.hpp b/src/esengine/renderer/rhi/GfxEnums.hppindex f819188a2..0d5246a86 100644--- a/src/esengine/renderer/rhi/GfxEnums.hpp+++ b/src/esengine/renderer/rhi/GfxEnums.hpp@@ -442,6 +442,19 @@ enum class GfxDeviceLostReason : u8 {* Its own type because a device has an identity for its whole life,* while a loss report exists only after one.*/+/**+ * @brief What a device's clip volume does with depth.+ *+ * @details The engine builds every projection for [-1, 1], which its frustum+ * extraction and its published frustum-corner API also speak. A device+ * keeping [0, 1] is handed the same projection in its own terms by+ * RenderContext::updateCameraConstants, the only place that happens.+ */+enum class ClipDepthRange : u8 {+ MinusOneToOne, ///< OpenGL / OpenGL ES / WebGL.+ ZeroToOne, ///< WebGPU, and every native API behind it.+};+struct GfxDeviceIdentity {std::string backend; ///< "WebGL2", "WebGPU".std::string vendor;diff --git a/src/esengine/renderer/webgpu/WebGPUDevice.hpp b/src/esengine/renderer/webgpu/WebGPUDevice.hppindex 1dd70bfef..84023f6e6 100644--- a/src/esengine/renderer/webgpu/WebGPUDevice.hpp+++ b/src/esengine/renderer/webgpu/WebGPUDevice.hpp@@ -64,6 +64,8 @@ public:WGPUAdapter adapter = nullptr);~WebGPUDevice() override;+ ClipDepthRange clipDepthRange() const override { return ClipDepthRange::ZeroToOne; }+void init() override;void shutdown() override;diff --git a/tests/renderer/MockGfxDevice.hpp b/tests/renderer/MockGfxDevice.hppindex c1b349c10..5792e248f 100644--- a/tests/renderer/MockGfxDevice.hpp+++ b/tests/renderer/MockGfxDevice.hpp@@ -18,6 +18,10 @@ struct MockGfxDevice final : GfxDevice {using GfxDevice::markDeviceLost;using GfxDevice::setDeviceIdentity;+ // Which clip volume this stand-in keeps; settable so one harness can drive+ // both conventions rather than only the one the host happens to run.+ ClipDepthRange clipRange = ClipDepthRange::MinusOneToOne;+// Stands in for a backend that can (or cannot) get its device back.bool recreateSucceeds = true;int recreateCalls = 0;@@ -108,6 +112,8 @@ struct MockGfxDevice final : GfxDevice {u32 lastDrawIndexByteOffset = 0;u32 lastDrawInstanceCount = 0;+ ClipDepthRange clipDepthRange() const override { return clipRange; }+void init() override {}void shutdown() override {}diff --git a/tools/renderScenes.mjs b/tools/renderScenes.mjsindex 9f74865ee..de66b6c34 100644--- a/tools/renderScenes.mjs+++ b/tools/renderScenes.mjs@@ -255,9 +255,9 @@ export const SCENES = [// last, seen from an eye turned -60° about Y. Equal world z ties, and the tie puts// the FAR quad on top; only a viewer-measured depth puts the near (green) one there.{ id: "sort-view-depth", tier: "pr", webgpu: true, env: { ESTELLA_VERIFY_ORBIT: "-60,0", ESTELLA_VERIFY_SCENE: "/scenes/sort-view-depth.esscene", ESTELLA_VERIFY_MANIFEST: "/scenes/sort-view-depth.textures.json", ESTELLA_VERIFY_W: "256", ESTELLA_VERIFY_H: "256", ESTELLA_VERIFY_STEPS: "4", ESTELLA_VERIFY_EXPECT: "[{\"x\":0.5,\"y\":0.5,\"rgb\":[0,255,0],\"tol\":40},{\"x\":0.30,\"y\":0.5,\"rgb\":[0,255,0],\"tol\":40},{\"x\":0.70,\"y\":0.5,\"rgb\":[255,0,0],\"tol\":40}]" } },- // KNOWN RED ON WEBGPU: a sprite at z = +1 under an ortho camera at z = 0 is inside the- // symmetric box mat4.ts builds and below 0 of what WebGPU clips to. RenderFrame.cpp:954- // dodges this for shadows; a camera cannot, and celestial-heights' HealthBar_Fill is there.+ // A sprite at z = +1 under an ortho camera at z = 0: inside the symmetric box the+ // engine builds, and below 0 of what WebGPU keeps. Both backends draw it only while+ // updateCameraConstants converts the projection into the clip volume each one has.{ id: "ortho-clip-behind-camera", tier: "pr", webgpu: true, env: { ESTELLA_VERIFY_SCENE: "/scenes/ortho-clip-behind-camera.esscene", ESTELLA_VERIFY_MANIFEST: "/scenes/ortho-clip-behind-camera.textures.json", ESTELLA_VERIFY_W: "256", ESTELLA_VERIFY_H: "256", ESTELLA_VERIFY_STEPS: "4", ESTELLA_VERIFY_EXPECT: "[{\"x\":0.30,\"y\":0.5,\"rgb\":[255,0,0],\"tol\":40},{\"x\":0.70,\"y\":0.5,\"rgb\":[0,255,0],\"tol\":40}]" } },// Two quads crossing: one flat, one turned 60° about Y, so each is nearer on// one side. Painter's order cannot draw that — with `opaque` the halves resolve