light/modules/engine/src/utils/file_manager.cpp

111 lines
2.2 KiB
C++
Raw Normal View History

2025-07-05 13:28:41 +03:30
#define STB_IMAGE_IMPLEMENTATION
#include <engine/utils/file_manager.hpp>
#include <stb_image.h>
namespace Light {
2025-07-05 16:07:51 +03:30
BasicFileHandle::BasicFileHandle(
2025-07-05 13:28:41 +03:30
uint8_t *data,
uint32_t size,
const std::string &path,
const std::string &name,
const std::string &extension
)
: m_data(data)
, m_size(size)
, m_path(path)
, m_name(name)
, m_extension(extension)
2025-07-05 13:28:41 +03:30
{
}
2025-07-05 16:07:51 +03:30
void BasicFileHandle::release()
2025-07-05 13:28:41 +03:30
{
delete m_data;
m_data = nullptr;
m_size = 0ull;
2025-07-05 13:28:41 +03:30
}
2025-07-05 16:07:51 +03:30
BasicFileHandle FileManager::read_text_file(const std::string &path)
2025-07-05 13:28:41 +03:30
{
// parse path info
std::string name = path.substr(0, path.find('.') + -1);
std::string extension = path.substr(path.find('.') + 1);
// open file
std::ifstream file(path.c_str(), std::ios_base::in | std::ios_base::binary);
// check
if (!file)
{
lt_log(warn, "Failed to load text file: {}", path);
2025-07-05 13:28:41 +03:30
file.close();
return NULL;
}
// fetch file size
file.seekg(0, std::ios::end);
uint32_t size = file.tellg();
file.seekg(0, std::ios::beg);
if (!size)
lt_log(warn, "Empty text file: {}", path);
2025-07-05 13:28:41 +03:30
// read file
uint8_t *data = new uint8_t[size];
file.read(reinterpret_cast<char *>(data), size);
file.close();
2025-07-05 16:07:51 +03:30
return BasicFileHandle(data, size, path, name, extension);
2025-07-05 13:28:41 +03:30
}
2025-07-05 16:07:51 +03:30
ImageFileHandle FileManager::read_image_file(const std::string &path, int32_t desiredComponents)
2025-07-05 13:28:41 +03:30
{
// parse path info
std::string name = path.substr(0, path.find('.') + -1);
std::string extension = path.substr(path.find('.') + 1);
// load image
int32_t width = 0, height = 0, fetchedComponents = 0;
uint8_t *pixels = stbi_load(
path.c_str(),
&width,
&height,
&fetchedComponents,
desiredComponents
);
// check
if (!pixels)
lt_log(warn, "Failed to load image file: <{}>", path);
2025-07-05 13:28:41 +03:30
else if (fetchedComponents != desiredComponents)
lt_log(warn,
2025-07-05 13:28:41 +03:30
"Mismatch of fetched/desired components: <{}> ({}/{})",
name + '.' + extension,
fetchedComponents,
desiredComponents);
2025-07-05 16:07:51 +03:30
return ImageFileHandle(
2025-07-05 13:28:41 +03:30
pixels,
width * height,
path,
name,
extension,
width,
height,
fetchedComponents,
desiredComponents
);
}
2025-07-05 16:07:51 +03:30
void ImageFileHandle::release()
2025-07-05 13:28:41 +03:30
{
stbi_image_free(reinterpret_cast<void *>(m_data));
m_data = nullptr;
m_size = 0ull;
2025-07-05 13:28:41 +03:30
}
} // namespace Light