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.

8.1 KB
Raw Blame
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
/**
 * @file    BatchPlugin.cpp
 * @brief   Shared quad / nine-slice geometry construction for batch render-type plugins.
 *
 * @author  ESEngine Team
 * @date    2026
 *
 * @copyright Copyright (c) 2026 ESEngine Team
 *            Licensed under the Apache License, Version 2.0.
 */
#include "BatchPlugin.hpp"

#include <algorithm>
#include <cmath>

namespace esengine {

void BatchPlugin::emitQuad(
    TransientBufferPool& buffers, DrawList& draw_list, const ClipState& clips,
    const glm::vec3& position, const glm::vec2& size, const glm::vec2& pivotNorm,
    f32 angle, const glm::vec2& uvOffset, const glm::vec2& uvScale,
    const glm::vec4& color, const BatchDrawKey& key
) {
    f32 ox = 0.5f - pivotNorm.x;
    f32 oy = 0.5f - pivotNorm.y;
    const u32 packedColor = packColor(color);  // constant across the 4 verts

    BatchVertex verts[4];
    if (std::abs(angle) > 0.001f) {
        f32 cosA = std::cos(angle);
        f32 sinA = std::sin(angle);
        for (u32 i = 0; i < 4; ++i) {
            f32 lx = (BATCH_QUAD_POSITIONS[i].x + ox) * size.x;
            f32 ly = (BATCH_QUAD_POSITIONS[i].y + oy) * size.y;
            verts[i].position = glm::vec3(
                position.x + lx * cosA - ly * sinA,
                position.y + lx * sinA + ly * cosA,
                position.z
            );
            verts[i].color = packedColor;
            verts[i].texCoord = BATCH_QUAD_TEX_COORDS[i] * uvScale + uvOffset;
        }
    } else {
        for (u32 i = 0; i < 4; ++i) {
            verts[i].position = glm::vec3(
                position.x + (BATCH_QUAD_POSITIONS[i].x + ox) * size.x,
                position.y + (BATCH_QUAD_POSITIONS[i].y + oy) * size.y,
                position.z
            );
            verts[i].color = packedColor;
            verts[i].texCoord = BATCH_QUAD_TEX_COORDS[i] * uvScale + uvOffset;
        }
    }

    appendQuad(buffers, draw_list, clips, verts, key);
}

void BatchPlugin::emitNineSlice(
    TransientBufferPool& buffers, DrawList& draw_list, const ClipState& clips,
    const glm::vec3& position, const glm::vec2& size, const glm::vec2& pivotNorm,
    f32 angle, const glm::vec2& texSize, const glm::vec4& border,
    const glm::vec2& uvOffset, const glm::vec2& uvScale,
    const glm::vec4& color, const BatchDrawKey& key
) {
    f32 L = border.x;
    f32 R = border.y;
    f32 T = border.z;
    f32 B = border.w;
    if (size.x == 0.0f || size.y == 0.0f) return;
    if (uvScale.x < 0.0f) std::swap(L, R);
    if (uvScale.y < 0.0f) std::swap(T, B);

    // Fit destination borders when the box is smaller than their sum, by ONE
    // factor for both axes — the rule CSS applies to border radii. Fitting each
    // axis on its own squeezes a short panel's corners into ellipses: a 20px
    // round corner on a 30px-tall box became 20x15. Source UV borders still
    // sample the original texture region.
    const f32 directionX = std::copysign(1.0f, size.x);
    const f32 directionY = std::copysign(1.0f, size.y);
    const f32 fitX = L + R > 0.0f ? std::abs(size.x) / (L + R) : 1.0f;
    const f32 fitY = T + B > 0.0f ? std::abs(size.y) / (T + B) : 1.0f;
    const f32 fit = std::min(1.0f, std::min(fitX, fitY));
    const f32 sx = directionX * fit;
    const f32 sy = directionY * fit;

    f32 baseX = position.x - size.x * pivotNorm.x;
    f32 baseY = position.y - size.y * pivotNorm.y;

    f32 x[4] = { baseX, baseX + L * sx, baseX + size.x - R * sx, baseX + size.x };
    f32 y[4] = { baseY, baseY + B * sy, baseY + size.y - T * sy, baseY + size.y };

    f32 u[4], v[4];
    if (texSize.x > 0.0f && texSize.y > 0.0f) {
        const f32 uvDirectionX = std::copysign(1.0f, uvScale.x);
        const f32 uvDirectionY = std::copysign(1.0f, uvScale.y);
        u[0] = uvOffset.x;
        u[1] = uvOffset.x + uvDirectionX * L / texSize.x;
        u[2] = uvOffset.x + uvScale.x - uvDirectionX * R / texSize.x;
        u[3] = uvOffset.x + uvScale.x;
        v[0] = uvOffset.y;
        v[1] = uvOffset.y + uvDirectionY * B / texSize.y;
        v[2] = uvOffset.y + uvScale.y - uvDirectionY * T / texSize.y;
        v[3] = uvOffset.y + uvScale.y;
    } else {
        u[0] = uvOffset.x;
        u[1] = uvOffset.x;
        u[2] = uvOffset.x + uvScale.x;
        u[3] = uvOffset.x + uvScale.x;
        v[0] = uvOffset.y;
        v[1] = uvOffset.y;
        v[2] = uvOffset.y + uvScale.y;
        v[3] = uvOffset.y + uvScale.y;
    }

    f32 cosA = std::cos(angle);
    f32 sinA = std::sin(angle);
    const u32 pc = packColor(color);

    for (i32 row = 0; row < 3; ++row) {
        for (i32 col = 0; col < 3; ++col) {
            f32 pw = x[col + 1] - x[col];
            f32 ph = y[row + 1] - y[row];
            if (pw * directionX <= 0.0f || ph * directionY <= 0.0f) continue;

            BatchVertex verts[4];
            verts[0] = { rotatePoint(position, x[col],     y[row],     cosA, sinA), pc, {u[col],     v[row]}     };
            verts[1] = { rotatePoint(position, x[col + 1], y[row],     cosA, sinA), pc, {u[col + 1], v[row]}     };
            verts[2] = { rotatePoint(position, x[col + 1], y[row + 1], cosA, sinA), pc, {u[col + 1], v[row + 1]} };
            verts[3] = { rotatePoint(position, x[col],     y[row + 1], cosA, sinA), pc, {u[col],     v[row + 1]} };

            appendQuad(buffers, draw_list, clips, verts, key);
        }
    }
}

void BatchPlugin::emitRadialFill(
    TransientBufferPool& buffers, DrawList& draw_list, const ClipState& clips,
    const glm::vec3& center, const glm::vec2& size, f32 angle,
    f32 startAngle, f32 sweep,
    const glm::vec2& uvOffset, const glm::vec2& uvScale,
    const glm::vec4& color, const BatchDrawKey& key
) {
    constexpr f32 TWO_PI = 6.2831853071795864f;
    sweep = std::clamp(sweep, 0.0f, TWO_PI);
    const glm::vec2 absSize = glm::abs(size);
    const glm::vec2 direction{size.x < 0 ? -1.0f : 1.0f, size.y < 0 ? -1.0f : 1.0f};
    f32 hx = absSize.x * 0.5f, hy = absSize.y * 0.5f;
    if (sweep <= 0.0001f || hx <= 0.0f || hy <= 0.0f) return;

    // Sample angles are the two endpoints plus any box corner the sweep crosses,
    // measured as a clockwise distance from startAngle. Because the box edge
    // between two corners is straight, a fan vertex at each corner reproduces the
    // rectangle boundary exactly — no faceting.
    f32 deltas[6];
    u32 n = 0;
    deltas[n++] = 0.0f;
    const f32 cornerAngle[4] = {
        std::atan2(hy, hx), std::atan2(hy, -hx),
        std::atan2(-hy, -hx), std::atan2(-hy, hx),
    };
    for (u32 k = 0; k < 4; ++k) {
        f32 d = startAngle - cornerAngle[k];
        d -= TWO_PI * std::floor(d / TWO_PI);  // wrap into [0, TWO_PI)
        if (d > 0.0001f && d < sweep - 0.0001f) deltas[n++] = d;
    }
    deltas[n++] = sweep;
    for (u32 i = 1; i < n; ++i) {  // insertion sort (n <= 6)
        f32 v = deltas[i];
        i32 j = static_cast<i32>(i) - 1;
        while (j >= 0 && deltas[j] > v) { deltas[j + 1] = deltas[j]; --j; }
        deltas[j + 1] = v;
    }

    const f32 cosR = std::cos(angle), sinR = std::sin(angle);
    const u32 pc = packColor(color);

    BatchVertex verts[7];
    verts[0] = { center, pc, uvOffset + glm::vec2(0.5f, 0.5f) * uvScale };  // fan hub = box center
    for (u32 i = 0; i < n; ++i) {
        f32 a = startAngle - deltas[i];
        f32 ca = std::cos(a), sa = std::sin(a);
        f32 aca = std::abs(ca), asa = std::abs(sa);
        // Ray from center at angle a exits the centered box at the nearer axis wall.
        f32 t = std::min(aca > 1e-6f ? hx / aca : 1e30f,
                         asa > 1e-6f ? hy / asa : 1e30f);
        glm::vec2 p{ t * ca, t * sa };  // box-local, centered
        verts[i + 1] = {
            rotatePoint(center, center.x + p.x * direction.x, center.y + p.y * direction.y, cosR, sinR),
            pc,
            uvOffset + glm::vec2(p.x / absSize.x + 0.5f, p.y / absSize.y + 0.5f) * uvScale,
        };
    }

    u32 indices[15];
    u32 ic = 0;
    for (u32 i = 1; i + 1 <= n; ++i) {  // fan triangles (hub, i, i+1)
        indices[ic++] = 0;
        indices[ic++] = i;
        indices[ic++] = i + 1;
    }
    if (ic == 0) return;
    appendIndexedBatch(buffers, draw_list, clips, verts, n + 1, indices, ic, key);
}

}  // namespace esengine