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.

11.0 KB
Raw Blame
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
/**
 * @file    RenderContext.hpp
 * @brief   Rendering context containing all renderer state
 * @details Replaces global renderer state with an injectable context object
 *          that owns shader and geometry resources for basic 2D rendering.
 *
 * @author  ESEngine Team
 * @date    2026
 *
 * @copyright Copyright (c) 2026 ESEngine Team
 *            Licensed under the Apache License, Version 2.0.
 */
#pragma once

// =============================================================================
// Includes
// =============================================================================

// Project includes
#include "../../core/Types.hpp"
#include "../rhi/Buffer.hpp"
#include "../rhi/GfxEnums.hpp"
#include "../store/LightStore.hpp"
#include "../store/ProbeStore.hpp"
#include "../store/ReflectionStore.hpp"
#include "../rhi/PerDrawBlocks.hpp"
#include "../store/MaterialStore.hpp"
#include "../rhi/Shader.hpp"

// Third-party
#include <glm/glm.hpp>

namespace esengine {

// =============================================================================
// RenderContext Class
// =============================================================================

/**
 * @brief Rendering context containing shared renderer state
 *
 * @details Owns the resources and state needed for basic 2D rendering,
 *          including the quad VAO, color shader, and view-projection matrix.
 *          Replaces global static state with dependency injection.
 *
 * @code
 * RenderContext context;
 * context.init();
 *
 * Renderer renderer(context);
 * renderer.beginFrame();
 * renderer.drawQuad({100, 100}, {50, 50}, {1, 0, 0, 1});
 * renderer.endFrame();
 *
 * context.shutdown();
 * @endcode
 */
class GfxDevice;

class RenderContext {
public:
    explicit RenderContext(GfxDevice& device);
    RenderContext() = delete;
    ~RenderContext();

    // Non-copyable
    RenderContext(const RenderContext&) = delete;
    RenderContext& operator=(const RenderContext&) = delete;

    // =========================================================================
    // Lifecycle
    // =========================================================================

    /**
     * @brief Initializes rendering resources
     * @details Creates the quad VAO, shaders, and default textures.
     */
    void init();

    /**
     * @brief Releases all rendering resources
     */
    void shutdown();

    /**
     * @brief Builds again what this context made from code alone and the device lost: call once the device is back.
     */
    void restoreBuiltinContent();

    /**
     * @brief Checks if the context is initialized
     * @return True if init() has been called successfully
     */
    bool isInitialized() const { return initialized_; }

    // =========================================================================
    // Program readiness
    // =========================================================================

    /**
     * @brief Which generation of renderer PROGRAM readiness is current.
     * @details A record stamped with an older epoch names programs that may no
     *          longer exist, so it is re-derived rather than trusted. Distinct
     *          from the device generation, which says which device the GPU work
     *          happened on rather than whether readiness survived.
     */
    u64 programEpoch() const { return program_epoch_; }

    /**
     * @brief Declares that programs which WERE ready have gone cold.
     *
     * @details Renderer-wide, not stock-only: ANY operation that can make a
     *          previously-ready program requirement cold owes this call — a
     *          cache emptied after a device rebuild, a pipeline flush, a shader
     *          hot reload. Skipping it leaves a stamp vouching for nothing.
     */
    void advanceProgramEpoch() { ++program_epoch_; }

    // =========================================================================
    // State Access
    // =========================================================================

    /**
     * @brief Gets the current view-projection matrix
     * @return Reference to the matrix
     */
    glm::mat4& viewProjection() { return viewProjection_; }

    /**
     * @brief Gets the current view-projection matrix (const)
     * @return Const reference to the matrix
     */
    const glm::mat4& viewProjection() const { return viewProjection_; }

    // =========================================================================
    // Internal Resources
    // =========================================================================

    /**
     * @brief Gets the white texture handle's raw value (for untextured quads)
     */
    u32 getWhiteTextureId() const { return static_cast<u32>(whiteTexture_); }

    /// The white 1x1 as a typed handle — what a lost texture is parked on until
    /// its content is re-uploaded.
    TextureHandle getWhiteTexture() const { return whiteTexture_; }


    /**
     * @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 The same, with the picture shifted by @p jitterNdc (a fraction of the
     *        clip square) — what temporal anti-aliasing samples a different
     *        sub-pixel position with each frame.
     * @details Only the UPLOADED matrix moves. The engine's own copy, which culling
     *          and the camera position are read from, is the unshifted one.
     */
    void updateCameraConstants(const glm::mat4& viewProjection, const glm::vec2& jitterNdc);

    /**
     * @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 Frame constants for @p viewProjection in a buffer the CALLER owns, bound.
     * @details For a pass that draws several views. A buffer write is a queue
     *          operation and does not land between draws already recorded into an
     *          open pass, so views sharing one UBO all read the last write. One
     *          buffer each makes the BINDING, an encoder command, what varies.
     */
    void useFrameConstants(BufferHandle ubo, const glm::mat4& viewProjection);

    /** @brief The buffer the camera's FrameConstants live in, for a compute pass that reads them (it is bound at group 0). */
    BufferHandle frameUbo() const { return frameUbo_; }

    /** @brief Bytes a buffer passed to useFrameConstants must hold. */
    static u32 frameConstantsSize();

    /** @brief Uploads the frame clock + canvas size into the injected TimeConstants UBO. */
    void setFrameTime(f32 elapsedSec, u32 viewportW, u32 viewportH);

    /**
     * @brief The editor view's exposure, in stops, carried to the output blit in
     *        u_time.z. VIEW state: zero (the default, and every packaged build) is
     *        exp2(0) = 1, an exact no-op.
     */
    void setViewExposure(f32 ev) { viewExposure_ = ev; }
    f32 viewExposure() const { return viewExposure_; }

    /**
     * @brief The engine-side material registry (handle -> resolved render state).
     * @details Written by the SDK material binding (defineMaterial) and read by the render
     *          collect path to resolve a component's material handle into shader + pipeline
     *          state. Lives here so both sides reach it without a global lookup.
     */
    MaterialStore& materials() { return materials_; }
    const MaterialStore& materials() const { return materials_; }

    /**
     * @brief The engine-side per-frame 2D light registry (binding 2 LightConstants UBO).
     * @details Filled by the render collect path from the scene's Light components and uploaded
     *          once per frame; Lit material shaders read it. Lives here next to materials() so
     *          the render path reaches one store / one UBO without a global lookup.
     */
    LightStore& lights() { return lights_; }
    const LightStore& lights() const { return lights_; }

    /** @brief The frame's probe volumes. Gathered beside the lights, because it
     *         answers the same question at the points a light cannot be asked. */
    ProbeStore& probes() { return probes_; }
    const ProbeStore& probes() const { return probes_; }

    /** @brief The frame's reflection probes — the same question about the half of
     *         the environment a surface MIRRORS rather than scatters. */
    ReflectionStore& reflections() { return reflections_; }
    const ReflectionStore& reflections() const { return reflections_; }

private:
    void initDefaultTextures();
    TextureHandle make1x1Texture(u32 rgba, u32 layers = 1);
    TextureHandle makeRipplesTexture();
    void initFrameUbo();

    void uploadFrameConstants(const glm::mat4& upload, const glm::mat4& engine);

    glm::mat4 viewProjection_{1.0f};
    u64 program_epoch_ = 0;

    TextureHandle whiteTexture_ = TextureHandle::Invalid;
    /// Layers (two: one layer is a plain 2D texture) of white, black and a flat normal: what an unset `textureArray` param binds.
    TextureHandle whiteArrayTexture_ = TextureHandle::Invalid;
    TextureHandle blackArrayTexture_ = TextureHandle::Invalid;
    TextureHandle flatNormalArrayTexture_ = TextureHandle::Invalid;
    TextureHandle blackTexture_ = TextureHandle::Invalid;
    TextureHandle flatNormalTexture_ = TextureHandle::Invalid;
    TextureHandle ripplesTexture_ = TextureHandle::Invalid;
    BufferHandle frameUbo_ = BufferHandle::Invalid;
    BufferHandle timeUbo_ = BufferHandle::Invalid;
    BufferHandle drawParamsFallback_ = BufferHandle::Invalid;
    /// A block each per skinned draw, per morphed one, per draw standing in a
    /// volume, and per draw reading the record texture. One buffer EACH and not
    /// one shared: see PerDrawBlocks.
    PerDrawBlocks skinBlocks_;
    PerDrawBlocks morphBlocks_;
    PerDrawBlocks probeBlocks_;
    PerDrawBlocks instanceBlocks_;
    PerDrawBlocks planarBlocks_;

public:
    /** @brief The blocks the draw loop rewrites before each draw. */
    PerDrawBlockSet perDrawBlocks() {
        return {&skinBlocks_, &morphBlocks_, &probeBlocks_, &instanceBlocks_, &planarBlocks_};
    }
    /** @brief Hand every one of them back at the top of a frame. */
    void beginPerDrawBlocks() {
        skinBlocks_.beginFrame();
        morphBlocks_.beginFrame();
        probeBlocks_.beginFrame();
        instanceBlocks_.beginFrame();
        planarBlocks_.beginFrame();
    }

private:
    f32 lastElapsed_ = 0.0f;
    f32 viewExposure_ = 0.0f;
    MaterialStore materials_;
    LightStore lights_;
    ProbeStore probes_;
    ReflectionStore reflections_;

    GfxDevice& device_;
    bool initialized_ = false;
};

}  // namespace esengine