From 065810b24d2036088b9fa5b0ae989094e00ac635 Mon Sep 17 00:00:00 2001 From: Fernando Raviola Date: Sat, 22 Aug 2020 16:28:55 -0300 Subject: [PATCH] minor optimizations --- include/ecs/ecs.h | 7 ++++++- src/systems/CallbackSystem.cpp | 16 ++++++++-------- src/systems/PlayerSystem.cpp | 17 +++++++++-------- 3 files changed, 23 insertions(+), 17 deletions(-) diff --git a/include/ecs/ecs.h b/include/ecs/ecs.h index 1238cc4..b7ff313 100644 --- a/include/ecs/ecs.h +++ b/include/ecs/ecs.h @@ -176,9 +176,14 @@ class World { for (auto entity : entities) if (entity->has()) callback(entity); } + template + void findAny(const std::function& callback) { + for (auto entity : entities) if (entity->hasAny()) callback(entity); + } + template std::vector findAny() { - // todo: Optimize, avoid creating a new vector an returning it by copy + //todo: optimize, this should return an iterator and not a new vector std::vector result; std::copy_if( entities.begin(), diff --git a/src/systems/CallbackSystem.cpp b/src/systems/CallbackSystem.cpp index 66dd43b..fc0c523 100644 --- a/src/systems/CallbackSystem.cpp +++ b/src/systems/CallbackSystem.cpp @@ -5,15 +5,15 @@ void CallbackSystem::onAddedToWorld(World* world) { } void CallbackSystem::tick(World* world) { - for (auto entities : world->find()) { - auto callback = entities->get(); - if (callback->time <= 0) { - entities->remove(); - continue; + world->find([](Entity* entity){ + auto callback = entity->get(); + if (callback->time > 0) { + callback->time--; + if (callback->time == 0) callback->callback(); + } else { + entity->remove(); } - callback->time--; - if (callback->time <= 0) callback->callback(); - } + }); } void CallbackSystem::handleEvent(SDL_Event& event) { diff --git a/src/systems/PlayerSystem.cpp b/src/systems/PlayerSystem.cpp index 04893b9..35cc373 100644 --- a/src/systems/PlayerSystem.cpp +++ b/src/systems/PlayerSystem.cpp @@ -95,13 +95,14 @@ void PlayerSystem::onGameOver(World* world, Entity* player) { kinetic->accY = 0.0f; kinetic->accX = 0.0f; - for (auto walkable : world->findAny()) { - if (walkable == player) continue; - walkable->remove(); - walkable->remove(); - walkable->remove(); - walkable->remove(); - } + world->findAny([=](Entity* walker) { + if (walker != player) { + walker->remove(); + walker->remove(); + walker->remove(); + walker->remove(); + } + }); player->assign([=]() { player->remove(); @@ -110,7 +111,7 @@ void PlayerSystem::onGameOver(World* world, Entity* player) { kinetic->accY = 0.0f; kinetic->accX = 0.0f; - player->assign([=]() { gameOverCallback(); }, 200); + player->assign([&]() { gameOverCallback(); }, 200); }, 50); }