nanoMMO 0.97.8
Building an MMO: The Engineering Series
Loading...
Searching...
No Matches
login_screen.cc
Go to the documentation of this file.
2
3#include <imgui.h>
4#include <raylib.h>
5
6#include <algorithm>
7#include <cfloat>
8#include <cmath>
9#include <cstdint>
10#include <optional>
11#include <string>
12#include <utility>
13#include <vector>
14
15#include "absl/strings/str_cat.h"
16#include "absl/strings/str_join.h"
17#include "absl/strings/substitute.h"
18#include "client/messages.h"
19#include "client/names.h"
20#include "client/scene.h"
21#include "client/theme.h"
22#include "client/translations.h"
23#include "extras/IconsFontAwesome6.h"
24#include "protocol/limits.h"
25#include "protocol/version.h"
26
27namespace nanommo {
28
29namespace {
30
31constexpr ImGuiWindowFlags kWindowFlags = ImGuiWindowFlags_NoMove |
32 ImGuiWindowFlags_NoResize |
33 ImGuiWindowFlags_NoSavedSettings;
34
35// A window that's only a place to draw in, and to take the mouse.
36constexpr ImGuiWindowFlags kBare =
37 ImGuiWindowFlags_NoDecoration | ImGuiWindowFlags_NoMove |
38 ImGuiWindowFlags_NoBackground | ImGuiWindowFlags_NoSavedSettings |
39 ImGuiWindowFlags_NoNav | ImGuiWindowFlags_NoBringToFrontOnFocus;
40
41// How far a pixel of a drag turns the character, in radians, and how near and
42// far the preview's camera goes, in metres.
43constexpr float kTurnPerPixel = 0.012f;
44constexpr float kNearest = 2.2f;
45constexpr float kFarthest = 5.5f;
46constexpr float kZoomStep = 0.3f;
47
48// In points, from the corner of the window to the version.
49constexpr float kCornerMargin = 14.0f;
50
51// In points: the buttons that do something, such as entering the world or
52// making a character, which are all one height, and side by side, one width.
53constexpr float kActionWidth = 300.0f;
54constexpr float kActionHeight = 52.0f;
55
56void ShowErrorText(const std::string& error) {
57 if (!error.empty()) {
58 ImGui::PushTextWrapPos(0.0f);
59 ImGui::TextColored({1.0f, 0.45f, 0.4f, 1.0f},
60 ICON_FA_TRIANGLE_EXCLAMATION " %s", error.c_str());
61 ImGui::PopTextWrapPos();
62 }
63}
64
65// A row to pick, as a world or a character is: its name, in carved capitals,
66// with a line under it, lit while it's picked, with an ember's edge. Returns
67// whether it was clicked, and sets twice when that was a double click.
68bool Row(const char* id, const std::string& name, const std::string& line,
69 bool picked, bool* twice = nullptr) {
70 const float height = Ui(58.0f);
71 const float width = ImGui::GetContentRegionAvail().x;
72 const bool clicked = ImGui::InvisibleButton(id, {width, height});
73 const bool hovered = ImGui::IsItemHovered();
74 if (twice != nullptr) {
75 *twice = hovered && ImGui::IsMouseDoubleClicked(ImGuiMouseButton_Left);
76 }
77 const ImVec2 min = ImGui::GetItemRectMin();
78 const ImVec2 max = ImGui::GetItemRectMax();
79 ImDrawList* draw = ImGui::GetWindowDrawList();
80 if (picked) {
81 draw->AddRectFilledMultiColor(
82 min, max, Faded(colors::kCrimson, 0.55f), Faded(colors::kWine, 0.2f),
84 draw->AddRectFilled(min, {min.x + Ui(3.0f), max.y}, colors::kEmber);
85 draw->AddRect(min, max, Faded(colors::kGoldDark, 0.7f), 0.0f, 0, Ui(1.0f));
86 } else if (hovered) {
87 draw->AddRectFilled(min, max, Faded(colors::kWine, 0.45f));
88 }
89 DrawGradientText(draw, GetFonts().title, Ui(18.0f),
90 {min.x + Ui(14.0f), min.y + Ui(8.0f)},
92 picked ? colors::kGold : colors::kMuted, name.c_str());
93 DrawShadowedText(draw, GetFonts().text, Ui(15.0f),
94 {min.x + Ui(14.0f), min.y + Ui(32.0f)}, colors::kMuted,
95 line.c_str());
96 return clicked;
97}
98
99// A button with a triangle on it, pointing the way: left, for a way below
100// zero, or right.
101bool Arrow(const char* id, float width, float way) {
102 const bool clicked = GameButton(id, {width, 0.0f});
103 const ImVec2 min = ImGui::GetItemRectMin();
104 const ImVec2 max = ImGui::GetItemRectMax();
105 const ImVec2 centre{(min.x + max.x) / 2.0f, (min.y + max.y) / 2.0f};
106 const float half = Ui(6.0f);
107 ImVec2 tip{centre.x + way * half, centre.y};
108 ImVec2 top{centre.x - way * half * 0.7f, centre.y - half};
109 ImVec2 bottom{centre.x - way * half * 0.7f, centre.y + half};
110 // ImGui smooths the edges of a shape whose corners go round clockwise.
111 if (way < 0.0f) {
112 std::swap(top, bottom);
113 }
114 ImGui::GetWindowDrawList()->AddTriangleFilled(tip, bottom, top,
116 return clicked;
117}
118
119// One of a few, by its name, between an arrow back and an arrow on, which go
120// round them, under its label, in the player's language. With only one,
121// there's nothing to choose, so it isn't shown.
122void Stepper(const char* label, const std::vector<std::string>& names,
123 uint32_t* at) {
124 if (names.size() < 2) {
125 return;
126 }
127 ImGui::TextDisabled("%s", Tr(label));
128 const auto count = static_cast<uint32_t>(names.size());
129 *at %= count;
130 ImGui::PushID(label);
131 const float arrow = Ui(38.0f);
132 const float gap = ImGui::GetStyle().ItemSpacing.x;
133 const float middle = ImGui::GetContentRegionAvail().x - 2.0f * (arrow + gap);
134 if (Arrow("##back", arrow, -1.0f)) {
135 *at = (*at + count - 1) % count;
136 }
137 ImGui::SameLine();
138 ImGui::Dummy({middle, Ui(34.0f)});
139 const ImVec2 min = ImGui::GetItemRectMin();
140 const ImVec2 max = ImGui::GetItemRectMax();
141 ImFont* font = GetFonts().text;
142 const float size = Ui(17.0f);
143 const std::string& name = names[*at];
144 const ImVec2 extent = font->CalcTextSizeA(size, FLT_MAX, 0.0f, name.c_str());
146 ImGui::GetWindowDrawList(), font, size,
147 {(min.x + max.x - extent.x) / 2.0f, (min.y + max.y - extent.y) / 2.0f},
148 colors::kPaper, name.c_str());
149 ImGui::SameLine();
150 if (Arrow("##on", arrow, 1.0f)) {
151 *at = (*at + 1) % count;
152 }
153 ImGui::PopID();
154}
155
156// The players' colours, as 0xRRGGBBAA, for the shirt's swatches.
157google::protobuf::RepeatedField<uint32_t> Shirts() {
158 google::protobuf::RepeatedField<uint32_t> colors;
159 for (int shirt = 0; shirt < kShirtColors; ++shirt) {
160 colors.Add(static_cast<uint32_t>(
161 ColorToInt(ShirtColor(static_cast<uint32_t>(shirt)))));
162 }
163 return colors;
164}
165
166// Colours, as 0xRRGGBBAA, each a round swatch to click, with gold round the
167// one picked, under its label, in the player's language, unless there's only
168// one.
169void Swatches(const char* label,
170 const google::protobuf::RepeatedField<uint32_t>& palette,
171 uint32_t* at) {
172 if (palette.size() < 2) {
173 return;
174 }
175 ImGui::TextDisabled("%s", Tr(label));
176 *at %= static_cast<uint32_t>(palette.size());
177 ImGui::PushID(label);
178 const float size = Ui(34.0f);
179 ImDrawList* draw = ImGui::GetWindowDrawList();
180 for (int i = 0; i < palette.size(); ++i) {
181 if (i > 0) {
182 ImGui::SameLine();
183 }
184 ImGui::PushID(i);
185 if (ImGui::InvisibleButton("##swatch", {size, size})) {
186 *at = static_cast<uint32_t>(i);
187 }
188 const bool hovered = ImGui::IsItemHovered();
189 const ImVec2 min = ImGui::GetItemRectMin();
190 const ImVec2 max = ImGui::GetItemRectMax();
191 const ImVec2 centre{(min.x + max.x) / 2.0f, (min.y + max.y) / 2.0f};
192 const Color color = GetColor(palette[i]);
193 draw->AddCircleFilled(centre, size * 0.36f,
194 IM_COL32(color.r, color.g, color.b, 255));
195 draw->AddCircle(centre, size * 0.36f, colors::kShadow, 0, Ui(1.0f));
196 if (*at == static_cast<uint32_t>(i)) {
197 draw->AddCircle(centre, size * 0.47f, colors::kGold, 0, Ui(2.0f));
198 } else if (hovered) {
199 draw->AddCircle(centre, size * 0.47f, Faded(colors::kPaper, 0.5f), 0,
200 Ui(1.5f));
201 }
202 ImGui::PopID();
203 }
204 ImGui::PopID();
205}
206
207// What each build or way to wear the hair is called, in the player's
208// language, or, without a name, its number.
209template <typename Named>
210std::vector<std::string> NamesOf(
211 const google::protobuf::RepeatedPtrField<Named>& each) {
212 std::vector<std::string> names;
213 names.reserve(each.size());
214 for (int i = 0; i < each.size(); ++i) {
215 names.push_back(each[i].name().empty() ? absl::StrCat(i + 1)
216 : NameOf(each[i]));
217 }
218 return names;
219}
220
221} // namespace
222
223Figure LoginScreen::FigureOf(const protocol::CharacterListing& character,
224 const ItemTable& items,
225 const figures::Figures& figures) {
226 Figure figure;
227 figure.id = character.id();
228 if (character.has_looks()) {
229 figure.features = FeaturesOf(figures, character.looks());
230 }
231 figure.name = character.name();
232 figure.level = static_cast<int>(character.level());
233 figure.weapon = character.weapon();
234 figure.wearing = {character.wearing().begin(), character.wearing().end()};
235 // A character that's never entered gets the kit as it does: it's shown in
236 // it now, the way the world will dress it.
237 if (character.fresh()) {
238 std::vector<items::Slot> taken;
239 for (const items::Stack& stack : items.starting) {
240 const auto item = items.by_id.find(stack.item());
241 if (item == items.by_id.end() || !item->second.has_equip()) {
242 continue;
243 }
244 const items::Slot slot = item->second.equip().slot();
245 if (std::ranges::find(taken, slot) != taken.end()) {
246 continue;
247 }
248 taken.push_back(slot);
249 if (slot == items::SLOT_MAIN_HAND) {
250 figure.weapon = stack.item();
251 } else {
252 figure.wearing.push_back(stack.item());
253 }
254 }
255 }
256 figure.from = protocol::MOTION_IDLE;
257 figure.to = protocol::MOTION_IDLE;
258 figure.blend = 1.0f;
259 return figure;
260}
261
262std::optional<protocol::LoginRequest> LoginScreen::Build() {
263 const ImVec2 screen = ImGui::GetIO().DisplaySize;
264 ImDrawList* back = ImGui::GetBackgroundDrawList();
265 DrawBackdrop(back, screen, static_cast<float>(ImGui::GetTime()));
266 // The game's name, high up, over the login only: once in, the worlds and
267 // the characters have the screen.
268 if (step_ == Step::kAccount) {
269 DrawLogo(back, {screen.x / 2.0f, screen.y * 0.14f}, Ui(92.0f));
270 }
271
272 // The version, in the corner, as most other games show it, so a player can
273 // tell which one they have.
274 const std::string version = absl::StrCat("nanoMMO ", kVersion);
275 ImFont* font = GetFonts().text;
276 const float size = Ui(14.0f);
277 const ImVec2 extent =
278 font->CalcTextSizeA(size, FLT_MAX, 0.0f, version.c_str());
279 back->AddText(font, size,
280 {screen.x - extent.x - Ui(kCornerMargin),
281 screen.y - extent.y - Ui(kCornerMargin)},
282 colors::kFaint, version.c_str());
283
284 switch (step_) {
285 case Step::kAccount:
286 return BuildAccount();
287 case Step::kWorlds:
288 return BuildWorlds();
289 case Step::kCharacters:
290 return BuildCharacters();
291 case Step::kCreate:
292 return BuildCreate();
293 }
294 return std::nullopt;
295}
296
297void LoginScreen::Show(const protocol::LoginReply& reply) {
298 // The server's sentence, in the language in use. A login server before
299 // 0.96.0, which turns this client away for its version, sends the English
300 // alone.
301 error_ = reply.ok() ? ""
302 : reply.has_why() ? Translated(reply.why())
303 : reply.error();
304 // Without a session, the login failed, or the one we had ran out: back to
305 // the login, with what the server said.
306 if (reply.session().empty()) {
307 session_.clear();
308 step_ = Step::kAccount;
309 return;
310 }
311 if (session_.empty()) {
312 step_ = Step::kWorlds;
313 }
314 session_ = reply.session();
315 if (reply.ok()) {
316 worlds_ = {reply.worlds().begin(), reply.worlds().end()};
317 selected_world_ = std::clamp(
318 selected_world_, 0, std::max(static_cast<int>(worlds_.size()) - 1, 0));
319 }
320 characters_ = {reply.characters().begin(), reply.characters().end()};
321 // The one just made, by its name, or else the one picked, while it's
322 // still there, or else the first.
323 const std::vector<const protocol::CharacterListing*> here = Here();
324 const auto named = std::ranges::find_if(
325 here, [&](const auto* c) { return c->name() == new_name_.data(); });
326 if (reply.ok() && named != here.end() && new_name_[0] != '\0') {
327 picked_ = (*named)->id();
328 new_name_.fill('\0');
329 // Made: back to the characters, with them picked.
330 if (step_ == Step::kCreate) {
331 step_ = Step::kCharacters;
332 }
333 } else if (std::ranges::none_of(
334 here, [&](const auto* c) { return c->id() == picked_; })) {
335 picked_ = here.empty() ? 0 : here.front()->id();
336 }
337}
338
339std::string LoginScreen::character_name() const {
340 const auto found = std::ranges::find_if(
341 characters_, [&](const auto& c) { return c.id() == picked_; });
342 return found != characters_.end() ? found->name() : "";
343}
344
345protocol::LoginRequest LoginScreen::WithSession() const {
346 protocol::LoginRequest request;
347 request.set_session(session_);
348 return request;
349}
350
351std::vector<const protocol::CharacterListing*> LoginScreen::Here() const {
352 std::vector<const protocol::CharacterListing*> here;
353 for (const protocol::CharacterListing& character : characters_) {
354 if (world_ && character.world() == world_->name()) {
355 here.push_back(&character);
356 }
357 }
358 return here;
359}
360
361int LoginScreen::CountIn(const std::string& world) const {
362 return static_cast<int>(std::ranges::count_if(
363 characters_, [&](const auto& c) { return c.world() == world; }));
364}
365
366std::optional<protocol::LoginRequest> LoginScreen::BuildAccount() {
367 const ImVec2 screen = ImGui::GetIO().DisplaySize;
368 ImGui::SetNextWindowPos({screen.x / 2.0f, screen.y * 0.55f}, ImGuiCond_Always,
369 {0.5f, 0.5f});
370 ImGui::SetNextWindowSize({Ui(380.0f), 0.0f});
371 BeginPanel("Your account", nullptr, kWindowFlags);
372 ImGui::TextDisabled("%s", Tr("Name"));
373 if (ImGui::IsWindowAppearing()) {
374 ImGui::SetKeyboardFocusHere();
375 }
376 ImGui::SetNextItemWidth(-FLT_MIN);
377 ImGui::InputText("##name", username_.data(), username_.size());
378 ImGui::TextDisabled("%s", Tr("Password"));
379 ImGui::SetNextItemWidth(-FLT_MIN);
380 const bool enter = ImGui::InputText(
381 "##password", password_.data(), password_.size(),
382 ImGuiInputTextFlags_Password | ImGuiInputTextFlags_EnterReturnsTrue);
383 ImGui::Spacing();
384 const bool log_in = GameButton("Log in", {-1.0f, 0.0f}, true) || enter;
385 const bool create = GameButton("Make an account", {-1.0f, 0.0f});
386 ShowErrorText(error_);
387 EndPanel();
388
389 if (!log_in && !create) {
390 return std::nullopt;
391 }
392 protocol::LoginRequest request;
393 request.set_username(username_.data());
394 request.set_password(password_.data());
395 request.set_new_account(create);
396 request.set_version(kVersion);
397 // We don't keep the password once it's on its way: the session the reply
398 // brings stands in for it.
399 password_.fill('\0');
400 error_.clear();
401 return request;
402}
403
404std::optional<protocol::LoginRequest> LoginScreen::BuildWorlds() {
405 const ImVec2 screen = ImGui::GetIO().DisplaySize;
406 ImGui::SetNextWindowPos({screen.x / 2.0f, screen.y * 0.5f}, ImGuiCond_Always,
407 {0.5f, 0.5f});
408 ImGui::SetNextWindowSize({Ui(480.0f), 0.0f});
409 // The arrow keys and Enter pick a world, so ImGui's own keyboard navigation
410 // stays out of this window.
411 BeginPanel("Choose a world", nullptr, kWindowFlags | ImGuiWindowFlags_NoNav);
412 bool refresh = ImGui::IsWindowAppearing() || ImGui::IsKeyPressed(ImGuiKey_F5);
413 const int count = static_cast<int>(worlds_.size());
414 if (ImGui::IsKeyPressed(ImGuiKey_DownArrow) && selected_world_ + 1 < count) {
415 ++selected_world_;
416 }
417 if (ImGui::IsKeyPressed(ImGuiKey_UpArrow) && selected_world_ > 0) {
418 --selected_world_;
419 }
420 bool pick = ImGui::IsKeyPressed(ImGuiKey_Enter);
421
422 for (int i = 0; i < count; ++i) {
423 const protocol::WorldListing& world = worlds_[i];
424 // Translators: How many are playing in the world.
425 std::vector<std::string> line = {absl::Substitute(
426 TrN("$0 playing", "$0 playing", world.players()), world.players())};
427 if (const int yours = CountIn(world.name()); yours > 0) {
428 line.push_back(absl::Substitute(Tr("$0 of your characters"), yours));
429 }
430 if (world.content() != content_) {
431 line.push_back(Tr("other content"));
432 }
433 ImGui::PushID(i);
434 bool twice = false;
435 if (Row("##world", world.name(), absl::StrJoin(line, ", "),
436 i == selected_world_, &twice)) {
437 selected_world_ = i;
438 }
439 pick = pick || twice;
440 ImGui::PopID();
441 }
442 if (count == 0) {
443 // A world is a nanommo_server, which Consul lists once it's started.
444 ImGui::TextDisabled("%s", Tr("No worlds are up."));
445 ImGui::TextDisabled("%s", Tr("Start nanommo_server, then Refresh."));
446 }
447 ImGui::Spacing();
448 const float third = (ImGui::GetContentRegionAvail().x -
449 2.0f * ImGui::GetStyle().ItemSpacing.x) /
450 3.0f;
451 const bool log_out = GameButton("Log out", {third, 0.0f});
452 ImGui::SameLine();
453 refresh = GameButton("Refresh", {third, 0.0f}) || refresh;
454 ImGui::SameLine();
455 pick = GameButton("Continue", {third, 0.0f}, true) || pick;
456 ShowErrorText(error_);
457 EndPanel();
458
459 if (log_out) {
460 session_.clear();
461 characters_.clear();
462 error_.clear();
463 step_ = Step::kAccount;
464 return std::nullopt;
465 }
466 if (pick && count > 0) {
467 const protocol::WorldListing& picked = worlds_[selected_world_];
468 // A client draws what the world sends from its own content, so with
469 // other content, it would draw the wrong things, or nothing.
470 if (picked.content() != content_) {
471 error_ = absl::Substitute(Tr("$0 has other content than this client, so "
472 "they can't play together."),
473 picked.name());
474 } else {
475 world_ = picked;
476 error_.clear();
477 deleting_ = false;
478 step_ = Step::kCharacters;
479 const std::vector<const protocol::CharacterListing*> here = Here();
480 picked_ = here.empty() ? 0 : here.front()->id();
481 // Nobody here yet: straight to making someone.
482 if (here.empty()) {
483 StartCreating();
484 }
485 return std::nullopt;
486 }
487 }
488 if (!refresh) {
489 return std::nullopt;
490 }
491 return WithSession();
492}
493
494std::optional<protocol::LoginRequest> LoginScreen::BuildCharacters() {
495 if (!world_) {
496 return std::nullopt;
497 }
498 const protocol::WorldListing& world = *world_;
499 const std::vector<const protocol::CharacterListing*> here = Here();
500 const auto picked = std::ranges::find_if(
501 here, [&](const auto* c) { return c->id() == picked_; });
502 const protocol::CharacterListing* character =
503 picked != here.end() ? *picked : nullptr;
504 const ImVec2 screen = ImGui::GetIO().DisplaySize;
505 const bool typing = ImGui::GetIO().WantTextInput;
506 if (!typing && !here.empty() && picked != here.end()) {
507 if (ImGui::IsKeyPressed(ImGuiKey_DownArrow) && picked + 1 != here.end()) {
508 picked_ = (*(picked + 1))->id();
509 deleting_ = false;
510 }
511 if (ImGui::IsKeyPressed(ImGuiKey_UpArrow) && picked != here.begin()) {
512 picked_ = (*(picked - 1))->id();
513 deleting_ = false;
514 }
515 }
516
517 // Back to the worlds, in the top left.
518 ImGui::SetNextWindowPos({Ui(24.0f), Ui(24.0f)});
519 ImGui::Begin("##back", nullptr, kBare | ImGuiWindowFlags_AlwaysAutoResize);
520 const bool back = GameButton("« Worlds", {0.0f, 0.0f});
521 ImGui::End();
522
523 if (character != nullptr) {
524 // Translators: $0 is their level, and $1 the land they're in.
525 DrawStage(character->name(),
526 absl::Substitute(Tr("Level $0, in the $1"), character->level(),
527 LandName(character->land())));
528 }
529
530 // The characters, and a way to make a new one, on the right.
531 ImGui::SetNextWindowPos({screen.x - Ui(48.0f), screen.y * 0.48f},
532 ImGuiCond_Always, {1.0f, 0.5f});
533 ImGui::SetNextWindowSize({Ui(360.0f), 0.0f});
534 BeginPanel((world.name() + "###characters").c_str(), nullptr,
535 kWindowFlags | ImGuiWindowFlags_NoNav);
536 // Back from the world, or in from the worlds: the list as it is now.
537 const bool refresh = ImGui::IsWindowAppearing();
538 for (const protocol::CharacterListing* each : here) {
539 ImGui::PushID(static_cast<int>(each->id()));
540 // Translators: $0 is their level, and $1 the land they're in.
541 if (Row("##character", each->name(),
542 absl::Substitute(Tr("Level $0, $1"), each->level(),
543 LandName(each->land())),
544 each->id() == picked_)) {
545 picked_ = each->id();
546 deleting_ = false;
547 }
548 ImGui::PopID();
549 }
550 if (here.empty()) {
551 ImGui::TextDisabled("%s", Tr("Nobody yet."));
552 }
553 ImGui::Spacing();
554 // The login server would turn a fifth away, so we don't ask it to.
555 const bool create =
556 static_cast<int>(here.size()) < kCharactersPerWorld &&
557 GameButton("New character", {-1.0f, Ui(kActionHeight)}, here.empty());
558 if (static_cast<int>(here.size()) >= kCharactersPerWorld) {
559 ImGui::TextDisabled(
560 "%s", absl::Substitute(Tr("$0 is the most a world has room for."),
562 .c_str());
563 }
564 ShowErrorText(error_);
565 EndPanel();
566
567 // Into the world, at the bottom, with a way to delete the one picked.
568 bool enter = false;
569 bool delete_it = false;
570 if (character != nullptr) {
571 ImGui::SetNextWindowPos({screen.x * 0.42f, screen.y - Ui(36.0f)},
572 ImGuiCond_Always, {0.5f, 1.0f});
573 ImGui::Begin("##enter", nullptr, kBare | ImGuiWindowFlags_AlwaysAutoResize);
574 const ImVec2 action = Ui(ImVec2{kActionWidth, kActionHeight});
575 if (!deleting_) {
576 enter = GameButton("Enter the world", action, true) ||
577 (!typing && ImGui::IsKeyPressed(ImGuiKey_Enter));
578 ImGui::SameLine();
579 deleting_ = GameButton("Delete", action);
580 } else {
581 ImGui::TextColored(
582 {1.0f, 0.7f, 0.4f, 1.0f}, "%s",
583 absl::Substitute(Tr("Delete $0 for good?"), character->name())
584 .c_str());
585 delete_it = GameButton("Delete", action, true);
586 ImGui::SameLine();
587 if (GameButton("Keep", action)) {
588 deleting_ = false;
589 }
590 }
591 ImGui::End();
592 }
593
594 if (back) {
595 step_ = Step::kWorlds;
596 error_.clear();
597 deleting_ = false;
598 return std::nullopt;
599 }
600 if (create) {
601 StartCreating();
602 return std::nullopt;
603 }
604 protocol::LoginRequest request = WithSession();
605 if (enter && character != nullptr) {
606 request.set_enter(true);
607 request.set_character(character->id());
608 } else if (delete_it && character != nullptr) {
609 request.set_delete_character(true);
610 request.set_character(character->id());
611 deleting_ = false;
612 } else if (!refresh) {
613 return std::nullopt;
614 }
615 error_.clear();
616 return request;
617}
618
619std::optional<protocol::LoginRequest> LoginScreen::BuildCreate() {
620 if (!world_) {
621 return std::nullopt;
622 }
623 const ImVec2 screen = ImGui::GetIO().DisplaySize;
624
625 // Back to the characters, in the top left.
626 ImGui::SetNextWindowPos({Ui(24.0f), Ui(24.0f)});
627 ImGui::Begin("##back", nullptr, kBare | ImGuiWindowFlags_AlwaysAutoResize);
628 const bool back = GameButton("« Characters", {0.0f, 0.0f});
629 ImGui::End();
630
631 DrawStage(new_name_[0] != '\0' ? new_name_.data() : Tr("A new character"),
632 absl::Substitute(Tr("Level 1, new to $0"), world_->name()));
633
634 // Their name, and how they look, on the right. Each change shows on the
635 // stage straight away.
636 ImGui::SetNextWindowPos({screen.x - Ui(48.0f), screen.y * 0.48f},
637 ImGuiCond_Always, {1.0f, 0.5f});
638 ImGui::SetNextWindowSize({Ui(380.0f), 0.0f});
639 BeginPanel("A new character###create", nullptr,
640 kWindowFlags | ImGuiWindowFlags_NoNav);
641 ImGui::TextDisabled("%s", Tr("Name"));
642 if (ImGui::IsWindowAppearing()) {
643 ImGui::SetKeyboardFocusHere();
644 }
645 ImGui::SetNextItemWidth(-FLT_MIN);
646 const bool named = ImGui::InputTextWithHint(
647 "##name", Tr("Their name"), new_name_.data(), new_name_.size(),
648 ImGuiInputTextFlags_EnterReturnsTrue);
649 ImGui::Spacing();
650 uint32_t build = looks_.build();
651 uint32_t skin = looks_.skin();
652 uint32_t hair = looks_.hair();
653 uint32_t hair_color = looks_.hair_color();
654 uint32_t shirt = looks_.shirt();
655 Stepper("Build", NamesOf(rig_.builds()), &build);
656 Swatches("Skin", figures_.skins(), &skin);
657 Stepper("Hair", NamesOf(figures_.hairs()), &hair);
658 Swatches("Hair colour", figures_.hair_colors(), &hair_color);
659 Swatches("Shirt", Shirts(), &shirt);
660 looks_.set_build(build);
661 looks_.set_skin(skin);
662 looks_.set_hair(hair);
663 looks_.set_hair_color(hair_color);
664 looks_.set_shirt(shirt);
665 ImGui::Spacing();
666 ImGui::Spacing();
667 const float half =
668 (ImGui::GetContentRegionAvail().x - ImGui::GetStyle().ItemSpacing.x) /
669 2.0f;
670 // Side by side, and as big as each other, though only Create's lit.
671 const float height = Ui(kActionHeight);
672 if (GameButton("Random", {half, height})) {
673 PickAnyLooks();
674 }
675 ImGui::SameLine();
676 const bool create = GameButton("Create", {half, height}, true) || named;
677 ShowErrorText(error_);
678 EndPanel();
679
680 if (back) {
681 step_ = Step::kCharacters;
682 error_.clear();
683 return std::nullopt;
684 }
685 if (!create || !world_) {
686 return std::nullopt;
687 }
688 // The reply lists them, and Show picks them and goes back to the
689 // characters; or it says what's wrong, such as a name that's taken, and we
690 // stay, with all that was chosen.
691 protocol::LoginRequest request = WithSession();
692 request.set_create_character(true);
693 request.set_world(world_->name());
694 request.set_name(new_name_.data());
695 *request.mutable_looks() = looks_;
696 error_.clear();
697 return request;
698}
699
700void LoginScreen::DrawStage(const std::string& name, const std::string& line) {
701 const ImVec2 screen = ImGui::GetIO().DisplaySize;
702 const ImVec2 stage{Ui(380.0f), Ui(506.0f)};
703 const ImVec2 stage_min{screen.x * 0.42f - stage.x / 2.0f,
704 screen.y * 0.5f - stage.y / 2.0f};
705 const ImVec2 stage_max{stage_min.x + stage.x, stage_min.y + stage.y};
706 ImGui::SetNextWindowPos(stage_min);
707 ImGui::SetNextWindowSize({stage.x, stage.y + Ui(90.0f)});
708 ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, {0.0f, 0.0f});
709 ImGui::Begin("##stage", nullptr, kBare);
710 ImGui::PopStyleVar();
711 ImDrawList* draw = ImGui::GetWindowDrawList();
712 // The fire's glow behind, and nothing on the floor.
713 const ImVec2 floor{(stage_min.x + stage_max.x) / 2.0f,
714 stage_max.y - stage.y * 0.035f};
715 for (int ring = 8; ring >= 1; --ring) {
716 const float share = static_cast<float>(ring) / 8.0f;
717 draw->AddEllipseFilled({floor.x, floor.y - stage.y * 0.4f},
718 {stage.x * 0.55f * share, stage.y * 0.55f * share},
719 Faded(colors::kCrimson, 0.035f));
720 }
721 ImGui::SetCursorScreenPos(stage_min);
722 ImGui::InvisibleButton("##preview", stage);
723 // OpenGL keeps the rows bottom up, so the UVs turn the picture over.
724 draw->AddImage(static_cast<ImTextureID>(preview_.texture().id), stage_min,
725 stage_max, {0.0f, 1.0f}, {1.0f, 0.0f});
726 const ImGuiIO& io = ImGui::GetIO();
727 if (ImGui::IsItemActive()) {
728 turn_ += io.MouseDelta.x * kTurnPerPixel / UiScale();
729 }
730 if (ImGui::IsItemHovered()) {
731 ImGui::SetMouseCursor(ImGuiMouseCursor_ResizeEW);
732 distance_ =
733 std::clamp(distance_ - io.MouseWheel * kZoomStep, kNearest, kFarthest);
734 }
735 // Its name, under it.
736 ImFont* title = GetFonts().title;
737 const float name_size = Ui(30.0f);
738 const ImVec2 name_extent =
739 title->CalcTextSizeA(name_size, FLT_MAX, 0.0f, name.c_str());
740 DrawGradientText(draw, title, name_size,
741 {floor.x - name_extent.x / 2.0f, stage_max.y + Ui(6.0f)},
742 colors::kGoldLight, colors::kGold, name.c_str());
743 const float line_size = Ui(17.0f);
744 const ImVec2 line_extent =
745 GetFonts().text->CalcTextSizeA(line_size, FLT_MAX, 0.0f, line.c_str());
747 draw, GetFonts().text, line_size,
748 {floor.x - line_extent.x / 2.0f, stage_max.y + Ui(10.0f) + name_extent.y},
749 colors::kMuted, line.c_str());
750 ImGui::End();
751}
752
753void LoginScreen::StartCreating() {
754 step_ = Step::kCreate;
755 new_name_.fill('\0');
756 error_.clear();
757 deleting_ = false;
758 turn_ = 0.0f;
759 PickAnyLooks();
760}
761
762void LoginScreen::PickAnyLooks() {
763 const auto any = [](int count) {
764 return count > 0 ? static_cast<uint32_t>(GetRandomValue(0, count - 1)) : 0u;
765 };
766 looks_.set_build(any(rig_.builds_size()));
767 looks_.set_skin(any(figures_.skins_size()));
768 looks_.set_hair_color(any(figures_.hair_colors_size()));
769 looks_.set_hair(any(figures_.hairs_size()));
770 looks_.set_shirt(any(kShirtColors));
771}
772
773protocol::CharacterListing LoginScreen::Draft() const {
774 protocol::CharacterListing draft;
775 draft.set_name(new_name_.data());
776 draft.set_level(1);
777 draft.set_fresh(true);
778 *draft.mutable_looks() = looks_;
779 return draft;
780}
781
782void LoginScreen::Render(const Renderer& renderer) {
783 // The one being made, or the one picked.
784 std::optional<protocol::CharacterListing> shown;
785 if (step_ == Step::kCreate) {
786 shown = Draft();
787 } else if (step_ == Step::kCharacters && world_) {
788 const auto found = std::ranges::find_if(
789 characters_, [&](const auto& c) { return c.id() == picked_; });
790 if (found != characters_.end()) {
791 shown = *found;
792 }
793 }
794 if (!shown) {
795 return;
796 }
797 Figure figure = FigureOf(*shown, items_, figures_);
798 figure.yaw = turn_;
799 // Its idle, from when the client started: it breathes, and looks round.
800 figure.to_time = static_cast<float>(GetTime());
801 // The camera looks at the middle, and closer up, higher, so that the top of
802 // the picture stays two metres up and the head stays in it.
803 constexpr float kFov = 35.0f;
804 constexpr float kTop = 2.0f;
805 const float height =
806 std::max(0.9f, kTop - distance_ * std::tan(kFov / 2.0f * DEG2RAD));
807 const Camera3D camera{
808 .position = {0.0f, height + 0.1f, distance_},
809 .target = {0.0f, height, 0.0f},
810 .up = {0.0f, 1.0f, 0.0f},
811 .fovy = kFov,
812 .projection = CAMERA_PERSPECTIVE,
813 };
814 preview_.RenderPreview(renderer, figure, camera);
815}
816
817} // namespace nanommo
void Show(const protocol::LoginReply &reply)
std::string character_name() const
The name of the character picked, once it's entering.
void Render(const Renderer &renderer)
const std::optional< protocol::WorldListing > & world() const
The world picked, which a token from an enter request is for.
static Figure FigureOf(const protocol::CharacterListing &character, const ItemTable &items, const figures::Figures &figures=figures::Figures::default_instance())
std::optional< protocol::LoginRequest > Build()
constexpr ImU32 kFaint
Definition theme.h:28
constexpr ImU32 kEmber
Definition theme.h:19
constexpr ImU32 kCrimson
Definition theme.h:17
constexpr ImU32 kGoldDark
Definition theme.h:23
constexpr ImU32 kShadow
Definition theme.h:29
constexpr ImU32 kGoldLight
Definition theme.h:22
constexpr ImU32 kMuted
Definition theme.h:27
constexpr ImU32 kWine
Definition theme.h:16
constexpr ImU32 kPaper
Definition theme.h:26
constexpr ImU32 kGold
Definition theme.h:21
Definition chat.cc:9
constexpr int kShirtColors
How many colours there are to dye a player's clothes in.
Definition scene.h:11
bool BeginPanel(const char *name, bool *open, ImGuiWindowFlags flags, float alpha)
Definition theme.cc:320
std::string Translated(const protocol::Message &message, const Content &content)
Definition messages.cc:108
void DrawLogo(ImDrawList *draw, ImVec2 top_centre, float size)
Definition theme.cc:606
Color ShirtColor(uint32_t shirt)
Definition scene.cc:20
constexpr int kCharactersPerWorld
Definition limits.h:8
float Ui(float points)
Definition theme.h:67
void EndPanel()
Definition theme.cc:379
const char * Tr(const char *text)
const char * TrN(const char *one, const char *many, uint64_t n)
The form for the count: in English, one for 1 and many for the rest.
std::string LandName(std::string_view land)
Definition names.cc:92
ImU32 Faded(ImU32 color, float share)
The same colour, with its alpha times the share.
Definition theme.cc:59
void DrawBackdrop(ImDrawList *draw, ImVec2 size, float time)
Definition theme.cc:563
Features FeaturesOf(const figures::Figures &figures, uint32_t id)
Definition figures.cc:74
bool GameButton(const char *label, ImVec2 size, bool primary, bool enabled)
Definition theme.cc:381
void DrawGradientText(ImDrawList *draw, ImFont *font, float size, ImVec2 at, ImU32 top, ImU32 bottom, const char *text)
Definition theme.cc:283
void DrawShadowedText(ImDrawList *draw, ImFont *font, float size, ImVec2 at, ImU32 color, const char *text)
Text with a shadow under it.
Definition theme.cc:272
std::string Row(const Event &event, const Content &content, std::string_view world, absl::Time time)
Definition events.cc:77
float UiScale()
Definition theme.cc:100
const Fonts & GetFonts()
Definition theme.cc:66
const char * NameOf(const items::Item &item)
Definition names.cc:14
uint32_t id
Definition animator.h:21
protocol::Motion from
Definition animator.h:73
std::string name
Definition animator.h:22
uint32_t weapon
What a player holds, by its id in the items file.
Definition animator.h:56
protocol::Motion to
Definition animator.h:77
std::vector< uint32_t > wearing
What else a player wears, by its ids in the items file.
Definition animator.h:58
std::optional< Features > features
Definition animator.h:38
ImFont * text
Definition theme.h:42
ImFont * title
Definition theme.h:44
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::map< uint32_t, items::Item > by_id
Definition items.h:19