nanoMMO 0.97.8
Building an MMO: The Engineering Series
Loading...
Searching...
No Matches
world.cc
Go to the documentation of this file.
1#include "server/world.h"
2
3#include <algorithm>
4#include <chrono>
5#include <cmath>
6#include <cstddef>
7#include <iterator>
8#include <limits>
9#include <map>
10#include <memory>
11#include <numbers>
12#include <optional>
13#include <random>
14#include <set>
15#include <string>
16#include <string_view>
17#include <utility>
18#include <vector>
19
20#include "absl/strings/match.h"
21#include "absl/strings/str_cat.h"
22#include "content/factions.h"
23#include "protocol/messages.h"
24#include "server/levels.h"
25#include "server/monsters.h"
26#include "tracy/Tracy.hpp"
27
28namespace nanommo {
29
30namespace {
31
32// For the monster a player picked, wherever it is.
33constexpr float kAnyDistance = std::numeric_limits<float>::infinity();
34
35// Whether the skill hurts the one monster the player picked: it does damage,
36// and not to all around them. A heal doesn't.
37bool OneMonster(const skills::Effect& effect) {
38 return effect.damage() > 0 && !effect.all();
39}
40
41float Distance(const Player& player, const Monster& monster) {
42 return std::hypot(monster.x - player.x, monster.z - player.z);
43}
44
45float Distance(const Player& a, const Player& b) {
46 return std::hypot(b.x - a.x, b.z - a.z);
47}
48
49float Distance(const Player& player, Place place) {
50 return std::hypot(place.x - player.x, place.z - player.z);
51}
52
53// Where the unit is, a monster or a player, by its id among them, while it's
54// alive and within reach of the player, or nothing.
55template <typename Unit>
56std::optional<Place> Within(const std::map<uint32_t, Unit>& units, uint32_t id,
57 const Player& player, float reach) {
58 const auto found = units.find(id);
59 if (found == units.end() || found->second.motion == Motion::kDead ||
60 Distance(player, found->second) > reach) {
61 return std::nullopt;
62 }
63 return Place{.x = found->second.x, .z = found->second.z};
64}
65
66// What's offered in a trade stays where it is until the trade's over, as the
67// trade takes it from there.
68absl::Status Offered() {
69 return Refusal(absl::StatusCode::kFailedPrecondition,
70 Msg("You can't, while it's offered in your trade."));
71}
72
73// Why a player who's dead can't.
74absl::Status Dead() {
75 return Refusal(absl::StatusCode::kFailedPrecondition,
76 Msg("You can't, while you're dead."));
77}
78
79// Whether the unit, a monster or a duel's opponent, is within the slice in
80// front of the player, as wide as the arc, in degrees. Without one, it's all
81// the way round.
82template <typename Unit>
83bool InArc(const Player& player, const Unit& unit, float arc) {
84 if (arc <= 0.0f) {
85 return true;
86 }
87 const float toward = std::atan2(unit.x - player.x, unit.z - player.z);
88 const float off =
89 std::remainder(toward - player.yaw, 2.0f * std::numbers::pi_v<float>);
90 return std::abs(off) <= arc / 2.0f * std::numbers::pi_v<float> / 180.0f;
91}
92
93// Whether the monster's health has fallen to the phase's share of its most.
94bool FallenTo(const Monster& monster, const monsters::Phase& phase) {
95 return monster.health * 100 <=
96 monster.max_health * static_cast<int>(phase.health());
97}
98
99void RunDown(std::map<uint32_t, std::chrono::nanoseconds>& cooldowns,
100 std::chrono::nanoseconds time) {
101 for (auto it = cooldowns.begin(); it != cooldowns.end();) {
102 it->second -= time;
103 it = it->second <= std::chrono::nanoseconds::zero() ? cooldowns.erase(it)
104 : std::next(it);
105 }
106}
107
108void Add(Stats& stats, const items::Modifier& modifier) {
109 switch (modifier.stat()) {
110 case items::STAT_DAMAGE:
111 stats.damage += modifier.amount();
112 break;
113 case items::STAT_HEALTH:
114 stats.health += modifier.amount();
115 break;
116 case items::STAT_ARMOUR:
117 stats.armour += modifier.amount();
118 break;
119 default:
120 break;
121 }
122}
123
124// "A", "A and B", or "A, B and C", of one thing or more, in the client's
125// language too: from the end, the last two in a sentence, and each before
126// them in a sentence with the rest.
127Part List(std::vector<Part> things) {
128 Part list = std::move(things.back());
129 things.pop_back();
130 if (!things.empty()) {
131 // Translators: The last two of a list, such as what a monster dropped.
132 list = Of(Msg("$0 and $1", std::move(things.back()), std::move(list)));
133 things.pop_back();
134 }
135 while (!things.empty()) {
136 // Translators: One of a list, and the rest of it after a comma.
137 list = Of(Msg("$0, $1", std::move(things.back()), std::move(list)));
138 things.pop_back();
139 }
140 return list;
141}
142
143// So much gold, as loot.
144Part Gold(uint32_t gold) { return Of(MsgN("$0 gold", "$0 gold", gold, gold)); }
145
146} // namespace
147
148int MaxHealthOf(const Player& player) {
149 return MaxHealth(LevelFor(player.experience).number) + player.stats.health;
150}
151
152namespace {
153
154// Adds to the player's experience, and heals them fully as they reach a new
155// level. Returns whether they did. A boss's helpers who died in the fight get
156// their share too, and come back at full health anyway.
157bool Gain(Player& player, uint32_t experience) {
158 const int level = LevelFor(player.experience).number;
159 player.experience += experience;
160 if (LevelFor(player.experience).number > level) {
161 if (player.motion != Motion::kDead) {
162 player.health = MaxHealthOf(player);
163 }
164 return true;
165 }
166 return false;
167}
168
169// "30 seconds", "a minute" or "2 minutes".
170Sentence InWords(std::chrono::nanoseconds time) {
171 const auto seconds = static_cast<uint64_t>(
172 std::chrono::duration_cast<std::chrono::seconds>(time).count());
173 // Translators: How long until a boss rises again.
174 if (seconds % 60 != 0) {
175 return MsgN("$0 second", "$0 seconds", seconds, seconds);
176 }
177 // Translators: How long until a boss rises again.
178 return MsgN("a minute", "$0 minutes", seconds / 60, seconds / 60);
179}
180
181} // namespace
182
183Part Of(const Npc& npc) {
184 protocol::Arg arg;
185 arg.set_npc(npc.kind);
186 return {.arg = std::move(arg), .english = npc.name};
187}
188
189uint32_t MainHandOf(const Player& player) {
190 const items::Stack* held = player.inventory.At(Worn(items::SLOT_MAIN_HAND));
191 return held != nullptr ? held->item() : 0;
192}
193
194std::vector<uint32_t> WornOf(const Player& player) {
195 std::vector<uint32_t> worn;
196 for (const items::Slot slot :
197 {items::SLOT_OFF_HAND, items::SLOT_HEAD, items::SLOT_BODY,
198 items::SLOT_LEGS, items::SLOT_FEET}) {
199 if (const items::Stack* item = player.inventory.At(Worn(slot))) {
200 worn.push_back(item->item());
201 }
202 }
203 return worn;
204}
205
207 std::shared_ptr<const Content> content,
208 std::shared_ptr<Paths> paths)
209 : terrain_(std::move(terrain)),
210 content_(std::move(content)),
211 paths_(paths != nullptr ? std::move(paths)
212 : std::make_shared<Paths>(terrain_)),
213 random_(seed) {}
214
215void World::Join(uint32_t id, Player player) {
216 // What they picked, the way they walked, and what they were making, were
217 // another land's.
218 player.target = 0;
219 player.target_player = 0;
220 player.way.clear();
221 player.crafting = 0;
222 // Saved somewhere that's sea now, such as on a terrain from another seed.
223 if (!terrain_.Walkable(player.x, player.z)) {
224 player.x = 0.0f;
225 player.z = 0.0f;
226 }
227 // A bag that's never had a revision has never been anyone's: a new player,
228 // or one from before bags, gets the kit, once, which a trip through a gate
229 // doesn't give them again.
230 const ItemTable& items = content_->items;
231 if (player.inventory.revision() == 0) {
232 for (const items::Stack& stack : items.starting) {
233 if (!player.inventory.Wear(items, stack)) {
234 player.inventory.Add(items, stack);
235 }
236 }
237 }
238 // The kit's items get their serials here, and so do those from before
239 // serials, the first time they're back.
240 player.inventory.Number(items);
241 Dress(player);
242 // Zero when none was saved, as for a player from before we kept health.
243 if (player.health <= 0) {
244 player.health = MaxHealthOf(player);
245 }
246 player.skills.insert(content_->skills.starting.begin(),
247 content_->skills.starting.end());
248 players_[id] = std::move(player);
249}
250
251void World::Leave(uint32_t id) {
252 // Both have to be here to trade, or to duel.
253 const Part gone = Name(players_.at(id).name);
254 if (const uint32_t other = trades_.End(id); other != 0) {
255 Tell(other, Msg("$0 has gone, so the trade's off.", gone));
256 }
257 if (const uint32_t other = duels_.End(id); other != 0) {
258 Tell(other, Msg("$0 has gone, so the duel's off.", gone));
259 }
260 players_.erase(id);
261 history_.Leave(id);
262}
263
264absl::Status World::MoveItem(uint32_t id, const protocol::Place& from,
265 const protocol::Place& to, uint32_t count) {
266 const auto found = players_.find(id);
267 if (found == players_.end()) {
268 return Refusal(absl::StatusCode::kNotFound,
269 Msg("There's nobody to move it."));
270 }
271 if (trades_.Holds(id, from) || trades_.Holds(id, to)) {
272 return Offered();
273 }
274 Player& player = found->second;
275 const absl::Status moved =
276 player.inventory.Move(content_->items, from, to, count);
277 if (moved.ok() && (from.has_worn() || to.has_worn())) {
278 Dress(player);
279 }
280 return moved;
281}
282
283absl::Status World::DestroyItem(uint32_t id, const protocol::Place& place) {
284 const auto found = players_.find(id);
285 if (found == players_.end()) {
286 return Refusal(absl::StatusCode::kNotFound,
287 Msg("There's nobody to throw it away."));
288 }
289 if (trades_.Holds(id, place)) {
290 return Offered();
291 }
292 Player& player = found->second;
293 const absl::Status destroyed = player.inventory.Destroy(place);
294 if (destroyed.ok() && place.has_worn()) {
295 Dress(player);
296 }
297 return destroyed;
298}
299
300absl::Status World::UseItem(uint32_t id, uint32_t slot) {
301 const auto found = players_.find(id);
302 if (found == players_.end()) {
303 return Refusal(absl::StatusCode::kNotFound,
304 Msg("There's nobody to use it."));
305 }
306 Player& player = found->second;
307 const protocol::Place place = InBag(slot);
308 if (trades_.Holds(id, place)) {
309 return Offered();
310 }
311 const items::Stack* stack = player.inventory.At(place);
312 if (stack == nullptr) {
313 return Refusal(absl::StatusCode::kNotFound, Msg("There's nothing there."));
314 }
315 const auto item = content_->items.by_id.find(stack->item());
316 if (item == content_->items.by_id.end()) {
317 return Refusal(absl::StatusCode::kFailedPrecondition,
318 Msg("You can't use that."));
319 }
320 if (!item->second.has_use()) {
321 return Refusal(absl::StatusCode::kFailedPrecondition,
322 Msg("You can't use the $0.", Of(item->second)));
323 }
324 const items::Use& use = item->second.use();
325 if (player.motion == Motion::kDead) {
326 return Dead();
327 }
328 const auto cooling = player.item_cooldowns.find(item->first);
329 if (cooling != player.item_cooldowns.end()) {
330 // Translators: $1 is how many seconds, and s their symbol.
331 return Refusal(
332 absl::StatusCode::kFailedPrecondition,
333 Msg("You can use another $0 in $1 s.", Of(item->second),
334 std::chrono::ceil<std::chrono::seconds>(cooling->second).count()));
335 }
336 if (use.heal() > 0 && player.health >= MaxHealthOf(player)) {
337 return Refusal(absl::StatusCode::kFailedPrecondition,
338 Msg("You're at full health already."));
339 }
340 Heal(id, player, static_cast<int>(use.heal()));
341 if (use.cooldown_ms() > 0) {
342 player.item_cooldowns[item->first] =
343 std::chrono::milliseconds(use.cooldown_ms());
344 }
345 Event& used = Record(Event::Kind::kUse, id, player);
346 used.item = item->first;
347 used.count = 1;
348 return player.inventory.TakeOne(place);
349}
350
351absl::Status World::Craft(uint32_t id, uint32_t recipe) {
352 const auto player = players_.find(id);
353 const auto found = content_->recipes.find(recipe);
354 if (player == players_.end() || found == content_->recipes.end()) {
355 return Refusal(absl::StatusCode::kNotFound, Msg("There's no such recipe."));
356 }
357 const recipes::Recipe& making = found->second;
358 if (player->second.motion == Motion::kDead) {
359 return Dead();
360 }
361 if (player->second.crafting != 0) {
362 return Refusal(absl::StatusCode::kAlreadyExists,
363 Msg("You're making something already."));
364 }
365 if (LevelFor(player->second.experience).number <
366 static_cast<int>(making.level())) {
367 return Refusal(absl::StatusCode::kFailedPrecondition,
368 Msg("You can make $0 from level $1.",
369 Of(content_->items, making.output().item(),
370 making.output().count()),
371 making.level()));
372 }
373 // The same check as once it's made, so that it says now what's missing.
374 if (const absl::StatusOr<Inventory> bag = Made(id, player->second, making);
375 !bag.ok()) {
376 return bag.status();
377 }
378 player->second.crafting = recipe;
379 player->second.crafted = std::chrono::nanoseconds::zero();
380 return absl::OkStatus();
381}
382
383void World::StopCrafting(uint32_t id) {
384 const auto found = players_.find(id);
385 if (found != players_.end()) {
386 Interrupt(id, found->second);
387 }
388}
389
390absl::Status World::AskToTrade(uint32_t id, std::string_view name) {
391 const auto player = players_.find(id);
392 const auto other = std::ranges::find_if(players_, [name](const auto& entry) {
393 return absl::EqualsIgnoreCase(entry.second.name, name);
394 });
395 if (player == players_.end() || other == players_.end()) {
396 return Refusal(absl::StatusCode::kNotFound,
397 Msg("Nobody of that name is here."));
398 }
399 if (other == player) {
400 return Refusal(absl::StatusCode::kInvalidArgument,
401 Msg("You can't trade with yourself."));
402 }
403 const Part asker = Name(player->second.name);
404 const Part asked = Name(other->second.name);
405 if (Distance(player->second, other->second) > kTradeReach) {
406 return Refusal(absl::StatusCode::kOutOfRange,
407 Msg("You're too far away to trade with $0.", asked));
408 }
409 if (trades_.With(id) != 0) {
410 return Refusal(absl::StatusCode::kFailedPrecondition,
411 Msg("You're trading already."));
412 }
413 if (trades_.With(other->first) != 0) {
414 return Refusal(absl::StatusCode::kFailedPrecondition,
415 Msg("$0 is trading with someone already.", asked));
416 }
417 if (!trades_.Ask(id, other->first)) {
418 // Translators: /trade is the chat's command, which stays as it is.
419 Tell(other->first,
420 Msg("$0 asks to trade. Type /trade $0 to say yes.", asker));
421 Tell(id, Msg("You asked $0 to trade.", asked));
422 } else {
423 // A trade holds what each offers, which may be what they're making
424 // something from, so both stop.
425 Interrupt(id, player->second);
426 Interrupt(other->first, other->second);
427 }
428 return absl::OkStatus();
429}
430
431absl::Status World::OfferToTrade(uint32_t id,
432 const protocol::TradeOffer& offer) {
433 const auto player = players_.find(id);
434 if (player == players_.end()) {
435 return Refusal(absl::StatusCode::kNotFound,
436 Msg("There's nobody to trade."));
437 }
438 return trades_.Offer(id, player->second.inventory, content_->items, offer);
439}
440
441absl::StatusOr<uint32_t> World::ReadyToTrade(uint32_t id, bool ready,
442 uint32_t revision) {
443 const uint32_t other = trades_.With(id);
444 if (other == 0) {
445 return Refusal(absl::StatusCode::kFailedPrecondition,
446 Msg("You're not trading with anyone."));
447 }
448 Player& player = players_.at(id);
449 Player& them = players_.at(other);
450 if (ready && Distance(player, them) > kTradeReach) {
451 return Refusal(
452 absl::StatusCode::kOutOfRange,
453 Msg("You're too far away to trade with $0.", Name(them.name)));
454 }
455 const absl::StatusOr<bool> both = trades_.Ready(id, ready, revision);
456 if (!both.ok()) {
457 return both.status();
458 }
459 if (!*both) {
460 return 0;
461 }
462 // Both are ready, so they trade, here and now.
463 const absl::Status traded =
464 trades_.Complete(id, player.inventory, them.inventory, content_->items);
465 if (!traded.ok()) {
466 Tell(other, SentenceOf(traded));
467 return traded;
468 }
469 Tell(id, Msg("You traded with $0.", Name(them.name)));
470 Tell(other, Msg("You traded with $0.", Name(player.name)));
471 return other;
472}
473
474void World::CancelTrade(uint32_t id) {
475 if (const uint32_t other = trades_.End(id); other != 0) {
476 Tell(other, Msg("$0 called the trade off.", Name(players_.at(id).name)));
477 }
478}
479
480protocol::Trade World::TradeOf(uint32_t id) const {
481 protocol::Trade trade;
482 if (const uint32_t other = trades_.With(id); other != 0) {
483 trade.set_partner(players_.at(other).name);
484 *trade.mutable_yours() = trades_.SideOf(id);
485 *trade.mutable_theirs() = trades_.SideOf(other);
486 trade.set_revision(trades_.RevisionOf(id));
487 }
488 return trade;
489}
490
491std::set<uint32_t> World::TakeTradeNews() { return trades_.TakeNews(); }
492
493absl::Status World::AskToDuel(uint32_t id, std::string_view name) {
494 const auto player = players_.find(id);
495 const auto other = std::ranges::find_if(players_, [name](const auto& entry) {
496 return absl::EqualsIgnoreCase(entry.second.name, name);
497 });
498 if (player == players_.end() || other == players_.end()) {
499 return Refusal(absl::StatusCode::kNotFound,
500 Msg("Nobody of that name is here."));
501 }
502 if (other == player) {
503 return Refusal(absl::StatusCode::kInvalidArgument,
504 Msg("You can't duel yourself."));
505 }
506 // Asking back the one who asked is a yes.
507 if (const Duels::Duel* duel = duels_.Of(id);
508 duel != nullptr && duel->state == Duels::State::kAsked &&
509 duel->challenged == id && duel->challenger == other->first) {
510 return AnswerDuel(id, true);
511 }
512 const Part asker = Name(player->second.name);
513 const Part asked = Name(other->second.name);
514 if (Distance(player->second, other->second) > Duels::kReach) {
515 return Refusal(absl::StatusCode::kOutOfRange,
516 Msg("You're too far away to duel $0.", asked));
517 }
518 if (duels_.Of(id) != nullptr) {
519 return Refusal(absl::StatusCode::kFailedPrecondition,
520 Msg("You're in a duel already."));
521 }
522 if (duels_.Of(other->first) != nullptr) {
523 return Refusal(absl::StatusCode::kFailedPrecondition,
524 Msg("$0 is in a duel already.", asked));
525 }
526 duels_.Ask(id, other->first);
527 // Translators: /duel yes is the chat's command, which stays as it is.
528 Tell(other->first,
529 Msg("$0 asks you to duel. Type /duel yes to say yes.", asker));
530 Tell(id, Msg("You asked $0 to duel.", asked));
531 return absl::OkStatus();
532}
533
534absl::Status World::AnswerDuel(uint32_t id, bool yes) {
535 const Duels::Duel* duel = duels_.Of(id);
536 if (duel == nullptr || duel->challenged != id ||
537 duel->state != Duels::State::kAsked) {
538 return Refusal(absl::StatusCode::kNotFound,
539 Msg("Nobody's asked you to duel."));
540 }
541 const uint32_t asker = duel->challenger;
542 const Player& challenger = players_.at(asker);
543 const Player& player = players_.at(id);
544 if (!yes) {
545 duels_.End(id);
546 Tell(asker, Msg("$0 said no to a duel.", Name(player.name)));
547 return absl::OkStatus();
548 }
549 // They may have walked apart while the ask waited.
550 if (Distance(player, challenger) > Duels::kReach) {
551 return Refusal(
552 absl::StatusCode::kOutOfRange,
553 Msg("You're too far away to duel $0.", Name(challenger.name)));
554 }
555 duels_.Accept(id, {.x = challenger.x, .z = challenger.z});
556 // Both stop what they were making, to fight.
557 Interrupt(id, players_.at(id));
558 Interrupt(asker, players_.at(asker));
559 return absl::OkStatus();
560}
561
562absl::Status World::Yield(uint32_t id) {
563 const Duels::Duel* duel = duels_.Of(id);
564 if (duel == nullptr) {
565 return Refusal(absl::StatusCode::kNotFound, Msg("You're not in a duel."));
566 }
567 if (duel->state == Duels::State::kFighting) {
568 Lose(id);
569 return absl::OkStatus();
570 }
571 const uint32_t other = duels_.End(id);
572 Tell(other, Msg("$0 called the duel off.", Name(players_.at(id).name)));
573 return absl::OkStatus();
574}
575
576uint32_t World::CallOffDuel(uint32_t id) { return duels_.End(id); }
577
578protocol::Duel World::DuelOf(uint32_t id) const {
579 protocol::Duel shown;
580 const Duels::Duel* duel = duels_.Of(id);
581 if (duel == nullptr) {
582 return shown;
583 }
584 const uint32_t other = duel->Against(id);
585 shown.set_opponent(players_.at(other).name);
586 shown.set_opponent_id(other);
587 switch (duel->state) {
589 shown.set_state(duel->challenger == id ? protocol::DUEL_ASKING
590 : protocol::DUEL_ASKED);
591 return shown;
593 shown.set_state(protocol::DUEL_COUNTDOWN);
594 shown.set_countdown(static_cast<uint32_t>(
595 std::chrono::duration_cast<std::chrono::milliseconds>(duel->left)
596 .count()));
597 break;
599 shown.set_state(protocol::DUEL_FIGHTING);
600 break;
601 }
602 shown.mutable_flag()->set_x(duel->flag.x);
603 shown.mutable_flag()->set_z(duel->flag.z);
604 return shown;
605}
606
607std::set<uint32_t> World::TakeDuelNews() { return duels_.TakeNews(); }
608
609void World::SetGuild(uint32_t id, uint32_t guild) {
610 const auto found = players_.find(id);
611 if (found != players_.end()) {
612 found->second.guild = guild;
613 }
614}
615
616void World::SetWars(const std::vector<War>& wars) {
617 wars_.clear();
618 for (const War& war : wars) {
619 wars_[war.challenger] = war;
620 wars_[war.challenged] = war;
621 }
622}
623
624bool World::Hostile(uint32_t id, uint32_t other) const {
625 const auto player = players_.find(id);
626 const auto them = players_.find(other);
627 if (player == players_.end() || them == players_.end() || other == id) {
628 return false;
629 }
630 return other == duels_.Opponent(id) ||
631 WarBetween(player->second, them->second) != nullptr;
632}
633
634const War* World::WarBetween(const Player& player, const Player& other) const {
635 // Nobody's at war with a player in no guild, whose guild is 0.
636 const auto war = wars_.find(player.guild);
637 if (war == wars_.end() || war->second.Against(player.guild) != other.guild) {
638 return nullptr;
639 }
640 return &war->second;
641}
642
643std::vector<WarKill> World::TakeWarKills() {
644 return std::exchange(war_kills_, {});
645}
646
647void World::Dress(Player& player) const {
648 const items::Weapon* before = player.stats.weapon;
649 // Whether the skill they're using has landed its first blow, with the
650 // weapon they held for it.
651 bool landed = false;
652 if (player.motion == Motion::kSkill) {
653 const skills::Effect& effect = player.effect;
654 const uint32_t first =
655 effect.blows_size() > 0 ? effect.blows(0).at_ms() : effect.hit_ms();
656 landed = player.cast >= std::chrono::milliseconds(first);
657 }
658 player.stats = {};
659 for (const auto& [slot, stack] : player.inventory.items().worn()) {
660 const auto item = content_->items.by_id.find(stack.item());
661 if (item == content_->items.by_id.end()) {
662 continue;
663 }
664 for (const items::Modifier& modifier : item->second.equip().modifiers()) {
665 Add(player.stats, modifier);
666 }
667 for (const items::Modifier& roll : stack.rolls()) {
668 Add(player.stats, roll);
669 }
670 if (slot == items::SLOT_MAIN_HAND && item->second.has_weapon()) {
671 player.stats.weapon = &item->second.weapon();
672 }
673 }
674 // Less to wear can mean less health to have, and a swing with a weapon
675 // that's been put away is over, before its blow lands. After, it plays out,
676 // with the effect it started with, as putting the weapon away and back
677 // would end it early, for the next swing to start sooner.
678 player.health = std::min(player.health, MaxHealthOf(player));
679 if (player.motion == Motion::kSkill && player.stats.weapon != before &&
680 !landed && content_->skills.by_id.at(player.skill).effect().weapon()) {
681 player.motion = Motion::kIdle;
682 }
683}
684
685uint32_t World::Spawn(Monster monster) {
686 monster.home_x = monster.x;
687 monster.home_z = monster.z;
688 monster.health = monster.max_health;
689 // A rest of its own, so that the monsters don't all set off together.
690 monster.rest = RandomRest(random_);
691 const uint32_t id = next_monster_++;
692 monsters_[id] = monster;
693 return id;
694}
695
696uint32_t World::Spawn(Npc npc) {
697 const uint32_t id = next_npc_++;
698 npcs_[id] = std::move(npc);
699 return id;
700}
701
702void World::SetInput(uint32_t id, float x, float z, bool run, bool attack) {
703 const auto found = players_.find(id);
704 if (found == players_.end() || !std::isfinite(x) || !std::isfinite(z)) {
705 return;
706 }
707 // So that moving diagonally isn't faster, and a modified client can't ask
708 // for more speed.
709 const float length = std::hypot(x, z);
710 if (length > 1.0f) {
711 x /= length;
712 z /= length;
713 }
714 found->second.input_x = x;
715 found->second.input_z = z;
716 found->second.input_run = run;
717 found->second.input_attack = attack;
718}
719
720void World::Pick(uint32_t id, uint32_t monster, uint32_t player) {
721 const auto found = players_.find(id);
722 if (found == players_.end()) {
723 return;
724 }
725 // A player they may hurt goes in place of a monster, and anyone else is
726 // nobody.
727 const bool hostile = player != 0 && Hostile(id, player);
728 found->second.target = hostile ? 0 : monster;
729 found->second.target_player = hostile ? player : 0;
730}
731
732void World::SetBehind(uint32_t id, std::chrono::nanoseconds behind) {
733 const auto found = players_.find(id);
734 if (found != players_.end()) {
735 found->second.behind = behind;
736 }
737}
738
739void World::Respawn(uint32_t id) {
740 const auto found = players_.find(id);
741 if (found == players_.end()) {
742 return;
743 }
744 Player& player = found->second;
745 if (player.motion != Motion::kDead ||
746 player.respawn > std::chrono::nanoseconds::zero()) {
747 return;
748 }
749 player.x = 0.0f;
750 player.z = 0.0f;
751 player.motion = Motion::kIdle;
752 player.health = MaxHealthOf(player);
753}
754
755void World::WalkTo(uint32_t id, Place to) {
756 ZoneScoped;
757 const auto found = players_.find(id);
758 if (found == players_.end() || found->second.motion == Motion::kDead ||
759 !std::isfinite(to.x) || !std::isfinite(to.z)) {
760 return;
761 }
762 Player& player = found->second;
763 const std::vector<Place> way = paths_->Find({player.x, player.z}, to);
764 player.way.assign(way.begin(), way.end());
765}
766
767void World::UseSkill(uint32_t id, uint32_t skill) {
768 const auto found = players_.find(id);
769 if (found != players_.end()) {
770 found->second.input_skill = skill;
771 }
772}
773
774absl::Status World::Learn(uint32_t id, uint32_t npc, uint32_t skill) {
775 const auto player = players_.find(id);
776 const auto trainer = npcs_.find(npc);
777 const auto taught = content_->skills.by_id.find(skill);
778 if (player == players_.end() || trainer == npcs_.end() ||
779 !trainer->second.teaches.contains(skill) ||
780 taught == content_->skills.by_id.end()) {
781 return Refusal(absl::StatusCode::kNotFound,
782 Msg("Nobody here teaches that."));
783 }
784 if (std::hypot(trainer->second.x - player->second.x,
785 trainer->second.z - player->second.z) > kTalkReach) {
786 return Refusal(
787 absl::StatusCode::kOutOfRange,
788 Msg("You're too far away to learn from the $0.", Of(trainer->second)));
789 }
790 const uint32_t level = taught->second.level();
791 if (LevelFor(player->second.experience).number < static_cast<int>(level)) {
792 return Refusal(
793 absl::StatusCode::kFailedPrecondition,
794 Msg("You can learn $0 from level $1.", Of(taught->second), level));
795 }
796 if (player->second.skills.contains(skill)) {
797 return Refusal(absl::StatusCode::kAlreadyExists,
798 Msg("You know $0 already.", Of(taught->second)));
799 }
800 player->second.skills.insert(skill);
801 return absl::OkStatus();
802}
803
804absl::Status World::TakeQuest(uint32_t id, uint32_t npc, uint32_t quest) {
805 const auto player = players_.find(id);
806 const auto giver = npcs_.find(npc);
807 const auto given = content_->quests.find(quest);
808 if (player == players_.end() || giver == npcs_.end() ||
809 given == content_->quests.end() ||
810 given->second.giver() != giver->second.kind) {
811 return Refusal(absl::StatusCode::kNotFound,
812 Msg("Nobody here gives that quest."));
813 }
814 if (std::hypot(giver->second.x - player->second.x,
815 giver->second.z - player->second.z) > kTalkReach) {
816 // Translators: $0 is an NPC, as "Guard".
817 return Refusal(
818 absl::StatusCode::kOutOfRange,
819 Msg("You're too far away to talk to the $0.", Of(giver->second)));
820 }
821 if (player->second.quests.contains(quest)) {
822 return Refusal(absl::StatusCode::kAlreadyExists,
823 Msg("You're on $0 already.", Of(given->second)));
824 }
825 if (player->second.quests_done.contains(quest)) {
826 return Refusal(absl::StatusCode::kAlreadyExists,
827 Msg("You've done $0 already.", Of(given->second)));
828 }
829 player->second.quests[quest] = 0;
830 ++player->second.quests_revision;
831 Record(Event::Kind::kTake, id, player->second).quest = quest;
832 return absl::OkStatus();
833}
834
835absl::Status World::Enlist(uint32_t id, uint32_t npc) {
836 const auto player = players_.find(id);
837 const auto herald = npcs_.find(npc);
838 const factions::Faction* faction =
839 herald != npcs_.end() ? HeraldOf(content_->factions, herald->second.kind)
840 : nullptr;
841 if (player == players_.end() || faction == nullptr) {
842 return Refusal(absl::StatusCode::kNotFound,
843 Msg("Nobody here swears players to a faction."));
844 }
845 if (std::hypot(herald->second.x - player->second.x,
846 herald->second.z - player->second.z) > kTalkReach) {
847 return Refusal(
848 absl::StatusCode::kOutOfRange,
849 Msg("You're too far away to talk to the $0.", Of(herald->second)));
850 }
851 // For now, there's no leaving a faction, nor swearing to another.
852 if (const auto sworn = content_->factions.find(player->second.faction);
853 sworn != content_->factions.end()) {
854 // Translators: $0 is a faction, as "Concordia".
855 return Refusal(absl::StatusCode::kAlreadyExists,
856 Msg("You're sworn to $0 already.", Of(sworn->second)));
857 }
858 player->second.faction = faction->id();
859 // Translators: $0 is a faction, as "Concordia".
860 Tell(id, Msg("You've joined $0.", Of(*faction)));
861 return absl::OkStatus();
862}
863
864absl::Status World::GiveUp(uint32_t id, uint32_t quest) {
865 const auto player = players_.find(id);
866 if (player == players_.end() || !player->second.quests.contains(quest)) {
867 return Refusal(absl::StatusCode::kNotFound,
868 Msg("You're not on that quest."));
869 }
870 player->second.quests.erase(quest);
871 ++player->second.quests_revision;
872 return absl::OkStatus();
873}
874
875absl::Status World::TurnIn(uint32_t id, uint32_t npc, uint32_t quest) {
876 const auto player = players_.find(id);
877 const auto giver = npcs_.find(npc);
878 const auto given = content_->quests.find(quest);
879 if (player == players_.end() || giver == npcs_.end() ||
880 given == content_->quests.end() ||
881 given->second.giver() != giver->second.kind) {
882 return Refusal(absl::StatusCode::kNotFound,
883 Msg("Nobody here takes that quest."));
884 }
885 if (std::hypot(giver->second.x - player->second.x,
886 giver->second.z - player->second.z) > kTalkReach) {
887 return Refusal(
888 absl::StatusCode::kOutOfRange,
889 Msg("You're too far away to talk to the $0.", Of(giver->second)));
890 }
891 const quests::Quest& done = given->second;
892 const auto on = player->second.quests.find(quest);
893 if (on == player->second.quests.end()) {
894 return Refusal(absl::StatusCode::kNotFound,
895 Msg("You're not on $0.", Of(done)));
896 }
897 if (on->second < done.kill().count()) {
898 // Translators: $0 is the quest, $1 how many kills it asks for, and $2 how
899 // many there have been.
900 return Refusal(absl::StatusCode::kFailedPrecondition,
901 Msg("$0 asks for $1, and you've killed $2.", Of(done),
902 done.kill().count(), on->second));
903 }
904 // The prizes go into a copy of the bag, so that it's all of them or none.
905 Inventory bag = player->second.inventory;
906 std::vector<Part> prizes = {Of(MsgN("$0 experience", "$0 experience",
907 done.experience(), done.experience()))};
908 for (const quests::Prize& prize : done.prizes()) {
909 const auto item = content_->items.by_id.find(prize.item());
910 if (item == content_->items.by_id.end()) {
911 continue;
912 }
913 if (Give(bag, prize.item(), prize.count()) < prize.count()) {
914 return Refusal(absl::StatusCode::kResourceExhausted,
915 Msg("Your bag is full. Make room for the prizes first."));
916 }
917 prizes.push_back(Of(item->second, prize.count()));
918 }
919 player->second.inventory = std::move(bag);
920 Record(Event::Kind::kTurnIn, id, player->second).quest = quest;
921 for (const quests::Prize& prize : done.prizes()) {
922 Event& given = Record(Event::Kind::kPrize, id, player->second);
923 given.quest = quest;
924 given.item = prize.item();
925 given.count = prize.count();
926 }
927 if (Gain(player->second, done.experience())) {
928 Record(Event::Kind::kLevel, id, player->second).level =
929 static_cast<uint32_t>(LevelFor(player->second.experience).number);
930 }
931 player->second.quests.erase(on);
932 player->second.quests_done.insert(quest);
933 ++player->second.quests_revision;
934 // Translators: $0 is the quest, and $1 its prizes, as "100 experience and a
935 // Bone".
936 Tell(id, Msg("You've done $0, for $1.", Of(done), List(std::move(prizes))));
937 return absl::OkStatus();
938}
939
940void World::Step(std::chrono::nanoseconds time) {
941 ZoneScoped;
942 // The time this step takes the world to, as the worlds sent after it will
943 // show it.
944 clock_ += time;
945 for (auto& [id, player] : players_) {
946 Act(id, player, time);
947 }
948 // Called up while the blows land, adds would be hit by the blow that called
949 // them, so they come once they've all landed.
950 for (const auto& [boss, phase] : std::exchange(calls_, {})) {
951 CallAdds(boss, phase);
952 }
953 for (auto& [id, monster] : monsters_) {
954 Act(monster, time);
955 }
956 // An add goes once its boss is back in its first phase, at home or alive
957 // again, so that the next fight starts without it.
958 std::erase_if(monsters_, [this](const auto& entry) {
959 const uint32_t boss = entry.second.called_by;
960 if (boss == 0) {
961 return false;
962 }
963 const auto found = monsters_.find(boss);
964 return found == monsters_.end() ||
965 (found->second.motion != Motion::kDead && found->second.phase == 0);
966 });
967 Referee(time);
968 for (const auto& [id, player] : players_) {
969 history_.Record(id, clock_, {.x = player.x, .z = player.z});
970 }
971}
972
973void World::Act(uint32_t id, Player& player, std::chrono::nanoseconds time) {
974 // Cooldowns run down whatever the player's doing.
975 RunDown(player.cooldowns, time);
976 RunDown(player.item_cooldowns, time);
977 // A skill moves them as it goes, and the dead don't move.
978 player.steered =
979 player.motion == Motion::kSkill || player.motion == Motion::kDead;
980 // The dead wait, and then stay down until they ask to come back.
981 if (player.motion == Motion::kDead) {
982 player.input_skill = 0;
983 player.respawn =
984 std::max(player.respawn - time, std::chrono::nanoseconds::zero());
985 return;
986 }
987 if (player.motion == Motion::kSkill) {
988 const skills::Effect& effect = player.effect;
989 const auto before = player.cast;
990 player.cast += time;
991 Stride(player, effect);
992 // A skill without blows of its own lands once, at its hit.
993 skills::Blow once;
994 once.set_at_ms(effect.hit_ms());
995 once.set_push(effect.push());
996 const int blows = std::max(effect.blows_size(), 1);
997 for (int index = 0; index < blows; ++index) {
998 const skills::Blow& blow =
999 effect.blows_size() > 0 ? effect.blows(index) : once;
1000 const std::chrono::milliseconds hit(blow.at_ms());
1001 const bool armed =
1002 !effect.weapon() || player.stats.weapon == player.cast_weapon;
1003 if (before < hit && player.cast >= hit && armed) {
1004 Land(id, player, effect, blow, index, blows);
1005 }
1006 }
1007 if (player.cast < std::chrono::milliseconds(effect.cast_ms())) {
1008 return;
1009 }
1010 player.motion = Motion::kIdle;
1011 // A swing that goes on into another leaves a moment to use it.
1012 const skills::Skill& done = content_->skills.by_id.at(player.skill);
1013 player.chain = done.next();
1014 player.chain_left = std::chrono::milliseconds(done.window_ms());
1015 }
1016 player.chain_left =
1017 std::max(player.chain_left - time, std::chrono::nanoseconds::zero());
1018 // Space is the skill everyone has, a swing of what they hold, and the next
1019 // in its chain while there's time to use it.
1020 if (player.input_attack && player.input_skill == 0) {
1021 player.input_skill =
1022 player.chain != 0 &&
1023 player.chain_left > std::chrono::nanoseconds::zero()
1024 ? player.chain
1025 : content_->skills.attack;
1026 }
1027 // A skill asked for while the player was busy waits until now, and one they
1028 // can't use yet goes. A swing or a skill at the monster they picked, out of
1029 // reach, runs them up to it first, unless they walk off themselves.
1030 const bool walking = player.input_x != 0.0f || player.input_z != 0.0f;
1031 // What they're making goes on while they stand still, and moving, a swing
1032 // or a skill stops it.
1033 if (walking || !player.way.empty() || player.input_skill != 0) {
1034 Interrupt(id, player);
1035 } else {
1036 Make(id, player, time);
1037 }
1038 // The keys, a swing or a skill call off a walk the player asked for.
1039 if (walking || player.input_skill != 0) {
1040 player.way.clear();
1041 }
1042 if (player.input_skill != 0) {
1043 const skills::Skill* skill = Usable(player, player.input_skill);
1044 const skills::Effect effect =
1045 skill != nullptr ? EffectOf(player, *skill) : skills::Effect();
1046 const bool far = OneMonster(effect) &&
1047 Target(player, kAnyDistance).has_value() &&
1048 !Target(player, effect.reach()).has_value();
1049 if (skill != nullptr && !far) {
1050 player.input_skill = 0;
1051 Start(player, *skill);
1052 return;
1053 }
1054 if (skill != nullptr && !walking) {
1055 Approach(player, effect.reach(), time);
1056 return;
1057 }
1058 player.input_skill = 0;
1059 }
1060 if (!player.way.empty()) {
1061 Follow(player, time);
1062 return;
1063 }
1064 Move(player, time);
1065}
1066
1067void World::Move(Player& player, std::chrono::nanoseconds time) {
1068 Go(player, player.input_x, player.input_z, player.input_run, time);
1069}
1070
1071void World::Go(Player& player, float to_x, float to_z, bool run,
1072 std::chrono::nanoseconds time) {
1073 float x = player.x;
1074 float z = player.z;
1075 WalkAlong(terrain_, x, z, to_x, to_z, run,
1076 std::chrono::duration<float>(time).count());
1077 // Motion comes from how far it actually went, so that a player pushing
1078 // against the edge or the sea stands still, instead of walking on the spot.
1079 const float dx = x - player.x;
1080 const float dz = z - player.z;
1081 if (dx == 0.0f && dz == 0.0f) {
1082 player.motion = Motion::kIdle;
1083 } else {
1084 player.motion = run ? Motion::kRun : Motion::kWalk;
1085 player.yaw = std::atan2(dx, dz);
1086 }
1087 player.x = x;
1088 player.z = z;
1089}
1090
1091void World::Follow(Player& player, std::chrono::nanoseconds time) {
1092 player.steered = true;
1093 const Place next = player.way.front();
1094 const float distance = std::hypot(next.x - player.x, next.z - player.z);
1095 const float step = kRunSpeed * std::chrono::duration<float>(time).count();
1096 if (distance > 0.0f) {
1097 // The last step to each place is shorter, so that it stops there.
1098 const float share = std::min(distance / step, 1.0f);
1099 const float x = player.x;
1100 const float z = player.z;
1101 Go(player, (next.x - x) / distance * share, (next.z - z) / distance * share,
1102 true, time);
1103 // Something the squares missed is in the way after all: they stop.
1104 if (player.x == x && player.z == z) {
1105 player.way.clear();
1106 return;
1107 }
1108 }
1109 if (distance <= step) {
1110 player.way.pop_front();
1111 }
1112}
1113
1114void World::Approach(Player& player, float reach,
1115 std::chrono::nanoseconds time) {
1116 player.steered = true;
1117 const std::optional<Place> to = Target(player, kAnyDistance);
1118 if (!to) {
1119 return;
1120 }
1121 const float distance = std::hypot(to->x - player.x, to->z - player.z);
1122 const float step = kRunSpeed * std::chrono::duration<float>(time).count();
1123 // The last step is shorter, so that it stops within the reach.
1124 const float share =
1125 std::clamp((distance - reach * kCloseIn) / step, 0.0f, 1.0f);
1126 Go(player, (to->x - player.x) / distance * share,
1127 (to->z - player.z) / distance * share, true, time);
1128}
1129
1130std::optional<Place> World::Target(const Player& player, float reach) const {
1131 if (player.target_player == 0) {
1132 return Within(monsters_, player.target, player, reach);
1133 }
1134 // A player is where the player saw them, as for their blows, so that's
1135 // what they aim at, and run up to.
1136 if (!Within(players_, player.target_player, player, kAnyDistance)) {
1137 return std::nullopt;
1138 }
1139 const Place seen = Seen(player, player.target_player);
1140 if (Distance(player, seen) > reach) {
1141 return std::nullopt;
1142 }
1143 return seen;
1144}
1145
1146Place World::Seen(const Player& player, uint32_t other) const {
1147 if (player.behind > std::chrono::nanoseconds::zero()) {
1148 if (const std::optional<Place> then =
1149 history_.At(other, clock_ - player.behind)) {
1150 return *then;
1151 }
1152 }
1153 const Player& them = players_.at(other);
1154 return {.x = them.x, .z = them.z};
1155}
1156
1157// Turns the player towards what they picked, if it's within reach. Without
1158// it, they swing at the air the way they face.
1159void World::Aim(Player& player, float reach) {
1160 if (const std::optional<Place> at = Target(player, reach)) {
1161 player.yaw = std::atan2(at->x - player.x, at->z - player.z);
1162 }
1163}
1164
1165const skills::Skill* World::Usable(const Player& player, uint32_t id) const {
1166 const auto found = content_->skills.by_id.find(id);
1167 if (found == content_->skills.by_id.end() || !player.skills.contains(id) ||
1168 player.cooldowns.contains(id)) {
1169 return nullptr;
1170 }
1171 const skills::Effect& effect = found->second.effect();
1172 if (effect.weapon()
1173 ? player.stats.weapon == nullptr
1174 : OneMonster(effect) && !Target(player, kAnyDistance).has_value()) {
1175 return nullptr;
1176 }
1177 return &found->second;
1178}
1179
1180skills::Effect World::EffectOf(const Player& player,
1181 const skills::Skill& skill) const {
1182 skills::Effect effect = skill.effect();
1183 const items::Weapon* weapon = player.stats.weapon;
1184 if (effect.weapon() && weapon != nullptr) {
1185 const float pace = effect.pace() > 0.0f ? effect.pace() : 1.0f;
1186 auto paced = [pace](uint32_t whole) {
1187 return static_cast<uint32_t>(
1188 std::lround(pace * static_cast<float>(whole)));
1189 };
1190 effect.set_reach(weapon->reach());
1191 effect.set_damage(std::max(paced(weapon->damage()), 1u));
1192 effect.set_cast_ms(paced(weapon->swing_ms()));
1193 effect.set_hit_ms(paced(weapon->hit_ms()));
1194 }
1195 return effect;
1196}
1197
1198void World::Start(Player& player, const skills::Skill& skill) {
1199 player.motion = Motion::kSkill;
1200 player.skill = skill.id();
1201 player.cast = std::chrono::nanoseconds::zero();
1202 // Any skill uses up the chain, which the swing's end starts again.
1203 player.chain = 0;
1204 ++player.casts;
1205 player.effect = EffectOf(player, skill);
1206 player.cast_weapon = player.stats.weapon;
1207 if (skill.cooldown_ms() > 0) {
1208 player.cooldowns[skill.id()] =
1209 std::chrono::milliseconds(skill.cooldown_ms());
1210 }
1211 Aim(player, player.effect.reach());
1212 player.cast_x = player.x;
1213 player.cast_z = player.z;
1214}
1215
1216// Along the way they faced as it started, which Aim turned them to, and like
1217// a walk where something's in the way.
1218void World::Stride(Player& player, const skills::Effect& effect) {
1219 if (effect.strides_size() == 0) {
1220 return;
1221 }
1222 const float ahead = AheadAt(
1223 effect, std::chrono::duration<float, std::milli>(player.cast).count());
1224 const float edge = terrain_.edge();
1225 Walk(terrain_, player.x, player.z,
1226 std::clamp(player.cast_x + std::sin(player.yaw) * ahead, -edge, edge),
1227 std::clamp(player.cast_z + std::cos(player.yaw) * ahead, -edge, edge));
1228}
1229
1230void World::Land(uint32_t id, Player& player, const skills::Effect& effect,
1231 const skills::Blow& blow, int index, int blows) {
1232 const int level = LevelFor(player.experience).number;
1233 if (index == 0) {
1234 Heal(id, player, static_cast<int>(effect.heal()));
1235 }
1236 if (effect.damage() == 0) {
1237 return;
1238 }
1239 // The blows share the damage, and the last takes what doesn't divide. A
1240 // quick swing takes its share of what the level and the gear add, as it does
1241 // of the weapon's.
1242 const float pace =
1243 effect.weapon() && effect.pace() > 0.0f ? effect.pace() : 1.0f;
1244 const int total =
1245 static_cast<int>(effect.damage()) +
1246 static_cast<int>(std::lround(
1247 pace * static_cast<float>(ExtraDamage(level) + player.stats.damage)));
1248 const int damage = total / blows + (index == blows - 1 ? total % blows : 0);
1249 // A boss on its way home can't be hurt, so that nobody wears it down from
1250 // past its leash.
1251 for (auto& [monster_id, monster] : monsters_) {
1252 if ((effect.all() || monster_id == player.target) &&
1253 monster.motion != Motion::kDead && !monster.evading &&
1254 Distance(player, monster) <= effect.reach() &&
1255 InArc(player, monster, effect.arc())) {
1256 // A boss stands its ground: a crowd's blows would shove it about, and
1257 // out of its own leash.
1258 if (!monster.boss()) {
1259 Push(player, monster, blow.push());
1260 Throw(monster, blow.lift());
1261 }
1262 Hurt(id, player, monster_id, monster, damage);
1263 }
1264 }
1265 // The players they may hurt too, their opponent in a duel and enemies at
1266 // war, each when it's for them or all around, but a player isn't pushed or
1267 // thrown, as their own keys move them. A player can run from a blow as fast
1268 // as the one who swung, so it's checked against where the player's client
1269 // drew them, a moment in the past. A monster's hit where it is, above, as
1270 // it's pushed and thrown from there: it stands still to swing, and comes to
1271 // whoever hurt it, so where a client drew it a moment ago is near enough.
1272 // Most blows are by players in neither a duel nor a war, who can't hurt a
1273 // player.
1274 if (duels_.Opponent(id) == 0 && !wars_.contains(player.guild)) {
1275 return;
1276 }
1277 for (auto& [other, them] : players_) {
1278 if ((!effect.all() && other != player.target_player) ||
1279 them.motion == Motion::kDead || !Hostile(id, other)) {
1280 continue;
1281 }
1282 const Place seen = Seen(player, other);
1283 if (Distance(player, seen) <= effect.reach() &&
1284 InArc(player, seen, effect.arc())) {
1285 Hurt(id, other, them, damage);
1286 }
1287 }
1288}
1289
1290// Away from the player. A push that comes while another is going on starts
1291// again from where the monster is.
1292void World::Push(const Player& player, Monster& monster, float metres) {
1293 const float distance = Distance(player, monster);
1294 if (metres == 0.0f || distance == 0.0f) {
1295 return;
1296 }
1297 monster.pushed_from_x = monster.x;
1298 monster.pushed_from_z = monster.z;
1299 monster.push_x = (monster.x - player.x) / distance * metres;
1300 monster.push_z = (monster.z - player.z) / distance * metres;
1301 monster.pushed = std::chrono::nanoseconds::zero();
1302}
1303
1304// Like a walk: where the sea or a tree is in the way, it slides along it, or
1305// stays put. Each tick goes to where the push has reached by then, eased out,
1306// so that it's fast at first and slows to a stop at its whole length.
1307bool World::Slide(Monster& monster, std::chrono::nanoseconds time) {
1308 if (monster.pushed >= kPushTime) {
1309 return false;
1310 }
1311 monster.pushed =
1312 std::min<std::chrono::nanoseconds>(monster.pushed + time, kPushTime);
1313 const float done = std::chrono::duration<float>(monster.pushed) /
1314 std::chrono::duration<float>(kPushTime);
1315 const float eased = 1.0f - (1.0f - done) * (1.0f - done);
1316 const float edge = terrain_.edge();
1317 Walk(terrain_, monster.x, monster.z,
1318 std::clamp(monster.pushed_from_x + monster.push_x * eased, -edge, edge),
1319 std::clamp(monster.pushed_from_z + monster.push_z * eased, -edge, edge));
1320 return true;
1321}
1322
1323// As a ball thrown straight up: fast at first, slowing to the top, and back
1324// down.
1325void World::Throw(Monster& monster, float lift) {
1326 const bool flying = monster.height > 0.0f || monster.rise > 0.0f;
1327 // Long enough up, or just down, nothing throws it up again, though a blow
1328 // can still dash it down.
1329 const bool spent = flying ? monster.in_air >= kMostInAir
1330 : monster.steady > std::chrono::nanoseconds::zero();
1331 if (spent && lift >= 0.0f) {
1332 return;
1333 }
1334 // Up to the lift's height off the ground, however high it is already, so
1335 // that blow after blow doesn't send it ever higher.
1336 if (lift > monster.height) {
1337 monster.rise = std::max(
1338 monster.rise, std::sqrt(2.0f * kGravity * (lift - monster.height)));
1339 } else if (lift < 0.0f && flying) {
1340 monster.rise = -std::sqrt(2.0f * kGravity * -lift);
1341 } else if (flying) {
1342 monster.rise = std::max(monster.rise, kPop);
1343 } else {
1344 return;
1345 }
1346 // Thrown, it drops the swing or the skill it was in the middle of.
1347 if (monster.motion == Motion::kAttack || monster.motion == Motion::kSkill) {
1348 monster.motion = Motion::kIdle;
1349 }
1350}
1351
1352bool World::Fly(Monster& monster, std::chrono::nanoseconds time) {
1353 if (monster.height <= 0.0f && monster.rise <= 0.0f) {
1354 monster.steady =
1355 std::max(monster.steady - time, std::chrono::nanoseconds::zero());
1356 return false;
1357 }
1358 monster.in_air += time;
1359 // Its time up there's over: it goes no higher.
1360 if (monster.in_air >= kMostInAir) {
1361 monster.rise = std::min(monster.rise, 0.0f);
1362 }
1363 const float seconds = std::chrono::duration<float>(time).count();
1364 monster.height += (monster.rise - kGravity * seconds / 2.0f) * seconds;
1365 monster.rise -= kGravity * seconds;
1366 if (monster.height <= 0.0f) {
1367 monster.height = 0.0f;
1368 monster.rise = 0.0f;
1369 monster.in_air = std::chrono::nanoseconds::zero();
1370 monster.steady = kSteady;
1371 return false;
1372 }
1373 return true;
1374}
1375
1376void World::Hurt(uint32_t id, Player& player, uint32_t monster_id,
1377 Monster& monster, int damage) {
1378 // What the blow takes is the player's threat, which the monster goes by.
1379 const int taken = std::min(damage, monster.health);
1380 monster.threat[id] += taken;
1381 monster.health -= taken;
1382 Event& hit = Record(Event::Kind::kHit, id, player);
1383 hit.monster = monster.kind;
1384 hit.monster_id = monster_id;
1385 hit.amount = static_cast<uint32_t>(damage);
1386 if (monster.health > 0) {
1387 // A boss goes into each phase its health has fallen to, in turn.
1388 while (monster.phase + 1 < monster.phases.size() &&
1389 FallenTo(monster, monster.phases[monster.phase + 1])) {
1390 ++monster.phase;
1391 calls_.emplace_back(monster_id, monster.phase);
1392 }
1393 return;
1394 }
1395 monster.motion = Motion::kDead;
1396 monster.respawn = monster.respawn_time;
1397 // A boss's adds fall with it.
1398 for (auto& [add_id, add] : monsters_) {
1399 if (add.called_by == monster_id) {
1400 add.health = 0;
1401 add.motion = Motion::kDead;
1402 }
1403 }
1404 if (!monster.boss()) {
1405 Reward(id, player, monster);
1406 return;
1407 }
1408 // A boss takes a crowd, so it's everyone's who took enough of its health,
1409 // and not the last blow's, each with a roll of their own, and the land hears
1410 // who took the most.
1411 const Player* most = nullptr;
1412 int taken_most = 0;
1413 int helped = 0;
1414 for (const auto& [helper, threat] : monster.threat) {
1415 const auto found = players_.find(helper);
1416 if (found == players_.end() ||
1417 threat * 100 < monster.max_health * kEnoughHelp) {
1418 continue;
1419 }
1420 Reward(helper, found->second, monster);
1421 ++helped;
1422 if (threat > taken_most) {
1423 most = &found->second;
1424 taken_most = threat;
1425 }
1426 }
1427 const Sentence again = InWords(monster.respawn_time);
1428 Announce(monster, [&](Part boss) {
1429 if (most == nullptr) {
1430 return Msg("The $0 has fallen. It rises again in $1.", std::move(boss),
1431 again);
1432 }
1433 if (helped < 2) {
1434 // Translators: $1 is who took the most of its health, and $2 how long
1435 // until it's back.
1436 return Msg("The $0 has fallen to $1. It rises again in $2.",
1437 std::move(boss), Name(most->name), again);
1438 }
1439 // Translators: $1 is who took the most of its health, $2 how many others
1440 // helped, and $3 how long until it's back.
1441 return MsgN("The $0 has fallen to $1 and $2 other. It rises again in $3.",
1442 "The $0 has fallen to $1 and $2 others. It rises again in $3.",
1443 static_cast<uint64_t>(helped - 1), std::move(boss),
1444 Name(most->name), helped - 1, again);
1445 });
1446}
1447
1448void World::Reward(uint32_t id, Player& player, const Monster& monster) {
1449 Record(Event::Kind::kKill, id, player).monster = monster.kind;
1450 if (Gain(player, monster.experience)) {
1451 Record(Event::Kind::kLevel, id, player).level =
1452 static_cast<uint32_t>(LevelFor(player.experience).number);
1453 }
1454 Loot(id, player, monster);
1455 Count(id, player, monster);
1456}
1457
1458void World::Hurt(uint32_t from, uint32_t id, Player& player, int damage) {
1459 // A blow stops what they're making, as moving does.
1460 Interrupt(id, player);
1461 // At war, a blow kills, as a monster's does, but gives no experience, and
1462 // nothing drops. The kill counts for the killer's side.
1463 if (from != duels_.Opponent(id)) {
1464 const int taken = std::min(damage, player.health);
1465 player.health -= taken;
1466 Record(Event::Kind::kHurt, id, player).amount =
1467 static_cast<uint32_t>(taken);
1468 if (player.health > 0) {
1469 return;
1470 }
1471 player.motion = Motion::kDead;
1472 player.respawn = kRespawnTime;
1473 player.way.clear();
1474 Record(Event::Kind::kDeath, id, player);
1475 const Player& killer = players_.at(from);
1476 war_kills_.push_back({.war = WarBetween(killer, player)->id,
1477 .killer = from,
1478 .victim = id,
1479 .guild = killer.guild});
1480 return;
1481 }
1482 // Nobody dies in a duel: the blow that would leave them nothing leaves them
1483 // one, and they've lost.
1484 const int taken = std::min(damage, player.health - 1);
1485 if (taken > 0) {
1486 player.health -= taken;
1487 Record(Event::Kind::kHurt, id, player).amount =
1488 static_cast<uint32_t>(taken);
1489 }
1490 if (taken < damage) {
1491 Lose(id);
1492 }
1493}
1494
1495void World::Heal(uint32_t id, Player& player, int health) {
1496 const int healed = std::min(health, MaxHealthOf(player) - player.health);
1497 if (healed <= 0) {
1498 return;
1499 }
1500 player.health += healed;
1501 Record(Event::Kind::kHeal, id, player).amount = static_cast<uint32_t>(healed);
1502}
1503
1504void World::Loot(uint32_t id, Player& player, const Monster& monster) {
1505 const auto kind = content_->monsters.kinds.find(monster.kind);
1506 if (kind == content_->monsters.kinds.end()) {
1507 return;
1508 }
1509 std::vector<Part> kept;
1510 std::vector<Part> left;
1511 for (const monsters::Drop& drop : kind->second.loot()) {
1512 const auto item = content_->items.by_id.find(drop.item());
1513 if (item == content_->items.by_id.end() ||
1514 !std::bernoulli_distribution(drop.chance())(random_)) {
1515 continue;
1516 }
1517 const uint32_t least = std::max(drop.min(), 1u);
1518 const uint32_t count = std::uniform_int_distribution(
1519 least, std::max(drop.max(), least))(random_);
1520 const uint32_t fitted = Give(player.inventory, drop.item(), count);
1521 if (fitted > 0) {
1522 kept.push_back(Of(item->second, fitted));
1523 Event& looted = Record(Event::Kind::kLoot, id, player);
1524 looted.monster = monster.kind;
1525 looted.item = drop.item();
1526 looted.count = fitted;
1527 }
1528 if (fitted < count) {
1529 left.push_back(Of(item->second, count - fitted));
1530 }
1531 }
1532 // Gold takes no slot, so a full bag takes it too.
1533 if (const monsters::Gold& gold = kind->second.gold(); gold.max() > 0) {
1534 const uint32_t coins =
1535 std::uniform_int_distribution(gold.min(), gold.max())(random_);
1536 if (const uint32_t carried = coins - player.inventory.AddGold(coins);
1537 carried > 0) {
1538 kept.push_back(Gold(carried));
1539 }
1540 }
1541 if (!kept.empty()) {
1542 // Translators: $0 is a monster, and $1 what it dropped, as "2 Bones and
1543 // 5 gold".
1544 Tell(id,
1545 Msg("The $0 dropped $1.", Of(kind->second), List(std::move(kept))));
1546 }
1547 if (!left.empty()) {
1548 // Translators: $0 is what didn't fit, as "2 Bones and a Sword".
1549 Tell(id, Msg("Your bag is full, so you left $0 behind.",
1550 List(std::move(left))));
1551 }
1552}
1553
1554void World::Count(uint32_t id, Player& player, const Monster& monster) {
1555 const auto kind = content_->monsters.kinds.find(monster.kind);
1556 for (auto& [quest, kills] : player.quests) {
1557 const auto found = content_->quests.find(quest);
1558 if (found == content_->quests.end() ||
1559 kind == content_->monsters.kinds.end()) {
1560 continue;
1561 }
1562 const quests::Kill& kill = found->second.kill();
1563 if (kill.monster() != monster.kind || kills >= kill.count()) {
1564 continue;
1565 }
1566 ++kills;
1567 ++player.quests_revision;
1568 const Part asked = Of(kind->second, kill.count());
1569 const auto giver = content_->npcs.kinds.find(found->second.giver());
1570 if (kills == kill.count() && giver != content_->npcs.kinds.end()) {
1571 // Translators: $0 is the quest, $1 how many have been killed, $2 how
1572 // many of which monster it asks for, as "10 Skeletons", and $3 who gave
1573 // it.
1574 Tell(id, Msg("$0: $1 of $2 killed. Go back to the $3.", Of(found->second),
1575 kills, asked, Of(giver->second)));
1576 continue;
1577 }
1578 // Translators: $0 is the quest, $1 how many have been killed, and $2 how
1579 // many of which monster it asks for, as "10 Skeletons".
1580 Tell(id, Msg("$0: $1 of $2 killed.", Of(found->second), kills, asked));
1581 }
1582}
1583
1584uint32_t World::Give(Inventory& bag, uint32_t item, uint32_t count) {
1585 const auto found = content_->items.by_id.find(item);
1586 if (found == content_->items.by_id.end()) {
1587 return 0;
1588 }
1589 // What stacks goes as one stack, and what doesn't one at a time, each with
1590 // rolls and a serial of its own.
1591 const bool stacks = StackSize(found->second) > 1;
1592 const uint32_t each = stacks ? count : 1;
1593 uint32_t fitted = 0;
1594 for (uint32_t made = 0; made < count; made += each) {
1595 items::Stack stack;
1596 stack.set_item(item);
1597 stack.set_count(each);
1598 if (!stacks) {
1599 stack.set_serial(NewSerial());
1600 }
1601 for (const items::Roll& roll : found->second.rolls()) {
1602 items::Modifier* rolled = stack.add_rolls();
1603 rolled->set_stat(roll.stat());
1604 rolled->set_amount(
1605 std::uniform_int_distribution(roll.min(), roll.max())(random_));
1606 }
1607 fitted += each - bag.Add(content_->items, stack);
1608 }
1609 return fitted;
1610}
1611
1612absl::StatusOr<Inventory> World::Made(uint32_t id, const Player& player,
1613 const recipes::Recipe& recipe) {
1614 const recipes::ItemCount& output = recipe.output();
1615 // Into a copy, so that it's all of it or none, which goes into the bag as
1616 // one change, and one save.
1617 Inventory bag = player.inventory;
1618 for (const recipes::ItemCount& input : recipe.inputs()) {
1619 // From the first slot on, as many as it takes, a stack at a time.
1620 uint32_t left = input.count();
1621 for (uint32_t slot = 0; slot < kBagSlots && left > 0; ++slot) {
1622 const items::Stack* stack = bag.At(InBag(slot));
1623 if (stack == nullptr || stack->item() != input.item() ||
1624 trades_.Holds(id, InBag(slot))) {
1625 continue;
1626 }
1627 const uint32_t taken = std::min(left, CountOf(*stack));
1628 // Take refuses a stack shorter than it says, and then nothing's made.
1629 if (absl::Status took = bag.Take(InBag(slot), taken); !took.ok()) {
1630 return took;
1631 }
1632 left -= taken;
1633 }
1634 if (left > 0) {
1635 // Translators: $0 is so many of an item, as "10 Bones", and $1 what's
1636 // made, as "a Bone Sword".
1637 return Refusal(absl::StatusCode::kFailedPrecondition,
1638 Msg("You need $0 in your bag to make $1.",
1639 Of(content_->items, input.item(), input.count()),
1640 Of(content_->items, output.item(), output.count())));
1641 }
1642 }
1643 // As loot is, each one of what doesn't stack with a serial of its own.
1644 if (Give(bag, output.item(), output.count()) < output.count()) {
1645 return Refusal(absl::StatusCode::kResourceExhausted,
1646 Msg("Your bag is full. Make room for $0 first.",
1647 Of(content_->items, output.item(), output.count())));
1648 }
1649 return bag;
1650}
1651
1652void World::Make(uint32_t id, Player& player, std::chrono::nanoseconds time) {
1653 // No recipe has the id 0, which is making nothing.
1654 const auto found = content_->recipes.find(player.crafting);
1655 if (found == content_->recipes.end()) {
1656 return;
1657 }
1658 player.crafted += time;
1659 const recipes::Recipe& recipe = found->second;
1660 if (player.crafted < std::chrono::seconds(recipe.seconds())) {
1661 return;
1662 }
1663 player.crafting = 0;
1664 const Part made =
1665 Of(content_->items, recipe.output().item(), recipe.output().count());
1666 // Their bag may have changed since they started, so it's checked again.
1667 absl::StatusOr<Inventory> bag = Made(id, player, recipe);
1668 if (!bag.ok()) {
1669 // Translators: $1 is why, a sentence of its own.
1670 Tell(id, Msg("You couldn't make $0. $1", made, SentenceOf(bag.status())));
1671 return;
1672 }
1673 player.inventory = *std::move(bag);
1674 Event& crafted = Record(Event::Kind::kCraft, id, player);
1675 crafted.item = recipe.output().item();
1676 crafted.count = recipe.output().count();
1677 Tell(id, Msg("You made $0.", made));
1678}
1679
1680void World::Interrupt(uint32_t id, Player& player) {
1681 const auto found = content_->recipes.find(player.crafting);
1682 if (found == content_->recipes.end()) {
1683 return;
1684 }
1685 const recipes::ItemCount& output = found->second.output();
1686 Tell(id, Msg("You stopped making $0.",
1687 Of(content_->items, output.item(), output.count())));
1688 player.crafting = 0;
1689}
1690
1691std::vector<Notice> World::TakeNotices() { return std::exchange(notices_, {}); }
1692
1693void World::Tell(uint32_t player, Sentence said, protocol::Channel channel) {
1694 notices_.push_back({.player = player,
1695 .text = std::move(said.english),
1696 .message = std::move(said.message),
1697 .channel = channel});
1698}
1699
1700std::vector<Event> World::TakeEvents() { return std::exchange(events_, {}); }
1701
1702Event& World::Record(Event::Kind kind, uint32_t id, const Player& player) {
1703 return events_.emplace_back(Event{.kind = kind,
1704 .player = player.name,
1705 .player_id = id,
1706 .land = player.land,
1707 .x = player.x,
1708 .z = player.z});
1709}
1710
1711void World::Referee(std::chrono::nanoseconds time) {
1712 for (const Duels::Duel& asked : duels_.Step(time)) {
1713 Tell(asked.challenger, Msg("$0 didn't answer, so there's no duel.",
1714 Name(players_.at(asked.challenged).name)));
1715 }
1716 // Losing ends a duel, so the losers are found first, and lose after.
1717 std::vector<uint32_t> losers;
1718 for (const auto& [challenger, duel] : duels_.all()) {
1719 if (duel.state != Duels::State::kFighting) {
1720 continue;
1721 }
1722 for (const uint32_t side : {duel.challenger, duel.challenged}) {
1723 const Player& player = players_.at(side);
1724 const bool strayed =
1725 std::hypot(player.x - duel.flag.x, player.z - duel.flag.z) >
1727 if (strayed) {
1728 Tell(side, Msg("You went too far from the flag."));
1729 }
1730 if (strayed || player.motion == Motion::kDead) {
1731 losers.push_back(side);
1732 break;
1733 }
1734 }
1735 }
1736 for (const uint32_t loser : losers) {
1737 Lose(loser);
1738 }
1739}
1740
1741void World::Lose(uint32_t id) {
1742 const uint32_t winner = duels_.End(id);
1743 // Neither can hit the other any more.
1744 players_.at(id).target_player = 0;
1745 players_.at(winner).target_player = 0;
1746 Tell(id, Msg("$0 won the duel.", Name(players_.at(winner).name)));
1747 Tell(winner, Msg("You won the duel against $0.", Name(players_.at(id).name)));
1748}
1749
1750void World::Act(Monster& monster, std::chrono::nanoseconds time) {
1751 // As a player's, its cooldowns run down whatever it's doing.
1752 RunDown(monster.cooldowns, time);
1753 if (monster.motion == Motion::kDead) {
1754 // A push the killing blow started ends with the monster, but one thrown
1755 // up still comes down.
1756 monster.pushed = kPushTime;
1757 Fly(monster, time);
1758 // An add doesn't come back. It goes with its boss.
1759 if (monster.called_by != 0) {
1760 return;
1761 }
1762 const std::chrono::nanoseconds before = monster.respawn;
1763 Revive(monster, time, random_);
1764 // The land hears that a boss is about to come back, and that it has.
1765 if (monster.boss() && monster.motion != Motion::kDead) {
1766 Announce(monster, [](Part boss) {
1767 return Msg("The $0 has risen.", std::move(boss));
1768 });
1769 } else if (monster.boss() && before > kRisesSoon &&
1770 monster.respawn <= kRisesSoon) {
1771 Announce(monster, [](Part boss) {
1772 return Msg("The $0 rises again in $1.", std::move(boss),
1773 InWords(kRisesSoon));
1774 });
1775 }
1776 return;
1777 }
1778 // Pushed, it goes where the blow sends it, and a swing it started goes on.
1779 const bool pushed = Slide(monster, time);
1780 if (Fly(monster, time)) {
1781 return;
1782 }
1783 if (monster.motion == Motion::kAttack) {
1784 const auto before = monster.swing;
1785 monster.swing += time;
1786 if (before < monster.hit_time && monster.swing >= monster.hit_time) {
1787 Hit(monster);
1788 }
1789 if (monster.swing < monster.swing_time) {
1790 return;
1791 }
1792 monster.motion = Motion::kIdle;
1793 }
1794 // A push doesn't stop a skill either, and it lands where it was aimed.
1795 if (monster.motion == Motion::kSkill) {
1796 monster.cast += time;
1797 if (monster.cast <
1798 std::chrono::milliseconds(monster.casting.telegraph_ms())) {
1799 return;
1800 }
1801 LandSkill(monster);
1802 monster.motion = Motion::kIdle;
1803 }
1804 if (pushed) {
1805 monster.motion = Motion::kIdle;
1806 return;
1807 }
1808 Hunt(monster, players_, terrain_, time, random_);
1809}
1810
1811void World::CallAdds(uint32_t id, std::size_t phase) {
1812 const Monster& boss = monsters_.at(id);
1813 if (boss.motion == Motion::kDead) {
1814 return;
1815 }
1816 for (const monsters::Add& add : boss.phases[phase].adds()) {
1817 const auto kind = content_->monsters.kinds.find(add.kind());
1818 if (kind == content_->monsters.kinds.end()) {
1819 continue;
1820 }
1821 // Round the boss, evenly spaced, or where it stands, over the sea.
1822 for (uint32_t i = 0; i < add.count(); ++i) {
1823 const float angle = 2.0f * std::numbers::pi_v<float> *
1824 static_cast<float>(i) /
1825 static_cast<float>(add.count());
1826 float x = boss.x + kAddsAround * std::sin(angle);
1827 float z = boss.z + kAddsAround * std::cos(angle);
1828 if (!terrain_.Walkable(x, z)) {
1829 x = boss.x;
1830 z = boss.z;
1831 }
1832 // It fights where its boss does, for whoever it sees there.
1833 Monster called = MonsterOf(kind->second, x, z);
1834 called.called_by = id;
1835 called.sight = boss.sight;
1836 called.leash = boss.leash;
1837 Spawn(std::move(called));
1838 }
1839 }
1840}
1841
1842void World::Announce(const Monster& boss,
1843 const std::function<Sentence(Part boss)>& news) {
1844 const auto kind = content_->monsters.kinds.find(boss.kind);
1845 if (kind == content_->monsters.kinds.end()) {
1846 return;
1847 }
1848 const Sentence line = news(Of(kind->second));
1849 for (const auto& [id, player] : players_) {
1850 Tell(id, line, protocol::CHANNEL_LAND);
1851 }
1852}
1853
1854void World::Hit(Monster& monster) {
1855 const auto found = players_.find(monster.prey);
1856 if (found == players_.end()) {
1857 return;
1858 }
1859 Player& player = found->second;
1860 if (player.motion == Motion::kDead ||
1861 Distance(player, monster) > monster.reach) {
1862 return;
1863 }
1864 Hit(found->first, player, monster, monster.damage);
1865}
1866
1867void World::Hit(uint32_t id, Player& player, const Monster& monster, int blow) {
1868 // As a player's blow does, it stops what they're making.
1869 Interrupt(id, player);
1870 // What the player wears takes the blow, down to one.
1871 const int damage = std::max(blow - player.stats.armour, 1);
1872 player.health = std::max(player.health - damage, 0);
1873 Event& hurt = Record(Event::Kind::kHurt, id, player);
1874 hurt.monster = monster.kind;
1875 hurt.amount = static_cast<uint32_t>(damage);
1876 if (player.health > 0) {
1877 return;
1878 }
1879 player.motion = Motion::kDead;
1880 player.respawn = kRespawnTime;
1881 player.way.clear();
1882 Record(Event::Kind::kDeath, id, player).monster = monster.kind;
1883}
1884
1885void World::LandSkill(const Monster& monster) {
1886 const Place aimed{.x = monster.cast_x, .z = monster.cast_z};
1887 for (auto& [id, player] : players_) {
1888 if (player.motion != Motion::kDead &&
1889 InShape(monster.casting, aimed, monster.yaw,
1890 {.x = player.x, .z = player.z})) {
1891 Hit(id, player, monster, static_cast<int>(monster.casting.damage()));
1892 }
1893 }
1894}
1895
1896} // namespace nanommo
static constexpr float kFlagReach
Definition duels.h:32
static constexpr float kReach
A player asks another within this many metres of them.
Definition duels.h:22
bool Wear(const ItemTable &table, const items::Stack &stack)
Definition inventory.cc:180
absl::Status Destroy(const protocol::Place &place)
Throws away all of what's at the place.
Definition inventory.cc:289
uint32_t revision() const
Definition inventory.h:36
absl::Status Move(const ItemTable &table, const protocol::Place &from, const protocol::Place &to, uint32_t count=0)
Definition inventory.cc:193
absl::Status TakeOne(const protocol::Place &place)
Takes one off the stack at the place, as using one does.
Definition inventory.cc:249
uint32_t Add(const ItemTable &table, const items::Stack &stack)
Definition inventory.cc:121
const protocol::Inventory & items() const
Definition inventory.h:35
const items::Stack * At(const protocol::Place &place) const
What's at the place, or nullptr when it's empty, or isn't a place.
Definition inventory.cc:90
void Number(const ItemTable &table)
Definition inventory.cc:155
void Step(std::chrono::nanoseconds time)
Definition world.cc:940
const Terrain & terrain() const
Definition world.h:516
protocol::Duel DuelOf(uint32_t id) const
Definition world.cc:578
World(uint32_t seed=std::mt19937::default_seed, Terrain terrain=Terrain(), std::shared_ptr< const Content > content=std::make_shared< Content >(), std::shared_ptr< Paths > paths=nullptr)
Definition world.cc:206
std::vector< Notice > TakeNotices()
The lines for players since the last time, which it hands over.
Definition world.cc:1691
void SetGuild(uint32_t id, uint32_t guild)
The player's guild, by its id, or 0 for none.
Definition world.cc:609
void Join(uint32_t id, Player player)
Definition world.cc:215
std::vector< Event > TakeEvents()
What's happened since the last time, which it hands over.
Definition world.cc:1700
protocol::Trade TradeOf(uint32_t id) const
Definition world.cc:480
absl::Status Craft(uint32_t id, uint32_t recipe)
Definition world.cc:351
absl::StatusOr< uint32_t > ReadyToTrade(uint32_t id, bool ready, uint32_t revision)
Definition world.cc:441
absl::Status AnswerDuel(uint32_t id, bool yes)
Definition world.cc:534
static constexpr float kAddsAround
How far from a boss its adds come, in metres.
Definition world.h:332
std::set< uint32_t > TakeTradeNews()
Definition world.cc:491
void UseSkill(uint32_t id, uint32_t skill)
Definition world.cc:767
void Pick(uint32_t id, uint32_t monster, uint32_t player=0)
Definition world.cc:720
static constexpr std::chrono::seconds kRespawnTime
Definition world.h:329
void StopCrafting(uint32_t id)
Stops what the player's making, if anything, and they lose nothing.
Definition world.cc:383
std::vector< WarKill > TakeWarKills()
Definition world.cc:643
absl::Status Learn(uint32_t id, uint32_t npc, uint32_t skill)
Definition world.cc:774
static constexpr int kEnoughHelp
Definition world.h:336
absl::Status TakeQuest(uint32_t id, uint32_t npc, uint32_t quest)
Definition world.cc:804
static constexpr std::chrono::seconds kRisesSoon
How long before a boss comes back to life its land hears that it will.
Definition world.h:339
void WalkTo(uint32_t id, Place to)
Definition world.cc:755
absl::Status AskToTrade(uint32_t id, std::string_view name)
Definition world.cc:390
void Respawn(uint32_t id)
Definition world.cc:739
uint32_t Spawn(Monster monster)
Definition world.cc:685
void Leave(uint32_t id)
Definition world.cc:251
absl::Status OfferToTrade(uint32_t id, const protocol::TradeOffer &offer)
What the player offers in their trade, as Trades::Offer has it.
Definition world.cc:431
absl::Status MoveItem(uint32_t id, const protocol::Place &from, const protocol::Place &to, uint32_t count=0)
Definition world.cc:264
static constexpr float kCloseIn
Definition world.h:325
void SetInput(uint32_t id, float x, float z, bool run, bool attack=false)
Definition world.cc:702
absl::Status TurnIn(uint32_t id, uint32_t npc, uint32_t quest)
Definition world.cc:875
static constexpr float kTalkReach
Definition world.h:341
absl::Status Enlist(uint32_t id, uint32_t npc)
Definition world.cc:835
uint32_t CallOffDuel(uint32_t id)
Definition world.cc:576
absl::Status DestroyItem(uint32_t id, const protocol::Place &place)
Throws away all of what's at the place, unless they offer it in a trade.
Definition world.cc:283
void SetBehind(uint32_t id, std::chrono::nanoseconds behind)
Definition world.cc:732
absl::Status AskToDuel(uint32_t id, std::string_view name)
Definition world.cc:493
void SetWars(const std::vector< War > &wars)
Definition world.cc:616
absl::Status Yield(uint32_t id)
Definition world.cc:562
static constexpr float kTradeReach
Two players trade within talking reach, as close as they'd stand to talk.
Definition world.h:344
std::set< uint32_t > TakeDuelNews()
Definition world.cc:607
void CancelTrade(uint32_t id)
Calls the player's trade off, for both of them.
Definition world.cc:474
absl::Status UseItem(uint32_t id, uint32_t slot)
Definition world.cc:300
bool Hostile(uint32_t id, uint32_t other) const
Definition world.cc:624
static constexpr float kRunSpeed
Definition world.h:320
absl::Status GiveUp(uint32_t id, uint32_t quest)
Definition world.cc:864
Vector3 Place(const Point &point, const Terrain &terrain)
Definition film.cc:212
Definition chat.cc:9
const factions::Faction * HeraldOf(const std::map< uint32_t, factions::Faction > &factions, uint32_t kind)
Definition factions.cc:46
uint32_t CountOf(const items::Stack &stack)
How many are in the stack, which is one when it doesn't say.
Definition items.cc:102
bool InShape(const monsters::Skill &skill, Place from, float yaw, Place place)
Definition monsters.cc:172
Sentence MsgN(std::string_view one, std::string_view many, uint64_t count, Parts... parts)
Definition messages.h:100
std::chrono::nanoseconds RandomRest(std::mt19937 &random)
Definition monsters.cc:156
absl::Status Refusal(absl::StatusCode code, const Sentence &why)
Definition messages.cc:218
Sentence SentenceOf(const absl::Status &status)
Definition messages.cc:224
constexpr std::chrono::milliseconds kPushTime
How long a blow's push takes, fast at first and slowing, as a shove does.
Definition world.h:136
Level LevelFor(uint32_t experience)
Definition levels.cc:5
float AheadAt(const skills::Effect &effect, float ms)
Definition skills.cc:115
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
uint32_t StackSize(const items::Item &item)
How many of the item go in one slot of a bag.
Definition items.cc:98
protocol::Place Worn(items::Slot slot)
A slot that's worn.
Definition places.cc:13
float Gain(float slider)
Definition sound.cc:13
Sentence Msg(std::string_view text, Parts... parts)
Definition messages.h:92
void Walk(const Terrain &terrain, float &x, float &z, float to_x, float to_z)
Definition walking.cc:8
protocol::Place InBag(uint32_t slot)
A place in the bag, by its slot from zero.
Definition places.cc:7
std::vector< uint32_t > WornOf(const Player &player)
Definition world.cc:194
Part Name(std::string_view name)
Definition messages.cc:113
int MaxHealthOf(const Player &player)
Definition world.cc:148
Monster MonsterOf(const monsters::Kind &kind, float x, float z)
Definition monsters.cc:86
int MaxHealth(int level)
Definition levels.cc:15
Part Of(const items::Item &item, uint32_t count)
Definition messages.cc:139
int ExtraDamage(int level)
What a level adds to the damage of the weapon a player holds.
Definition levels.cc:17
uint32_t MainHandOf(const Player &player)
Definition world.cc:189
void Revive(Monster &monster, std::chrono::nanoseconds time, std::mt19937 &random)
Definition monsters.cc:293
bool Dead(const protocol::World &seen, uint32_t monster)
Definition quests.cc:89
uint64_t NewSerial()
Definition inventory.cc:84
constexpr std::chrono::milliseconds kMostInAir
Definition world.h:149
constexpr float kPop
Definition world.h:144
void WalkAlong(const Terrain &terrain, float &x, float &z, float direction_x, float direction_z, bool run, float seconds)
Definition walking.cc:19
constexpr float kGravity
Definition world.h:140
constexpr std::chrono::milliseconds kSteady
Definition world.h:150
std::chrono::nanoseconds left
How long the ask has left, and then the countdown.
Definition duels.h:42
uint32_t challenger
Who asked, and who they asked, by their ids.
Definition duels.h:38
uint32_t challenged
Definition duels.h:39
uint32_t Against(uint32_t id) const
The other side from the player's, by their id.
Definition duels.h:46
uint32_t item
An item dropped, given for a quest, used or made, and how many.
Definition world.h:295
uint32_t quest
Definition world.h:297
uint32_t count
Definition world.h:296
The items in the items file, by id.
Definition items.h:18
std::vector< items::Stack > starting
What each new player starts with.
Definition items.h:21
std::chrono::nanoseconds rest
Definition world.h:187
std::string name
Definition world.h:235
uint32_t kind
By its id in the NPCs file.
Definition world.h:237
In metres from the middle of a land.
Definition lands.h:13
float z
Definition lands.h:15
float x
Definition lands.h:14
uint32_t experience
Definition world.h:64
std::chrono::nanoseconds respawn
While they're dead, how long until they can come back.
Definition world.h:116
const items::Weapon * cast_weapon
Definition world.h:99
uint32_t guild
Definition world.h:55
std::string name
Definition world.h:49
std::set< uint32_t > skills
The skills the player knows, by their ids in the skills file.
Definition world.h:72
uint32_t target_player
Definition world.h:87
uint32_t target
Definition world.h:83
int land
Which of the world's lands, by its place in kLands.
Definition world.h:67
uint32_t input_skill
A skill the player asked for, which waits until they're free.
Definition world.h:128
std::set< uint32_t > quests_done
The quests they've turned in, which they can't take again.
Definition world.h:77
float input_z
Definition world.h:124
uint32_t crafting
Definition world.h:131
std::chrono::nanoseconds cast
Definition world.h:94
std::deque< Place > way
Definition world.h:119
uint32_t quests_revision
Definition world.h:80
std::chrono::nanoseconds chain_left
Definition world.h:109
std::map< uint32_t, std::chrono::nanoseconds > item_cooldowns
Definition world.h:114
float input_x
Definition world.h:123
uint32_t skill
Definition world.h:93
uint32_t chain
Definition world.h:108
skills::Effect effect
Definition world.h:98
bool input_attack
Definition world.h:126
std::map< uint32_t, uint32_t > quests
Definition world.h:75
Motion motion
Definition world.h:63
std::map< uint32_t, std::chrono::nanoseconds > cooldowns
How long until each skill they've used is ready again, by its id.
Definition world.h:111
uint32_t faction
Definition world.h:58
Inventory inventory
What the player carries and wears.
Definition world.h:69
Stats stats
Definition world.h:70
protocol::Message message
Definition messages.h:34
std::string english
Definition messages.h:35
const items::Weapon * weapon
The weapon in the player's main hand, from the content, or nullptr.
Definition world.h:45