Extra2D/src/assets/loaders/shader_loader.cpp

107 lines
2.8 KiB
C++
Raw Normal View History

#include <assets/loaders/shader_loader.h>
#include <module/module_registry.h>
#include <platform/file_module.h>
#include <renderer/shader.h>
#include <utils/logger.h>
namespace extra2d {
namespace {
/**
* @brief FileModule
*/
FileModule *getFileModule() { return getModule<FileModule>(); }
/**
* @brief 使 FileModule
*/
bool fileExists(const std::string &path) {
FileModule *fileModule = getFileModule();
if (fileModule) {
return fileModule->exists(path);
}
return false;
}
/**
* @brief 使 FileModule RomFS
*/
std::string readFileToString(const std::string &path) {
FileModule *fileModule = getFileModule();
if (fileModule) {
return fileModule->readString(path);
}
return "";
}
} // anonymous namespace
Ptr<Shader> ShaderLoader::load(const std::string &path) {
std::string basePath = path;
std::string::size_type dotPos = basePath.rfind('.');
if (dotPos != std::string::npos) {
basePath = basePath.substr(0, dotPos);
}
std::string vertPath = basePath + ".vert";
std::string fragPath = basePath + ".frag";
if (!fileExists(vertPath)) {
vertPath = basePath + ".vs";
}
if (!fileExists(fragPath)) {
fragPath = basePath + ".fs";
}
return load(vertPath, fragPath);
}
Ptr<Shader> ShaderLoader::load(const std::string &vertPath,
const std::string &fragPath) {
// 读取顶点着色器文件
std::string vsSource = readFileToString(vertPath);
if (vsSource.empty()) {
E2D_ERROR("ShaderLoader: 读取顶点着色器失败: {}", vertPath);
return Ptr<Shader>();
}
// 读取片段着色器文件
std::string fsSource = readFileToString(fragPath);
if (fsSource.empty()) {
E2D_ERROR("ShaderLoader: 读取片段着色器失败: {}", fragPath);
return Ptr<Shader>();
}
// 从源码加载着色器
Ptr<Shader> shader = makePtr<Shader>();
if (!shader->loadFromSource(vsSource, fsSource)) {
E2D_ERROR("ShaderLoader: 编译着色器失败 {} + {}", vertPath, fragPath);
return Ptr<Shader>();
}
E2D_DEBUG("ShaderLoader: 已加载着色器 {} + {}", vertPath, fragPath);
return shader;
}
Ptr<Shader> ShaderLoader::loadFromMemory(const uint8_t *data, size_t size) {
E2D_ERROR("ShaderLoader: loadFromMemory 不支持着色器");
return Ptr<Shader>();
}
Ptr<Shader> ShaderLoader::loadFromSource(const std::string &vsSource,
const std::string &fsSource) {
Ptr<Shader> shader = makePtr<Shader>();
if (!shader->loadFromSource(vsSource, fsSource)) {
E2D_ERROR("ShaderLoader: 从源码编译着色器失败");
return Ptr<Shader>();
}
E2D_DEBUG("ShaderLoader: 已从源码编译着色器");
return shader;
}
} // namespace extra2d