From 27dd8b268fbe37fa6eed0c0fc0f013134e5e2dc9 Mon Sep 17 00:00:00 2001 From: Stanislaw Halik Date: Sat, 18 Mar 2023 16:44:39 +0100 Subject: editor/app: don't duplicate characters on load --- editor/app.cpp | 43 ++++++++++++++++++++++++++++++++++++------- editor/app.hpp | 1 + editor/update.cpp | 11 +++++++---- 3 files changed, 44 insertions(+), 11 deletions(-) (limited to 'editor') diff --git a/editor/app.cpp b/editor/app.cpp index 5820c165..c795d403 100644 --- a/editor/app.cpp +++ b/editor/app.cpp @@ -6,7 +6,7 @@ #include "loader/loader.hpp" #include "world.hpp" #include "src/anim-atlas.hpp" -#include "character.hpp" +#include "src/character.hpp" #include #include #include @@ -43,6 +43,40 @@ void app::reset_world() reset_world(floormat::world{}); } +void app::ensure_player_character(world& w) +{ + if (_character_id) + if (auto C = w.find_entity(_character_id); C && C->type == entity_type::character) + return; + _character_id = 0; + + auto id = (std::uint64_t)-1; + + for (const auto& [coord, c] : w.chunks()) + { + for (const auto& e_ : c.entities()) + { + const auto& e = *e_; + if (e.type == entity_type::character) + { + const auto& C = static_cast(e); + if (C.playable) + id = std::min(id, C.id); + } + } + } + + if (id != (std::uint64_t)-1) + _character_id = id; + else + { + character_proto cproto; + cproto.name = "Player"_s; + cproto.playable = true; + _character_id = w.make_entity(w.make_id(), global_coords{}, cproto)->id; + } +} + void app::reset_world(struct world&& w) { _popup_target = {}; @@ -51,12 +85,7 @@ void app::reset_world(struct world&& w) return; auto& w2 = M->reset_world(std::move(w)); w2.collect(true); - { - character_proto cproto; - cproto.name = "Player"_s; - cproto.playable = true; - _character_id = w2.make_entity(w2.make_id(), global_coords{}, cproto)->id; - } + ensure_player_character(w2); } int app::exec() diff --git a/editor/app.hpp b/editor/app.hpp index 2407f7cb..dc8fed2c 100644 --- a/editor/app.hpp +++ b/editor/app.hpp @@ -77,6 +77,7 @@ private: void update_character(float dt); void reset_world(); void reset_world(struct world&& w); + void ensure_player_character(world& w); void draw() override; diff --git a/editor/update.cpp b/editor/update.cpp index cbe08c05..7c084a85 100644 --- a/editor/update.cpp +++ b/editor/update.cpp @@ -198,10 +198,13 @@ void app::update_world(float dt) void app::update_character([[maybe_unused]] float dt) { - auto& w = M->world(); - auto c = w.find_entity(_character_id); - if (c) - c->set_keys(keys[key_left], keys[key_right], keys[key_up], keys[key_down]); + if (_character_id) + { + auto& w = M->world(); + auto c = w.find_entity(_character_id); + if (c) + c->set_keys(keys[key_left], keys[key_right], keys[key_up], keys[key_down]); + } } void app::set_cursor() -- cgit v1.2.3