Skip to content

Commit

Permalink
Work in progress
Browse files Browse the repository at this point in the history
  • Loading branch information
skhaz committed Dec 15, 2024
1 parent 541f6a9 commit 3ccd438
Show file tree
Hide file tree
Showing 23 changed files with 107 additions and 49 deletions.
1 change: 0 additions & 1 deletion conanfile.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@ class MeuProjetoConan(ConanFile):

def requirements(self):
self.requires("chipmunk2d/7.0.3")
self.requires("fmt/11.0.2")
self.requires("libspng/0.7.4")
self.requires("nlohmann_json/3.11.3")
self.requires("ogg/1.3.5")
Expand Down
8 changes: 6 additions & 2 deletions src/color.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -11,11 +11,15 @@ color::color(const SDL_Color &scolor) noexcept
color::color(const std::string &hex)
: _r(0), _g(0), _b(0), _a(255) {
if (hex.length() != 7 && hex.length() != 9) [[unlikely]] {
throw std::invalid_argument(fmt::format("Invalid hex code format: '{}'. Use #RRGGBB or #RRGGBBAA.", hex));
std::ostringstream oss;
oss << "Invalid hex code format: '" << hex << "'. Use #RRGGBB or #RRGGBBAA.";
throw std::invalid_argument(oss.str());
}

if (hex[0] != '#') [[unlikely]] {
throw std::invalid_argument(fmt::format("Hex code '{}' must start with '#'.", hex));
std::ostringstream oss;
oss << "Hex code '" << hex << "' must start with '#'.";
throw std::invalid_argument(oss.str());
}

_r = static_cast<uint8_t>(std::stoi(hex.substr(1, 2), nullptr, 16));
Expand Down
1 change: 1 addition & 0 deletions src/common.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,7 @@
#include <random>
#include <ranges>
#include <sstream>
#include <stdexcept>
#include <string>
#include <string_view>
#include <unordered_map>
Expand Down
4 changes: 0 additions & 4 deletions src/engine.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -134,10 +134,6 @@ void engine::prefetch(const std::vector<std::string> &filenames) noexcept {
_resourcemanager->prefetch(filenames);
}

void engine::set_scene(const std::string_view name) noexcept {
_scenemanager->set(name);
}

#ifdef EMSCRIPTEN
template <class T>
inline void run(void *arg) noexcept {
Expand Down
1 change: 0 additions & 1 deletion src/engine.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,6 @@ class engine : public input::eventreceiver {
bool is_keydown(const input::keyevent &event) const noexcept;
void prefetch(const std::vector<std::string> &filenames) noexcept;
void run() noexcept;
void set_scene(const std::string_view name) noexcept;
void _loop() noexcept;

protected:
Expand Down
2 changes: 1 addition & 1 deletion src/entity.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ entity::entity(entityprops &&props) noexcept
: _props(std::move(props)) {}

entity::~entity() noexcept {
fmt::println("entity of type '{}' destroyed", kind());
std::cout << "entity of type '" << kind() << "' destroyed" << std::endl;
}

std::shared_ptr<entity> entity::create(entityprops &&props) {
Expand Down
4 changes: 2 additions & 2 deletions src/entitymanager.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ entitymanager::entitymanager(std::shared_ptr<world> world, std::shared_ptr<resou
_resourcemanager(std::move(resourcemanager)) {}

std::shared_ptr<entity> entitymanager::spawn(const std::string &kind) {
const auto buffer = storage::io::read(fmt::format("entities/{}.json", kind));
const auto buffer = storage::io::read((std::ostringstream() << "entities/" << kind << ".json").str());
const auto j = json::parse(buffer);

auto spritesheet = j.contains("spritesheet")
Expand Down Expand Up @@ -93,7 +93,7 @@ std::shared_ptr<entity> entitymanager::spawn(const std::string &kind) {
};

auto e = entity::create(std::move(props));
fmt::println("[entitymanager] spawn {} kind {}", e->id(), kind);
std::cout << "[entitymanager] spawn " << e->id() << " kind " << kind << std::endl;
_entities.emplace_back(e);
return e;
}
Expand Down
4 changes: 3 additions & 1 deletion src/filesystem.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@ using namespace storage;

void filesystem::mount(std::string_view filename, std::string_view mountpoint) noexcept(false) {
if (PHYSFS_mount(filename.data(), mountpoint.data(), true) == 0) [[unlikely]] {
throw std::runtime_error(fmt::format("[PHYSFS_mount] failed to mount {} to {}. reason: {}", filename, mountpoint, PHYSFS_getErrorByCode(PHYSFS_getLastErrorCode())));
std::ostringstream oss;
oss << "[PHYSFS_mount] failed to mount " << filename << " to " << mountpoint << ". reason: " << PHYSFS_getErrorByCode(PHYSFS_getLastErrorCode());
throw std::runtime_error(oss.str());
}
}
12 changes: 8 additions & 4 deletions src/fontfactory.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -12,9 +12,9 @@ std::shared_ptr<font> fontfactory::get(const std::string &family) {
return it->second;
}

fmt::println("[fontfactory] cache miss {}", family);
std::cout << "[fontfactory] cache miss " << family << std::endl;

const auto &buffer = storage::io::read(fmt::format("fonts/{}.json", family));
const auto &buffer = storage::io::read("fonts/" + family + ".json");
const auto &j = json::parse(buffer);
const auto &alphabet = j["alphabet"].get<std::string>();
const auto spacing = j["spacing"].get<int16_t>();
Expand All @@ -37,7 +37,9 @@ std::shared_ptr<font> fontfactory::get(const std::string &family) {
};

if (!surface) [[unlikely]] {
throw std::runtime_error(fmt::format("[SDL_CreateRGBSurfaceWithFormatFrom] Error: {}", SDL_GetError()));
std::ostringstream oss;
oss << "[SDL_CreateRGBSurfaceWithFormatFrom] Error: " << SDL_GetError();
throw std::runtime_error(oss.str());
}

const auto pixels = static_cast<uint32_t *>(surface->pixels);
Expand All @@ -52,7 +54,9 @@ std::shared_ptr<font> fontfactory::get(const std::string &family) {
}

if (x >= size.width()) [[unlikely]] {
throw std::runtime_error(fmt::format("Error: Missing glyph for '{}'", letter));
std::ostringstream oss;
oss << "Error: Missing glyph for '" << letter << "'";
throw std::runtime_error(oss.str());
}

width = 0;
Expand Down
2 changes: 1 addition & 1 deletion src/framerate.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ void framerate::loop(float_t delta) noexcept {
_start = now;

if (_elapsed >= 1000) {
fmt::println("{:.1f}", (_frames / (_elapsed / 1000.0f)));
std::cout << std::fixed << std::setprecision(1) << (_frames / (_elapsed / 1000.0f)) << std::endl;
_elapsed = 0;
_frames = 0;
}
Expand Down
20 changes: 16 additions & 4 deletions src/helpers.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -4,23 +4,35 @@ std::pair<std::vector<uint8_t>, geometry::size> _load_png(std::string_view filen
auto ctx = std::unique_ptr<spng_ctx, decltype(&spng_ctx_free)>(spng_ctx_new(0), spng_ctx_free);

if (const auto error = spng_set_png_buffer(ctx.get(), buffer.data(), buffer.size()); error != SPNG_OK) [[unlikely]] {
throw std::runtime_error(fmt::format("[spng_set_png_buffer] error while parsing image: {}, error: {}", filename, spng_strerror(error)));
std::ostringstream oss;
oss << "[spng_set_png_buffer] error while parsing image: " << filename
<< ", error: " << spng_strerror(error);
throw std::runtime_error(oss.str());
}

spng_ihdr ihdr{};
if (const auto error = spng_get_ihdr(ctx.get(), &ihdr); error != SPNG_OK) [[unlikely]] {
throw std::runtime_error(fmt::format("[spng_get_ihdr] error while getting image information: {}, error: {}", filename, spng_strerror(error)));
std::ostringstream oss;
oss << "[spng_get_ihdr] error while getting image information: " << filename
<< ", error: " << spng_strerror(error);
throw std::runtime_error(oss.str());
}

const int format{SPNG_FMT_RGBA8};
size_t length{0};
if (const auto error = spng_decoded_image_size(ctx.get(), format, &length); error != SPNG_OK) [[unlikely]] {
throw std::runtime_error(fmt::format("[spng_decoded_image_size] error while getting image size: {}, error: {}", filename, spng_strerror(error)));
std::ostringstream oss;
oss << "[spng_decoded_image_size] error while getting image size: " << filename
<< ", error: " << spng_strerror(error);
throw std::runtime_error(oss.str());
}

std::vector<uint8_t> output(length);
if (const auto error = spng_decode_image(ctx.get(), output.data(), length, format, SPNG_DECODE_TRNS); error != SPNG_OK) [[unlikely]] {
throw std::runtime_error(fmt::format("[spng_decode_image] error while decoding image: {}, error: {}", filename, spng_strerror(error)));
std::ostringstream oss;
oss << "[spng_decode_image] error while decoding image: " << filename
<< ", error: " << spng_strerror(error);
throw std::runtime_error(oss.str());
}

const auto size = geometry::size{static_cast<int32_t>(ihdr.width), static_cast<int32_t>(ihdr.height)};
Expand Down
16 changes: 13 additions & 3 deletions src/io.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -5,18 +5,28 @@ using namespace storage;
std::vector<uint8_t> io::read(std::string_view filename) noexcept(false) {
std::unique_ptr<PHYSFS_File, decltype(&PHYSFS_close)> ptr(PHYSFS_openRead(filename.data()), PHYSFS_close);
if (!ptr) [[unlikely]] {
throw std::runtime_error(fmt::format("[PHYSFS_openRead] error while opening file: {}, error: {}", filename, PHYSFS_getErrorByCode(PHYSFS_getLastErrorCode())));
std::ostringstream oss;
oss << "[PHYSFS_openRead] error while opening file: " << filename
<< ", error: " << PHYSFS_getErrorByCode(PHYSFS_getLastErrorCode());
throw std::runtime_error(oss.str());
}

PHYSFS_sint64 length = PHYSFS_fileLength(ptr.get());
if (length <= 0) [[unlikely]] {
throw std::runtime_error(fmt::format("[PHYSFS_fileLength] invalid file length, file: {}, error: {}", filename, PHYSFS_getErrorByCode(PHYSFS_getLastErrorCode())));
std::ostringstream oss;
oss << "[PHYSFS_fileLength] invalid file length, file: " << filename
<< ", error: " << PHYSFS_getErrorByCode(PHYSFS_getLastErrorCode());
throw std::runtime_error(oss.str());
}

std::vector<uint8_t> buffer(length);
auto bytesRead = PHYSFS_readBytes(ptr.get(), buffer.data(), length);
if (bytesRead != length) [[unlikely]] {
throw std::runtime_error(fmt::format("[PHYSFS_readBytes] error reading file: {}, expected {} bytes but read {}, error: {}", filename, length, bytesRead, PHYSFS_getErrorByCode(PHYSFS_getLastErrorCode())));
std::ostringstream oss;
oss << "[PHYSFS_readBytes] error reading file: " << filename
<< ", expected " << length << " bytes but read " << bytesRead
<< ", error: " << PHYSFS_getErrorByCode(PHYSFS_getLastErrorCode());
throw std::runtime_error(oss.str());
}

return buffer;
Expand Down
15 changes: 12 additions & 3 deletions src/pixmap.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -18,14 +18,20 @@ pixmap::pixmap(const std::shared_ptr<renderer> &renderer, std::string_view filen
SDL_FreeSurface
};
if (!surface) [[unlikely]] {
throw std::runtime_error(fmt::format("[SDL_CreateRGBSurfaceWithFormat] error while creating surface, file: {}, error: {}", filename, SDL_GetError()));
std::ostringstream oss;
oss << "[SDL_CreateRGBSurfaceWithFormat] error while creating surface, file: "
<< filename << ", error: " << SDL_GetError();
throw std::runtime_error(oss.str());
}

std::memcpy(surface->pixels, output.data(), output.size());

_texture = texture_ptr(SDL_CreateTextureFromSurface(*renderer, surface.get()), SDL_Deleter());
if (!_texture) [[unlikely]] {
throw std::runtime_error(fmt::format("[SDL_CreateTextureFromSurface] error while creating texture from surface, file: {}", filename));
std::ostringstream oss;
oss << "[SDL_CreateTextureFromSurface] error while creating texture from surface, file: "
<< filename;
throw std::runtime_error(oss.str());
}
}

Expand All @@ -34,7 +40,10 @@ pixmap::pixmap(const std::shared_ptr<renderer> &renderer, std::unique_ptr<SDL_Su

_texture = texture_ptr(SDL_CreateTextureFromSurface(*renderer, surface.get()), SDL_Deleter());
if (!_texture) [[unlikely]] {
throw std::runtime_error(fmt::format("[SDL_CreateTextureFromSurface] error while creating texture, SDL Error: {}", SDL_GetError()));
std::ostringstream oss;
oss << "[SDL_CreateTextureFromSurface] error while creating texture, SDL Error: "
<< SDL_GetError();
throw std::runtime_error(oss.str());
}
}

Expand Down
6 changes: 3 additions & 3 deletions src/pixmappool.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ const std::shared_ptr<pixmap> pixmappool::get(const std::string &filename) {
return it->second;
}

fmt::println("[pixmappool] cache miss {}", filename);
std::cout << "[pixmappool] cache miss " << filename << std::endl;

assert(_renderer);

Expand All @@ -21,10 +21,10 @@ const std::shared_ptr<pixmap> pixmappool::get(const std::string &filename) {
}

void pixmappool::flush() noexcept {
fmt::println("[pixmappool] actual size {}", _pool.size());
std::cout << "[pixmappool] actual size " << _pool.size() << std::endl;

const auto count = std::erase_if(_pool, [](const auto &pair) { return pair.second.use_count() == MINIMAL_USE_COUNT; });
fmt::println("[pixmappool] {} objects have been flushed", count);
std::cout << "[pixmappool] " << count << " objects have been flushed" << std::endl;
}

void pixmappool::update(float_t delta) noexcept {
Expand Down
4 changes: 3 additions & 1 deletion src/renderer.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,9 @@ using namespace graphics;
renderer::renderer(SDL_Window *window)
: _renderer(SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC), SDL_Deleter()) {
if (!_renderer) [[unlikely]] {
throw std::runtime_error(fmt::format("[SDL_CreateRenderer] failed to create renderer: {}", SDL_GetError()));
std::ostringstream oss;
oss << "[SDL_CreateRenderer] failed to create renderer: " << SDL_GetError();
throw std::runtime_error(oss.str());
}
}

Expand Down
4 changes: 2 additions & 2 deletions src/scenemanager.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,8 @@ using json = nlohmann::json;
scenemanager::scenemanager(std::shared_ptr<graphics::pixmappool> pixmappool) noexcept
: _pixmappool(std::move(pixmappool)) {}

void scenemanager::set(const std::string_view name) noexcept {
const auto buffer = storage::io::read(fmt::format("scenes/{}.json", name));
void scenemanager::set(const std::string &name) noexcept {
const auto buffer = storage::io::read("scenes/" + name + ".json");
const auto j = json::parse(buffer);
_background = _pixmappool->get(j["background"].get<std::string>());
_size = {j.at("width").get<int32_t>(), j.at("height").get<int32_t>()};
Expand Down
2 changes: 1 addition & 1 deletion src/scenemanager.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ class scenemanager {
public:
scenemanager(std::shared_ptr<graphics::pixmappool> pixmappool) noexcept;

void set(const std::string_view name) noexcept;
void set(const std::string &name) noexcept;
void update(float_t delta) noexcept;
void draw() const noexcept;

Expand Down
10 changes: 6 additions & 4 deletions src/scriptengine.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -25,8 +25,8 @@ using namespace math;
using namespace storage;
using namespace network;

sol::table require(sol::state &lua, std::string_view module) {
const auto data = io::read(fmt::format("scripts/{}.lua", module));
sol::table require(sol::state &lua, const std::string &module) {
const auto data = io::read("scripts/" + module + ".lua");
const auto script = std::string(data.begin(), data.end());
const auto result = lua.script(script);

Expand Down Expand Up @@ -116,7 +116,7 @@ void scriptengine::run() {

lua.open_libraries();

lua["require"] = [&lua](std::string_view module) {
lua["require"] = [&lua](const std::string &module) {
return require(lua, module);
};

Expand Down Expand Up @@ -179,7 +179,9 @@ void scriptengine::run() {
} else if (value.is<float>()) {
e.set_kv(key, value.as<float>());
} else {
throw std::runtime_error(fmt::format("Unsupported type for key: {}", key));
std::ostringstream oss;
oss << "Unsupported type for key: " << key;
throw std::runtime_error(oss.str());
}
}
};
Expand Down
18 changes: 13 additions & 5 deletions src/socket.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,7 @@ using json = nlohmann::json;
socket::socket() noexcept {
_queue.reserve(8);

const auto url = fmt::format("http://{}:3000/socket", emscripten_run_script_string("window.location.hostname"));

const auto url = "http://" + std::string(emscripten_run_script_string("window.location.hostname")) + ":3000/socket";
EmscriptenWebSocketCreateAttributes attrs = {
url.c_str(),
nullptr,
Expand Down Expand Up @@ -116,16 +115,25 @@ socket::~socket() noexcept {
}

void socket::emit(const std::string &topic, const std::string &data) noexcept {
send(fmt::format(R"({{"event": {{"topic": "{}", "data": {}}}}})", topic, data));
std::ostringstream oss;
oss << R"({"event": {"topic": ")" << topic << R"(", "data": )" << data << R"(}})";
send(oss.str());
}

void socket::on(const std::string &topic, std::function<void(const std::string &)> callback) noexcept {
send(fmt::format(R"({{"subscribe": "{}"}})", topic));
std::ostringstream oss;
oss << R"({"subscribe": ")" << topic << R"("})";
send(oss.str());
_callbacks[topic].push_back(std::move(callback));
}

void socket::rpc(const std::string &method, const std::string &arguments, std::function<void(const std::string &)> callback) noexcept {
send(fmt::format(R"({{"rpc": {{"request": {{"id": {}, "method": "{}", "arguments": {}}}}}}})", ++counter, method, arguments));
std::ostringstream oss;
oss << R"({"rpc": {"request": {"id": )" << ++counter
<< R"(, "method": ")" << method
<< R"(", "arguments": )" << arguments << R"(}}})";
send(oss.str());

_callbacks[std::to_string(counter)].push_back(std::move(callback));
}

Expand Down
10 changes: 8 additions & 2 deletions src/soundfx.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,10 @@ soundfx::soundfx(std::shared_ptr<audiodevice> audiodevice, std::string_view file
: _audiodevice(std::move(audiodevice)) {
std::unique_ptr<PHYSFS_File, decltype(&PHYSFS_close)> fp{PHYSFS_openRead(filename.data()), PHYSFS_close};
if (!fp) [[unlikely]] {
throw std::runtime_error(fmt::format("[PHYSFS_openRead] error while opening file: {}, error: {}", filename, PHYSFS_getErrorByCode(PHYSFS_getLastErrorCode())));
std::ostringstream oss;
oss << "[PHYSFS_openRead] error while opening file: " << filename
<< ", error: " << PHYSFS_getErrorByCode(PHYSFS_getLastErrorCode());
throw std::runtime_error(oss.str());
}

std::unique_ptr<OggVorbis_File, decltype(&ov_clear)> vf{new OggVorbis_File, ov_clear};
Expand Down Expand Up @@ -106,7 +109,10 @@ soundfx::soundfx(std::shared_ptr<audiodevice> audiodevice, std::string_view file
do {
offset = ov_read(vf.get(), reinterpret_cast<char *>(array.data()), length, bigendian, 2, 1, nullptr);
if (offset < 0) [[unlikely]] {
throw std::runtime_error(fmt::format("[ov_read] error while reading file: {}, error: {}", filename, ov_strerror(offset)));
std::ostringstream oss;
oss << "[ov_read] error while reading file: " << filename
<< ", error: " << ov_strerror(offset);
throw std::runtime_error(oss.str());
}
data.insert(data.end(), array.begin(), std::ranges::next(array.begin(), offset));
} while (offset > 0);
Expand Down
Loading

0 comments on commit 3ccd438

Please sign in to comment.