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.

14.4 KB
Raw Blame
// Who owns which square of the shadow texture. A frame sees some of this now —
// point-shadow resolves in two faces of a cube and goes red if every tile reports one
// rect — but only the tiles its own fragments land in. The arithmetic is pinned here.

#include "esengine/renderer/store/ShadowAtlas.hpp"
#include "esengine/renderer/store/ShadowPlan.hpp"

#include <cstdio>
#include <cmath>

using namespace esengine;

static int g_failures = 0;
#define CHECK(cond, msg)                                                        \
    do {                                                                        \
        if (!(cond)) { std::printf("FAIL: %s\n", msg); ++g_failures; }          \
        else { std::printf("ok:   %s\n", msg); }                                \
    } while (0)

static bool near(f32 a, f32 b) { return std::fabs(a - b) < 1e-6f; }

static bool isTile(const ShadowTile& t, u32 x, u32 y, u32 size) {
    return t.x == x && t.y == y && t.size == size;
}

static bool isRect(const glm::vec4& r, f32 x, f32 y, f32 size) {
    return near(r.x, x) && near(r.y, y) && near(r.z, size);
}

int main() {
    AtlasRefusal why = AtlasRefusal::None;
    // The frame's own atlas: 2048 handed out in 512 cells, a cascade taking 2x2.
    ShadowAtlas atlas(2048, 512);

    const i32 first = atlas.allocate(4, 2, why);
    CHECK(first == 0, "the first claim starts at tile 0");
    CHECK(atlas.tileCount() == 4, "four cascades claim four tiles");

    // The order the expression this replaced produced: 0 lower-left, 1 lower-right,
    // 2 upper-left, 3 upper-right. A different order is a different picture, and
    // no pixel gate would say so.
    CHECK(isTile(atlas.tile(0), 0, 0, 1024), "tile 0 is the lower-left quadrant");
    CHECK(isTile(atlas.tile(1), 1024, 0, 1024), "tile 1 is the lower-right quadrant");
    CHECK(isTile(atlas.tile(2), 0, 1024, 1024), "tile 2 is the upper-left quadrant");
    CHECK(isTile(atlas.tile(3), 1024, 1024, 1024), "tile 3 is the upper-right quadrant");

    // What the shader indexes with — the same squares as a fraction of the atlas.
    CHECK(isRect(atlas.unitRect(0), 0.0f, 0.0f, 0.5f), "tile 0's rect is (0, 0, 1/2)");
    CHECK(isRect(atlas.unitRect(1), 0.5f, 0.0f, 0.5f), "tile 1's rect is (1/2, 0, 1/2)");
    CHECK(isRect(atlas.unitRect(2), 0.0f, 0.5f, 0.5f), "tile 2's rect is (0, 1/2, 1/2)");
    CHECK(isRect(atlas.unitRect(3), 0.5f, 0.5f, 0.5f), "tile 3's rect is (1/2, 1/2, 1/2)");

    // A full atlas has nothing left, and says so rather than handing out a square
    // somebody else is already drawing into.
    CHECK(atlas.allocate(1, 2, why) < 0, "a full atlas refuses the next claim");

    // All or nothing: a caller that gets half a cascade set would leave the rest
    // reading depths that belong to another light.
    ShadowAtlas partial(2048, 512);
    CHECK(partial.allocate(3, 2, why) == 0, "three of the four fit");
    CHECK(partial.allocate(2, 2, why) < 0, "two more do not, and the claim is refused");
    CHECK(partial.tileCount() == 3, "a refused claim leaves the atlas as it was");
    CHECK(partial.allocate(1, 2, why) == 3, "and the one that does fit still can");

    // Tiles need not all be one size — which is the whole reason the rect is data.
    // A spot light taking one cell sits beside a cascade taking four.
    ShadowAtlas mixed(2048, 512);
    CHECK(mixed.allocate(1, 2, why) == 0, "a 2x2 block lands first");
    const i32 small = mixed.allocate(2, 1, why);
    CHECK(small == 1, "single cells claim after it");
    CHECK(isTile(mixed.tile(1), 1024, 0, 512), "the first single cell clears the block");
    CHECK(isRect(mixed.unitRect(1), 0.5f, 0.0f, 0.25f), "and reports a quarter-side rect");

    // A point light's cube: six single cells claimed together, contiguous and in the
    // order the faces are rendered — which is what lets a light name a first tile and a
    // count rather than six indices.
    ShadowAtlas cube(2048, 512);
    CHECK(cube.allocate(SHADOW_CUBE_FACES, 1, why) == 0, "a cube claims its six faces at once");
    CHECK(cube.tileCount() == 6, "and gets all six");
    CHECK(isTile(cube.tile(0), 0, 0, 512), "face 0 takes the first cell");
    CHECK(isTile(cube.tile(5), 512, 512, 512), "face 5 the sixth, the row filled in order");
    // What a sun standing beside it can still have: the cube left a row half used, and a
    // 2x2 block only starts on a multiple of 2 — so the sun loses cascades, not its map.
    CHECK(cube.allocate(4, 2, why) < 0, "four cascades no longer fit beside a cube");
    CHECK(cube.allocate(2, 2, why) == 6, "two do, in the rows the cube did not reach");
    CHECK(isTile(cube.tile(6), 0, 1024, 1024), "the first of them clearing the cube's rows");

    // The budget is the shader's array bound, not the texture's room: a 4096 atlas
    // of 512 cells has 64 of them and the block still stops at MAX_SHADOW_TILES.
    ShadowAtlas wide(4096, 512);
    CHECK(wide.allocate(MAX_SHADOW_TILES + 1, 1, why) < 0, "the tile budget is a hard bound");
    CHECK(wide.allocate(MAX_SHADOW_TILES, 1, why) == 0, "and exactly the bound fits");

    // A frame gives it all back: a tile means nothing once the depths in it are
    // from a frame that is gone.
    ShadowAtlas reused(2048, 512);
    reused.allocate(4, 2, why);
    reused.reset();
    CHECK(reused.tileCount() == 0, "reset empties the atlas");
    CHECK(reused.allocate(4, 2, why) == 0, "and the next frame claims the same squares");
    CHECK(isTile(reused.tile(0), 0, 0, 1024), "starting again at the lower-left");

    // A block larger than the grid has nowhere to go, and a zero-sized claim is not
    // a claim — both answer rather than indexing something that is not there.
    ShadowAtlas small2(1024, 512);
    CHECK(small2.allocate(1, 4, why) < 0, "a block wider than the atlas is refused");
    CHECK(small2.allocate(0, 2, why) < 0, "so is a claim for no tiles");
    CHECK(small2.allocate(1, 0, why) < 0, "so is a claim for empty ones");

    // Each refusal is a DIFFERENT answer, and only one of them is fixed by a bigger
    // atlas. Folded into one "no room" they would send a reader to raise a size that
    // was never the limit.
    ShadowAtlas reasons(2048, 512);
    reasons.allocate(1, 8, why);
    CHECK(why == AtlasRefusal::TooLarge, "a block wider than the atlas says so");
    reasons.allocate(MAX_SHADOW_TILES + 1, 1, why);
    CHECK(why == AtlasRefusal::TileBudget, "past the shader's array bound says budget");
    ShadowAtlas filled(1024, 512);
    filled.allocate(4, 1, why);
    CHECK(why == AtlasRefusal::None, "a claim that fits refuses nothing");
    filled.allocate(1, 1, why);
    CHECK(why == AtlasRefusal::NoSpace, "and the one after it is out of room, not out of budget");

    // Giving way, and what it gives way FROM. A sun asks for a cascade set and takes
    // fewer rather than costing a positional light its map — which is correct, and was
    // indistinguishable from casting nothing.
    ShadowAtlas contended(2048, 512);
    i32 at = -1;
    const ShadowGrant cubeGrant = claimTiles(contended, Entity::make(1, 1), SHADOW_CUBE_FACES, 1, at);
    CHECK(cubeGrant.granted == SHADOW_CUBE_FACES && at == 0, "the cube claims first and whole");
    const ShadowGrant sun = claimTiles(contended, Entity::make(2, 1), MAX_SHADOW_CASCADES, 2, at,
                                      ShadowClaim::AllowFewer);
    CHECK(sun.requested == MAX_SHADOW_CASCADES, "the sun asked for a whole cascade set");
    CHECK(sun.granted > 0 && sun.granted < sun.requested, "and settled for fewer");
    CHECK(sun.reduced() && !sun.denied(), "which is a reduction, not a denial");
    CHECK(sun.refusal == AtlasRefusal::NoSpace,
          "and the reason is the FIRST attempt's, not the last one that happened to work");

    // A smaller atlas is the case a reader hits first, and the one they can act on.
    ShadowAtlas cramped(1024, 512);
    i32 none = -1;
    claimTiles(cramped, Entity::make(3, 1), 4, 1, none);
    const ShadowGrant denied = claimTiles(cramped, Entity::make(4, 1), 1, 1, none);
    CHECK(denied.denied() && none < 0, "a caster the atlas cannot fit keeps nothing");
    CHECK(denied.refusal == AtlasRefusal::NoSpace, "and says the atlas was full");
    CHECK(denied.granted == 0 && denied.requested == 1, "recording both halves of the claim");

    // Three point lights in a sixteen-tile budget must never leave the third
    // with four cube faces. The refused claim leaves room for the sun instead.
    for (const u32 size : {2048u, 4096u}) {
        ShadowAtlas points(size, 512);
        claimTiles(points, Entity::make(20, 1), SHADOW_CUBE_FACES, 1, at);
        claimTiles(points, Entity::make(21, 1), SHADOW_CUBE_FACES, 1, at);
        const ShadowGrant third = claimTiles(points, Entity::make(22, 1), SHADOW_CUBE_FACES, 1, at);
        CHECK(third.denied() && at < 0, "a point shadow cannot keep an incomplete cube");
        CHECK(third.refusal == AtlasRefusal::TileBudget, "a larger atlas does not bypass the tile limit");
        CHECK(points.tileCount() == 12, "a refused cube consumes no tiles");
        const ShadowGrant moon = claimTiles(points, Entity::make(23, 1), 1, 2, at);
        if (size == 4096) {
            CHECK(moon.granted == 1 && at == 12, "a free 2x2 block holds a complete sun map");
        } else {
            CHECK(moon.denied() && moon.refusal == AtlasRefusal::NoSpace,
                  "a single free row cannot fit a 2x2 sun map");
            const ShadowGrant spot = claimTiles(points, Entity::make(25, 1), 1, 1, at);
            CHECK(spot.granted == 1 && at == 12, "the free row still holds a complete spot map");
        }
    }
    ShadowAtlas tooSmallForCube(1024, 512);
    const ShadowGrant noCube = claimTiles(tooSmallForCube, Entity::make(24, 1), SHADOW_CUBE_FACES, 1, at);
    CHECK(noCube.denied() && noCube.refusal == AtlasRefusal::NoSpace,
          "four free cells still cannot hold a six-face point shadow");
    CHECK(tooSmallForCube.tileCount() == 0, "a spatial refusal also rolls back every cube face");

    ShadowPlanReport previous;
    previous.grants.push_back(denied);
    CHECK(previous.hasSameDenial(denied), "an unchanged denied light does not need another warning");
    ShadowGrant changed = denied;
    changed.refusal = AtlasRefusal::TileBudget;
    CHECK(!previous.hasSameDenial(changed), "a different refusal needs a new warning");
    changed = denied; changed.requested++;
    CHECK(!previous.hasSameDenial(changed), "a changed claim needs a new warning");
    changed = denied; changed.light = Entity::make(4, 2);
    CHECK(!previous.hasSameDenial(changed), "a reused entity slot is a new light");
    previous.grants[0].granted = 1;
    CHECK(!previous.hasSameDenial(denied), "a recovered light can warn if it loses its map again");
    previous.clear();
    CHECK(!previous.hasSameDenial(denied), "a light returning after an empty frame can warn again");

    // The report's own arithmetic: what a frame says it handed out is what the atlas
    // actually holds. A grant nobody claimed would make every later number a guess.
    ShadowPlanReport report;
    ShadowAtlas counted(2048, 512);
    for (u32 i = 0; i < 3; ++i) {
        i32 first = -1;
        report.grants.push_back(claimTiles(counted, Entity::make(i + 10, 1), 2, 2, first));
    }
    for (const ShadowGrant& g : report.grants) {
        report.requestedTiles += g.requested;
        report.grantedTiles += g.granted;
    }
    CHECK(report.grantedTiles == counted.tileCount(),
          "the tiles the report says were granted are the tiles the atlas holds");
    CHECK(report.requestedTiles == 6, "and what was asked for is counted apart from it");
    CHECK(report.deniedCasters() + report.reducedCasters() > 0,
          "three two-tile claims do not all fit in four cells, and the report says which");

    ShadowAtlas fitted(4096, 1024);
    CHECK(fitted.occupiedSize() == 0, "an empty atlas needs no texture");
    fitted.allocate(1, 2, why);
    CHECK(fitted.occupiedSize() == 2048, "one high-quality sun keeps its 2048-texel map");
    CHECK(isRect(fitted.unitRect(0, fitted.occupiedSize()), 0, 0, 1),
          "a single sun fills the fitted texture");
    CHECK(fitted.allocate(4, 2, why) < 0 && fitted.occupiedSize() == 2048,
          "a partially allocated refusal does not grow the texture");
    CHECK(fitted.allocate(3, 2, why) == 1 && fitted.occupiedSize() == 4096,
          "fitting storage preserves the full cascade budget");
    fitted.reset();
    CHECK(fitted.occupiedSize() == 0, "reset releases the previous occupied extent");
    fitted.allocate(1, 1, why);
    CHECK(fitted.occupiedSize() == 1024, "a spot uses one cell after a full frame");
    fitted.allocate(1, 1, why);
    CHECK(fitted.occupiedSize() == 2048, "the second spot grows the texture without moving tiles");
    fitted.allocate(1, 1, why);
    CHECK(fitted.occupiedSize() == 4096, "a third column rounds storage up to the next texture size");
    CHECK(tooSmallForCube.occupiedSize() == 0, "a refused cube leaves no storage requirement");

    // UVs and PCF steps must still address the same texels at every quality budget.
    for (u32 budget = 512; budget <= 4096; budget *= 2) {
        for (u32 cell = 128; cell <= budget / 2; cell *= 2) {
            ShadowAtlas sampled(budget, cell);
            for (u32 count = 0; count < MAX_SHADOW_TILES; ++count) {
                if (sampled.allocate(1, count % 3 == 0 ? 2 : 1, why) < 0) {
                    continue;
                }
                const u32 side = sampled.occupiedSize();
                bool contained = side > 0 && side <= budget && (side & (side - 1)) == 0;
                bool sameTexels = true;
                for (u32 i = 0; i < sampled.tileCount(); ++i) {
                    const ShadowTile& tile = sampled.tile(i);
                    const glm::vec4 rect = sampled.unitRect(i, side);
                    contained &= tile.x + tile.size <= side && tile.y + tile.size <= side;
                    for (const f32 uv : {0.0f, 0.25f, 0.5f, 0.75f, 1.0f}) {
                        sameTexels &= near((rect.x + uv * rect.z) * side, tile.x + uv * tile.size);
                        sameTexels &= near((rect.y + uv * rect.z) * side, tile.y + uv * tile.size);
                    }
                    sameTexels &= near((1.0f / side) / rect.z, 1.0f / tile.size);
                }
                CHECK(contained, "fitted storage contains every mixed-size tile within budget");
                CHECK(sameTexels, "fitted UVs and PCF offsets preserve pixel resolution");
            }
        }
    }

    std::printf(g_failures ? "\n%d check(s) failed\n" : "\nall checks passed\n", g_failures);
    return g_failures == 0 ? 0 : 1;
}