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.

12.3 KB
Raw Blame
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
/**
 * @file    Shader.hpp
 * @brief   GPU shader program abstraction
 * @details Provides a cross-platform shader abstraction for OpenGL ES/WebGL
 *          including compilation, linking, and uniform management.
 *
 * @author  ESEngine Team
 * @date    2025
 *
 * @copyright Copyright (c) 2025 ESEngine Team
 *            Licensed under the Apache License, Version 2.0.
 */
#pragma once

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

// Project includes
#include "../../core/Types.hpp"
#include "../../math/Math.hpp"
#include "../draw/DrawParams.hpp"
#include "./GfxEnums.hpp"

// Standard library
#include <initializer_list>
#include <functional>
#include <string>
#include <unordered_map>
#include <vector>

namespace esengine {

class GfxDevice;

struct AttribBinding {
    u32 index;
    const char* name;
};

/** @brief Which pipeline stage rejected a shader during compile/link. */
enum class ShaderStageFailure : u8 {
    None,
    Vertex,
    Fragment,
    Link,
};

// Forward declare Shader for the outcome struct.
class Shader;

/**
 * @brief Result returned by Shader::createEx when you need the raw driver log.
 *
 * On success `shader` is non-null and `failedStage == None`. On failure
 * `shader` is null, `failedStage` identifies which step rejected the source,
 * and `log` carries the GL info log verbatim (ready to feed into
 * ShaderParser::remapCompilerLog).
 */
struct ShaderCompileOutcome {
    Unique<Shader> shader;
    ShaderStageFailure failedStage = ShaderStageFailure::None;
    std::string log;
};

// =============================================================================
// Shader Class
// =============================================================================

/**
 * @brief GPU shader program for rendering
 *
 * @details Encapsulates an OpenGL/WebGL shader program consisting of
 *          a vertex shader and fragment shader. Provides uniform setting
 *          with location caching for performance.
 *
 * @code
 * auto shader = Shader::create(vertexSource, fragmentSource);
 * shader->bind();
 * shader->setUniform("u_projection", projectionMatrix);
 * shader->setUniform("u_color", glm::vec4(1.0f, 0.0f, 0.0f, 1.0f));
 * @endcode
 */
class Shader {
public:
    Shader() = default;
    ~Shader();

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

    // Movable
    Shader(Shader&& other) noexcept;
    Shader& operator=(Shader&& other) noexcept;

    // =========================================================================
    // Creation
    // =========================================================================

    /**
     * @brief Creates a shader from source code strings
     * @param vertexSrc Vertex shader GLSL source
     * @param fragmentSrc Fragment shader GLSL source
     * @return Unique pointer to the shader, or nullptr on failure
     */
    static Unique<Shader> create(GfxDevice& device, const std::string& vertexSrc, const std::string& fragmentSrc,
                                 GfxShaderLanguage language = GfxShaderLanguage::GLSL_ES300);

    /**
     * @brief Creates a shader with explicit attribute bindings applied before linking
     * @param vertexSrc Vertex shader GLSL source
     * @param fragmentSrc Fragment shader GLSL source
     * @param bindings Attribute location bindings
     * @return Unique pointer to the shader, or nullptr on failure
     */
    static Unique<Shader> createWithBindings(GfxDevice& device,
                                              const std::string& vertexSrc, const std::string& fragmentSrc,
                                              std::initializer_list<AttribBinding> bindings,
                                              GfxShaderLanguage language = GfxShaderLanguage::GLSL_ES300,
                                              bool deferLink = false);

    /** @brief The source language this program was compiled from. */
    GfxShaderLanguage language() const { return language_; }

    /**
     * @brief Creates a shader from file paths
     * @param vertexPath Path to vertex shader file
     * @param fragmentPath Path to fragment shader file
     * @return Unique pointer to the shader, or nullptr on failure
     */
    static Unique<Shader> createFromFile(GfxDevice& device,
                                         const std::string& vertexPath, const std::string& fragmentPath);

    /**
     * @brief Creates a shader and exposes the driver log on failure
     *
     * Same behaviour as createWithBindings but returns a ShaderCompileOutcome
     * so callers (notably ShaderLoader) can remap the GL log back to the
     * original .esshader file and line numbers.
     */
    static ShaderCompileOutcome createEx(GfxDevice& device,
                                         const std::string& vertexSrc,
                                         const std::string& fragmentSrc,
                                         std::initializer_list<AttribBinding> bindings = {},
                                         GfxShaderLanguage language = GfxShaderLanguage::GLSL_ES300,
                                         bool deferLink = false);

    /**
     * @brief Runs @p fn on this shader once it has linked: at once for one that has.
     * @details What is done to a program only after it links (a sampler pinned to its unit) is handed here, so a shader made with deferLink is not
     *          waited for just to be finished.
     */
    void whenLinked(std::function<void(Shader&)> fn);

    // =========================================================================
    // Operations
    // =========================================================================

    /** @brief Binds the shader for rendering */
    void bind() const;

    /** @brief Unbinds the shader */
    void unbind() const;

    // =========================================================================
    // Uniforms
    // =========================================================================

    /**
     * @brief Sets an integer uniform
     * @param name Uniform name in shader
     * @param value Integer value
     */
    void setUniform(const std::string& name, i32 value) const;
    void setUniform(const std::string& name, f32 value) const;
    void setUniform(const std::string& name, const glm::vec2& value) const;
    void setUniform(const std::string& name, const glm::vec3& value) const;
    void setUniform(const std::string& name, const glm::vec4& value) const;
    void setUniform(const std::string& name, const glm::mat3& value) const;
    void setUniform(const std::string& name, const glm::mat4& value) const;

    void setUniform(i32 location, i32 value) const;
    void setUniform(i32 location, f32 value) const;
    void setUniform(i32 location, const glm::vec2& value) const;
    void setUniform(i32 location, const glm::vec3& value) const;
    void setUniform(i32 location, const glm::vec4& value) const;
    void setUniform(i32 location, const glm::mat3& value) const;
    void setUniform(i32 location, const glm::mat4& value) const;

    // =========================================================================
    // Attributes
    // =========================================================================

    /**
     * @brief Gets the location of a vertex attribute
     * @param name Attribute name in shader
     * @return Location, or -1 if not found
     */
    i32 getAttribLocation(const std::string& name) const;

    i32 getUniformLocation(const std::string& name) const;

    /**
     * @brief True if the linked program declares this uniform.
     * @details Silent probe (no "not found" warning), for call sites that
     *          intentionally supply a superset of uniforms — e.g. the
     *          post-process pipeline applies a whole effect's uniform set to
     *          each of its sub-pass shaders, which each use only a subset.
     */
    bool hasUniform(const std::string& name) const;

    /** @brief Returns reflected metadata for every active uniform, populated at link time */
    const std::vector<GfxUniformInfo>& getActiveUniforms() const { ensureLinked(); return activeUniforms_; }

    // =========================================================================
    // DrawParams (per-draw parameter block)
    // =========================================================================

    /**
     * @brief Adopts the layout rewriteLooseUniforms produced for this program.
     * @details Allocates the zeroed CPU shadow, so unset members read 0 — the
     *          same value their loose-uniform ancestors read. From here on the
     *          name-based setUniform overloads write into the shadow instead of
     *          issuing loose uniform uploads; commitParams() flushes it.
     */
    void adoptDrawParams(DrawParamsLayout layout);

    /** @brief True when this program carries a DrawParams block. */
    bool hasDrawParams() const { return !drawParams_.empty(); }

    /**
     * @brief Uploads the shadow (when dirty) and binds this shader's params UBO
     *        at DRAW_PARAMS_BINDING.
     * @details Call before any draw with this shader — the binding slot is
     *          shared, so the previous committer's buffer is bound otherwise.
     *          No-op for shaders without a DrawParams block.
     */
    void commitParams();

    // =========================================================================
    // State
    // =========================================================================

    /**
     * @brief Checks if the shader compiled and linked successfully
     * @return True if the shader is usable
     */
    bool isValid() const { return program_ != ShaderHandle::Invalid; }

    /** @brief Gets the device program handle */
    ShaderHandle handle() const { return program_; }

    /** @brief Gets the program handle's raw value, for command payloads and sort keys */
    u32 getProgramId() const { return static_cast<u32>(program_); }

private:
    /**
     * @brief Compiles and links shader sources
     * @param vertexSrc Vertex shader source
     * @param fragmentSrc Fragment shader source
     * @return True on success
     */
    bool compile(const std::string& vertexSrc, const std::string& fragmentSrc,
                 const std::vector<AttribBinding>& bindings = {},
                 std::string* outLog = nullptr,
                 ShaderStageFailure* outFailedStage = nullptr,
                 GfxShaderLanguage language = GfxShaderLanguage::GLSL_ES300,
                 bool deferLink = false);

    void reflectActiveUniforms();

    /** @brief What is done to a linked program: reflect it, bind its blocks, pin its samplers, then whatever was asked for with whenLinked. */
    void finishLink();
    /** @brief Waits for the program to link if it was made with deferLink and nothing has needed it yet. */
    void ensureLinked() const;

    /** @brief Resolve + cache a uniform location; warns on miss only when asked. */
    i32 cacheUniformLocation(const std::string& name, bool warnOnMiss) const;

    /** @brief Writes a param into the shadow if `name` is a DrawParams member.
     *  @return True when consumed (caller must not fall through to a loose upload). */
    bool writeParam(const std::string& name, DrawParamType type, const void* src) const;

    GfxDevice* device_ = nullptr;  ///< Set by the create* factories; all GL goes through it.
    GfxShaderLanguage language_ = GfxShaderLanguage::GLSL_ES300;
    ShaderHandle program_ = ShaderHandle::Invalid;
    /// False from a deferLink creation until the program has linked and finishLink has run.
    mutable bool linked_ = true;
    std::vector<std::function<void(Shader&)>> afterLink_;

    /** @brief Cached uniform locations (mutable for const uniform setters) */
    mutable std::unordered_map<std::string, i32> uniformCache_;
    mutable std::unordered_map<std::string, i32> attribCache_;
    std::vector<GfxUniformInfo> activeUniforms_;

    DrawParamsLayout drawParams_;
    /// CPU shadow of the DrawParams block (mutable: the const name-based
    /// setUniform overloads write here, mirroring the mutable location cache).
    mutable std::vector<u8> paramsShadow_;
    mutable bool paramsDirty_ = false;
    BufferHandle paramsUbo_ = BufferHandle::Invalid;
};

}  // namespace esengine