zecsy/zecsy.hpp

89 lines
1.9 KiB
C++
Raw Normal View History

2025-02-14 21:35:40 +03:00
#pragma once
#include <cstdint>
#include <bitset>
2025-02-14 22:18:00 +03:00
#include <format>
#include <exception>
2025-02-14 21:35:40 +03:00
#ifndef MAX_ZECSY_ENTITIES
#define MAX_ZECSY_ENTITIES 65536
#endif // !MAX_ZECSY_ENTITIES
namespace zecsy
{
using entity_id = uint64_t;
2025-02-14 22:18:00 +03:00
class entity final
{
public:
entity(class world* w, entity_id id);
entity() = default;
entity(const entity &) = default;
entity(entity &&) = default;
entity &operator=(const entity &) = default;
entity &operator=(entity &&) = default;
operator entity_id() const;
bool is_alive() const;
private:
entity_id id = 0;
class world* w = nullptr;
};
2025-02-14 21:35:40 +03:00
class world final
{
public:
world() = default;
world(const world &) = default;
world(world &&) = default;
world &operator=(const world &) = default;
world &operator=(world &&) = default;
2025-02-14 22:18:00 +03:00
entity make_entity();
void destroy_entity(entity_id e);
2025-02-14 21:35:40 +03:00
bool is_alive(entity_id e) const;
private:
std::bitset<MAX_ZECSY_ENTITIES> entities_bitset;
entity_id entity_counter = 0;
};
2025-02-14 22:18:00 +03:00
inline entity::entity(class world* w, entity_id id): w(w), id(id)
{
}
inline entity::operator entity_id() const
2025-02-14 21:35:40 +03:00
{
return id;
}
2025-02-14 22:18:00 +03:00
inline bool entity::is_alive() const
{
return w && w->is_alive(id);
}
inline entity world::make_entity()
{
auto id = (++entity_counter)%MAX_ZECSY_ENTITIES;
if(is_alive(id))
{
throw std::runtime_error(std::format("entity_id #{} already in use,"
" can't make a new entity", id));
}
entities_bitset.set(id);
return entity(this, id);
}
inline void world::destroy_entity(entity_id e)
{
entities_bitset.reset(e);
}
2025-02-14 21:35:40 +03:00
inline bool world::is_alive(entity_id e) const
{
return entities_bitset.test(e);
}
};