3 Commits

Author SHA1 Message Date
d6f304e6ca feat(entity): add client-to-server entity creation and destruction requests
Extend the network protocol with `C2SEntityCreateRequest` and `C2SEntityDestoryRequest` packets. Refactor entity managers to split public client-facing create/destroy methods that send requests over the network, from internal handlers that process received packets. Add utility functions for converting protobuf Vec3 to glm::vec3.
2026-07-30 15:53:09 +08:00
826c6600d0 feat(gameplay): add entity destruction support 2026-07-30 15:24:19 +08:00
b166bab4f3 feat(gameplay): implement entity system with concurrent task handling and fix model loading 2026-07-30 15:05:56 +08:00
15 changed files with 277 additions and 46 deletions

View File

@@ -10,15 +10,19 @@ namespace Cubed {
class ClientWorld;
class ClientEntityManager {
public:
enum class Command { CREATE };
enum class Command { CREATE, DESTORY };
ClientEntityManager(ClientWorld& world);
void update();
void init();
// not thread safe
void add_entity(EntityID id, std::string_view name, const glm::vec3& pos);
void receive_entity_create(S2CEntityCreate& s2c);
void receive_entity_destory(EntityID id);
void destory(EntityID id);
void create(std::string_view name, const glm::vec3& pos);
const entt::registry& get_registry() const;
private:
struct EntityCreateElement {
@@ -30,7 +34,7 @@ private:
using acc = EntityMap::accessor;
using cacc = EntityMap::const_accessor;
using CreateFunc = std::function<void(EntityID id)>;
using TaskElement = std::variant<EntityCreateElement>;
using TaskElement = std::variant<EntityCreateElement, EntityID>;
using TaskPair = std::pair<Command, TaskElement>;
ClientWorld& m_world;
@@ -40,8 +44,18 @@ private:
tbb::concurrent_queue<TaskPair> m_tasks;
void handle_task();
template <typename... Args> void add_entity(EntityID id, Args&&... args) {
void handle_entity_destory(EntityID id);
// not thread safe
void handle_entity_create(EntityID id, std::string_view name,
const glm::vec3& pos);
template <typename... Args>
void create_entity_in_registry(EntityID id, Args&&... args) {
{
cacc a;
if (m_entities.find(a, id)) {
return;
}
}
auto entity = m_registry.create();
((m_registry.emplace<std::remove_cvref_t<Args>>(

View File

@@ -86,6 +86,7 @@ public:
WorldScene& world_scene();
ClientPlayerManager& player_manager();
ClientEntityManager& entity_manager();
std::shared_ptr<NetworkClient> get_client() const;
void set_direct_exit();
void receive_chat_message(ChatMsg& msg);

View File

@@ -62,6 +62,9 @@ enum class PacketEnum : uint16_t {
S2C_CLEAR_ALL_CHUNKS = 3005,
UPDATE_TIME = 3006,
S2C_ENTITY_CREATE = 3007,
S2C_ENTITY_DESTORY = 3008,
C2S_ENTITY_CREATE_REQUEST = 3009,
C2S_ENTITY_DESTORY_REQUEST = 3010,
CHAT_MSG = 4001,
VOICE_MSG = 4002,
PING = 9001,
@@ -115,6 +118,15 @@ template <> constexpr uint16_t get_packet_id<S2C_ClearAllChunks>() {
template <> constexpr uint16_t get_packet_id<S2CEntityCreate>() {
return std::to_underlying(PacketEnum::S2C_ENTITY_CREATE);
}
template <> constexpr uint16_t get_packet_id<S2CEntityDestory>() {
return std::to_underlying(PacketEnum::S2C_ENTITY_DESTORY);
}
template <> constexpr uint16_t get_packet_id<C2SEntityCreateRequest>() {
return std::to_underlying(PacketEnum::C2S_ENTITY_CREATE_REQUEST);
}
template <> constexpr uint16_t get_packet_id<C2SEntityDestoryRequest>() {
return std::to_underlying(PacketEnum::C2S_ENTITY_DESTORY_REQUEST);
}
template <> constexpr uint16_t get_packet_id<UpdateTime>() {
return std::to_underlying(PacketEnum::UPDATE_TIME);
}
@@ -184,6 +196,12 @@ Packet make_packet(const T& msg) {
return packet;
}
template <typename T>
requires std::derived_from<T, google::protobuf::Message>
Packet make_packet(const T* msg) {
return make_packet(*msg);
}
inline PacketHeader decode_packet_header(std::span<const uint8_t> header) {
if (header.size() < HEADER_LEN)
throw std::runtime_error("Invalid header");

View File

@@ -4,31 +4,48 @@
#include <entt/entt.hpp>
#include <tbb/concurrent_hash_map.h>
#include <tbb/concurrent_queue.h>
namespace Cubed {
class ServerWorld;
class Session;
class ServerEntityManager {
public:
ServerEntityManager(ServerWorld& world);
void init();
void update();
// not thread safe
void add_entity(std::string_view name, const glm::vec3& pos);
void destory(EntityID id);
void handle_player_login(std::shared_ptr<Session> session);
private:
enum class Command { CREATE, SEND_ALL_ENTITIES, DESTORY };
struct EntityCreateElement {
std::string name;
glm::vec3 pos;
};
using EntityMap = tbb::concurrent_hash_map<EntityID, entt::entity>;
using acc = EntityMap::accessor;
using cacc = EntityMap::const_accessor;
using CreateFunc = std::function<EntityID()>;
using TaskElement =
std::variant<std::shared_ptr<Session>, EntityCreateElement, EntityID>;
using TaskPair = std::pair<Command, TaskElement>;
ServerWorld& m_world;
tbb::concurrent_queue<TaskPair> m_tasks;
entt::registry m_registry;
EntityID m_next = 0;
EntityMap m_entities;
std::unordered_map<std::string_view, CreateFunc> m_factories;
void send_entity_create(EntityID id, std::string_view name,
void create_entity(std::string_view name, const glm::vec3& pos);
void handle_entity_create(EntityID id, std::string_view name,
const glm::vec3& pos);
template <typename... Args> EntityID add_entity(Args&&... args) {
void handle_entity_destory(EntityID id);
void handle_task();
void send_all_entities(std::shared_ptr<Session>& session);
template <typename... Args>
EntityID create_entity_in_factory(Args&&... args) {
auto entity = m_registry.create();
((m_registry.emplace<std::remove_cvref_t<Args>>(

View File

@@ -86,6 +86,10 @@ public:
void handle_chat_message(ChatMsg& msg);
void handle_voice_message(VoiceMsg& msg);
void handle_entity_create(C2SEntityCreateRequest& req);
void handle_entity_destory(C2SEntityDestoryRequest& req);
int chunk_size() const;
std::vector<std::shared_ptr<Session>> get_all_session() const;

View File

@@ -11,5 +11,11 @@ template <Ptr T> void set_net_pos(T ptr, const glm::vec3& pos) {
p->set_y(pos.y);
p->set_z(pos.z);
}
inline glm::vec3 get_net_pos(const Vec3* p) {
return glm::vec3{p->x(), p->y(), p->z()};
}
inline glm::vec3 get_net_pos(const Vec3& p) {
return glm::vec3{p.x(), p.y(), p.z()};
}
} // namespace Tools
} // namespace Cubed

View File

@@ -1,32 +1,39 @@
#include "Cubed/gameplay/client_entity_manager.hpp"
#include "Cubed/gameplay/client_world.hpp"
#include "Cubed/gameplay/creatures/pig.hpp"
#include "Cubed/gameplay/ecs/client_entity.hpp"
#include "Cubed/gameplay/ecs/identity.hpp"
#include "Cubed/gameplay/ecs/transform.hpp"
#include "Cubed/render/model_manager.hpp"
#include "Cubed/tools/cubed_assert.hpp"
#include "Cubed/tools/net_utils.hpp"
using namespace google::protobuf;
namespace Cubed {
ClientEntityManager::ClientEntityManager(ClientWorld& world) : m_world(world) {}
void ClientEntityManager::update() { handle_task(); }
void ClientEntityManager::init() {
m_factories.emplace("cubed:pig", [this](EntityID id) {
BaseClientCreature c;
c.model = ModelManager::instance().get_model_id("cubed:pig");
add_entity(id, Entity{id}, EntityInfo{"cubed:pig", ""}, std::move(c),
PigTag{});
create_entity_in_registry(id, Entity{id}, EntityInfo{"cubed:pig", ""},
std::move(c), PigTag{});
});
}
// not thread safe
void ClientEntityManager::add_entity(EntityID id, std::string_view name,
void ClientEntityManager::handle_entity_create(EntityID id,
std::string_view name,
const glm::vec3& pos) {
ASSERT(m_factories.contains(name));
m_factories[name](id);
acc a;
ASSERT(m_entities.find(a, id));
auto* c = m_registry.try_get<Transform>(a->second);
auto* c = m_registry.try_get<BaseClientCreature>(a->second);
ASSERT(c);
c->position.value = pos;
c->transform.position.value = pos;
}
void ClientEntityManager::receive_entity_create(S2CEntityCreate& s2c) {
@@ -37,17 +44,57 @@ void ClientEntityManager::receive_entity_create(S2CEntityCreate& s2c) {
m_tasks.emplace(Command::CREATE, std::move(c));
}
void ClientEntityManager::receive_entity_destory(EntityID id) {
m_tasks.emplace(Command::DESTORY, id);
}
void ClientEntityManager::destory(EntityID id) {
auto client = m_world.get_client();
Arena arena;
auto* msg = Arena::Create<C2SEntityDestoryRequest>(&arena);
msg->set_id(id);
msg->set_uuid(m_world.get_player().get_uuid());
client->send(make_packet(*msg));
}
void ClientEntityManager::create(std::string_view name, const glm::vec3& pos) {
auto client = m_world.get_client();
Arena arena;
auto* msg = Arena::Create<C2SEntityCreateRequest>(&arena);
msg->set_name(name);
msg->set_uuid(m_world.get_player().get_uuid());
Tools::set_net_pos(msg, pos);
client->send(make_packet(msg));
}
void ClientEntityManager::handle_task() {
TaskPair pair;
while (m_tasks.try_pop(pair)) {
switch (pair.first) {
case Command::CREATE:
case Command::CREATE: {
auto* p = std::get_if<EntityCreateElement>(&pair.second);
ASSERT(p);
handle_entity_create(p->id, p->name, p->pos);
add_entity(p->id, p->name, p->pos);
} break;
case Command::DESTORY: {
auto* p = std::get_if<EntityID>(&pair.second);
ASSERT(p);
handle_entity_destory(*p);
} break;
}
}
}
void ClientEntityManager::handle_entity_destory(EntityID id) {
acc a;
if (!m_entities.find(a, id)) {
return;
}
m_registry.destroy(a->second);
m_entities.erase(a);
}
const entt::registry& ClientEntityManager::get_registry() const {
return m_registry;
}
} // namespace Cubed

View File

@@ -682,6 +682,9 @@ Config& ClientWorld::get_config() { return m_config; }
WorldScene& ClientWorld::world_scene() { return m_world_scene; }
ClientPlayerManager& ClientWorld::player_manager() { return m_player_manager; }
ClientEntityManager& ClientWorld::entity_manager() { return m_entity_manager; }
std::shared_ptr<NetworkClient> ClientWorld::get_client() const {
return m_client;
}
void ClientWorld::set_direct_exit() { m_exit_direct = true; }
void ClientWorld::request_exit() {
if (m_receive_exit) {
@@ -731,6 +734,7 @@ void ClientWorld::send_chat_message(ChatMessage& message) {
void ClientWorld::update(float delta_time) {
m_player_manager.update(delta_time);
m_entity_manager.update();
{
std::lock_guard lk(m_delete_vbo_mutex);
m_pending_delete_vbo.clear();

View File

@@ -93,7 +93,7 @@ asio::awaitable<void> NetworkClient::read_loop() {
} break;
case std::to_underlying(PacketEnum::BLOCK_CHANGE_RSP): {
auto* rsp = Arena::Create<BlockChangeRsp>(&arena);
Logger::info("Client: Receive Block Change rsp");
if (decode_packet(*rsp, body_data, header)) {
m_world.receive_block_change(*rsp);
}
@@ -148,6 +148,13 @@ asio::awaitable<void> NetworkClient::read_loop() {
if (decode_packet(*msg, body_data, header)) {
m_world.entity_manager().receive_entity_create(*msg);
}
} break;
case std::to_underlying(PacketEnum::S2C_ENTITY_DESTORY): {
auto* msg = Arena::Create<S2CEntityDestory>(&arena);
if (decode_packet(*msg, body_data, header)) {
m_world.entity_manager().receive_entity_destory(msg->id());
}
} break;
}
}

View File

@@ -17,13 +17,53 @@ void ServerEntityManager::init() {
m_factories.try_emplace("cubed:pig", [this]() {
BaseServerCreature c;
c.hitbox = HitboxManager::instance().get_hitbox_id("cubed:pig");
return add_entity(Entity{m_next}, EntityInfo{"cubed:pig", ""},
return create_entity_in_factory(Entity{m_next},
EntityInfo{"cubed:pig", ""},
std::move(c), PigTag{});
});
}
void ServerEntityManager::update() { handle_task(); }
void ServerEntityManager::handle_task() {
TaskPair pair;
while (m_tasks.try_pop(pair)) {
switch (pair.first) {
case Command::CREATE: {
auto* c = std::get_if<EntityCreateElement>(&pair.second);
ASSERT(c);
create_entity(c->name, c->pos);
} break;
case Command::SEND_ALL_ENTITIES: {
auto* c = std::get_if<std::shared_ptr<Session>>(&pair.second);
ASSERT(c);
send_all_entities(*c);
} break;
case Command::DESTORY: {
auto* c = std::get_if<EntityID>(&pair.second);
ASSERT(c);
handle_entity_destory(*c);
} break;
}
}
}
void ServerEntityManager::add_entity(std::string_view name,
const glm::vec3& pos) {
m_tasks.emplace(Command::CREATE,
EntityCreateElement{std::string(name), pos});
}
void ServerEntityManager::destory(EntityID id) {
m_tasks.emplace(Command::DESTORY, id);
}
void ServerEntityManager::handle_player_login(
std::shared_ptr<Session> session) {
m_tasks.emplace(Command::SEND_ALL_ENTITIES, std::move(session));
}
void ServerEntityManager::create_entity(std::string_view name,
const glm::vec3& pos) {
ASSERT(m_factories.contains(name));
auto e = m_factories[name]();
acc c;
@@ -32,10 +72,25 @@ void ServerEntityManager::add_entity(std::string_view name,
ASSERT(t);
t->transform.position.value = pos;
}
send_entity_create(e, name, pos);
handle_entity_create(e, name, pos);
}
void ServerEntityManager::send_entity_create(EntityID id, std::string_view name,
void ServerEntityManager::send_all_entities(std::shared_ptr<Session>& session) {
auto view = m_registry.view<Entity, EntityInfo, BaseServerCreature>();
for (auto& entity : view) {
auto [e, info, base] =
view.get<Entity, EntityInfo, BaseServerCreature>(entity);
Arena arena;
auto* s2c = Arena::Create<S2CEntityCreate>(&arena);
s2c->set_id(e.id);
s2c->set_name(info.name);
Tools::set_net_pos(s2c, base.transform.position.value);
session->send(make_packet(*s2c));
}
}
void ServerEntityManager::handle_entity_create(EntityID id,
std::string_view name,
const glm::vec3& pos) {
auto sessions = m_world.get_all_session();
@@ -50,4 +105,20 @@ void ServerEntityManager::send_entity_create(EntityID id, std::string_view name,
}
}
void ServerEntityManager::handle_entity_destory(EntityID id) {
acc a;
if (!m_entities.find(a, id)) {
return;
}
m_registry.destroy(a->second);
m_entities.erase(a);
auto sessions = m_world.get_all_session();
Arena arena;
auto* s2c = Arena::Create<S2CEntityDestory>(&arena);
s2c->set_id(id);
for (auto& s : sessions) {
s->send(make_packet(*s2c));
}
}
} // namespace Cubed

View File

@@ -5,6 +5,7 @@
#include "Cubed/tools/cubed_assert.hpp"
#include "Cubed/tools/log.hpp"
#include "Cubed/tools/math_tools.hpp"
#include "Cubed/tools/net_utils.hpp"
#include "Cubed/tools/uuid.hpp"
#include <nlohmann/json.hpp>
@@ -178,7 +179,7 @@ void ServerWorld::send_chunk(int task_id, const std::string& uuid,
void ServerWorld::init_world() {
m_entity_manager.init();
m_entity_manager.add_entity("cubed:pig", {0, 90, 0});
register_timer("player disconnect", 5, [this]() {
std::vector<std::string> disconnect;
{
@@ -527,6 +528,7 @@ void ServerWorld::hot_reload() {
void ServerWorld::update() {
// poll_finished_chunks();
m_entity_manager.update();
{
bool consumed = false;
std::unique_ptr<ServerChunk> chunk;
@@ -706,6 +708,7 @@ void ServerWorld::handle_player_login(const std::string& name,
boardcast_message("Server", std::format("Player {} Join Game", name),
Color::YELLOW, true);
m_entity_manager.handle_player_login(session);
}
void ServerWorld::handle_player_exit(const std::string& uuid) {
@@ -870,6 +873,14 @@ void ServerWorld::handle_block_change(const BlockChangeReq& req) {
}
}
void ServerWorld::handle_entity_create(C2SEntityCreateRequest& req) {
m_entity_manager.add_entity(req.name(), Tools::get_net_pos(req.pos()));
}
void ServerWorld::handle_entity_destory(C2SEntityDestoryRequest& req) {
m_entity_manager.destory(req.id());
}
int ServerWorld::rendering_distance() const {
return m_rendering_distance.load();
}

View File

@@ -82,7 +82,7 @@ asio::awaitable<void> Session::read_loop() {
}
if (cmd_id == std::to_underlying(PacketEnum::BLOCK_CHANGE_REQ)) {
auto* req = Arena::Create<BlockChangeReq>(&arena);
Logger::info("Session: Receive Block Change req");
if (decode_packet(*req, body_data, header)) {
m_server_world.handle_block_change(*req);
}
@@ -111,6 +111,20 @@ asio::awaitable<void> Session::read_loop() {
m_server_world.handle_voice_message(*msg);
}
}
if (cmd_id ==
std::to_underlying(PacketEnum::C2S_ENTITY_CREATE_REQUEST)) {
auto* msg = Arena::Create<C2SEntityCreateRequest>(&arena);
if (decode_packet(*msg, body_data, header)) {
m_server_world.handle_entity_create(*msg);
}
}
if (cmd_id ==
std::to_underlying(PacketEnum::C2S_ENTITY_DESTORY_REQUEST)) {
auto* msg = Arena::Create<C2SEntityDestoryRequest>(&arena);
if (decode_packet(*msg, body_data, header)) {
m_server_world.handle_entity_destory(*msg);
}
}
}
} catch (const asio::system_error& e) {
auto ec = e.code();

View File

@@ -7,3 +7,18 @@ message S2CEntityCreate {
string name = 2;
Vec3 pos = 3;
}
message S2CEntityDestory {
uint64 id = 1;
}
message C2SEntityDestoryRequest {
string uuid = 1;
uint64 id = 2;
}
message C2SEntityCreateRequest {
string uuid = 1;
string name = 2;
Vec3 pos = 3;
}

View File

@@ -34,7 +34,7 @@ ModelManager::Handle ModelManager::get_model(const std::string& model_name) {
ModelManager::Handle ModelManager::get_model(ModelID id) {
ModelMap::const_accessor cacc;
if (!m_models.find(cacc, id)) {
if (m_models.find(cacc, id)) {
return {cacc->second, cacc->first};
}
return load_model(get_model_name(id));
@@ -73,10 +73,10 @@ ModelManager::Handle ModelManager::load_model(std::string_view model_name) {
}
std::string path;
if (space[0] == "cubed") {
path = std::format("{}model/creature/{}/{}.gbl", ASSETS_PATH, space[1],
path = std::format("{}model/creature/{}/{}.glb", ASSETS_PATH, space[1],
space[1]);
} else {
path = std::format("./{}/model/creature/{}/{}.gbl", space[0], space[1],
path = std::format("./{}/model/creature/{}/{}.glb", space[0], space[1],
space[1]);
}
auto model = m_loader.load(path);

View File

@@ -3,6 +3,7 @@
#include "Cubed/camera.hpp"
#include "Cubed/debug_collector.hpp"
#include "Cubed/gameplay/client_world.hpp"
#include "Cubed/gameplay/ecs/client_entity.hpp"
#include "Cubed/render/renderer.hpp"
#include "Cubed/render/renderer_constants.hpp"
#include "Cubed/scene/world_scene.hpp"
@@ -294,14 +295,15 @@ void WorldRenderer::shadow_entity(ClientWorld& world,
auto& shader = m_renderer.get_shader("depth_model");
shader.use();
shader.set_loc("lightSpaceMatrix", light_matrix);
/*
auto& registry = world.get_registry();
auto view = registry.view<Transform, Model>();
for (auto entity : view) {
auto [transform, model] = view.get<Transform, Model>(entity);
m_renderer.model_renderer().shadow_pass(model.name, transform.pos,
glEnable(GL_DEPTH_TEST);
auto& registry = world.entity_manager().get_registry();
auto view = registry.view<BaseClientCreature>();
for (auto entity : view) {
auto& creature = view.get<BaseClientCreature>(entity);
m_renderer.model_renderer().shadow_pass(
creature.model, creature.transform.position.value,
world.world_scene().camera());
}*/
}
m_player_renderer.render(shader, world, true);
}
@@ -714,15 +716,15 @@ void WorldRenderer::render_entity(ClientWorld& world) {
m_depth_map_texture->bind(0);
glEnable(GL_DEPTH_TEST);
/*
auto& registry = world.get_registry();
auto view = registry.view<Transform, Model>();
auto& registry = world.entity_manager().get_registry();
auto view = registry.view<BaseClientCreature>();
for (auto entity : view) {
auto [transform, model] = view.get<Transform, Model>(entity);
m_renderer.model_renderer().render_model(model.name, transform.pos,
auto& creature = view.get<BaseClientCreature>(entity);
m_renderer.model_renderer().render_model(
creature.model, creature.transform.position.value,
world.world_scene().camera());
}
*/
m_player_renderer.render(shader, world, false);
}