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.

2.4 KB
Raw Blame
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
#pragma once

#include "../../core/Types.hpp"
#include "./Framebuffer.hpp"

#include <glm/glm.hpp>
#include <vector>

namespace esengine {

class RenderTarget {
public:
    RenderTarget() = default;
    ~RenderTarget() = default;

    RenderTarget(const RenderTarget&) = delete;
    RenderTarget& operator=(const RenderTarget&) = delete;
    RenderTarget(RenderTarget&&) = default;
    RenderTarget& operator=(RenderTarget&&) = default;

    /** @param asDrawn On a device that stores targets top-down, hand out the texture drawn into rather than a copy turned to the
     *                 bottom-up rows a camera's target is read in: for a target drawn and read by shaders that know the device's rows
     *                 (a baked surface), which a copy of the whole of it each time it is drawn would only cost. */
    void init(GfxDevice& device, u32 width, u32 height, bool depth = true, bool linearFilter = false, bool asDrawn = false);
    void shutdown();

    void bind();
    void unbind();
    void resize(u32 width, u32 height);

    TextureHandle getColorTexture() const;
    void publish();
    TextureHandle getDepthTexture() const;
    glm::uvec2 getSize() const { return { width_, height_ }; }
    u32 getWidth() const { return width_; }
    u32 getHeight() const { return height_; }

    bool isValid() const { return framebuffer_ != nullptr; }
    FramebufferHandle getFramebuffer() const;

private:
    GfxDevice* device_ = nullptr;
    Unique<Framebuffer> framebuffer_;
    Unique<Framebuffer> published_;
    u32 width_ = 0;
    u32 height_ = 0;
    bool has_depth_ = true;
    bool linear_filter_ = false;
};

class RenderTargetManager {
public:
    using Handle = u32;
    static constexpr Handle INVALID_HANDLE = 0;

    RenderTargetManager() = default;
    ~RenderTargetManager() = default;

    /** @brief Binds the device used to create render targets. Call once at setup. */
    void setDevice(GfxDevice& device) { device_ = &device; }

    Handle create(u32 width, u32 height, bool depth = true, bool linearFilter = false, bool asDrawn = false);
    RenderTarget* get(Handle handle);
    void release(Handle handle);

    bool isValid(Handle handle) const;

private:
    GfxDevice* device_ = nullptr;
    std::vector<Unique<RenderTarget>> targets_;
    std::vector<Handle> free_list_;
    Handle next_handle_ = 1;
};

}  // namespace esengine