summaryrefslogtreecommitdiff
path: root/sim/src/TurretControl.cpp
blob: 19dbe213db5b44bced78eadb61a1f626879b4dd7 (plain)
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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
#include <kurator/sim/TurretControl.h>

#include <entt/entity/registry.hpp>
#include <entt/signal/dispatcher.hpp>

#include <kurator/sim/components.h>
#include <kurator/sim/events.h>
#include <kurator/universe/TurretType.h>


namespace kurator
{
namespace sim
{


bool consume(float& dt, double& target);


void
TurretControl::update(entt::registry& registry, entt::dispatcher& dispatcher, const float dt)
{
	auto view = registry.view<TurretControl, universe::TurretType>();
	for (auto&& [entity, control, def] : view.each()) {
		if (!registry.valid(control.owner)) {
			registry.destroy(entity);
			continue;
		}
		const auto& [state, transform] = registry.get<AIState, Transform>(control.owner);  // no checks
		if (!registry.valid(state.target))
			continue;
		const auto& target = registry.get<Transform>(state.target);
		const auto distance = transform.position.distance(target.position);
		if (distance > def.optimal_range * 2.5)
			continue;
		auto remaining_dt = dt;
		while (remaining_dt > 0.0) {
			if (control.rounds < 1 && consume(remaining_dt, control.reload))
				control.rounds = def.rounds;
			if (control.rounds > 0 && consume(remaining_dt, control.delay)) {
				auto& target_points = registry.get<HitPoints>(state.target);
				const auto damage = def.effective_damage(distance);
				if (damage > 0.0) {
					target_points.health -= damage;
					dispatcher.trigger(Hit{damage, control.owner, state.target});
				}
				control.delay = def.rate_of_fire;
				if (--control.rounds < 1)
					control.reload = def.reload;
			}
		}
	}
}


bool
consume(float& dt, double& target)
{
	if (target <= 0.0)
		return true;
	const auto _dt = dt;
	dt -= target;
	target -= _dt;
	return target <= 0.0;
}


}  // namespace sim
}  // namespace kurator