Aegis2D
Modular C++26 2D game engine for networked games
Loading...
Searching...
No Matches
waves.hpp
Go to the documentation of this file.
1
3#pragma once
7
8#include <algorithm>
9#include <cmath>
10#include <cstddef>
11#include <cstdint>
12#include <filesystem>
13#include <span>
14#include <string>
15#include <string_view>
16#include <vector>
17
18namespace aegis2d::ecs {
19
21struct WaveSpawn {
24 std::string type;
28 std::size_t wave = 0;
30 float time = 0.0F;
31};
32
33namespace detail {
34
35[[nodiscard]] inline std::string at_index(std::string_view parent, std::size_t index) {
36 return std::string{parent} + '.' + std::to_string(index);
37}
38
39[[nodiscard]] inline float seconds_at(const core::Config& config, const std::string& path,
40 float fallback) {
41 if (!config.contains(path)) {
42 return fallback;
43 }
44 const auto value = config.number(path);
45 if (!value || !std::isfinite(*value) || *value < 0.0) {
46 throw core::ConfigError{path + ": must be a number of seconds, 0 or more"};
47 }
48 return static_cast<float>(*value);
49}
50
51[[nodiscard]] inline Vec2 vec2_at(const core::Config& config, const std::string& path) {
52 const auto x = config.number(path + ".0");
53 const auto y = config.number(path + ".1");
54 if (!x || !y || config.contains(path + ".2") || !std::isfinite(*x) || !std::isfinite(*y)) {
55 throw core::ConfigError{path + ": must be [x, y]"};
56 }
57 return Vec2{static_cast<float>(*x), static_cast<float>(*y)};
58}
59
60} // namespace detail
61
92public:
94 WaveSchedule() = default;
95
102 [[nodiscard]] static WaveSchedule from_config(const core::Config& config,
103 std::span<const std::string_view> types = {}) {
104 WaveSchedule schedule;
105 float previous_end = 0.0F;
106 for (std::size_t wave = 0; config.contains(detail::at_index("waves", wave)); ++wave) {
107 const std::string path = detail::at_index("waves", wave);
108 const float begin = previous_end + detail::seconds_at(config, path + ".delay", 0.0F);
109 const std::string groups = path + ".spawns";
110 if (!config.contains(groups + ".0")) {
111 throw core::ConfigError{groups + ": a wave needs at least one spawn"};
112 }
113 float end = begin;
114 for (std::size_t group = 0; config.contains(detail::at_index(groups, group)); ++group) {
115 end = std::max(end, schedule.add_group(config, detail::at_index(groups, group),
116 wave, begin, types));
117 }
118 previous_end = end;
119 ++schedule.waves_;
120 }
121 if (schedule.waves_ == 0) {
122 throw core::ConfigError{"waves: needs a list of at least one wave"};
123 }
124 std::ranges::stable_sort(schedule.spawns_, {}, &WaveSpawn::time);
125 schedule.duration_ = schedule.spawns_.back().time;
126 if (config.contains("loop")) {
127 const auto loop = config.boolean("loop");
128 if (!loop) {
129 throw core::ConfigError{"loop: must be true or false"};
130 }
131 schedule.loop_ = *loop;
132 }
133 if (schedule.loop_ && !(schedule.duration_ > 0.0F)) {
134 throw core::ConfigError{"loop: the waves must last more than 0 s to loop"};
135 }
136 return schedule;
137 }
138
144 [[nodiscard]] static WaveSchedule from_string(std::string_view text,
145 std::span<const std::string_view> types = {}) {
146 return from_config(core::Config::from_string(text), types);
147 }
148
155 [[nodiscard]] static WaveSchedule from_file(const std::filesystem::path& path,
156 std::span<const std::string_view> types = {}) {
157 const core::Config config = core::Config::from_file(path);
158 try {
159 return from_config(config, types);
160 } catch (const core::ConfigError& error) {
161 throw core::ConfigError{path.string() + ": " + error.what()};
162 }
163 }
164
170 void update(const Tick& tick, std::vector<WaveSpawn>& due) {
171 due.clear();
172 elapsed_ += tick.delta();
173 while (true) {
174 while (next_ < spawns_.size() && spawns_.at(next_).time <= elapsed_) {
175 due.push_back(spawns_.at(next_));
176 ++next_;
177 }
178 if (!loop_ || next_ < spawns_.size()) {
179 return;
180 }
181 elapsed_ -= duration_;
182 next_ = 0;
183 }
184 }
185
187 void restart() noexcept {
188 elapsed_ = 0.0F;
189 next_ = 0;
190 }
191
194 [[nodiscard]] bool finished() const noexcept { return !loop_ && next_ >= spawns_.size(); }
195
198 [[nodiscard]] const std::vector<WaveSpawn>& spawns() const noexcept { return spawns_; }
199
202 [[nodiscard]] std::size_t waves() const noexcept { return waves_; }
203
206 [[nodiscard]] bool loops() const noexcept { return loop_; }
207
210 [[nodiscard]] float duration() const noexcept { return duration_; }
211
214 [[nodiscard]] float elapsed() const noexcept { return elapsed_; }
215
216private:
217 float add_group(const core::Config& config, const std::string& path, std::size_t wave,
218 float begin, std::span<const std::string_view> types) {
219 const auto type = config.string(path + ".type");
220 if (!type || type->empty()) {
221 throw core::ConfigError{path + ".type: must be the name of an entity type"};
222 }
223 if (!types.empty() && std::ranges::find(types, std::string_view{*type}) == types.end()) {
224 std::string known;
225 for (const std::string_view name : types) {
226 known += known.empty() ? "" : ", ";
227 known += name;
228 }
229 throw core::ConfigError{path + ".type: unknown type \"" + *type +
230 "\" (known: " + known + ")"};
231 }
232 const Vec2 position = detail::vec2_at(config, path + ".position");
233 const float at = detail::seconds_at(config, path + ".at", 0.0F);
234 const float every = detail::seconds_at(config, path + ".every", 0.0F);
235 const Vec2 step =
236 config.contains(path + ".step") ? detail::vec2_at(config, path + ".step") : Vec2{};
237 std::int64_t count = 1;
238 if (config.contains(path + ".count")) {
239 const auto value = config.integer(path + ".count");
240 if (!value || *value < 1 || *value > max_group) {
241 throw core::ConfigError{path + ".count: must be a whole number from 1 to " +
242 std::to_string(max_group)};
243 }
244 count = *value;
245 }
246 float last = begin;
247 for (std::int64_t member = 0; member < count; ++member) {
248 const auto index = static_cast<float>(member);
249 const float time = begin + at + (every * index);
250 spawns_.push_back(WaveSpawn{
251 .type = *type, .position = position + (step * index), .wave = wave, .time = time});
252 last = std::max(last, time);
253 }
254 return last;
255 }
256
257 static constexpr std::int64_t max_group = 1000;
258
259 std::vector<WaveSpawn> spawns_;
260 std::size_t waves_ = 0;
261 bool loop_ = false;
262 float duration_ = 0.0F;
263 float elapsed_ = 0.0F;
264 std::size_t next_ = 0;
265};
266
267} // namespace aegis2d::ecs
Thrown when a configuration cannot be read or parsed.
Definition config.hpp:23
JSON configuration file (server port, window size...) read through typed getters.
Definition config.hpp:58
static Config from_file(const std::filesystem::path &path)
Reads and parses a JSON file.
std::optional< std::string > string(std::string_view path) const
Reads a string.
std::optional< bool > boolean(std::string_view path) const
Reads a boolean.
std::optional< std::int64_t > integer(std::string_view path) const
Reads an integer.
std::optional< double > number(std::string_view path) const
Reads a number, integer or not.
bool contains(std::string_view path) const
Tells whether a value exists at path, whatever its type.
static Config from_string(std::string_view text)
Parses JSON text.
Enemy waves from a data file: which entities appear, where and when.
Definition waves.hpp:91
static WaveSchedule from_string(std::string_view text, std::span< const std::string_view > types={})
Reads a schedule from JSON text.
Definition waves.hpp:144
static WaveSchedule from_config(const core::Config &config, std::span< const std::string_view > types={})
Reads a schedule from a loaded configuration.
Definition waves.hpp:102
float elapsed() const noexcept
Time spent in the schedule (in the current loop).
Definition waves.hpp:214
float duration() const noexcept
Time of the last spawn.
Definition waves.hpp:210
const std::vector< WaveSpawn > & spawns() const noexcept
Every spawn of the schedule.
Definition waves.hpp:198
WaveSchedule()=default
Creates an empty schedule, finished from the start.
void update(const Tick &tick, std::vector< WaveSpawn > &due)
Moves time forward by one tick and lists the spawns that fall in it.
Definition waves.hpp:170
bool loops() const noexcept
Tells whether the schedule starts again after its last spawn.
Definition waves.hpp:206
std::size_t waves() const noexcept
Number of waves in the file.
Definition waves.hpp:202
static WaveSchedule from_file(const std::filesystem::path &path, std::span< const std::string_view > types={})
Reads a schedule from a JSON file, e.g. core::asset_path("waves/stage1.json").
Definition waves.hpp:155
void restart() noexcept
Goes back to the start of the schedule.
Definition waves.hpp:187
bool finished() const noexcept
Tells whether every spawn has been listed.
Definition waves.hpp:194
JSON configuration with dotted-path lookups, which can be changed and saved.
Vector and matrix types of the engine (GLM behind engine names).
Vec2 vec2_at(const core::Config &config, const std::string &path)
Definition waves.hpp:51
float seconds_at(const core::Config &config, const std::string &path, float fallback)
Definition waves.hpp:39
std::string at_index(std::string_view parent, std::size_t index)
Definition waves.hpp:35
Entity-Component-System used by client and server.
Definition animation.hpp:13
std::string_view name() noexcept
Name of the module, used to check that it is linked.
glm::vec2 Vec2
2D vector of floats: positions, velocities, sizes (glm::vec2).
Definition math.hpp:19
One simulation step, as the systems see it.
Definition system.hpp:23
constexpr float delta() const noexcept
Duration of the step in seconds, to scale values given per second.
Definition system.hpp:32
One entity a WaveSchedule makes appear.
Definition waves.hpp:21
float time
When it appears, in seconds from the start of the schedule (of each loop).
Definition waves.hpp:30
std::size_t wave
Index of its wave in the file, from 0.
Definition waves.hpp:28
Vec2 position
Where it appears, in logical pixels.
Definition waves.hpp:26
std::string type
Name of the entity type, as written in the file (e.g. "grunt"); the game maps it to its creation func...
Definition waves.hpp:24
Systems and the scheduler that updates them in order, once per tick.