about summary refs log tree commit diff stats
path: root/data/maps/the_jubilant
diff options
context:
space:
mode:
Diffstat (limited to 'data/maps/the_jubilant')
0 files changed, 0 insertions, 0 deletions
a id='n84' href='#n84'>84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903
#include "ap_state.h"

#define HAS_STD_FILESYSTEM
#define _WEBSOCKETPP_CPP11_STRICT_
#pragma comment(lib, "crypt32")

#include <fmt/core.h>
#include <hkutil/string.h>

#include <any>
#include <apclient.hpp>
#include <apuuid.hpp>
#include <bitset>
#include <chrono>
#include <exception>
#include <filesystem>
#include <list>
#include <memory>
#include <mutex>
#include <set>
#include <sstream>
#include <thread>
#include <tuple>

#include "game_data.h"
#include "ipc_state.h"
#include "logger.h"
#include "tracker_frame.h"
#include "tracker_state.h"

constexpr int AP_MAJOR = 0;
constexpr int AP_MINOR = 4;
constexpr int AP_REVISION = 5;

constexpr const char* CERT_STORE_PATH = "cacert.pem";
constexpr int ITEM_HANDLING = 7;  // <- all

constexpr int CONNECTION_TIMEOUT = 50000;  // 50 seconds
constexpr int CONNECTION_BACKOFF_INTERVAL = 100;

constexpr int PANEL_COUNT = 803;
constexpr int PANEL_BITFIELD_LENGTH = 48;
constexpr int PANEL_BITFIELDS = 17;

namespace {

const std::set<long> kNonProgressionItems = {
    444409,  // :)
    444575,  // The Feeling of Being Lost
    444576,  // Wanderlust
    444577,  // Empty White Hallways
    444410,  // Slowness Trap
    444411,  // Iceland Trap
    444412,  // Atbash Trap
    444413,  // Puzzle Skip
    444680,  // Speed Boost
};

struct APState {
  // Initialized on main thread
  bool initialized = false;
  TrackerFrame* tracker_frame = nullptr;
  std::list<std::string> tracked_data_storage_keys;

  // Client
  std::mutex client_mutex;
  std::unique_ptr<APClient> apclient;

  // Protected state
  std::mutex state_mutex;

  std::string status_message = "Not connected to Archipelago.";

  bool connected = false;
  std::string connection_failure;
  int remaining_loops = 0;

  std::string data_storage_prefix;
  std::string victory_data_storage_key;

  std::string save_name;

  std::map<int64_t, int> inventory;
  std::set<int64_t> checked_locations;
  std::map<std::string, std::any> data_storage;
  std::optional<std::tuple<int, int>> player_pos;
  std::bitset<PANEL_COUNT> solved_panels;

  DoorShuffleMode door_shuffle_mode = kNO_DOORS;
  bool group_doors = false;
  bool color_shuffle = false;
  PanelShuffleMode panel_shuffle_mode = kNO_PANELS;
  bool painting_shuffle = false;
  int mastery_requirement = 21;
  int level_2_requirement = 223;
  LocationChecks location_checks = kNORMAL_LOCATIONS;
  VictoryCondition victory_condition = kTHE_END;
  bool early_color_hallways = false;
  bool pilgrimage_enabled = false;
  bool pilgrimage_allows_roof_access = false;
  bool pilgrimage_allows_paintings = false;
  SunwarpAccess sunwarp_access = kSUNWARP_ACCESS_NORMAL;
  bool sunwarp_shuffle = false;
  bool postgame_shuffle = true;

  std::map<std::string, std::string> painting_mapping;
  std::set<std::string> painting_codomain;
  std::map<int, SunwarpMapping> sunwarp_mapping;

  void Connect(std::string server, std::string player, std::string password) {
    Initialize();

    {
      std::lock_guard state_guard(state_mutex);
      SetStatusMessage("Connecting to Archipelago server....");
    }
    TrackerLog(fmt::format("Connecting to Archipelago server ({})...", server));

    // Creating and setting up the client has to all be done while holding the
    // client mutex, so that the other thread doesn't try to poll before we add
    // handlers, etc.
    {
      TrackerLog("Destroying old AP client...");

      std::lock_guard client_guard(client_mutex);

      if (apclient) {
        DestroyClient();
      }

      std::string cert_store = "";
      if (std::filesystem::exists(CERT_STORE_PATH)) {
        cert_store = CERT_STORE_PATH;
      }

      apclient = std::make_unique<APClient>(ap_get_uuid(""), "Lingo", server,
                                            cert_store);

      {
        std::lock_guard state_guard(state_mutex);

        connected = false;
        connection_failure.clear();
        remaining_loops = CONNECTION_TIMEOUT / CONNECTION_BACKOFF_INTERVAL;

        save_name.clear();
        inventory.clear();
        checked_locations.clear();
        data_storage.clear();
        player_pos = std::nullopt;
        solved_panels.reset();
        victory_data_storage_key.clear();
        door_shuffle_mode = kNO_DOORS;
        group_doors = false;
        color_shuffle = false;
        panel_shuffle_mode = kNO_PANELS;
        painting_shuffle = false;
        painting_mapping.clear();
        painting_codomain.clear();
        mastery_requirement = 21;
        level_2_requirement = 223;
        location_checks = kNORMAL_LOCATIONS;
        victory_condition = kTHE_END;
        early_color_hallways = false;
        pilgrimage_enabled = false;
        pilgrimage_allows_roof_access = false;
        pilgrimage_allows_paintings = false;
        sunwarp_access = kSUNWARP_ACCESS_NORMAL;
        sunwarp_shuffle = false;
        sunwarp_mapping.clear();
        postgame_shuffle = true;
      }

      apclient->set_room_info_handler(
          [this, player, password]() { OnRoomInfo(player, password); });

      apclient->set_location_checked_handler(
          [this](const std::list<int64_t>& locations) {
            OnLocationChecked(locations);
          });

      apclient->set_slot_disconnected_handler(
          [this]() { OnSlotDisconnected(); });

      apclient->set_socket_disconnected_handler(
          [this]() { OnSocketDisconnected(); });

      apclient->set_items_received_handler(
          [this](const std::list<APClient::NetworkItem>& items) {
            OnItemsReceived(items);
          });

      apclient->set_retrieved_handler(
          [this](const std::map<std::string, nlohmann::json>& data) {
            OnRetrieved(data);
          });

      apclient->set_set_reply_handler(
          [this](const std::string& key, const nlohmann::json& value,
                 const nlohmann::json&) { OnSetReply(key, value); });

      apclient->set_slot_connected_handler(
          [this, player, server](const nlohmann::json& slot_data) {
            OnSlotConnected(player, server, slot_data);
          });

      apclient->set_slot_refused_handler(
          [this](const std::list<std::string>& errors) {
            OnSlotRefused(errors);
          });
    }
  }

  std::string GetStatusMessage() {
    std::lock_guard state_guard(state_mutex);

    return status_message;
  }

  bool HasCheckedGameLocation(int location_id) {
    std::lock_guard state_guard(state_mutex);

    return checked_locations.count(location_id);
  }

  bool HasItem(int item_id, int quantity) {
    return inventory.count(item_id) && inventory.at(item_id) >= quantity;
  }

  bool HasItemSafe(int item_id, int quantity) {
    std::lock_guard state_guard(state_mutex);
    return HasItem(item_id, quantity);
  }

  bool HasAchievement(const std::string& name) {
    std::lock_guard state_guard(state_mutex);

    std::string key =
        fmt::format("{}Achievement|{}", data_storage_prefix, name);
    return data_storage.count(key) && std::any_cast<bool>(data_storage.at(key));
  }

  const std::set<std::string>& GetCheckedPaintings() {
    std::lock_guard state_guard(state_mutex);

    std::string key = fmt::format("{}Paintings", data_storage_prefix);
    if (!data_storage.count(key)) {
      data_storage[key] = std::set<std::string>();
    }

    return std::any_cast<const std::set<std::string>&>(data_storage.at(key));
  }

  bool IsPaintingChecked(const std::string& painting_id) {
    const auto& checked_paintings = GetCheckedPaintings();

    std::lock_guard state_guard(state_mutex);

    return checked_paintings.count(painting_id) ||
           (painting_mapping.count(painting_id) &&
            checked_paintings.count(painting_mapping.at(painting_id)));
  }

  void RevealPaintings() {
    std::lock_guard state_guard(state_mutex);

    std::vector<std::string> paintings;
    for (const PaintingExit& painting : GD_GetPaintings()) {
      paintings.push_back(painting.internal_id);
    }

    APClient::DataStorageOperation operation;
    operation.operation = "replace";
    operation.value = paintings;

    apclient->Set(fmt::format("{}Paintings", data_storage_prefix), "", true,
                  {operation});
  }

  bool HasReachedGoal() {
    std::lock_guard state_guard(state_mutex);

    return data_storage.count(victory_data_storage_key) &&
           std::any_cast<int>(data_storage.at(victory_data_storage_key)) ==
               30;  // CLIENT_GOAL
  }

  bool IsPanelSolved(int solve_index) {
    std::lock_guard state_guard(state_mutex);

    return solved_panels.test(solve_index);
  }

 private:
  void Initialize() {
    if (!initialized) {
      TrackerLog("Initializing APState...");

      std::thread([this]() { Thread(); }).detach();

      for (int panel_id : GD_GetAchievementPanels()) {
        tracked_data_storage_keys.push_back(fmt::format(
            "Achievement|{}", GD_GetPanel(panel_id).achievement_name));
      }

      for (int i = 0; i < PANEL_BITFIELDS; i++) {
        tracked_data_storage_keys.push_back(fmt::format("Panels_{}", i));
      }

      tracked_data_storage_keys.push_back("PlayerPos");
      tracked_data_storage_keys.push_back("Paintings");

      initialized = true;
    }
  }

  void Thread() {
    std::string display_error;

    for (;;) {
      {
        std::lock_guard client_guard(client_mutex);
        if (apclient) {
          apclient->poll();

          {
            std::lock_guard state_guard(state_mutex);

            if (!connected) {
              if (!connection_failure.empty()) {
                TrackerLog(connection_failure);

                display_error = connection_failure;
                connection_failure.clear();

                DestroyClient();
              } else {
                remaining_loops--;

                if (remaining_loops <= 0) {
                  DestroyClient();

                  SetStatusMessage("Disconnected from Archipelago.");
                  TrackerLog("Timeout while connecting to Archipelago server.");

                  display_error =
                      "Timeout while connecting to Archipelago server.";
                }
              }
            }
          }
        }
      }

      if (!display_error.empty()) {
        wxMessageBox(display_error, "Connection failed", wxOK | wxICON_ERROR);
        display_error.clear();
      }

      std::this_thread::sleep_for(std::chrono::milliseconds(100));
    }
  }

  void OnRoomInfo(std::string player, std::string password) {
    {
      std::lock_guard state_guard(state_mutex);

      inventory.clear();

      SetStatusMessage("Connected to Archipelago server. Authenticating...");
    }

    TrackerLog(fmt::format(
        "Connected to Archipelago server. Authenticating as {} {}", player,
        (password.empty() ? "without password" : "with password " + password)));

    apclient->ConnectSlot(player, password, ITEM_HANDLING, {"Tracker"},
                          {AP_MAJOR, AP_MINOR, AP_REVISION});
  }

  void OnLocationChecked(const std::list<int64_t>& locations) {
    {
      std::lock_guard state_guard(state_mutex);

      for (const int64_t location_id : locations) {
        checked_locations.insert(location_id);
        TrackerLog(fmt::format("Location: {}", location_id));
      }
    }

    RefreshTracker(StateUpdate{.cleared_locations = true});
  }

  void OnSlotDisconnected() {
    std::lock_guard state_guard(state_mutex);

    SetStatusMessage(
        "Disconnected from Archipelago. Attempting to reconnect...");
    TrackerLog(
        "Slot disconnected from Archipelago. Attempting to reconnect...");
  }

  void OnSocketDisconnected() {
    std::lock_guard state_guard(state_mutex);

    SetStatusMessage(
        "Disconnected from Archipelago. Attempting to reconnect...");
    TrackerLog(
        "Socket disconnected from Archipelago. Attempting to reconnect...");
  }

  void OnItemsReceived(const std::list<APClient::NetworkItem>& items) {
    std::vector<ItemState> item_states;
    bool progression_items = false;

    {
      std::lock_guard state_guard(state_mutex);

      std::map<int64_t, int> index_by_item;

      for (const APClient::NetworkItem& item : items) {
        inventory[item.item]++;
        TrackerLog(fmt::format("Item: {}", item.item));

        index_by_item[item.item] = item.index;

        if (!kNonProgressionItems.count(item.item)) {
          progression_items = true;
        }
      }

      for (const auto& [item_id, item_index] : index_by_item) {
        item_states.push_back(ItemState{.name = GD_GetItemName(item_id),
                                        .amount = inventory[item_id],
                                        .index = item_index});
      }
    }

    RefreshTracker(StateUpdate{.items = item_states,
                               .progression_items = progression_items});
  }

  void OnRetrieved(const std::map<std::string, nlohmann::json>& data) {
    StateUpdate state_update;

    {
      std::lock_guard state_guard(state_mutex);

      for (const auto& [key, value] : data) {
        HandleDataStorage(key, value, state_update);
      }
    }

    RefreshTracker(state_update);
  }

  void OnSetReply(const std::string& key, const nlohmann::json& value) {
    StateUpdate state_update;

    {
      std::lock_guard state_guard(state_mutex);
      HandleDataStorage(key, value, state_update);
    }

    RefreshTracker(state_update);
  }

  void OnSlotConnected(std::string player, std::string server,
                       const nlohmann::json& slot_data) {
    IPC_SetTrackerSlot(server, player);

    TrackerLog("Connected to Archipelago!");

    {
      std::lock_guard state_guard(state_mutex);

      SetStatusMessage(
          fmt::format("Connected to Archipelago! ({}@{}).", player, server));

      save_name = fmt::format("zzAP_{}_{}.save", apclient->get_seed(),
                              apclient->get_player_number());
      data_storage_prefix =
          fmt::format("Lingo_{}_", apclient->get_player_number());
      door_shuffle_mode = slot_data["shuffle_doors"].get<DoorShuffleMode>();
      if (slot_data.contains("group_doors")) {
        group_doors = slot_data.contains("group_doors") &&
                      slot_data["group_doors"].get<int>() == 1;
      } else {
        // If group_doors doesn't exist yet, that means kPANELS_MODE is
        // actually kSIMPLE_DOORS.
        if (door_shuffle_mode == kPANELS_MODE) {
          door_shuffle_mode = kDOORS_MODE;
          group_doors = true;
        }
      }
      color_shuffle = slot_data["shuffle_colors"].get<int>() == 1;
      panel_shuffle_mode = slot_data["shuffle_panels"].get<PanelShuffleMode>();
      painting_shuffle = slot_data["shuffle_paintings"].get<int>() == 1;
      mastery_requirement = slot_data["mastery_achievements"].get<int>();
      level_2_requirement = slot_data["level_2_requirement"].get<int>();
      location_checks = slot_data["location_checks"].get<LocationChecks>();
      victory_condition =
          slot_data["victory_condition"].get<VictoryCondition>();
      early_color_hallways = slot_data.contains("early_color_hallways") &&
                             slot_data["early_color_hallways"].get<int>() == 1;
      pilgrimage_enabled = slot_data.contains("enable_pilgrimage") &&
                           slot_data["enable_pilgrimage"].get<int>() == 1;
      pilgrimage_allows_roof_access =
          slot_data.contains("pilgrimage_allows_roof_access") &&
          slot_data["pilgrimage_allows_roof_access"].get<int>() == 1;
      pilgrimage_allows_paintings =
          slot_data.contains("pilgrimage_allows_paintings") &&
          slot_data["pilgrimage_allows_paintings"].get<int>() == 1;
      sunwarp_access = slot_data.contains("sunwarp_access")
                           ? slot_data["sunwarp_access"].get<SunwarpAccess>()
                           : kSUNWARP_ACCESS_NORMAL;
      sunwarp_shuffle = slot_data.contains("shuffle_sunwarps") &&
                        slot_data["shuffle_sunwarps"].get<int>() == 1;
      postgame_shuffle = slot_data.contains("shuffle_postgame") &&
                         slot_data["shuffle_postgame"].get<int>() == 1;

      if (painting_shuffle && slot_data.contains("painting_entrance_to_exit")) {
        painting_mapping.clear();

        for (const auto& mapping_it :
             slot_data["painting_entrance_to_exit"].items()) {
          painting_mapping[mapping_it.key()] = mapping_it.value();
          painting_codomain.insert(mapping_it.value());
        }
      }

      if (sunwarp_shuffle && slot_data.contains("sunwarp_permutation")) {
        std::vector<int> inverted_sunwarps;
        for (const auto& item : slot_data["sunwarp_permutation"]) {
          inverted_sunwarps.push_back(item);
        }

        for (int i = 0; i < 6; i++) {
          sunwarp_mapping[inverted_sunwarps[i]] = SunwarpMapping{
              .dots = i + 1, .exit_index = inverted_sunwarps[i + 6]};
        }
      }

      std::list<std::string> corrected_keys;
      for (const std::string& key : tracked_data_storage_keys) {
        corrected_keys.push_back(data_storage_prefix + key);
      }

      victory_data_storage_key =
          fmt::format("_read_client_status_{}_{}", apclient->get_team_number(),
                      apclient->get_player_number());

      corrected_keys.push_back(victory_data_storage_key);

      apclient->Get(corrected_keys);
      apclient->SetNotify(corrected_keys);

      connected = true;
    }

    ResetReachabilityRequirements();
    RefreshTracker(std::nullopt);
  }

  void OnSlotRefused(const std::list<std::string>& errors) {
    std::vector<std::string> error_messages;
    error_messages.push_back("Could not connect to Archipelago.");

    for (const std::string& error : errors) {
      if (error == "InvalidSlot") {
        error_messages.push_back("Invalid player name.");
      } else if (error == "InvalidGame") {
        error_messages.push_back("The specified player is not playing Lingo.");
      } else if (error == "IncompatibleVersion") {
        error_messages.push_back(
            "The Archipelago server is not the correct version for this "
            "client.");
      } else if (error == "InvalidPassword") {
        error_messages.push_back("Incorrect password.");
      } else if (error == "InvalidItemsHandling") {
        error_messages.push_back(
            "Invalid item handling flag. This is a bug with the tracker. "
            "Please report it to the lingo-ap-tracker GitHub.");
      } else {
        error_messages.push_back("Unknown error.");
      }
    }

    {
      std::lock_guard state_guard(state_mutex);
      connection_failure = hatkirby::implode(error_messages, " ");

      SetStatusMessage("Disconnected from Archipelago.");
    }
  }

  // Assumes state mutex is locked.
  void SetStatusMessage(std::string msg) {
    status_message = std::move(msg);

    tracker_frame->UpdateStatusMessage();
  }

  // Assumes state mutex is locked.
  void HandleDataStorage(const std::string& key, const nlohmann::json& value, StateUpdate& state_update) {
    if (value.is_boolean()) {
      data_storage[key] = value.get<bool>();
      TrackerLog(fmt::format("Data storage {} retrieved as {}", key,
                             (value.get<bool>() ? "true" : "false")));

      if (key.find("Achievement|") != std::string::npos) {
        state_update.achievements = true;
      }
    } else if (value.is_number()) {
      data_storage[key] = value.get<int>();
      TrackerLog(fmt::format("Data storage {} retrieved as {}", key,
                             value.get<int>()));

      if (key == victory_data_storage_key) {
        state_update.cleared_locations = true;
      } else if (key.find("Panels_") != std::string::npos) {
        int bitfield_num =
            std::stoi(key.substr(data_storage_prefix.size() + 7));
        uint64_t bitfield_value = value.get<uint64_t>();
        for (int i = 0; i < PANEL_BITFIELD_LENGTH; i++) {
          if ((bitfield_value & (1LL << i)) != 0) {
            int solve_index = bitfield_num * PANEL_BITFIELD_LENGTH + i;
            
            if (!solved_panels.test(solve_index)) {
              state_update.panels.insert(solve_index);
            }
            
            solved_panels.set(solve_index);
          }
        }
      }
    } else if (value.is_object()) {
      if (key.ends_with("PlayerPos")) {
        auto map_value = value.get<std::map<std::string, int>>();
        player_pos = std::tuple<int, int>(map_value["x"], map_value["z"]);
        state_update.player_position = true;
      } else {
        data_storage[key] = value.get<std::map<std::string, int>>();
      }

      TrackerLog(fmt::format("Data storage {} retrieved as dictionary", key));
    } else if (value.is_null()) {
      if (key.ends_with("PlayerPos")) {
        player_pos = std::nullopt;
        state_update.player_position = true;
      } else {
        data_storage.erase(key);
      }

      TrackerLog(fmt::format("Data storage {} retrieved as null", key));
    } else if (value.is_array()) {
      auto list_value = value.get<std::vector<std::string>>();

      if (key.ends_with("Paintings")) {
        data_storage[key] =
            std::set<std::string>(list_value.begin(), list_value.end());
        state_update.paintings =
            std::vector<std::string>(list_value.begin(), list_value.end());
      } else {
        data_storage[key] = list_value;
      }

      TrackerLog(fmt::format("Data storage {} retrieved as list: [{}]", key,
                             hatkirby::implode(list_value, ", ")));
    }
  }

  // State mutex should NOT be locked.
  // nullopt state_update indicates a reset.
  void RefreshTracker(std::optional<StateUpdate> state_update) {
    TrackerLog("Refreshing display...");

    if (!state_update || state_update->progression_items ||
        !state_update->paintings.empty()) {
      std::string prev_msg;
      {
        std::lock_guard state_guard(state_mutex);

        prev_msg = status_message;
        SetStatusMessage(fmt::format("{} Recalculating...", status_message));
      }

      RecalculateReachability();

      {
        std::lock_guard state_guard(state_mutex);

        SetStatusMessage(prev_msg);
      }
    }
    

    if (!state_update) {
      tracker_frame->ResetIndicators();
    } else {
      tracker_frame->UpdateIndicators(*state_update);
    }
  }

  void DestroyClient() {
    apclient->reset();
    apclient.reset();
  }
};

APState& GetState() {
  static APState* instance = new APState();
  return *instance;
}

}  // namespace

void AP_SetTrackerFrame(TrackerFrame* arg) { GetState().tracker_frame = arg; }

void AP_Connect(std::string server, std::string player, std::string password) {
  GetState().Connect(server, player, password);
}

std::string AP_GetStatusMessage() { return GetState().GetStatusMessage(); }

std::string AP_GetSaveName() {
  std::lock_guard state_guard(GetState().state_mutex);

  return GetState().save_name;
}

bool AP_HasCheckedGameLocation(int location_id) {
  return GetState().HasCheckedGameLocation(location_id);
}

bool AP_HasItem(int item_id, int quantity) {
  return GetState().HasItem(item_id, quantity);
}

bool AP_HasItemSafe(int item_id, int quantity) {
  return GetState().HasItemSafe(item_id, quantity);
}

DoorShuffleMode AP_GetDoorShuffleMode() {
  std::lock_guard state_guard(GetState().state_mutex);

  return GetState().door_shuffle_mode;
}

bool AP_AreDoorsGrouped() {
  std::lock_guard state_guard(GetState().state_mutex);

  return GetState().group_doors;
}

bool AP_IsColorShuffle() {
  std::lock_guard state_guard(GetState().state_mutex);

  return GetState().color_shuffle;
}

bool AP_IsPaintingShuffle() {
  std::lock_guard state_guard(GetState().state_mutex);

  return GetState().painting_shuffle;
}

std::map<std::string, std::string> AP_GetPaintingMapping() {
  std::lock_guard state_guard(GetState().state_mutex);

  return GetState().painting_mapping;
}

bool AP_IsPaintingMappedTo(const std::string& painting_id) {
  std::lock_guard state_guard(GetState().state_mutex);

  return GetState().painting_codomain.count(painting_id);
}

std::set<std::string> AP_GetCheckedPaintings() {
  return GetState().GetCheckedPaintings();
}

bool AP_IsPaintingChecked(const std::string& painting_id) {
  return GetState().IsPaintingChecked(painting_id);
}

void AP_RevealPaintings() { GetState().RevealPaintings(); }

int AP_GetMasteryRequirement() {
  std::lock_guard state_guard(GetState().state_mutex);

  return GetState().mastery_requirement;
}

int AP_GetLevel2Requirement() {
  std::lock_guard state_guard(GetState().state_mutex);

  return GetState().level_2_requirement;
}

LocationChecks AP_GetLocationsChecks() {
  std::lock_guard state_guard(GetState().state_mutex);

  return GetState().location_checks;
}

bool AP_IsLocationVisible(int classification) {
  std::lock_guard state_guard(GetState().state_mutex);

  int world_state = 0;

  switch (GetState().location_checks) {
    case kNORMAL_LOCATIONS:
      world_state = kLOCATION_NORMAL;
      break;
    case kREDUCED_LOCATIONS:
      world_state = kLOCATION_REDUCED;
      break;
    case kPANELSANITY:
      world_state = kLOCATION_INSANITY;
      break;
    default:
      return false;
  }

  if (GetState().door_shuffle_mode == kDOORS_MODE &&
      !GetState().early_color_hallways) {
    world_state |= kLOCATION_SMALL_SPHERE_ONE;
  }

  return (world_state & classification);
}

PanelShuffleMode AP_GetPanelShuffleMode() {
  std::lock_guard state_guard(GetState().state_mutex);

  return GetState().panel_shuffle_mode;
}

VictoryCondition AP_GetVictoryCondition() {
  std::lock_guard state_guard(GetState().state_mutex);

  return GetState().victory_condition;
}

bool AP_HasAchievement(const std::string& achievement_name) {
  return GetState().HasAchievement(achievement_name);
}

bool AP_HasEarlyColorHallways() {
  std::lock_guard state_guard(GetState().state_mutex);

  return GetState().early_color_hallways;
}

bool AP_IsPilgrimageEnabled() {
  std::lock_guard state_guard(GetState().state_mutex);

  return GetState().pilgrimage_enabled;
}

bool AP_DoesPilgrimageAllowRoofAccess() {
  std::lock_guard state_guard(GetState().state_mutex);

  return GetState().pilgrimage_allows_roof_access;
}

bool AP_DoesPilgrimageAllowPaintings() {
  std::lock_guard state_guard(GetState().state_mutex);

  return GetState().pilgrimage_allows_paintings;
}

SunwarpAccess AP_GetSunwarpAccess() {
  std::lock_guard state_guard(GetState().state_mutex);

  return GetState().sunwarp_access;
}

bool AP_IsSunwarpShuffle() {
  std::lock_guard state_guard(GetState().state_mutex);

  return GetState().sunwarp_shuffle;
}

std::map<int, SunwarpMapping> AP_GetSunwarpMapping() {
  return GetState().sunwarp_mapping;
}

bool AP_IsPostgameShuffle() { return GetState().postgame_shuffle; }

bool AP_HasReachedGoal() { return GetState().HasReachedGoal(); }

std::optional<std::tuple<int, int>> AP_GetPlayerPosition() {
  std::lock_guard state_guard(GetState().state_mutex);

  return GetState().player_pos;
}

bool AP_IsPanelSolved(int solve_index) {
  return GetState().IsPanelSolved(solve_index);
}