nanoMMO 0.97.8
Building an MMO: The Engineering Series
Loading...
Searching...
No Matches
monsters.cc
Go to the documentation of this file.
1#include "server/monsters.h"
2
3#include <algorithm>
4#include <array>
5#include <chrono>
6#include <cmath>
7#include <cstdint>
8#include <map>
9#include <numbers>
10#include <utility>
11#include <vector>
12
13#include "terrain/lands.h"
14
15namespace nanommo {
16
17namespace {
18
19constexpr float kCampsFromTheMiddle = 30.0f;
20
21// So many places tried for each camp, before the land counts as full.
22constexpr int kTriesEach = 50;
23
24// Above the beach, and below the rock.
25constexpr float kLowestCamp = 1.0f;
26constexpr float kHighestCamp = 10.0f;
27
28// Where each camp's three monsters stand, from the middle of the camp.
29constexpr std::array<std::pair<float, float>, 3> kCampLayout = {{
30 {-1.5f, 0.0f},
31 {1.5f, 0.5f},
32 {0.0f, -1.5f},
33}};
34
35// The square root spreads the places evenly, not bunched up around home.
36void PickTarget(Monster& monster, const Terrain& terrain,
37 std::mt19937& random) {
38 std::uniform_real_distribution<float> unit(0.0f, 1.0f);
39 const float angle = 2.0f * std::numbers::pi_v<float> * unit(random);
40 const float distance = monster.wander * std::sqrt(unit(random));
41 monster.target_x = std::clamp(monster.home_x + distance * std::sin(angle),
42 -terrain.edge(), terrain.edge());
43 monster.target_z = std::clamp(monster.home_z + distance * std::cos(angle),
44 -terrain.edge(), terrain.edge());
45}
46
47// Whether the monster uses the skill, by its id, now: a boss, only if its
48// phase does.
49bool Uses(const Monster& monster, uint32_t skill) {
50 if (!monster.boss()) {
51 return true;
52 }
53 const auto& skills = monster.phases[monster.phase].skills();
54 return std::ranges::find(skills, skill) != skills.end();
55}
56
57// Runs a boss home, at the players' running speed. Once it's there, or
58// something's in its way, it's home, so that a tree can't keep it from
59// starting again, and it rests.
60void GoHome(Monster& monster, const Terrain& terrain,
61 std::chrono::nanoseconds time, std::mt19937& random) {
62 const float dx = monster.home_x - monster.x;
63 const float dz = monster.home_z - monster.z;
64 const float distance = std::hypot(dx, dz);
65 const float step =
66 World::kRunSpeed * std::chrono::duration<float>(time).count();
67 const float x = monster.x;
68 const float z = monster.z;
69 if (distance > step) {
70 Walk(terrain, monster.x, monster.z, x + dx / distance * step,
71 z + dz / distance * step);
72 monster.yaw = std::atan2(dx, dz);
73 monster.motion = Motion::kRun;
74 }
75 if (distance <= step || (monster.x == x && monster.z == z)) {
76 monster.x = monster.home_x;
77 monster.z = monster.home_z;
78 monster.evading = false;
79 monster.motion = Motion::kIdle;
80 monster.rest = RandomRest(random);
81 }
82}
83
84} // namespace
85
86Monster MonsterOf(const monsters::Kind& kind, float x, float z) {
87 const monsters::Fight& fight = kind.fight();
88 return {.kind = kind.id(),
89 .x = x,
90 .z = z,
91 .level = static_cast<int>(kind.level()),
92 .max_health = static_cast<int>(kind.max_health()),
93 .experience = kind.experience(),
94 .damage = static_cast<int>(fight.damage()),
95 .swing_time = std::chrono::milliseconds(fight.swing_ms()),
96 .hit_time = std::chrono::milliseconds(fight.hit_ms()),
97 .reach = fight.reach(),
98 .sight = fight.sight(),
99 .leash = fight.leash(),
100 .wander = fight.wander(),
101 .skills = {kind.skills().begin(), kind.skills().end()},
102 .phases = {kind.phases().begin(), kind.phases().end()},
103 .respawn_time = kind.respawn_ms() > 0
104 ? std::chrono::milliseconds(kind.respawn_ms())
106}
107
108void SpawnMonsters(World& land, int index, const MonsterTable& table) {
109 for (const monsters::Spawn& spawn : table.spawns) {
110 if (LandNamed(spawn.land()) == index) {
111 land.Spawn(MonsterOf(table.kinds.at(spawn.kind()), spawn.x(), spawn.z()));
112 }
113 }
114 const Terrain& terrain = land.terrain();
115 for (const monsters::Camps& camps : table.camps) {
116 if (LandNamed(camps.land()) != index) {
117 continue;
118 }
119 const monsters::Kind& kind = table.kinds.at(camps.kind());
120 for (const auto& [camp_x, camp_z] :
121 Camps(terrain, static_cast<int>(camps.count()))) {
122 for (const auto& [x, z] : kCampLayout) {
123 if (terrain.Walkable(camp_x + x, camp_z + z)) {
124 land.Spawn(MonsterOf(kind, camp_x + x, camp_z + z));
125 }
126 }
127 }
128 }
129}
130
131std::vector<std::pair<float, float>> Camps(const Terrain& terrain, int count) {
132 std::mt19937 random(terrain.seed());
133 std::uniform_real_distribution<float> place(-terrain.edge(), terrain.edge());
134 std::vector<std::pair<float, float>> camps;
135 // Darts thrown at the land: a place too near a camp we have is thrown
136 // again, as is one in the sea, so the camps spread over the land evenly,
137 // where places picked at random alone bunch up and leave gaps.
138 const auto spaced = [&camps](float x, float z) {
139 return std::ranges::none_of(camps, [x, z](const auto& camp) {
140 return std::hypot(camp.first - x, camp.second - z) < kCampSpacing;
141 });
142 };
143 for (int tries = 0; tries < kTriesEach * count && std::ssize(camps) < count;
144 ++tries) {
145 const float x = place(random);
146 const float z = place(random);
147 const float height = terrain.Height(x, z);
148 if (std::hypot(x, z) >= kCampsFromTheMiddle && height >= kLowestCamp &&
149 height <= kHighestCamp && terrain.Walkable(x, z) && spaced(x, z)) {
150 camps.emplace_back(x, z);
151 }
152 }
153 return camps;
154}
155
156std::chrono::nanoseconds RandomRest(std::mt19937& random) {
157 std::uniform_int_distribution<int> ms(kShortestRest.count(),
158 kLongestRest.count());
159 return std::chrono::milliseconds(ms(random));
160}
161
162void Wander(Monster& monster, const Terrain& terrain,
163 std::chrono::nanoseconds time, std::mt19937& random) {
164 if (monster.motion == Motion::kIdle) {
165 monster.rest -= time;
166 if (monster.rest > std::chrono::nanoseconds::zero()) {
167 return;
168 }
169 PickTarget(monster, terrain, random);
170 monster.motion = Motion::kWalk;
171 }
172
173 const float dx = monster.target_x - monster.x;
174 const float dz = monster.target_z - monster.z;
175 const float distance = std::hypot(dx, dz);
176 const float step =
177 World::kWalkSpeed * std::chrono::duration<float>(time).count();
178 const float x = monster.x;
179 const float z = monster.z;
180 if (distance <= step) {
181 Walk(terrain, monster.x, monster.z, monster.target_x, monster.target_z);
182 } else {
183 Walk(terrain, monster.x, monster.z, x + dx / distance * step,
184 z + dz / distance * step);
185 monster.yaw = std::atan2(dx, dz);
186 }
187 // There, or stuck at the sea, it rests before it picks another place.
188 if (distance <= step || (monster.x == x && monster.z == z)) {
189 monster.motion = Motion::kIdle;
190 monster.rest = RandomRest(random);
191 }
192}
193
194uint32_t Spot(const Monster& monster,
195 const std::map<uint32_t, Player>& players) {
196 const auto in_leash = [&monster](const Player& player) {
197 return player.motion != Motion::kDead &&
198 std::hypot(player.x - monster.home_x, player.z - monster.home_z) <=
199 monster.leash;
200 };
201 // Seen or not, so that a kick that knocks it out of sight doesn't make it
202 // forget them. On a tie, it keeps to the one it's fighting.
203 uint32_t hated = 0;
204 int most = 0;
205 for (const auto& [id, threat] : monster.threat) {
206 const auto player = players.find(id);
207 if (player != players.end() && in_leash(player->second) &&
208 (threat > most || (threat == most && id == monster.prey))) {
209 hated = id;
210 most = threat;
211 }
212 }
213 if (hated != 0) {
214 return hated;
215 }
216 uint32_t nearest = 0;
217 float closest = monster.sight;
218 for (const auto& [id, player] : players) {
219 const float away = std::hypot(player.x - monster.x, player.z - monster.z);
220 if (in_leash(player) && away <= closest) {
221 nearest = id;
222 closest = away;
223 }
224 }
225 return nearest;
226}
227
228void Hunt(Monster& monster, const std::map<uint32_t, Player>& players,
229 const Terrain& terrain, std::chrono::nanoseconds time,
230 std::mt19937& random) {
231 if (monster.evading) {
232 GoHome(monster, terrain, time, random);
233 return;
234 }
235 monster.prey = Spot(monster, players);
236 // Once everyone who's hurt it has died, left or got past its leash, it
237 // forgets them. A boss goes home to start again, healed, so that a fight
238 // that's lost doesn't leave it weaker for the next.
239 if (!monster.threat.empty() && !monster.threat.contains(monster.prey)) {
240 monster.threat.clear();
241 if (monster.boss()) {
242 monster.evading = true;
243 monster.health = monster.max_health;
244 monster.phase = 0;
245 monster.prey = 0;
246 GoHome(monster, terrain, time, random);
247 return;
248 }
249 }
250 if (monster.prey == 0) {
251 if (monster.motion == Motion::kRun) {
252 monster.motion = Motion::kIdle;
253 monster.rest = RandomRest(random);
254 }
255 Wander(monster, terrain, time, random);
256 return;
257 }
258
259 const Player& player = players.at(monster.prey);
260 const float dx = player.x - monster.x;
261 const float dz = player.z - monster.z;
262 const float distance = std::hypot(dx, dz);
263 monster.yaw = std::atan2(dx, dz);
264 // A skill that's ready goes in place of a swing: the monster stands where
265 // it is, facing the player, while the skill's shape shows. A boss uses its
266 // phase's.
267 for (const monsters::Skill& skill : monster.skills) {
268 if (Uses(monster, skill.id()) && distance <= skill.range() &&
269 !monster.cooldowns.contains(skill.id())) {
270 monster.motion = Motion::kSkill;
271 monster.casting = skill;
272 monster.cast = std::chrono::nanoseconds::zero();
273 monster.cast_x = monster.x;
274 monster.cast_z = monster.z;
275 monster.cooldowns[skill.id()] =
276 std::chrono::milliseconds(skill.cooldown_ms());
277 return;
278 }
279 }
280 if (distance <= monster.reach) {
281 monster.motion = Motion::kAttack;
282 monster.swing = std::chrono::nanoseconds::zero();
283 return;
284 }
285 const float step =
286 std::min(World::kRunSpeed * std::chrono::duration<float>(time).count(),
287 distance - monster.reach);
288 Walk(terrain, monster.x, monster.z, monster.x + dx / distance * step,
289 monster.z + dz / distance * step);
290 monster.motion = Motion::kRun;
291}
292
293void Revive(Monster& monster, std::chrono::nanoseconds time,
294 std::mt19937& random) {
295 monster.respawn -= time;
296 if (monster.respawn > std::chrono::nanoseconds::zero()) {
297 return;
298 }
299 monster.x = monster.home_x;
300 monster.z = monster.home_z;
301 monster.health = monster.max_health;
302 monster.phase = 0;
303 monster.motion = Motion::kIdle;
304 monster.threat.clear();
305 monster.rest = RandomRest(random);
306}
307
308} // namespace nanommo
float edge() const
Half a metre short of each side, so that players stay on the grid.
Definition terrain.h:91
uint32_t seed() const
Definition terrain.h:82
float Height(float x, float z) const
On the triangles between the grid's corners, as the client draws them.
Definition terrain.cc:102
bool Walkable(float x, float z) const
Definition terrain.cc:123
const Terrain & terrain() const
Definition world.h:516
static constexpr std::chrono::seconds kRespawnTime
Definition world.h:329
uint32_t Spawn(Monster monster)
Definition world.cc:685
static constexpr float kWalkSpeed
As walking.h has them, which the monsters go at too.
Definition world.h:319
static constexpr float kRunSpeed
Definition world.h:320
Definition chat.cc:9
constexpr std::chrono::milliseconds kLongestRest
Definition monsters.h:18
std::chrono::nanoseconds RandomRest(std::mt19937 &random)
Definition monsters.cc:156
constexpr float kCampSpacing
In metres between the middles of two camps, at least.
Definition monsters.h:27
void Wander(Monster &monster, const Terrain &terrain, std::chrono::nanoseconds time, std::mt19937 &random)
Definition monsters.cc:162
void SpawnMonsters(World &land, int index, const MonsterTable &table)
Definition monsters.cc:108
int LandNamed(std::string_view name)
Its place in the list, or the first land's for a name that isn't there.
Definition lands.cc:10
void Hunt(Monster &monster, const std::map< uint32_t, Player > &players, const Terrain &terrain, std::chrono::nanoseconds time, std::mt19937 &random)
Definition monsters.cc:228
void Walk(const Terrain &terrain, float &x, float &z, float to_x, float to_z)
Definition walking.cc:8
constexpr std::chrono::milliseconds kShortestRest
Definition monsters.h:17
Monster MonsterOf(const monsters::Kind &kind, float x, float z)
Definition monsters.cc:86
std::vector< std::pair< float, float > > Camps(const Terrain &terrain, int count)
Definition monsters.cc:131
void Revive(Monster &monster, std::chrono::nanoseconds time, std::mt19937 &random)
Definition monsters.cc:293
uint32_t Spot(const Monster &monster, const std::map< uint32_t, Player > &players)
Definition monsters.cc:194
The kinds of monster, by id, and where they spawn.
Definition monsters.h:17
std::vector< monsters::Spawn > spawns
Definition monsters.h:19
std::map< uint32_t, monsters::Kind > kinds
Definition monsters.h:18
std::vector< monsters::Camps > camps
Definition monsters.h:20
uint32_t prey
Definition world.h:188
std::chrono::nanoseconds rest
Definition world.h:187
std::map< uint32_t, std::chrono::nanoseconds > cooldowns
How long until each skill it's used is ready again, by its id.
Definition world.h:205
std::vector< monsters::Skill > skills
Definition world.h:174
std::chrono::nanoseconds swing
Definition world.h:196
std::chrono::nanoseconds cast
Definition world.h:201
float reach
In metres, from its kind's fight.
Definition world.h:167
std::chrono::nanoseconds respawn
Definition world.h:209
std::size_t phase
Definition world.h:178
Motion motion
Definition world.h:158
bool boss() const
A monster with phases is a boss.
Definition world.h:229
float target_z
Definition world.h:186
float target_x
Definition world.h:185
std::map< uint32_t, int > threat
Definition world.h:192
monsters::Skill casting
Definition world.h:200