Skip to content
Snippets Groups Projects

Compare revisions

Changes are shown as if the source revision was being merged into the target revision. Learn more about comparing revisions.

Source

Select target project
No results found

Target

Select target project
  • gamedev/fggl
  • onuralpsezer/fggl
2 results
Show changes
Showing
with 759 additions and 34 deletions
......@@ -25,8 +25,12 @@
namespace fggl::phys {
inline void build_noop(const entity::ComponentSpec & /*config*/,
entity::EntityManager & /*manager*/,
const entity::EntityID & /*entity*/) {}
entity::EntityManager &manager,
const entity::EntityID &entity,
modules::Services &/*services*/) {
manager.add<fggl::phys::RigidBody>(entity);
manager.add<fggl::phys::Dynamics>(entity);
}
class NullPhysicsEngine : public PhysicsEngine {
public:
......@@ -66,13 +70,13 @@ namespace fggl::phys {
struct NullPhysics {
constexpr static const char *name = "fggl::phys::null";
constexpr static const std::array<modules::ModuleService, 1> provides = {
constexpr static const std::array<modules::ServiceName, 1> provides = {
phys::PhysicsProvider::service
};
constexpr static const std::array<modules::ModuleService, 1> depends = {
constexpr static const std::array<modules::ServiceName, 1> depends = {
entity::EntityFactory::service
};
static bool factory(modules::ModuleService serviceName, modules::Services &serviceManager);
static bool factory(modules::ServiceName serviceName, modules::Services &serviceManager);
};
} // namespace fggl::phys
......
......@@ -27,7 +27,7 @@ namespace fggl::phys {
class PhysicsProvider {
public:
constexpr static const modules::ModuleService service = modules::make_service("fggl::phys::service");
constexpr static const auto service = modules::make_service("fggl::phys::service");
virtual ~PhysicsProvider() = default;
virtual PhysicsEngine *create(entity::EntityManager *entityManager, entity::EntityFactory *factory) = 0;
};
......
/*
* This file is part of FGGL.
*
* FGGL is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any
* later version.
*
* FGGL is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty
* of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License along with FGGL.
* If not, see <https://www.gnu.org/licenses/>.
*/
//
// Created by webpigeon on 19/09/22.
//
#ifndef FGGL_PLATFORM_FALLBACK_FILE_HPP
#define FGGL_PLATFORM_FALLBACK_FILE_HPP
#include <cstdio>
#include <cassert>
namespace fggl::platform {
class File {
public:
inline File(FILE* filePtr) : m_handle(filePtr) {
assert(filePtr != nullptr);
}
inline ~File() {
release();
}
template<typename T>
inline void write(const T* dataPtr) {
assert( m_handle != nullptr );
int status = fwrite(dataPtr, sizeof(T), 1, m_handle );
assert( status == 1);
}
template<typename T>
inline void writeArr(const T* dataPtr, std::size_t numElms) {
assert( m_handle != nullptr);
int status = fwrite(dataPtr, sizeof(T), numElms, m_handle );
assert( status == 1);
}
private:
std::FILE* m_handle;
inline void release() {
if ( m_handle != NULL) {
fclose(m_handle);
}
}
};
} // namespace fggl::platform
#endif //FGGL_PLATFORM_FALLBACK_FILE_HPP
......@@ -18,8 +18,8 @@
// see https://specifications.freedesktop.org/basedir-spec/basedir-spec-latest.html
//
#ifndef FGGL_PLATFORM_LINUX_PATHS_HPP
#define FGGL_PLATFORM_LINUX_PATHS_HPP
#ifndef FGGL_PLATFORM_FALLBACK_PATHS_HPP
#define FGGL_PLATFORM_FALLBACK_PATHS_HPP
#include "fggl/platform/paths.hpp"
......@@ -30,20 +30,60 @@
namespace fggl::platform {
/**
* The environment variable used for containing user configurations.
*
* The directory mentioned by this environment variable should be read/writeable.
* The directory should be used for storing user-editable configuration options (eg. preferences).
*/
constexpr const char *ENV_USER_CONFIG = "FGGL_CONFIG_HOME";
constexpr const char *ENV_USER_DATA = "FGGL_DATA_HOME";
constexpr const char *ENV_USER_CACHE = "FGGL_CACHE_HOME";
// fallback user paths defined in the XDG spec
/**
* Fallback user configuration directory.
*
* Default user configuration directory if none is set by the environment variable.
*/
constexpr const char *DEFAULT_USER_CONFIG = "user_config";
/**
* The environment variable used for containing engine data.
*
* This directory is used for storing persistent user data and therefore should be read/writable.
* The directory should be used for storing user-modifiable state (eg, save files) or downloaded modifications.
*/
constexpr const char *ENV_USER_DATA = "FGGL_DATA_HOME";
/**
* Fallback user data directory.
*
* Default user data directory if none is set by the environment variable.
*/
constexpr const char *DEFAULT_USER_DATA = "user_data";
/**
* The environment variable used for containing semi-persistent user data.
*
* The application should be able to expect this directory to exist while the application is running, but otherwise
* cannot expect the data to be persistent. It MAY be persistent but the application should not rely on this.
* It should be used for resources which can be re-generated if needed, but can be useful if already present.
*/
constexpr const char *ENV_USER_CACHE = "FGGL_CACHE_HOME";
struct EnginePaths {
std::filesystem::path userConfig;
std::filesystem::path userData;
std::filesystem::path userCache;
};
/**
* Fallback implementation of calc engine paths.
*
* For operating systems we don't know about, this simply uses the environment variables defined above and some
* sane defaults to construct the paths used to locate our data and user configuration.
*
* @param base an application-unique string used to construct the paths.
* @return the generated paths, for use with the rest of the engine.
*/
EnginePaths calc_engine_paths(const char *base);
// search routines for finding data and configuration files
......@@ -53,4 +93,4 @@ namespace fggl::platform {
}
#endif //FGGL_PLATFORM_LINUX_PATHS_HPP
#endif //FGGL_PLATFORM_FALLBACK_PATHS_HPP
......@@ -23,9 +23,10 @@
#include <vector>
#ifdef __linux__
#define FGGL_PLATFORM_PATHS linux
#include "fggl/platform/linux/paths.hpp"
#else
#define FGGL_PLATFORM_PATHS fallback
#include "fggl/platform/fallback/paths.hpp"
#endif
......
......@@ -25,6 +25,28 @@
namespace fggl::scenes {
class GameBase : public fggl::AppState {
public:
explicit GameBase(fggl::App &app);
void update(float dt) override;
void render(fggl::gfx::Graphics &gfx) override = 0;
protected:
inline auto input() -> input::Input & {
return *m_input;
}
inline void returnToMenu() {
m_owner.change_state(m_previous);
}
private:
input::Input *m_input;
std::string m_previous = "menu";
};
class Game : public fggl::AppState {
public:
......@@ -33,14 +55,15 @@ namespace fggl::scenes {
void activate() override;
void deactivate() override;
void update() override;
void update(float dt) override;
void render(fggl::gfx::Graphics &gfx) override;
protected:
inline auto world() -> entity::EntityManager & {
return *m_world;
}
protected:
bool hasPhys() const {
return m_phys != nullptr;
}
......@@ -54,6 +77,8 @@ namespace fggl::scenes {
return *m_input;
}
bool m_debug;
private:
input::Input *m_input;
std::unique_ptr<entity::EntityManager> m_world;
......
......@@ -26,23 +26,23 @@
namespace fggl::scenes {
using callback = std::function<void(void)>;
using Callback = std::function<void(void)>;
class BasicMenu : public AppState {
public:
explicit BasicMenu(App &owner);
void update() override;
void update(float dt) override;
void render(gfx::Graphics &paint) override;
void activate() override;
void deactivate() override;
void add(const std::string &label, callback cb);
void add(const std::string &label, const Callback& /*cb*/);
private:
input::Input *m_inputs;
std::map<const std::string, callback> m_items;
std::map<const std::string, Callback> m_items;
// menu state
std::string m_active;
......
/*
* This file is part of FGGL.
*
* FGGL is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any
* later version.
*
* FGGL is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty
* of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License along with FGGL.
* If not, see <https://www.gnu.org/licenses/>.
*/
//
// Created by webpigeon on 15/10/22.
//
#ifndef FGGL_SCRIPT_ENGINE_H
#define FGGL_SCRIPT_ENGINE_H
#include "fggl/modules/module.hpp"
namespace fggl::script {
class ScriptEngine {
public:
virtual ~ScriptEngine() = default;
// TODO use protected virtual pattern
// scene callbacks
virtual void onActivate() = 0;
virtual void onDeactivate() = 0;
virtual void onUpdate() = 0;
// trigger callback
virtual void onEvent(const std::string& name) = 0;
// run code in engine
virtual bool run(const char* script) = 0;
virtual bool load(const char* filename) = 0;
virtual void setGlobal(const char* name, void* ptr) = 0;
};
class ScriptProvider {
public:
constexpr static const modules::ServiceName service = modules::make_service("fggl::script::service");
virtual ScriptEngine* create() = 0;
};
}
#endif //FGGL_SCRIPT_ENGINE_H
......@@ -24,6 +24,7 @@
#include <cassert>
#include "fggl/util/safety.hpp"
#include "fggl/debug/logging.hpp"
namespace fggl::util {
......@@ -66,26 +67,68 @@ namespace fggl::util {
return hash;
}
template<unsigned N>
struct FString {
char c[N];
};
// https://stackoverflow.com/a/65440575
template<unsigned ...Len>
constexpr auto cat(const char (&...strings)[Len]) {
constexpr unsigned N = (... + Len) - sizeof...(Len);
FString<N + 1> result = {};
result.c[N] = '\0';
char* dst = result.c;
for (const char* src : {strings...}) {
for (; *src != '\0'; src++, dst++) {
*dst = *src;
}
}
return result;
}
// debug-only functions
#ifndef NDEBUG
GUID internString(const char *str);
std::string guidToString(GUID guid);
GUID intern_string(const char *str);
std::string guid_to_string(GUID guid);
#endif
constexpr GUID make_guid(const char *str) {
return GUID::make(hash_fnv1a_64(str));
return GUID(hash_fnv1a_64(str));
}
inline GUID make_guid_rt(const std::string &str) {
inline GUID make_guid_rt(const char* str) {
#ifndef NDEBUG
return internString(str.c_str());
return intern_string(str);
#else
return make_guid(str.c_str());
return make_guid(str);
#endif
}
inline GUID make_guid_rt(const std::string &str) {
return make_guid_rt(str.c_str());
}
} // namespace fggl::util
// formatter
template<> struct fmt::formatter<fggl::util::GUID> {
constexpr auto parse(format_parse_context& ctx) -> decltype(ctx.begin()) {
return ctx.begin();
}
template <typename FormatContext>
auto format(const fggl::util::GUID& guid, FormatContext& ctx) const -> decltype(ctx.out()) {
#ifndef NDEBUG
return fmt::format_to(ctx.out(), "GUID[{}]", guid_to_string(guid));
#else
return fmt::format_to(ctx.out(), "GUID[{}]", guid.get());
#endif
}
};
fggl::util::GUID operator "" _fid(const char *str);
fggl::util::GUID operator "" _fid(const char *str, std::size_t);
......
......@@ -47,14 +47,30 @@ namespace fggl::util {
return m_value;
}
constexpr explicit operator std::string_view() const { return m_value; }
/**
* Check for equality of two handles.
*
* Two values are considered the same of the values contained inside them are considered equal, and both
* types share the same tagging interface.
*
* @param other the value being compared against.
* @return true iff the contained values are equal
*/
bool operator==(const OpaqueName<T, Tag> &other) const {
return m_value == other.m_value;
}
/**
* Check for equality of two handles.
*
* Two values are considered the same of the values contained inside them are considered equal, and both
* types share the same tagging interface.
*
* @param other the value being compared against.
* @return true iff the contained values are not equal
*/
bool operator!=(const OpaqueName<T, Tag> &other) const {
return !(*this == other);
return m_value != other.m_value;
}
bool operator<(const OpaqueName<T, Tag> &other) const {
......@@ -65,6 +81,9 @@ namespace fggl::util {
return m_value <=> other.m_value;
}
/**
* Generate a new tagged instance of a handle.
*/
constexpr static OpaqueName<T, Tag> make(T value) {
return OpaqueName<T, Tag>(value);
}
......
......@@ -63,7 +63,7 @@ namespace fggl::util {
}
StateType &active() const {
assertm(m_states.find(m_active) != m_states.end(), "active state does not exist!");
ASSERT_MSG(m_states.find(m_active) != m_states.end(), "active state does not exist!");
return *(m_states.at(m_active).get());
}
......
# Integration Modules
This adds support for 3rd party libraries to the engine. These can be included in projects
to expose modules which can then be used in your applications.
## Integrations Provided
The following integration modules are povided in this folder. For more information please see the readme for that module.
| Integration | Module Name | Description |
|-------------|-----------------------|----------------------------------------------------|
| Bullet | `fggl::phys::Bullet3` | Provides Bullet3 integration into the game engine. |
| Lua | `fggl::script::Lua` | Provides LUA scripting support for the engine |
Modules that cannot be included for legal reasons will be packaged independently of this repository.
\ No newline at end of file
target_include_directories( fggl
PUBLIC
$<BUILD_INTERFACE:${CMAKE_CURRENT_LIST_DIR}/include>
$<INSTALL_INTERFACE:include>
)
add_library(fggl-lua)
find_package(Lua REQUIRED)
target_link_libraries(fggl-lua PUBLIC ${LUA_LIBRARIES})
target_include_directories(fggl-lua INTERFACE ${LUA_INCLUDE_DIR})
# Link to FGGL
target_link_libraries(fggl-lua PUBLIC fggl)
# sources and include directories
target_sources(fggl-lua
PRIVATE
src/engine.cpp
src/module.cpp
)
target_include_directories(fggl-lua
PUBLIC
$<BUILD_INTERFACE:${CMAKE_CURRENT_LIST_DIR}/include>
$<INSTALL_INTERFACE:include>
)
/*
* This file is part of FGGL.
*
* FGGL is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any
* later version.
*
* FGGL is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty
* of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License along with FGGL.
* If not, see <https://www.gnu.org/licenses/>.
*/
//
// Created by webpigeon on 15/10/22.
//
#ifndef FGGL_INTEGRATIONS_LUA_SCRIPT_LUA_ENGINE_HPP
#define FGGL_INTEGRATIONS_LUA_SCRIPT_LUA_ENGINE_HPP
#include "fggl/script/engine.hpp"
#include "fggl/data/storage.hpp"
extern "C" {
#include "lua.h"
#include "lauxlib.h"
#include "lualib.h"
};
namespace fggl::script::lua {
class LuaScriptEngine : public ScriptEngine {
public:
LuaScriptEngine(data::Storage* storage);
virtual ~LuaScriptEngine();
void onActivate() override;
void onDeactivate() override;
void onUpdate() override;
void onEvent(const std::string& name) override;
// running scripts
bool run(const char* script) override;
bool load(const char* filename) override;
// variables
void setGlobal(const char* name, void* ptr) override;
private:
data::Storage* m_storage;
lua_State* m_state;
void release();
};
class LuaScriptProvider : public ScriptProvider {
public:
LuaScriptProvider(data::Storage* storage);
virtual ~LuaScriptProvider() = default;
LuaScriptEngine* create() override;
private:
data::Storage* m_storage;
};
}
#endif //FGGL_INTEGRATIONS_LUA_SCRIPT_LUA_ENGINE_HPP
/*
* This file is part of FGGL.
*
* FGGL is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any
* later version.
*
* FGGL is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty
* of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License along with FGGL.
* If not, see <https://www.gnu.org/licenses/>.
*/
//
// Created by webpigeon on 15/10/22.
//
#ifndef FGGL_INTEGRATIONS_LUA_SCRIPT_LUA_MODULE_HPP
#define FGGL_INTEGRATIONS_LUA_SCRIPT_LUA_MODULE_HPP
#define FGGL_HAS_LUA
#include "fggl/modules/module.hpp"
#include "fggl/entity/module.hpp"
#include "fggl/script/engine.hpp"
#include "fggl/data/module.hpp"
#include "fggl/assets/packed/adapter.hpp"
namespace fggl::script::lua {
constexpr auto MIME_LUA = assets::from_mime("text/lua");
constexpr auto SCRIPT_LUA = assets::make_asset_type("script/lua");
struct Lua {
constexpr static const char* name = "fggl::script::lua";
constexpr static const std::array<modules::ServiceName, 1> provides = {
script::ScriptProvider::service
};
constexpr static const std::array<modules::ServiceName, 2> depends = {
data::SERVICE_STORAGE,
assets::CheckinAdapted::service
};
static bool factory(modules::ServiceName name, modules::Services& serviceManager);
};
} // namespace fggl::script::lua
namespace fggl::script {
using Lua = lua::Lua;
} // namespace fggl::script
#endif //FGGL_INTEGRATIONS_LUA_SCRIPT_LUA_MODULE_HPP
/*
* This file is part of FGGL.
*
* FGGL is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any
* later version.
*
* FGGL is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty
* of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License along with FGGL.
* If not, see <https://www.gnu.org/licenses/>.
*/
//
// Created by webpigeon on 15/10/22.
//
#include "fggl/script/lua/engine.hpp"
#include "fggl/debug/logging.hpp"
#include "fggl/scenes/game.hpp"
#include "fggl/entity/loader/loader.hpp"
#include <cassert>
extern "C" {
int lua_switch_scene(lua_State *L) {
auto *scene = lua_tostring(L, -1);
auto *statePtr = (fggl::AppState *) (lua_topointer(L, -2));
statePtr->owner().change_state(scene);
return 0;
}
int lua_create_entity(lua_State *L) {
/*auto *prototype = lua_tostring(L, -1);
auto *statePtr = (fggl::scenes::Game*) (lua_topointer(L, -2));
auto *factory = statePtr->owner().service<fggl::entity::EntityFactory>();
//factory->create( statePtr->world(), , [](){} );
*/
return 0;
}
static void open_lua_fggl(lua_State *L) {
// switch scene
lua_pushcfunction(L, lua_switch_scene);
lua_setglobal(L, "switch_scene");
}
}
namespace fggl::script::lua {
LuaScriptProvider::LuaScriptProvider(data::Storage *storage) : m_storage(storage) {
}
LuaScriptEngine *LuaScriptProvider::create() {
return new LuaScriptEngine(m_storage);
}
LuaScriptEngine::LuaScriptEngine(data::Storage* storage) : m_state(luaL_newstate()), m_storage(storage) {
luaL_openlibs(m_state);
open_lua_fggl(m_state);
}
LuaScriptEngine::~LuaScriptEngine() {
release();
}
void LuaScriptEngine::release() {
if ( m_state != nullptr ) {
lua_close(m_state);
m_state = nullptr;
}
}
void LuaScriptEngine::onActivate() {
lua_getglobal(m_state, "print");
lua_pushstring(m_state, "LUA activate triggered");
lua_call(m_state, 1, 0);
}
void LuaScriptEngine::onDeactivate() {
lua_getglobal(m_state, "print");
lua_pushstring(m_state, "LUA deactivate triggered");
lua_call(m_state, 1, 0);
}
void LuaScriptEngine::onUpdate() {
lua_getglobal(m_state, "print");
lua_pushstring(m_state, "LUA update triggered");
lua_call(m_state, 1, 0);
}
void LuaScriptEngine::onEvent(const std::string &name) {
lua_getglobal(m_state, "print");
lua_pushstring(m_state, "LUA event triggered");
lua_call(m_state, 1, 0);
}
bool LuaScriptEngine::run(const char *script) {
auto result = luaL_dostring(m_state, script);
if ( !result ) {
fggl::debug::warning("lua error: {}", lua_tostring(m_state, -1));
}
return result;
}
bool LuaScriptEngine::load(const char *filename) {
assert( filename != nullptr);
auto path = m_storage->resolvePath(data::StorageType::Data, filename);
if ( !std::filesystem::exists(path) ) {
fggl::debug::warning("lua error: file does not exist: {}", path.c_str());
return false;
}
// load the file ( OK = 0 = false because reasons...)
auto result = !luaL_dofile(m_state, path.c_str());
if ( !result ) {
fggl::debug::warning("lua error: {}", lua_tostring(m_state, -1));
return false;
}
return true;
}
void LuaScriptEngine::setGlobal(const char *name, void *ptr) {
lua_pushlightuserdata(m_state, ptr);
lua_setglobal(m_state, name);
}
}
\ No newline at end of file
/*
* This file is part of FGGL.
*
* FGGL is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any
* later version.
*
* FGGL is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty
* of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License along with FGGL.
* If not, see <https://www.gnu.org/licenses/>.
*/
//
// Created by webpigeon on 15/10/22.
//
#include "fggl/script/lua/module.hpp"
#include "fggl/script/lua/engine.hpp"
namespace fggl::script::lua {
static assets::AssetTypeID is_lua(std::filesystem::path path) {
if ( path.extension() == ".lua" ) {
return SCRIPT_LUA;
}
return assets::INVALID_ASSET_TYPE;
}
bool Lua::factory(modules::ServiceName service, modules::Services &serviceManager) {
if ( service == ScriptProvider::service ) {
auto *storageService = serviceManager.get<data::Storage>();
serviceManager.bind<ScriptProvider,LuaScriptProvider>(storageService);
auto *assetPacker = serviceManager.get<assets::CheckinAdapted>();
assetPacker->setLoader(MIME_LUA, assets::NEEDS_CHECKIN, is_lua);
return true;
}
return false;
}
}
\ No newline at end of file
add_executable(fgpak)
target_link_libraries(fgpak fggl)
target_sources(fgpak
PRIVATE
src/main.cpp
)
\ No newline at end of file
/*
* This file is part of FGGL.
*
* FGGL is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any
* later version.
*
* FGGL is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty
* of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License along with FGGL.
* If not, see <https://www.gnu.org/licenses/>.
*/
/*
* This file is part of FGGL.
*
* FGGL is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any
* later version.
*
* FGGL is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty
* of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License along with FGGL.
* If not, see <https://www.gnu.org/licenses/>.
*/
//
// Created by webpigeon on 11/09/22.
//
#ifndef FGGL_TOOLS_PACK_SRC_BINARY_HPP
#define FGGL_TOOLS_PACK_SRC_BINARY_HPP
#include <cstdint>
#include <iostream>
#include <cstdio>
#include "fggl/data/model.hpp"
namespace fggl::data {
enum class ModelType {
OPENGL
};
struct ModelHeader {
unsigned long guid;
std::size_t size;
ModelType type;
};
void write_mesh(FILE* file, const Mesh& mesh) {
static_assert( std::is_standard_layout_v<Vertex> );
static_assert( std::is_standard_layout_v<Mesh::IndexType> );
// write vertex data
std::size_t vertexCount = mesh.vertexCount();
fwrite( &vertexCount, sizeof(vertexCount), 1, file );
fwrite( mesh.vertexList().data(), sizeof(Vertex), vertexCount, file );
std::size_t indexCount = mesh.indexCount();
fwrite( &indexCount, sizeof(indexCount), 1, file);
fwrite( mesh.indexList().data(), sizeof(Mesh::IndexType), indexCount, file);
}
void write_model(FILE* file, const ModelHeader& header, const Mesh& mesh) {
assert( header.type == ModelType::OPENGL );
fwrite( &header , sizeof(ModelHeader), 1, file);
write_mesh(file, mesh);
}
void read_mesh(FILE* fin, data::Mesh& mesh) {
static_assert( std::is_standard_layout_v<Vertex> );
static_assert( std::is_standard_layout_v<Mesh::IndexType> );
std::size_t readCount;
// vertex data
std::size_t vertexCount = 0;
readCount = fread( &vertexCount, sizeof(vertexCount), 1, fin );
assert(ferror(fin) == 0);
if (readCount != 1) {
std::cerr << "failed to read vertex count" << std::endl;
return;
}
// push vertex data into mesh
auto* vertexData = new data::Vertex[vertexCount];
readCount = fread( vertexData, sizeof(Vertex), vertexCount, fin );
assert(ferror(fin) == 0);
if ( readCount != vertexCount ) {
std::cerr << "failed to read vertex data" << std::endl;
return;
}
for ( std::size_t i = 0; i < vertexCount; ++i) {
mesh.pushVertex(vertexData[i]);
}
delete[] vertexData;
// read index size
std::size_t indexCount = 0;
readCount = fread( &indexCount, sizeof(indexCount), 1, fin);
assert(ferror(fin) == 0);
if (readCount != 1 ) {
std::cerr << "failed to read index count" << std::endl;
return;
}
// read index data
auto* idxData = new Mesh::IndexType[indexCount];
readCount = fread( idxData, sizeof(Mesh::IndexType), indexCount, fin);
assert(ferror(fin) == 0);
if (readCount != indexCount) {
std::cerr << "failed to read index data, expected: " << indexCount << ", got: " << readCount << std::endl;
return;
}
for (int i=0; i < indexCount; ++i) {
mesh.pushIndex( idxData[i] );
}
delete[] idxData;
}
void read_model(FILE* file, ModelHeader& header, Mesh& mesh) {
fread( &header, sizeof(ModelHeader), 1, file);
if ( header.type == ModelType::OPENGL ) {
read_mesh(file, mesh);
}
}
}
#endif //FGGL_TOOLS_PACK_SRC_BINARY_HPP