Skip to content
Repos

DevPlaceApp

C++ 1.2 KB43 lines Opens in site

Directory Raw Download

#include "core/Assets.hpp"

#include <SDL3/SDL.h>

#include <cstdlib>
#include <filesystem>
#include <fstream>

namespace dp {

std::string Assets::root() {
  static const std::string cached = [] {
    namespace fs = std::filesystem;
    if (const char* env = std::getenv("DEVPLACE_ASSETS")) {
      if (fs::exists(env)) return std::string(env);
    }
    if (const char* base = SDL_GetBasePath()) {
      const fs::path p = fs::path(base) / "assets";
      if (fs::exists(p)) return p.string();
    }
#ifdef DEVPLACE_ASSET_DIR
    return std::string(DEVPLACE_ASSET_DIR);
#else
    return std::string("assets");
#endif
  }();
  return cached;
}

std::string Assets::path(const std::string& relative) { return root() + "/" + relative; }

bool Assets::readFile(const std::string& absolute, std::string& out, std::size_t maxBytes) {
  std::ifstream in(absolute, std::ios::binary | std::ios::ate);
  if (!in) return false;
  const std::streamsize size = in.tellg();
  if (size < 0 || static_cast<std::size_t>(size) > maxBytes) return false;
  out.resize(static_cast<std::size_t>(size));
  in.seekg(0);
  in.read(out.data(), size);
  return static_cast<bool>(in);
}

}  // namespace dp
22.3ms