LUS Cleanup: Console class is now in the Ship namespace

This commit is contained in:
Kenix3 2022-07-31 23:36:21 -04:00
parent 1bf7771981
commit 352b46c1f5
6 changed files with 266 additions and 263 deletions

View File

@ -10,35 +10,36 @@
#include "Utils/StringHelper.h"
#include "Lib/ImGui/imgui_internal.h"
std::map<ImGuiKey, std::string> Bindings;
std::map<ImGuiKey, std::string> BindingToggle;
namespace Ship {
std::map<ImGuiKey, std::string> Bindings;
std::map<ImGuiKey, std::string> BindingToggle;
static bool HelpCommand(const std::vector<std::string>&) {
static bool HelpCommand(const std::vector<std::string>&) {
INFO("SoH Commands:");
for(const auto& cmd : SohImGui::console->Commands) {
for (const auto& cmd : SohImGui::console->Commands) {
INFO("%s", (" - " + cmd.first).c_str());
}
return CMD_SUCCESS;
}
}
static bool ClearCommand(const std::vector<std::string>&) {
static bool ClearCommand(const std::vector<std::string>&) {
SohImGui::console->Log[SohImGui::console->selected_channel].clear();
return CMD_SUCCESS;
}
}
std::string toLowerCase(std::string in) {
std::string toLowerCase(std::string in) {
std::string cpy(in);
std::transform(cpy.begin(), cpy.end(), cpy.begin(), ::tolower);
return cpy;
}
}
static bool BindCommand(const std::vector<std::string>& args) {
if(args.size() > 2) {
static bool BindCommand(const std::vector<std::string>& args) {
if (args.size() > 2) {
const ImGuiIO* io = &ImGui::GetIO();;
for (size_t k = 0; k < std::size(io->KeysData); k++) {
std::string key(ImGui::GetKeyName(k));
if(toLowerCase(args[1]) == toLowerCase(key)) {
if (toLowerCase(args[1]) == toLowerCase(key)) {
std::vector<std::string> tmp;
const char* const delim = " ";
std::ostringstream imploded;
@ -50,9 +51,9 @@ static bool BindCommand(const std::vector<std::string>& args) {
}
}
return CMD_SUCCESS;
}
}
static bool BindToggleCommand(const std::vector<std::string>& args) {
static bool BindToggleCommand(const std::vector<std::string>& args) {
if (args.size() > 2) {
const ImGuiIO* io = &ImGui::GetIO();;
for (size_t k = 0; k < std::size(io->KeysData); k++) {
@ -66,16 +67,16 @@ static bool BindToggleCommand(const std::vector<std::string>& args) {
}
}
return CMD_SUCCESS;
}
}
std::string BuildUsage(const CommandEntry& entry) {
std::string BuildUsage(const CommandEntry& entry) {
std::string usage;
for (const auto& arg : entry.arguments)
usage += StringHelper::Sprintf(arg.optional ? "[%s] " : "<%s> ", arg.info.c_str());
return usage;
}
}
void Console::Init() {
void Console::Init() {
this->InputBuffer = new char[MAX_BUFFER_SIZE];
strcpy(this->InputBuffer, "");
this->FilterBuffer = new char[MAX_BUFFER_SIZE];
@ -84,10 +85,10 @@ void Console::Init() {
this->Commands["clear"] = { ClearCommand, "Clear the console history" };
this->Commands["bind"] = { BindCommand, "Binds key to commands" };
this->Commands["bind-toggle"] = { BindToggleCommand, "Bind key as a bool toggle" };
}
}
void Console::Update() {
for(auto [key, cmd] : Bindings) {
void Console::Update() {
for (auto [key, cmd] : Bindings) {
if (ImGui::IsKeyPressed(key)) Dispatch(cmd);
}
for (auto [key, var] : BindingToggle) {
@ -96,9 +97,9 @@ void Console::Update() {
Dispatch("set " + var + " " + std::to_string(cvar == nullptr ? 0 : !static_cast<bool>(cvar->value.valueS32)));
}
}
}
}
void Console::Draw() {
void Console::Draw() {
bool input_focus = false;
if (!this->opened) return;
@ -109,15 +110,15 @@ void Console::Draw() {
// SohImGui::ShowCursor(ImGui::IsWindowHovered(ImGuiHoveredFlags_RootAndChildWindows | ImGuiHoveredFlags_RectOnly), SohImGui::Dialogues::dConsole);
// Renders autocomplete window
if(this->OpenAutocomplete) {
if (this->OpenAutocomplete) {
ImGui::SetNextWindowSize(ImVec2(350, std::min(static_cast<int>(this->Autocomplete.size()), 3) * 20.f), ImGuiCond_Once);
ImGui::SetNextWindowPos(ImVec2(pos.x + 8, pos.y + size.y - 1));
ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(3, 3));
ImGui::Begin("##WndAutocomplete", nullptr, ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoMove );
ImGui::Begin("##WndAutocomplete", nullptr, ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoMove);
ImGui::BeginChild("AC_Child", ImVec2(0, 0), false, ImGuiWindowFlags_HorizontalScrollbar);
ImGui::PushStyleColor(ImGuiCol_FrameBgActive, ImVec4(.3f, .3f, .3f, 1.0f));
if (ImGui::BeginTable("AC_History", 1)) {
for (const auto &cmd : this->Autocomplete) {
for (const auto& cmd : this->Autocomplete) {
std::string usage = BuildUsage(this->Commands[cmd]);
std::string preview = cmd + " - " + this->Commands[cmd].description;
std::string autocomplete = (usage == NULLSTR ? cmd : usage);
@ -190,15 +191,15 @@ void Console::Draw() {
if (ImGui::BeginTable("History", 1)) {
if (ImGui::IsKeyPressed(ImGui::GetKeyIndex(ImGuiKey_DownArrow)))
if (this->selectedId < (int)this->Log.size() - 1) ++this->selectedId;
if (this->selectedId < (int)this->Log.size() - 1)++this->selectedId;
if (ImGui::IsKeyPressed(ImGui::GetKeyIndex(ImGuiKey_UpArrow)))
if (this->selectedId > 0) --this->selectedId;
if (this->selectedId > 0)--this->selectedId;
const std::vector<ConsoleLine> channel = this->Log[this->selected_channel];
for (int i = 0; i < static_cast<int>(channel.size()); i++) {
ConsoleLine line = channel[i];
if(!this->filter.empty() && line.text.find(this->filter) == std::string::npos) continue;
if(this->level_filter != NULLSTR && line.priority != (std::find(priority_filters.begin(), priority_filters.end(), this->level_filter) - priority_filters.begin()) - 1) continue;
if (!this->filter.empty() && line.text.find(this->filter) == std::string::npos) continue;
if (this->level_filter != NULLSTR && line.priority != (std::find(priority_filters.begin(), priority_filters.end(), this->level_filter) - priority_filters.begin()) - 1) continue;
std::string id = line.text + "##" + std::to_string(i);
ImGui::TableNextRow();
ImGui::TableSetColumnIndex(0);
@ -225,14 +226,14 @@ void Console::Draw() {
constexpr ImGuiInputTextFlags flags = ImGuiInputTextFlags_EnterReturnsTrue | ImGuiInputTextFlags_CallbackEdit |
ImGuiInputTextFlags_CallbackCompletion | ImGuiInputTextFlags_CallbackHistory;
ImGui::PushItemWidth(-53);
if(ImGui::InputTextWithHint("##CMDInput", ">", this->InputBuffer, MAX_BUFFER_SIZE, flags, &Console::CallbackStub, this)) {
if (ImGui::InputTextWithHint("##CMDInput", ">", this->InputBuffer, MAX_BUFFER_SIZE, flags, &Console::CallbackStub, this)) {
input_focus = true;
if(this->InputBuffer[0] != '\0' && this->InputBuffer[0] != ' ')
if (this->InputBuffer[0] != '\0' && this->InputBuffer[0] != ' ')
this->Dispatch(std::string(this->InputBuffer));
memset(this->InputBuffer, 0, MAX_BUFFER_SIZE);
}
if(this->CMDHint != NULLSTR) {
if (this->CMDHint != NULLSTR) {
if (ImGui::IsItemFocused()) {
ImGui::SetNextWindowPos(ImVec2(pos.x, pos.y + size.y));
ImGui::SameLine();
@ -246,7 +247,7 @@ void Console::Draw() {
ImGui::SameLine();
ImGui::SetCursorPosX(ImGui::GetCursorPosX() + ImGui::GetContentRegionAvail().x - 50);
if(ImGui::Button("Submit") && !input_focus && this->InputBuffer[0] != '\0' && this->InputBuffer[0] != ' '){
if (ImGui::Button("Submit") && !input_focus && this->InputBuffer[0] != '\0' && this->InputBuffer[0] != ' ') {
this->Dispatch(std::string(this->InputBuffer));
memset(this->InputBuffer, 0, MAX_BUFFER_SIZE);
}
@ -255,29 +256,29 @@ void Console::Draw() {
if (input_focus) ImGui::SetKeyboardFocusHere(-1);
ImGui::PopItemWidth();
ImGui::End();
}
}
void Console::Dispatch(const std::string& line) {
void Console::Dispatch(const std::string& line) {
this->CMDHint = NULLSTR;
this->History.push_back(line);
this->Log[this->selected_channel].push_back({ "> " + line } );
this->Log[this->selected_channel].push_back({ "> " + line });
const std::vector<std::string> cmd_args = StringHelper::Split(line, " ");
if (this->Commands.contains(cmd_args[0])) {
const CommandEntry entry = this->Commands[cmd_args[0]];
if(!entry.handler(cmd_args) && !entry.arguments.empty())
this->Log[this->selected_channel].push_back({ "[SOH] Usage: " + cmd_args[0] + " " + BuildUsage(entry), ERROR_LVL});
if (!entry.handler(cmd_args) && !entry.arguments.empty())
this->Log[this->selected_channel].push_back({ "[SOH] Usage: " + cmd_args[0] + " " + BuildUsage(entry), ERROR_LVL });
return;
}
this->Log[this->selected_channel].push_back({ "[SOH] Command not found", ERROR_LVL });
}
}
int Console::CallbackStub(ImGuiInputTextCallbackData* data) {
int Console::CallbackStub(ImGuiInputTextCallbackData* data) {
const auto instance = static_cast<Console*>(data->UserData);
const bool empty_history = instance->History.empty();
const int history_index = instance->HistoryIndex;
std::string history;
switch(data->EventKey) {
switch (data->EventKey) {
case ImGuiKey_Tab:
instance->Autocomplete.clear();
for (auto& [cmd, entry] : instance->Commands)
@ -287,7 +288,7 @@ int Console::CallbackStub(ImGuiInputTextCallbackData* data) {
break;
case ImGuiKey_UpArrow:
if (empty_history) break;
if(history_index < static_cast<int>(instance->History.size()) - 1) instance->HistoryIndex += 1;
if (history_index < static_cast<int>(instance->History.size()) - 1) instance->HistoryIndex += 1;
data->DeleteChars(0, data->BufTextLen);
data->InsertChars(0, instance->History[instance->HistoryIndex].c_str());
instance->CMDHint = NULLSTR;
@ -296,7 +297,7 @@ int Console::CallbackStub(ImGuiInputTextCallbackData* data) {
if (empty_history) break;
if (history_index > -1) instance->HistoryIndex -= 1;
data->DeleteChars(0, data->BufTextLen);
if(history_index >= 0)
if (history_index >= 0)
data->InsertChars(0, instance->History[history_index].c_str());
instance->CMDHint = NULLSTR;
break;
@ -318,9 +319,9 @@ int Console::CallbackStub(ImGuiInputTextCallbackData* data) {
}
}
return 0;
}
}
void Console::Append(const std::string& channel, Priority priority, const char* fmt, ...) {
void Console::Append(const std::string& channel, Priority priority, const char* fmt, ...) {
char buf[1024];
va_list args;
va_start(args, fmt);
@ -328,4 +329,5 @@ void Console::Append(const std::string& channel, Priority priority, const char*
buf[IM_ARRAYSIZE(buf) - 1] = 0;
va_end(args);
this->Log[channel].push_back({ std::string(buf), priority });
}
}

View File

@ -7,52 +7,53 @@
#include "Lib/ImGui/imgui.h"
#define LOG(msg, ...) SohImGui::console->Append("Main", Priority::LOG_LVL, msg, ##__VA_ARGS__)
#define INFO(msg, ...) SohImGui::console->Append("Main", Priority::INFO_LVL, msg, ##__VA_ARGS__)
#define WARNING(msg, ...) SohImGui::console->Append("Main", Priority::WARNING_LVL, msg, ##__VA_ARGS__)
#define ERROR(msg, ...) SohImGui::console->Append("Main", Priority::ERROR_LVL, msg, ##__VA_ARGS__)
#define CMD_SUCCESS true
#define CMD_FAILED false
#define MAX_BUFFER_SIZE 255
#define NULLSTR "None"
namespace Ship {
#define LOG(msg, ...) SohImGui::console->Append("Main", Ship::Priority::LOG_LVL, msg, ##__VA_ARGS__)
#define INFO(msg, ...) SohImGui::console->Append("Main", Ship::Priority::INFO_LVL, msg, ##__VA_ARGS__)
#define WARNING(msg, ...) SohImGui::console->Append("Main", Ship::Priority::WARNING_LVL, msg, ##__VA_ARGS__)
#define ERROR(msg, ...) SohImGui::console->Append("Main", Ship::Priority::ERROR_LVL, msg, ##__VA_ARGS__)
#define CMD_SUCCESS true
#define CMD_FAILED false
#define MAX_BUFFER_SIZE 255
#define NULLSTR "None"
typedef std::function<bool(std::vector<std::string> args)> CommandHandler;
typedef std::function<bool(std::vector<std::string> args)> CommandHandler;
enum Priority {
enum Priority {
INFO_LVL,
LOG_LVL,
WARNING_LVL,
ERROR_LVL
};
};
enum class ArgumentType {
enum class ArgumentType {
TEXT, NUMBER, PLAYER_POS, PLAYER_ROT
};
};
struct CommandArgument {
struct CommandArgument {
std::string info;
ArgumentType type = ArgumentType::NUMBER;
bool optional = false;
};
};
struct CommandEntry {
struct CommandEntry {
CommandHandler handler;
std::string description;
std::vector<CommandArgument> arguments;
};
};
struct ConsoleLine {
struct ConsoleLine {
std::string text;
Priority priority = Priority::INFO_LVL;
std::string channel = "Main";
};
};
class Console {
class Console {
int selectedId = -1;
std::vector<int> selectedEntries;
std::string filter;
std::string level_filter = NULLSTR;
std::vector<std::string> log_channels = { "Main", "SoH Logging"};
std::vector<std::string> log_channels = { "Main", "SoH Logging" };
std::vector<std::string> priority_filters = { "None", "Info", "Log", "Warning", "Error" };
std::vector<ImVec4> priority_colors = {
ImVec4(1.0f, 1.0f, 1.0f, 1.0f),
@ -60,7 +61,7 @@ class Console {
ImVec4(0.9f, 0.8f, 0.4f, 0.01f),
ImVec4(1.0f, 0.2f, 0.2f, 1.0f)
};
public:
public:
std::map<std::string, std::vector<ConsoleLine>> Log;
std::map<std::string, CommandEntry> Commands;
std::vector<std::string> Autocomplete;
@ -78,4 +79,5 @@ public:
void Append(const std::string& channel, Priority priority, const char* fmt, ...) IM_FMTARGS(4);
void Dispatch(const std::string& line);
static int CallbackStub(ImGuiInputTextCallbackData* data);
};
};
}

View File

@ -69,7 +69,7 @@ namespace SohImGui {
WindowDrawFunc drawFunc;
} CustomWindow;
extern Console* console;
extern Ship::Console* console;
extern Ship::InputEditor* controller;
extern Ship::GameOverlay* overlay;
extern bool needs_save;
@ -92,7 +92,7 @@ namespace SohImGui {
void Render(void);
void CancelFrame(void);
void ShowCursor(bool hide, Dialogues w);
void BindCmd(const std::string& cmd, CommandEntry entry);
void BindCmd(const std::string& cmd, Ship::CommandEntry entry);
void AddWindow(const std::string& category, const std::string& name, WindowDrawFunc drawFunc, bool isEnabled=false, bool isHidden=false);
void LoadResource(const std::string& name, const std::string& path, const ImVec4& tint = ImVec4(1, 1, 1, 1));
void LoadPickersColors(ImVec4& ColorArray, const char* cvarname, const ImVec4& default_colors, bool has_alpha=false);

View File

@ -358,7 +358,6 @@ static void gfx_dxgi_show_cursor(bool hide) {
* @bug When menubar is open in windowed mode and you toggle fullscreen
* ShowCursor no longer responds. Debugging shows the bool to be correct.
**/
INFO("renderer: %s", hide ? "true" : "false");
ShowCursor(hide);
}

View File

@ -34,7 +34,7 @@ public:
protected:
void sink_it_(const details::log_msg &msg) override
{
const Priority priority = convert_to_soh(msg.level);
const Ship::Priority priority = convert_to_soh(msg.level);
memory_buf_t formatted;
if (use_raw_msg_)
{
@ -53,24 +53,25 @@ protected:
void flush_() override {}
private:
static Priority convert_to_soh(spdlog::level::level_enum level) {
static Ship::Priority convert_to_soh(spdlog::level::level_enum level)
{
switch (level) {
case spdlog::level::trace:
return Priority::INFO_LVL;
return Ship::Priority::INFO_LVL;
case spdlog::level::debug:
return Priority::LOG_LVL;
return Ship::Priority::LOG_LVL;
case spdlog::level::info:
return Priority::LOG_LVL;
return Ship::Priority::LOG_LVL;
case spdlog::level::warn:
return Priority::WARNING_LVL;
return Ship::Priority::WARNING_LVL;
case spdlog::level::err:
return Priority::ERROR_LVL;
return Ship::Priority::ERROR_LVL;
case spdlog::level::critical:
return Priority::ERROR_LVL;
return Ship::Priority::ERROR_LVL;
default:
break;
}
return Priority::LOG_LVL;
return Ship::Priority::LOG_LVL;
}
std::string tag_;

View File

@ -463,50 +463,49 @@ void DebugConsole_Init(void) {
CMD_REGISTER("kill", { KillPlayerHandler, "Commit suicide." });
CMD_REGISTER("map", { LoadSceneHandler, "Load up kak?" });
CMD_REGISTER("rupee", { RuppeHandler, "Set your rupee counter.", {
{"amount", ArgumentType::NUMBER }
{"amount", Ship::ArgumentType::NUMBER }
}});
CMD_REGISTER("bItem", { BHandler, "Set an item to the B button.", { { "Item ID", ArgumentType::NUMBER } } });
CMD_REGISTER("health", { SetPlayerHealthHandler, "Set the health of the player.", {
{"health", ArgumentType::NUMBER }
CMD_REGISTER("bItem", { BHandler, "Set an item to the B button.", { { "Item ID", Ship::ArgumentType::NUMBER } } });
CMD_REGISTER("health", { SetPlayerHealthHandler, "Set the health of the player.", { { "health", Ship::ArgumentType::NUMBER }
}});
CMD_REGISTER("spawn", { ActorSpawnHandler, "Spawn an actor.", {
{ "actor_id", ArgumentType::NUMBER },
{ "data", ArgumentType::NUMBER },
{ "x", ArgumentType::PLAYER_POS, true },
{ "y", ArgumentType::PLAYER_POS, true },
{ "z", ArgumentType::PLAYER_POS, true },
{ "rx", ArgumentType::PLAYER_ROT, true },
{ "ry", ArgumentType::PLAYER_ROT, true },
{ "rz", ArgumentType::PLAYER_ROT, true }
CMD_REGISTER("spawn", { ActorSpawnHandler, "Spawn an actor.", { { "actor_id", Ship::ArgumentType::NUMBER },
{ "data", Ship::ArgumentType::NUMBER },
{ "x", Ship::ArgumentType::PLAYER_POS, true },
{ "y", Ship::ArgumentType::PLAYER_POS, true },
{ "z", Ship::ArgumentType::PLAYER_POS, true },
{ "rx", Ship::ArgumentType::PLAYER_ROT, true },
{ "ry", Ship::ArgumentType::PLAYER_ROT, true },
{ "rz", Ship::ArgumentType::PLAYER_ROT, true }
}});
CMD_REGISTER("pos", { SetPosHandler, "Sets the position of the player.", {
{ "x", ArgumentType::PLAYER_POS, true },
{ "y", ArgumentType::PLAYER_POS, true },
{ "z", ArgumentType::PLAYER_POS, true }
CMD_REGISTER("pos", { SetPosHandler, "Sets the position of the player.", { { "x", Ship::ArgumentType::PLAYER_POS, true },
{ "y", Ship::ArgumentType::PLAYER_POS, true },
{ "z", Ship::ArgumentType::PLAYER_POS, true }
}});
CMD_REGISTER("set", { SetCVarHandler,
"Sets a console variable.",
{ { "varName", ArgumentType::TEXT }, { "varValue", ArgumentType::TEXT } } });
CMD_REGISTER("get", { GetCVarHandler, "Gets a console variable.", { { "varName", ArgumentType::TEXT } } });
{ { "varName", Ship::ArgumentType::TEXT }, { "varValue", Ship::ArgumentType::TEXT } } });
CMD_REGISTER("get", { GetCVarHandler, "Gets a console variable.", { { "varName", Ship::ArgumentType::TEXT } } });
CMD_REGISTER("reset", { ResetHandler, "Resets the game." });
CMD_REGISTER("ammo", { AmmoHandler, "Changes ammo of an item.",
{ { "item", ArgumentType::TEXT },
{ "count", ArgumentType::NUMBER } } });
{ { "item", Ship::ArgumentType::TEXT }, { "count", Ship::ArgumentType::NUMBER } } });
CMD_REGISTER("bottle", { BottleHandler,
"Changes item in a bottle slot.",
{ { "item", ArgumentType::TEXT }, { "slot", ArgumentType::NUMBER } } });
{ { "item", Ship::ArgumentType::TEXT }, { "slot", Ship::ArgumentType::NUMBER } } });
CMD_REGISTER("item", { ItemHandler,
"Sets item ID in arg 1 into slot arg 2. No boundary checks. Use with caution.",
{ { "slot", ArgumentType::NUMBER }, { "item id", ArgumentType::NUMBER } } });
CMD_REGISTER("entrance",
{ EntranceHandler, "Sends player to the entered entrance (hex)", { { "entrance", ArgumentType::NUMBER } } });
{ { "slot", Ship::ArgumentType::NUMBER }, { "item id", Ship::ArgumentType::NUMBER } } });
CMD_REGISTER("entrance", { EntranceHandler,
"Sends player to the entered entrance (hex)",
{ { "entrance", Ship::ArgumentType::NUMBER } } });
CMD_REGISTER("save_state", { SaveStateHandler, "Save a state." });
CMD_REGISTER("load_state", { LoadStateHandler, "Load a state." });
CMD_REGISTER("set_slot", { StateSlotSelectHandler, "Selects a SaveState slot", {
{ "Slot number", ArgumentType::NUMBER, }
CMD_REGISTER("set_slot", { StateSlotSelectHandler, "Selects a SaveState slot", { {
"Slot number",
Ship::ArgumentType::NUMBER,
}
} });
DebugConsole_LoadCVars();
}