space-game001/UiManager.h
2025-12-22 15:40:45 +06:00

98 lines
2.2 KiB
C++

#pragma once
#include "Renderer.h"
#include "TextureManager.h"
#include "Environment.h"
#include "external/nlohmann/json.hpp"
#include <string>
#include <vector>
#include <memory>
#include <functional>
namespace ZL {
using json = nlohmann::json;
struct UiRect {
float x = 0;
float y = 0;
float w = 0;
float h = 0;
bool contains(float px, float py) const {
return px >= x && px <= x + w && py >= y && py <= y + h;
}
};
enum class ButtonState {
Normal,
Hover,
Pressed
};
struct UiButton {
std::string name;
UiRect rect;
std::shared_ptr<Texture> texNormal;
std::shared_ptr<Texture> texHover;
std::shared_ptr<Texture> texPressed;
ButtonState state = ButtonState::Normal;
VertexRenderStruct mesh;
std::function<void(const std::string&)> onClick;
void buildMesh();
void draw(Renderer& renderer) const;
};
struct UiNode {
std::string type;
UiRect rect;
std::string name;
std::vector<std::shared_ptr<UiNode>> children;
std::shared_ptr<UiButton> button;
std::string orientation = "vertical";
float spacing = 0.0f;
};
class UiManager {
public:
UiManager() = default;
void loadFromFile(const std::string& path, Renderer& renderer, const std::string& zipFile = "");
void draw(Renderer& renderer);
void onMouseMove(int x, int y);
void onMouseDown(int x, int y);
void onMouseUp(int x, int y);
std::shared_ptr<UiButton> findButton(const std::string& name);
bool setButtonCallback(const std::string& name, std::function<void(const std::string&)> cb);
bool pushMenuFromFile(const std::string& path, Renderer& renderer, const std::string& zipFile = "");
bool popMenu();
void clearMenuStack();
private:
std::shared_ptr<UiNode> parseNode(const json& j, Renderer& renderer, const std::string& zipFile);
void layoutNode(const std::shared_ptr<UiNode>& node);
void collectButtons(const std::shared_ptr<UiNode>& node);
std::shared_ptr<UiNode> root;
std::vector<std::shared_ptr<UiButton>> buttons;
std::shared_ptr<UiButton> pressedButton;
struct MenuState {
std::shared_ptr<UiNode> root;
std::vector<std::shared_ptr<UiButton>> buttons;
std::shared_ptr<UiButton> pressedButton;
std::string path;
};
std::vector<MenuState> menuStack;
};
} // namespace ZL