Extra2D/include/renderer/shader.h

99 lines
2.5 KiB
C++

#pragma once
#include <renderer/rhi/rhi.h>
#include <string>
#include <types/base/types.h>
#include <types/ptr/intrusive_ptr.h>
#include <types/ptr/ref_counted.h>
#include <unordered_map>
namespace extra2d {
/**
* @brief 着色器类
*
* 基于 RHI 的着色器包装类,管理着色器资源的创建和编译
* 支持从文件或源码加载
*/
class Shader : public RefCounted {
public:
/**
* @brief 默认构造函数
*/
Shader();
/**
* @brief 析构函数
*/
~Shader() override;
/**
* @brief 从源码加载着色器
* @param vsSource 顶点着色器源码
* @param fsSource 片段着色器源码
* @return 加载是否成功
*/
bool loadFromSource(const std::string &vsSource, const std::string &fsSource);
/**
* @brief 获取 RHI 着色器句柄
* @return RHI 着色器句柄
*/
ShaderHandle getHandle() const { return handle_; }
/**
* @brief 获取 RHI 管线句柄
* @return RHI 管线句柄
*/
PipelineHandle getPipeline() const { return pipeline_; }
/**
* @brief 检查是否已加载
* @return 是否已加载
*/
bool isLoaded() const { return handle_.isValid() && pipeline_.isValid(); }
/**
* @brief 使用自定义顶点布局从源码加载着色器
* @param vsSource 顶点着色器源码
* @param fsSource 片段着色器源码
* @param vertexLayout 顶点布局
* @return 加载是否成功
*/
bool loadFromSourceWithLayout(const std::string &vsSource,
const std::string &fsSource,
const VertexLayout &vertexLayout);
/**
* @brief 设置 Uniform Block 绑定槽位
* @param name Uniform Block 名称
* @param binding 绑定槽位
*/
void setUniformBlock(const std::string &name, uint32_t binding);
/**
* @brief 获取 Uniform Block 绑定槽位
* @param name Uniform Block 名称
* @return 绑定槽位,如果未找到返回 UINT32_MAX
*/
uint32_t getUniformBlockBinding(const std::string& name) const;
private:
/**
* @brief 添加版本声明(如果不存在)
* @param source 源码
* @param isVertex 是否为顶点着色器
* @return 处理后的源码
*/
std::string addVersionIfNeeded(const std::string &source, bool isVertex);
private:
ShaderHandle handle_; // RHI 着色器句柄
PipelineHandle pipeline_; // RHI 管线句柄
// Uniform Block 绑定映射
std::unordered_map<std::string, uint32_t> uniformBlockBindings_;
};
} // namespace extra2d