summary refs log tree commit diff stats
path: root/src/systems/scheduling.cpp
blob: 220efae88b72e026a2e4a08ed2a0f6a11180fb0c (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
#include "scheduling.h"
#include "game.h"
#include "components/schedulable.h"
#include "util.h"

void SchedulingSystem::tick(double dt)
{
  auto entities = game_.getEntityManager().getEntitiesWithComponents<
    SchedulableComponent>();

  for (id_type entity : entities)
  {
    auto& schedulable = game_.getEntityManager().
      getComponent<SchedulableComponent>(entity);

    for (auto& action : schedulable.actions)
    {
      std::get<0>(action) -= dt;

      if (std::get<0>(action) < 0)
      {
        std::get<1>(action)(entity);
      }
    }

    erase_if(schedulable.actions,
      [] (const SchedulableComponent::Action& action) {
        return (std::get<0>(action) < 0);
      });

    if (schedulable.actions.empty())
    {
      game_.getEntityManager().removeComponent<SchedulableComponent>(entity);
    }
  }
}

void SchedulingSystem::schedule(
  id_type entity,
  double length,
  std::function<void(id_type)> action)
{
  if (!game_.getEntityManager().hasComponent<SchedulableComponent>(entity))
  {
    game_.getEntityManager().emplaceComponent<SchedulableComponent>(entity);
  }

  auto& schedulable = game_.getEntityManager().
    getComponent<SchedulableComponent>(entity);

  schedulable.actions.emplace_back(
    length,
    std::move(action));
}