diff --git a/README.md b/README.md index 4d75ee6..20fe7d8 100644 --- a/README.md +++ b/README.md @@ -33,12 +33,15 @@ Design your own components however you wish using OpenGL 3.3 Core and ImGui APIs ## Hybrid Mode Neither Immediate Mode nor Retained Mode—but ***both***. CMaterial leverages Retained Mode at the **UI Layer** for the structural integrity of a mature framework, while empowering the **Component Layer** with Immediate Mode for unrestricted control over how every pixel is rendered. +## Pure Upper-Layer Construction +All of CMaterial's functionality is implemented entirely at the upper layer, **without modifying a single line of code from dependent libraries**. In most cases, you can update the dependent libraries on your own, enjoying all upstream updates **without spending time re-porting the framework**. + --- ## Libraries -- **[GLFW](https://github.com/glfw/glfw)** : A lightweight, cross-platform API for creating windows, contexts, handling input and events. -- **[GLAD](https://github.com/dav1dde/glad)** : A multi-Language Vulkan/GL/GLES/EGL/GLX/WGL loader-generator based on the official specifications. - **[ImGui](https://github.com/ocornut/imgui)** : A bloat-free Graphical User interface for C++ with minimal dependencies. +- **[GLAD](https://github.com/dav1dde/glad)** : A multi-Language Vulkan/GL/GLES/EGL/GLX/WGL loader-generator based on the official specifications. +- **[GLFW](https://github.com/glfw/glfw)** : A lightweight, cross-platform API for creating windows, contexts, handling input and events. - **[tweeny](https://github.com/mobius3/tweeny)** : An inbetweening library designed for the creation of complex animations and beautiful interactive software. - **[stb_image](https://github.com/nothings/stb)** : A highly renowned single-file public domain library for loading images in C/C++. - **[mimalloc](https://github.com/microsoft/mimalloc)** : A compact general purpose allocator with excellent performance. diff --git a/README_CN.md b/README_CN.md index 5e0739f..34ae9bc 100644 --- a/README_CN.md +++ b/README_CN.md @@ -33,12 +33,15 @@ ## 混合模式 不是即时模式,也不是保留模式——因为它***全都是***。CMaterial 允许你在 **UI 层** 使用保留模式,就像任何一个成熟的 GUI 框架那样,而同时在 **组件层** 使用即时模式,尽情的定义组件如何进行绘制。 +## 纯上层构建 +CMaterial 的所有功能实现全部处于上层,**没有更改任何一行来自依赖库的代码**。多数情况下,你可以自行更新依赖库,享受来自上游的全部更新,而**无需花费时间重新移植框架**。 + --- ## 依赖库 -- **[GLFW](https://github.com/glfw/glfw)** : 一个轻量级、跨平台的 API,用于创建窗口、上下文、读取输入及处理事件。 -- **[GLAD](https://github.com/dav1dde/glad)** : 基于官方规范的多语言 Vulkan/GL/GLES/EGL/GLX/WGL 加载器生成工具。 - **[ImGui](https://github.com/ocornut/imgui)** : 一个依赖极简、无冗余的 C++ 图形用户界面。 +- **[GLAD](https://github.com/dav1dde/glad)** : 基于官方规范的多语言 Vulkan/GL/GLES/EGL/GLX/WGL 加载器生成工具。 +- **[GLFW](https://github.com/glfw/glfw)** : 一个轻量级、跨平台的 API,用于创建窗口、上下文、读取输入及处理事件。 - **[tweeny](https://github.com/mobius3/tweeny)** : 一个专为游戏和其他精美交互式软件打造的复杂补间动画库。 - **[stb_image](https://github.com/nothings/stb)** : C/C++ 领域极具盛名的单头文件公共域图像加载库。 - **[mimalloc](https://github.com/microsoft/mimalloc)** : 一款性能卓越、体积精简的通用内存分配器。 diff --git a/src/content/animation/material/HoverAnimation.h b/src/content/animation/material/HoverAnimation.h new file mode 100644 index 0000000..d4add74 --- /dev/null +++ b/src/content/animation/material/HoverAnimation.h @@ -0,0 +1,26 @@ +// +// Created by Earth_Studio on 2026/5/13. +// + +#ifndef CMATERIAL_HOVERANIMATION_H +#define CMATERIAL_HOVERANIMATION_H +#include +#include "tweeny.h" + +namespace cmaterial::component::material::animation { + class HoverAnimation : public cmaterial::animation::IAnimation { + public: + HoverAnimation(double* alpha, double target, INode* parent) : IAnimation(parent) { + // 150ms = 15000 steps + bind(alpha, new tweeny::tween(tweeny::from(*alpha).to(target).during(15000))); + } + ~HoverAnimation() override { + for (auto& pair : animationBinders) delete pair.second; + animationBinders.clear(); + } + }; +} + + + +#endif //CMATERIAL_HOVERANIMATION_H diff --git a/src/content/animation/material/RippleAnimation.h b/src/content/animation/material/RippleAnimation.h new file mode 100644 index 0000000..4926bea --- /dev/null +++ b/src/content/animation/material/RippleAnimation.h @@ -0,0 +1,32 @@ +// +// Created by Earth_Studio on 2026/5/13. +// + +#ifndef CMATERIAL_RIPPLEANIMATION_H +#define CMATERIAL_RIPPLEANIMATION_H +#include "engine/animation/IAnimation.h" +#include "tweeny.h" + + +namespace cmaterial::component::material::animation { + class RippleAnimation : public cmaterial::animation::IAnimation { + public: + RippleAnimation(double* progress, double* alpha, INode* node) : IAnimation(node) { + progressTween = tweeny::from(0.0).to(1.0).during(40000).via(tweeny::easing::quadraticOut); + alphaTween = tweeny::from(0.12).to(0.0).during(40000).via(tweeny::easing::quadraticOut); + + bind(progress, &progressTween); + bind(alpha, &alphaTween); + } + ~RippleAnimation() override { + animationBinders.clear(); + } + + private: + tweeny::tween progressTween; + tweeny::tween alphaTween; + }; +} + + +#endif //CMATERIAL_RIPPLEANIMATION_H diff --git a/src/content/component/BasicButton/BasicButton.cpp b/src/content/component/BasicButton/BasicButton.cpp index 9926587..481f00b 100644 --- a/src/content/component/BasicButton/BasicButton.cpp +++ b/src/content/component/BasicButton/BasicButton.cpp @@ -4,7 +4,7 @@ #include "BasicButton.h" -void cmaterial::component::BasicButton::render(ImGuiIO *io) { +void cmaterial::component::BasicButton::update(ImGuiIO *io) { if (ImGui::Button(name.c_str())) onActive(); } \ No newline at end of file diff --git a/src/content/component/BasicButton/BasicButton.h b/src/content/component/BasicButton/BasicButton.h index 841e8bb..7d74d56 100644 --- a/src/content/component/BasicButton/BasicButton.h +++ b/src/content/component/BasicButton/BasicButton.h @@ -15,7 +15,7 @@ namespace cmaterial::component { BasicButton() = default; ~BasicButton() = default; - void render(ImGuiIO *io) override; + void update(ImGuiIO *io) override; void (*onActive)() =[]() {}; }; } diff --git a/src/content/component/CreatorButton/CreatorButton.h b/src/content/component/CreatorButton/CreatorButton.h index 402643f..3afab6e 100644 --- a/src/content/component/CreatorButton/CreatorButton.h +++ b/src/content/component/CreatorButton/CreatorButton.h @@ -16,7 +16,7 @@ namespace cmaterial::component { public: using IComponent::IComponent; - void render(ImGuiIO *io) override { + void update(ImGuiIO *io) override { if (ImGui::Button("SpawnWindow")) { static int count = 0; auto* req = new event::SpawnWindowRequest(); diff --git a/src/content/component/MultiLayerButton/MultiLayerButton.cpp b/src/content/component/MultiLayerButton/MultiLayerButton.cpp new file mode 100644 index 0000000..d707e0a --- /dev/null +++ b/src/content/component/MultiLayerButton/MultiLayerButton.cpp @@ -0,0 +1,18 @@ +// +// Created by Earth_Studio on 2026/4/25. +// + +#include "MultiLayerButton.h" + +namespace cmaterial::component { + MultiLayerButton::MultiLayerButton() { + addLayer(&backgroundLayer); + addLayer(&overlayLayer); + } + + void MultiLayerButton::update(ImGuiIO *io) { + ImGui::PushStyleColor(ImGuiCol_Button, ImVec4(0.0f, 1.0f, 0.0f, 1.0f)); + ImGui::Button(name.c_str()); + ImGui::PopStyleColor(); + } +} // namespace cmaterial::component diff --git a/src/content/component/MultiLayerButton/MultiLayerButton.h b/src/content/component/MultiLayerButton/MultiLayerButton.h new file mode 100644 index 0000000..32f3ec9 --- /dev/null +++ b/src/content/component/MultiLayerButton/MultiLayerButton.h @@ -0,0 +1,31 @@ +// +// Created by Earth_Studio on 2026/4/25. +// + +#ifndef CMATERIAL_ANIMATIONBUTTON_H +#define CMATERIAL_ANIMATIONBUTTON_H + + +#include "engine/component/IComponent.h" + +#include "layer/BackgroundLayer.h" +#include "layer/OverlayLayer.h" + + +namespace cmaterial::component { + class MultiLayerButton : public IComponent { + public: + MultiLayerButton(); + ~MultiLayerButton() = default; + + void update(ImGuiIO *io) override; + + private: + layer::animationbutton::BackgroundLayer backgroundLayer; + layer::animationbutton::OverlayLayer overlayLayer; + }; +} + + + +#endif //CMATERIAL_ANIMATIONBUTTON_H diff --git a/src/content/component/MultiLayerButton/layer/BackgroundLayer.cpp b/src/content/component/MultiLayerButton/layer/BackgroundLayer.cpp new file mode 100644 index 0000000..4011daf --- /dev/null +++ b/src/content/component/MultiLayerButton/layer/BackgroundLayer.cpp @@ -0,0 +1,18 @@ +// +// Created by Earth_Studio on 2026/4/27. +// + +#include "BackgroundLayer.h" + +namespace cmaterial::component::layer::animationbutton { + BackgroundLayer::BackgroundLayer() { + priority = -1; + } + + void BackgroundLayer::render(ImDrawList *drawList, ImVec2 startPos, ImVec2 size) { + ImGui::SetCursorPos(startPos); + ImGui::PushStyleColor(ImGuiCol_Button, ImVec4(0.0f, 0.0f, 1.0f, 1.0f)); + ImGui::Button("BackGround", ImVec2(size.x + 5, size.y + 5)); + ImGui::PopStyleColor(); + } +} diff --git a/src/content/component/MultiLayerButton/layer/BackgroundLayer.h b/src/content/component/MultiLayerButton/layer/BackgroundLayer.h new file mode 100644 index 0000000..11ee84c --- /dev/null +++ b/src/content/component/MultiLayerButton/layer/BackgroundLayer.h @@ -0,0 +1,22 @@ +// +// Created by Earth_Studio on 2026/4/27. +// + +#ifndef CMATERIAL_MULTILAYERBUTTON_BACKGROUNDLAYER_H +#define CMATERIAL_MULTILAYERBUTTON_BACKGROUNDLAYER_H +#include "engine/component/ILayer.hpp" + + +namespace cmaterial::component::layer::animationbutton { + class BackgroundLayer : public ILayer{ + public: + BackgroundLayer(); + ~BackgroundLayer() = default; + + void render(ImDrawList *drawList, ImVec2 startPos, ImVec2 size) override; + }; +} + + + +#endif //CMATERIAL_BACKGROUNDLAYER_H diff --git a/src/content/component/MultiLayerButton/layer/OverlayLayer.cpp b/src/content/component/MultiLayerButton/layer/OverlayLayer.cpp new file mode 100644 index 0000000..b6484a3 --- /dev/null +++ b/src/content/component/MultiLayerButton/layer/OverlayLayer.cpp @@ -0,0 +1,14 @@ +// +// Created by Earth_Studio on 2026/4/27. +// + +#include "OverlayLayer.h" + +namespace cmaterial::component::layer::animationbutton { + void OverlayLayer::render(ImDrawList *drawList, ImVec2 startPos, ImVec2 size) { + ImGui::SetCursorPos(startPos); + ImGui::PushStyleColor(ImGuiCol_Button, ImVec4(1.0f, 0.0f, 0.0f, 1.0f)); + ImGui::Button("OverLay", ImVec2(size.x - 5, size.y - 5)); + ImGui::PopStyleColor(); + } +} // namespace cmaterial::component::layer::animationbutton diff --git a/src/content/component/MultiLayerButton/layer/OverlayLayer.h b/src/content/component/MultiLayerButton/layer/OverlayLayer.h new file mode 100644 index 0000000..4c325df --- /dev/null +++ b/src/content/component/MultiLayerButton/layer/OverlayLayer.h @@ -0,0 +1,22 @@ +// +// Created by Earth_Studio on 2026/4/27. +// + +#ifndef CMATERIAL_OVERLAYLAYER_H +#define CMATERIAL_OVERLAYLAYER_H +#include "engine/component/ILayer.hpp" + + +namespace cmaterial::component::layer::animationbutton { + class OverlayLayer : public ILayer { + public: + OverlayLayer() = default; + ~OverlayLayer() = default; + + void render(ImDrawList *drawList, ImVec2 startPos, ImVec2 size) override; + }; +} + + + +#endif //CMATERIAL_OVERLAYLAYER_H diff --git a/src/content/component/material/Button/Button.cpp b/src/content/component/material/Button/Button.cpp new file mode 100644 index 0000000..455b888 --- /dev/null +++ b/src/content/component/material/Button/Button.cpp @@ -0,0 +1,71 @@ +// +// Created by Earth_Studio on 2026/5/12. +// + +#include "Button.h" + +#include "engine/animation/Player.h" +#include "engine/eventbus/EventBus.h" + +#include "content/component/material/Button/layer/RippleLayer.h" + +namespace cmaterial::component::material { + Button::Button() { + m_bgLayer = new layer::BGLayer(); + addLayer(m_bgLayer); + } + + Button::~Button() { + if (m_hoverAnim) { + cmaterial::animation::Player::stop(m_hoverAnim); + delete m_hoverAnim; + } + } + + void Button::update(ImGuiIO *io) { + m_bgLayer->primaryColor = this->primaryColor; + m_bgLayer->onPrimaryColor = this->onPrimaryColor; + + ImVec2 size(ImGui::CalcTextSize(name.c_str()).x + 48.0f, 40.0f); + ImVec2 p_min = ImGui::GetCursorScreenPos(); + ImGui::InvisibleButton(name.c_str(), size); + + bool hovered = ImGui::IsItemHovered(); + bool active = ImGui::IsItemActive(); + bool clicked = ImGui::IsItemClicked(); + + if (hovered && !m_isHovering) { + m_isHovering = true; + if (m_hoverAnim) { cmaterial::animation::Player::stop(m_hoverAnim); delete m_hoverAnim; } + m_hoverAnim = new animation::HoverAnimation(&m_bgLayer->hoverAlpha, 1.0, this); + m_hoverAnim->parent = this; + cmaterial::animation::Player::play(m_hoverAnim); + } else if (!hovered && m_isHovering) { + m_isHovering = false; + if (m_hoverAnim) { cmaterial::animation::Player::stop(m_hoverAnim); delete m_hoverAnim; } + m_hoverAnim = new animation::HoverAnimation(&m_bgLayer->hoverAlpha, 0.0, this); + m_hoverAnim->parent = this; + cmaterial::animation::Player::play(m_hoverAnim); + } + + if (clicked) { + addLayer(new layer::RippleLayer(io->MousePos, this->onPrimaryColor)); + } + + if (active && !m_isPressed) m_isPressed = true; + else if (!active && m_isPressed) { + m_isPressed = false; + if (hovered) { + // auto* e = new event::ButtonClickedEvent(); + // e->buttonName = this->name; + // e->buttonInstance = this; + // event::EventBus::postEvent(e); + } + } + + ImGui::GetWindowDrawList()->AddText( + ImVec2(p_min.x + 24.0f, p_min.y + (40.0f - ImGui::CalcTextSize(name.c_str()).y) / 2.0f), + ImGui::GetColorU32(onPrimaryColor), name.c_str() + ); + } +} \ No newline at end of file diff --git a/src/content/component/material/Button/Button.h b/src/content/component/material/Button/Button.h new file mode 100644 index 0000000..c6e7e22 --- /dev/null +++ b/src/content/component/material/Button/Button.h @@ -0,0 +1,32 @@ +// +// Created by Earth_Studio on 2026/5/12. +// + +#ifndef CMATERIAL_BUTTON_H +#define CMATERIAL_BUTTON_H +#include "content/animation/material/HoverAnimation.h" +#include "engine/component/IComponent.h" +#include "layer/BGLayer.h" + +namespace cmaterial::component::material { + class Button : public IComponent { + public: + Button(); + ~Button() override; + void update(ImGuiIO *io) override; + + ImVec4 primaryColor = ImVec4(0.404f, 0.314f, 0.643f, 1.0f); + ImVec4 onPrimaryColor = ImVec4(1.0f, 1.0f, 1.0f, 1.0f); + + private: + bool m_isHovering = false; + bool m_isPressed = false; + + layer::BGLayer * m_bgLayer = nullptr; + animation::HoverAnimation* m_hoverAnim = nullptr; + }; +} + + + +#endif //CMATERIAL_BUTTON_H diff --git a/src/content/component/material/Button/layer/BGLayer.h b/src/content/component/material/Button/layer/BGLayer.h new file mode 100644 index 0000000..901514a --- /dev/null +++ b/src/content/component/material/Button/layer/BGLayer.h @@ -0,0 +1,35 @@ +// +// Created by Earth_Studio on 2026/5/13. +// + +#ifndef CMATERIAL_BACKGROUNDLAYER_H +#define CMATERIAL_BACKGROUNDLAYER_H +#include "engine/component/ILayer.hpp" +#include "imgui.h" + + +namespace cmaterial::component::material::layer { + class BGLayer : public ILayer { + public: + BGLayer() { priority = -2; } + void render(ImDrawList* drawList, ImVec2 startPos, ImVec2 size) override { + float mix = static_cast(hoverAlpha) * 0.08f; + ImVec4 finalColor = ImVec4( + primaryColor.x * (1.0f - mix) + onPrimaryColor.x * mix, + primaryColor.y * (1.0f - mix) + onPrimaryColor.y * mix, + primaryColor.z * (1.0f - mix) + onPrimaryColor.z * mix, + primaryColor.w + ); + drawList->AddRectFilled(startPos, ImVec2(startPos.x + size.x, startPos.y + size.y), + ImGui::GetColorU32(finalColor), size.y / 2.0f); + } + + double hoverAlpha = 0.0; + ImVec4 primaryColor = ImVec4(0.404f, 0.314f, 0.643f, 1.0f); + ImVec4 onPrimaryColor = ImVec4(1.0f, 1.0f, 1.0f, 1.0f); + }; +} + + + +#endif //CMATERIAL_BACKGROUNDLAYER_H diff --git a/src/content/component/material/Button/layer/RippleLayer.cpp b/src/content/component/material/Button/layer/RippleLayer.cpp new file mode 100644 index 0000000..bbb1ef4 --- /dev/null +++ b/src/content/component/material/Button/layer/RippleLayer.cpp @@ -0,0 +1,44 @@ +// +// Created by Earth_Studio on 2026/5/13. +// + +#include "RippleLayer.h" + +#include "cmath" +#include "imgui.h" + +#include "engine/animation/Player.h" +#include "engine/component/IComponent.h" + +namespace cmaterial::component::material::layer { + RippleLayer::RippleLayer(ImVec2 pos, ImVec4 col) : m_clickPos(pos), m_color(col), m_anim(&m_progress, &m_alpha, this) { + priority = -1; + + cmaterial::animation::Player::play(&m_anim); + } + + RippleLayer::~RippleLayer() { + cmaterial::animation::Player::stop(&m_anim); + } + + void RippleLayer::render(ImDrawList* drawList, ImVec2 startPos, ImVec2 size) { + if (m_anim._isFinished) { + ((IComponent*) parent)->removeLayer(this); + return; + } + + if (m_alpha <= 0.0) return; + + ImVec2 maxPos(startPos.x + size.x, startPos.y + size.y); + drawList->PushClipRect(startPos, maxPos, true); + + float dx = std::max(m_clickPos.x - startPos.x, maxPos.x - m_clickPos.x); + float dy = std::max(m_clickPos.y - startPos.y, maxPos.y - m_clickPos.y); + float maxR = std::sqrt(dx * dx + dy * dy); + + ImU32 c = ImGui::GetColorU32(ImVec4(m_color.x, m_color.y, m_color.z, static_cast(m_alpha))); + drawList->AddCircleFilled(m_clickPos, maxR * static_cast(m_progress), c, 32); + + drawList->PopClipRect(); + } +} \ No newline at end of file diff --git a/src/content/component/material/Button/layer/RippleLayer.h b/src/content/component/material/Button/layer/RippleLayer.h new file mode 100644 index 0000000..f85e385 --- /dev/null +++ b/src/content/component/material/Button/layer/RippleLayer.h @@ -0,0 +1,34 @@ +// +// Created by Earth_Studio on 2026/5/13. +// + +#ifndef CMATERIAL_RIPPLELAYER_H +#define CMATERIAL_RIPPLELAYER_H +#include "engine/component/ILayer.hpp" +#include "imgui.h" + +#include "content/animation/material/RippleAnimation.h" + +namespace cmaterial::component::material::layer { + class RippleLayer : public ILayer { + public: + RippleLayer(ImVec2 pos, ImVec4 col); + ~RippleLayer() override; + + void render(ImDrawList* drawList, ImVec2 startPos, ImVec2 size) override; + + bool isAnimationFinished() const { return m_anim._isFinished; } + + private: + double m_progress = 0.0; + double m_alpha = 0.0; + ImVec2 m_clickPos; + ImVec4 m_color; + + animation::RippleAnimation m_anim; + }; +} + + + +#endif //CMATERIAL_RIPPLELAYER_H diff --git a/src/content/logic/event/SpawnWindowRequest.hpp b/src/content/logic/event/SpawnWindowRequest.hpp index 2620b48..89cd5bb 100644 --- a/src/content/logic/event/SpawnWindowRequest.hpp +++ b/src/content/logic/event/SpawnWindowRequest.hpp @@ -6,7 +6,7 @@ #define CMATERIAL_TESTEVENT_H -#include "engine/eventbus/IEvent.h" +#include "engine/eventbus/IEvent.hpp" #include diff --git a/src/content/logic/listener/WindowLogic.h b/src/content/logic/listener/WindowLogic.h index 5181bd2..7b604ef 100644 --- a/src/content/logic/listener/WindowLogic.h +++ b/src/content/logic/listener/WindowLogic.h @@ -18,7 +18,7 @@ namespace cmaterial::event { public: WindowLogic(Framework* a) : app(a) {} - EVENTHANDLER(cmaterial::event::SpawnWindowRequest, onSpawnRequest) + EVENTHANDLER(SpawnWindowRequest, onSpawnRequest) void onSpawnRequest(SpawnWindowRequest* e) { auto* newWin = new window::BasicWindow(e->title, 300, 100); app->addWindow(newWin); diff --git a/src/content/window/BasicWindow/BasicWindow.cpp b/src/content/window/BasicWindow/BasicWindow.cpp index 8f6e63c..1468f7f 100644 --- a/src/content/window/BasicWindow/BasicWindow.cpp +++ b/src/content/window/BasicWindow/BasicWindow.cpp @@ -6,44 +6,15 @@ #include "imgui.h" -#include -#include - -#include "engine/eventbus/EventBus.h" - namespace cmaterial::window { - void BasicWindow::render(ImGuiIO *io) { - ImGuiWindowFlags flags = ImGuiWindowFlags_NoDecoration | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoSavedSettings; - - ImGui::PushStyleVar(ImGuiStyleVar_FrameRounding, 10.0f); - ImGui::PushStyleVar(ImGuiStyleVar_WindowBorderSize, 0.0f); - ImGui::PushStyleVar(ImGuiStyleVar_FrameBorderSize, 1.0f); - if (ImGui::Begin(this->name.c_str(), nullptr, flags)) { - ImGui::Text("Hello, Engine!"); - ImGui::Text("Frame time: %.3f ms/frame (%.1f FPS)", 1000.0f / io->Framerate, io->Framerate); - - ImGui::Separator(); - - for (auto &pair: components) { - if (pair.second->getIsDead()) { - deadComponents.push_back(pair.first); - continue; - } - pair.second->render(io); - } - - for (const std::string &name: deadComponents) { - component::IComponent *component = components[name]; - components.erase(name); - delete component; - } + void BasicWindow::postInit(ImGuiIO *io) { + addStyle(ImGuiStyleVar_WindowBorderSize, 0.0f); + } - deadComponents.clear(); - } + void BasicWindow::render(ImGuiIO *io) { + ImGui::Text("Hello, Engine!"); + ImGui::Text("Frame time: %.3f ms/frame (%.1f FPS)", 1000.0f / io->Framerate, io->Framerate); - ImGui::End(); - ImGui::PopStyleVar(); - ImGui::PopStyleVar(); - ImGui::PopStyleVar(); + ImGui::Separator(); } } \ No newline at end of file diff --git a/src/content/window/BasicWindow/BasicWindow.h b/src/content/window/BasicWindow/BasicWindow.h index dda1d68..dd650fc 100644 --- a/src/content/window/BasicWindow/BasicWindow.h +++ b/src/content/window/BasicWindow/BasicWindow.h @@ -14,6 +14,7 @@ namespace cmaterial::window { using IWindow::IWindow; ~BasicWindow() = default; + void postInit(ImGuiIO *io) override; void render(ImGuiIO *io) override; }; } diff --git a/src/engine/animation/IAnimation.cpp b/src/engine/animation/IAnimation.cpp index 4c26009..434d0c8 100644 --- a/src/engine/animation/IAnimation.cpp +++ b/src/engine/animation/IAnimation.cpp @@ -6,9 +6,14 @@ #include +#include "Player.h" #include "tween.h" namespace cmaterial::animation { + IAnimation::IAnimation(INode* parent) { + this->parent = parent; + } + void IAnimation::reset() { for (auto binder : animationBinders) { if (_isReverse) @@ -18,15 +23,16 @@ namespace cmaterial::animation { } } - std::unordered_map *>* IAnimation::getAnimationBinders() { + std::vector *>>* IAnimation::getAnimationBinders() { return &animationBinders; } void IAnimation::bind(double* property, tweeny::tween* tween) { - animationBinders[property] = tween; + animationBinders.push_back({property, tween}); } IAnimation::~IAnimation() { + Player::stop(this); animationBinders.clear(); } } \ No newline at end of file diff --git a/src/engine/animation/IAnimation.h b/src/engine/animation/IAnimation.h index c29a336..fb1001d 100644 --- a/src/engine/animation/IAnimation.h +++ b/src/engine/animation/IAnimation.h @@ -8,24 +8,48 @@ #include +#include "engine/utils/INode.h" #include "tween.h" namespace cmaterial::animation { - class IAnimation { + /** + * @brief The base of the Animation. + * @details Basically, it's just a place to bind a property and a tweeny object. + * + * @details --- Extend Hook --- + * @details @code Constructor()@endcode : You should bind the properties and tweens in your own constructor. + * + * @details --- Property --- + * @details @code bool isLoop@endcode : Is this animation looping? + * @details @code double ...@endcode : Any property you want to apply animation to, you need to manually manage + * them. + * + * @details --- Helper --- + * @details @code void bind(double*, tween*)@endcode : Bind a property and a tween. + * + * @details --- DANGER ZONE --- + * @details @code bool _isFinished@endcode : Is the animation finished? You should read it ONLY! + * @details @code bool _isReverse@endcode : Is the animation reversed? You should read it ONLY! + * + * @warning You should extend it to make a custom Animation. NEVER USE THE INTERFACE DIRECTLY! + */ + class IAnimation : public utils::INode { public: + IAnimation(INode* parent); virtual ~IAnimation(); void reset(); - std::unordered_map *>* getAnimationBinders(); + std::vector *>>* getAnimationBinders(); bool isLoop = false; + bool _isFinished = false; bool _isReverse = false; - private: + protected: void bind(double* property, tweeny::tween* tween); - std::unordered_map *> animationBinders; + std::vector *>> animationBinders; }; } diff --git a/src/engine/animation/Player.cpp b/src/engine/animation/Player.cpp index 8efa118..b789e14 100644 --- a/src/engine/animation/Player.cpp +++ b/src/engine/animation/Player.cpp @@ -5,18 +5,42 @@ #include "Player.h" #include -#include + +#include "glad/gl.h" +#include "GLFW/glfw3.h" namespace cmaterial::animation { std::vector Player::playingAnimations; std::vector Player::finishedAnimations; void Player::play(IAnimation *animation) { - if (!animation) return; + if (animation == nullptr) return; + + if (std::ranges::find(playingAnimations, animation) != playingAnimations.end()) { + return; + } playingAnimations.push_back(animation); } + void Player::forward(IAnimation *animation) { + if (!animation) return; + + for (auto binder : *animation->getAnimationBinders()) { + binder.second->forward(); + } + animation->_isReverse = false; + } + + void Player::backward(IAnimation *animation) { + if (!animation) return; + + for (auto binder : *animation->getAnimationBinders()) { + binder.second->backward(); + } + animation->_isReverse = true; + } + void Player::reverse(IAnimation *animation) { if (!animation) return; @@ -37,21 +61,32 @@ namespace cmaterial::animation { std::erase(playingAnimations, animation); } - bool Player::update() { - if (playingAnimations.empty()) - return false; + std::vector* Player::update() { + static double lastTime = glfwGetTime(); + double currentTime = glfwGetTime(); + double dt = currentTime - lastTime; + lastTime = currentTime; - int dtTime = static_cast(ImGui::GetIO().DeltaTime * 100000.0f); - if (dtTime <= 0) dtTime = 1; // 1 step = 0.01 ms + if (dt > 0.1 || dt <= 0.0) + dt = 0.00001; + + int dtTime = static_cast(dt * 100000.0); // 1 step = 0.01 ms for (auto animation : playingAnimations) { bool allTweensFinished = true; for (auto binder : *animation->getAnimationBinders()) { *binder.first = binder.second->step(dtTime); - if (!binder.second->isFinished()) { - allTweensFinished = false; + if (!animation->_isReverse) { + if (!binder.second->isFinished()) { + allTweensFinished = false; + } + } else { + if (binder.second->progress() != 0) { + allTweensFinished = false; + } } + } if (allTweensFinished) { @@ -64,11 +99,12 @@ namespace cmaterial::animation { for (auto animation : finishedAnimations) { std::erase(playingAnimations, animation); + animation->_isFinished = true; } finishedAnimations.clear(); - return true; + return &playingAnimations; } void Player::shutdown() { diff --git a/src/engine/animation/Player.h b/src/engine/animation/Player.h index 74ce66f..a8af19c 100644 --- a/src/engine/animation/Player.h +++ b/src/engine/animation/Player.h @@ -12,16 +12,25 @@ namespace cmaterial::animation { - class Player{ + /** + * @brief The Animation player. + * @details You will play all the Animation in here. + * + * @details --- Danger Zone --- + * @details @code update()@endcode : This is used by the framework itself to update. DO NOT USE IT! + */ + class Player { public: Player() = default; ~Player(); static void play(IAnimation* animation); + static void forward(IAnimation* animation); + static void backward(IAnimation* animation); static void reverse(IAnimation* animation); static void stop(IAnimation* animation); - static bool update(); + static std::vector* update(); static void shutdown(); diff --git a/src/engine/component/IComponent.cpp b/src/engine/component/IComponent.cpp index 05daba7..59d2172 100644 --- a/src/engine/component/IComponent.cpp +++ b/src/engine/component/IComponent.cpp @@ -6,7 +6,12 @@ #include "GLFW/glfw3.h" #include "engine/eventbus/EventBus.h" -#include "engine/eventbus/internal/event/EmptyEvent.hpp" +#include "engine/eventbus/internal/event/ForceRedrawEvent.hpp" + +#include "ILayer.hpp" + +#include +#include namespace cmaterial::component { void IComponent::addComponent(IComponent *component) { @@ -16,11 +21,97 @@ namespace cmaterial::component { if (component->name.empty()) return; - components.insert({component->name, component}); - event::EventBus::postEvent(new event::internal::EmptyEvent); + component->parent = this; + components.push_back(component); + event::EventBus::postEvent(new event::internal::ForceRedrawEvent); } - bool IComponent::getIsDead() { + void IComponent::removeComponent(IComponent *component) { + if (component == nullptr) + return; + + component->parent = nullptr; + std::erase(components, component); + } + + void IComponent::addLayer(ILayer *layer) { + if (layer == nullptr) + return; + + layer->parent = this; + + std::vector& layers = (layer->priority < 0) ? layersBefore : layersAfter; + + auto it = std::ranges::lower_bound(layers, layer, + [](ILayer* a, ILayer* b) { + return a->priority < b->priority; + }); + + layers.insert(it, layer); + event::EventBus::postEvent(new event::internal::ForceRedrawEvent); + } + + void IComponent::removeLayer(ILayer *layer) { + if (layer == nullptr) + return; + + std::erase(layersBefore, layer); + std::erase(layersAfter, layer); + + delete layer; + } + + /** + * @brief The core of the update + render. Only render the component when the current frame is not virtual. + * @see IWindow + */ + void IComponent::drawComponent(ImGuiIO *io) { + if (!isActive) return; + + ImDrawList* drawList = ImGui::GetWindowDrawList(); + + ImDrawListSplitter splitter; + splitter.Split(drawList, 3); + + splitter.SetCurrentChannel(drawList, 1); + + ImGui::BeginGroup(); + this->update(io); + ImGui::EndGroup(); + + ImVec2 minPos = ImGui::GetItemRectMin(); + ImVec2 maxPos = ImGui::GetItemRectMax(); + ImVec2 size = ImVec2(maxPos.x - minPos.x, maxPos.y - minPos.y); + + splitter.SetCurrentChannel(drawList, 0); + for (auto* layer : layersBefore) { + layer->render(drawList, minPos, size); + } + + splitter.SetCurrentChannel(drawList, 2); + for (auto* layer : layersAfter) { + layer->render(drawList, minPos, size); + } + + splitter.Merge(drawList); + // TODO: child component render support, do this after Layout System complete. + } + + bool IComponent::getIsDead() const { return isDead; } + + IComponent::~IComponent() { + components.clear(); + + for (auto layerB : layersBefore) { + delete layerB; + } + layersBefore.clear(); + + for (auto layerA : layersAfter) { + delete layerA; + } + layersAfter.clear(); + } } diff --git a/src/engine/component/IComponent.h b/src/engine/component/IComponent.h index 6a461d8..4ba467d 100644 --- a/src/engine/component/IComponent.h +++ b/src/engine/component/IComponent.h @@ -9,23 +9,50 @@ #include "imgui.h" -#include #include #include -#include "ILayer.h" +#include "ILayer.hpp" +#include "engine/utils/INode.h" namespace cmaterial::component { - class IComponent { + /** + * @brief The base of Component. + * @details Basically, it's a state machine. + * @details You need to figure out how to distinguish between different states, when to post an Event, and how to + * draw your component every frame. + * @details It's probably the most complex part in CMaterial, but once you understand it, it's very easy to create + * any component for yourself. + * + * @details --- Extend Hook --- + * @details @code virtual update() = 0@endcode : The core update logic of the component. + * + * @details --- Property --- + * @details @code std::string name@endcode : The name of the Component. + * @details @code bool isActive@endcode : Should the Component update + render? + * + * @details --- DANGER ZONE --- + * @details @code virtual drawComponent()@endcode : The core of the update + render. Only render the component when + * the current frame is not virtual. + * @details If you TRULY have a compelling reason that you must use it, you can override it completely. But in most + * cases, you SHOULDN'T touch it. + * + * @warning You should extend it to make a custom Component. NEVER USE THE INTERFACE DIRECTLY! + */ + class IComponent : public utils::INode { public: - virtual ~IComponent() = default; - virtual void render(ImGuiIO *io) = 0; - virtual void addComponent(IComponent *component); + virtual ~IComponent(); - void addLayer(); + virtual void update(ImGuiIO *io) = 0; + virtual void drawComponent(ImGuiIO *io); - bool getIsDead(); + void addComponent(IComponent *component); + void removeComponent(IComponent *component); + void addLayer(ILayer *layer); + void removeLayer(ILayer *layer); + + bool getIsDead() const; std::string name; int xPercent = 0; @@ -34,8 +61,9 @@ namespace cmaterial::component { protected: bool isDead = false; - std::unordered_map components; - std::vector layers; + std::vector components; + std::vector layersBefore; + std::vector layersAfter; }; } diff --git a/src/engine/component/ILayer.cpp b/src/engine/component/ILayer.cpp deleted file mode 100644 index be70242..0000000 --- a/src/engine/component/ILayer.cpp +++ /dev/null @@ -1,9 +0,0 @@ -// -// Created by Earth_Studio on 2026/4/26. -// - -#include "ILayer.h" - -namespace cmaterial::component { - -} \ No newline at end of file diff --git a/src/engine/component/ILayer.h b/src/engine/component/ILayer.h deleted file mode 100644 index bb27561..0000000 --- a/src/engine/component/ILayer.h +++ /dev/null @@ -1,25 +0,0 @@ -// -// Created by Earth_Studio on 2026/4/26. -// - -#ifndef CMATERIAL_ILAYER_H -#define CMATERIAL_ILAYER_H - - -#include "imgui.h" - - -namespace cmaterial::component { - class ILayer { - public: - virtual ~ILayer() = default; - - virtual ImDrawData render() = 0; - - int priority = 0; - }; -} - - - -#endif //CMATERIAL_ILAYER_H diff --git a/src/engine/component/ILayer.hpp b/src/engine/component/ILayer.hpp new file mode 100644 index 0000000..96905e4 --- /dev/null +++ b/src/engine/component/ILayer.hpp @@ -0,0 +1,41 @@ +// +// Created by Earth_Studio on 2026/4/26. +// + +#ifndef CMATERIAL_ILAYER_H +#define CMATERIAL_ILAYER_H + + +#include "engine/utils/INode.h" +#include "imgui.h" + + +namespace cmaterial::component { + /** + * @brief The base of the Layer, the extra render part of the component. + * @details You may want to render some special effect on your component (e.g. shadow, ripple). Here + * is the perfect place for you to draw them. + * + * @details --- Extend Hook --- + * @details @code virtual render() = 0@endcode : The core render logic for the Layer. + * + * @details --- Property --- + * @details @code int priority@endcode : The render priority, just like the Z-axis. If priority < 0, the Layer will + * draw under the Component. If priority >= 0, the Layer will draw above the Component. The render order is based on + * the number, from smaller to bigger. + * + * @warning You should extend it to make a custom Layer. NEVER USE THE INTERFACE DIRECTLY! + */ + class ILayer : public utils::INode { + public: + ILayer() = default; + virtual ~ILayer() = default; + virtual void render(ImDrawList* drawList, ImVec2 startPos, ImVec2 size) = 0; + + int priority = 0; + }; +} + + + +#endif //CMATERIAL_ILAYER_H diff --git a/src/engine/eventbus/EventBus.cpp b/src/engine/eventbus/EventBus.cpp index 992427a..5b827fd 100644 --- a/src/engine/eventbus/EventBus.cpp +++ b/src/engine/eventbus/EventBus.cpp @@ -5,7 +5,7 @@ #include "EventBus.h" #include #include "GLFW/glfw3.h" -#include "IEvent.h" +#include "IEvent.hpp" #include "IListener.h" #include @@ -20,6 +20,9 @@ namespace cmaterial::event { std::mutex EventBus::queueMutex; std::mutex EventBus::registerMutex; + /** + * @brief Let a Listener start to work. + */ void EventBus::addListener(IListener* listener) { if (!listener) return; @@ -37,6 +40,9 @@ namespace cmaterial::event { } } + /** + * Post an Event to the Event System, Listener will receive it later. + */ void EventBus::postEvent(IEvent* event) { if (!event) return; @@ -65,7 +71,7 @@ namespace cmaterial::event { } for (auto* handler : handlersToCall) { - if (event->getIsCancelled()) break; + if (event->isCancelled) break; handler->execute(event); } @@ -75,6 +81,9 @@ namespace cmaterial::event { return true; } + /** + * @brief Let a Listener stop working. + */ void EventBus::removeListener(IListener* listener) { if (!listener) return; diff --git a/src/engine/eventbus/EventBus.h b/src/engine/eventbus/EventBus.h index 213fe56..2810458 100644 --- a/src/engine/eventbus/EventBus.h +++ b/src/engine/eventbus/EventBus.h @@ -18,6 +18,13 @@ namespace cmaterial::event { class IHandler; class IEvent; + /** + * @brief The core of the Event System. + * + * @details --- DANGER ZONE --- + * @details @code bool dispatch()@endcode : This is used by the framework itself to update. DO NOT USE IT! + * @details @code void shutdown()@endcode : This is used by the framework itself to clean. DO NOT USE IT! + */ class EventBus { public: ~EventBus(); diff --git a/src/engine/eventbus/IEvent.cpp b/src/engine/eventbus/IEvent.cpp deleted file mode 100644 index 965d172..0000000 --- a/src/engine/eventbus/IEvent.cpp +++ /dev/null @@ -1,11 +0,0 @@ -// -// Created by Earth_Studio on 2026/4/17. -// - -#include "IEvent.h" - -namespace cmaterial::event { - bool IEvent::getIsCancelled() { - return isCancelled; - } -} diff --git a/src/engine/eventbus/IEvent.h b/src/engine/eventbus/IEvent.h deleted file mode 100644 index 31088f6..0000000 --- a/src/engine/eventbus/IEvent.h +++ /dev/null @@ -1,33 +0,0 @@ -// -// Created by Earth_Studio on 2026/4/16. -// - -#ifndef CMATERIAL_IEVENT_H -#define CMATERIAL_IEVENT_H - - -namespace cmaterial::event { - class IEvent { - public: - virtual ~IEvent() = default; - virtual const void* getEventType() const = 0; - - bool getIsCancelled(); - - protected: - bool isCancelled = false; - -#define REGISTEREVENT(T) \ - static const void *getStaticType() { \ - static int dummy; \ - return &dummy; \ - } \ - const void *getEventType() const override { \ - return getStaticType(); \ - } - }; -} - - - -#endif //CMATERIAL_IEVENT_H diff --git a/src/engine/eventbus/IEvent.hpp b/src/engine/eventbus/IEvent.hpp new file mode 100644 index 0000000..8c092b4 --- /dev/null +++ b/src/engine/eventbus/IEvent.hpp @@ -0,0 +1,56 @@ +// +// Created by Earth_Studio on 2026/4/16. +// + +#ifndef CMATERIAL_IEVENT_H +#define CMATERIAL_IEVENT_H + + +namespace cmaterial::event { + /** + * @brief The base of the Event. + * @details You want to tell others something has happened, and this is the tool to make a message about + * "something". + * + * @details --- Require Macro --- + * @details @code REGISTEREVENT(EventClass)@endcode : You must write it in the first line of the class. + * + * @details --- Property --- + * @details @code any ...@endcode : These are properties you want to include in the message. You can add them by + * yourself. + * + * @details --- Advanced --- + * @details You can use @code struct@endcode to make an Event, because most of the time you may just want to send a + * message and give away some properties but don't want to give functions in the Event. + * + * @details --- DANGER ZONE --- + * @details @code bool isCancelled@endcode : Does the Event need to be cancelled? You shouldn't modify this because + * this should be modified by the Listener. + * + * @warning You should extend it to make a custom Event. NEVER USE THE INTERFACE DIRECTLY! + */ + class IEvent { + public: + virtual ~IEvent() = default; + virtual const void* getEventType() const = 0; + + /** + * @brief Does the Event need to be cancelled? + * @details In most cases, you won't need to change this. + */ + bool isCancelled = false; + +#define REGISTEREVENT(T) \ + static const void *getStaticType() { \ + static int dummy; \ + return &dummy; \ + } \ + const void *getEventType() const override { \ + return getStaticType(); \ + } + }; +} + + + +#endif //CMATERIAL_IEVENT_H diff --git a/src/engine/eventbus/IListener.h b/src/engine/eventbus/IListener.h index 6d9d76a..a7e7be2 100644 --- a/src/engine/eventbus/IListener.h +++ b/src/engine/eventbus/IListener.h @@ -37,6 +37,34 @@ namespace cmaterial::event { Order getOrder() const override { return order; } }; + /** + * @brief The base of the Listener. + * @details You want to do something after it happens, and this is the tool to make it. + * + * @details --- Require Macro --- + * @details @code EVENTHANDLER(EventClass, FunctionName)@endcode : You must write it before the function you want to + * make a Listener. + * @details @code EVENTHANDLER(EventClass, FunctionName, Order)@endcode : Same as the last one, but you can use the + * Order property to control the Listeners' execution order. @code HIGH@endcode means execute as early as possible, + * @code LOW@endcode means the opposite, @code DEFAULT@endcode is completely the same as the last macro. + * + * @details --- Tips --- + * @details Some Events will include some useful properties to use, you can get them like this: + * @details @code event->property@endcode + * @details You could implement several functions and mark them with different @code EVENTHANDLER@endcode to listen + * to different events in a single Listener. + * @details (e.g. @code onButtonClicked()@endcode + @code onButtonHover()@endcode -> @code ButtonListener@endcode ) + * + * @details --- Advanced --- + * @details You could use @code event->isCancelled = true@endcode to cancel an event. This will make lower-order + * Listeners stop doing their work. + * @details BUT, if two Listeners have the same Order, the first loaded Listener will cancel the second one. + * @details In most cases, you won't need this, because for GUI development, cancellation will usually not happen. + * @details UNLESS you use my EventBus to connect a custom backend (e.g. Network). But don't get me wrong — this is + * a usage I fully endorse, and it's even expected. + * + * @warning You should extend it to make a custom Listener. NEVER USE THE INTERFACE DIRECTLY! + */ class IListener { public: using Order = IHandler::Order; diff --git a/src/engine/eventbus/internal/event/EmptyEvent.hpp b/src/engine/eventbus/internal/event/ForceRedrawEvent.hpp similarity index 62% rename from src/engine/eventbus/internal/event/EmptyEvent.hpp rename to src/engine/eventbus/internal/event/ForceRedrawEvent.hpp index f97975b..e07493e 100644 --- a/src/engine/eventbus/internal/event/EmptyEvent.hpp +++ b/src/engine/eventbus/internal/event/ForceRedrawEvent.hpp @@ -4,12 +4,12 @@ #ifndef CMATERIAL_EMPTYEVENT_H #define CMATERIAL_EMPTYEVENT_H -#include "engine/eventbus/IEvent.h" +#include "engine/eventbus/IEvent.hpp" namespace cmaterial::event::internal { - struct EmptyEvent : IEvent { - REGISTEREVENT(EmptyEvent); + struct ForceRedrawEvent : IEvent { + REGISTEREVENT(ForceRedrawEvent); }; } diff --git a/src/engine/eventbus/internal/listener/ForceRedrawListener.hpp b/src/engine/eventbus/internal/listener/ForceRedrawListener.hpp new file mode 100644 index 0000000..67f23ee --- /dev/null +++ b/src/engine/eventbus/internal/listener/ForceRedrawListener.hpp @@ -0,0 +1,35 @@ +// +// Created by Earth_Studio on 2026/4/27. +// + +#ifndef CMATERIAL_FORCEREDRAWLISTENER_H +#define CMATERIAL_FORCEREDRAWLISTENER_H + + +#include "engine/eventbus/IListener.h" +#include "engine/eventbus/internal/event/ForceRedrawEvent.hpp" + +#include "glad/gl.h" +#include "GLFW/glfw3.h" + +namespace cmaterial::event::internal { + class ForceRedrawListener : public IListener { + public: + ForceRedrawListener(bool* isForceRedraw) { + this->isForceRedraw = isForceRedraw; + } + + EVENTHANDLER(ForceRedrawEvent, onForceRedraw); + void onForceRedraw(ForceRedrawEvent* e) { + *isForceRedraw = true; + glfwPostEmptyEvent(); // Just in case + }; + + private: + bool* isForceRedraw; + }; +} + + + +#endif //CMATERIAL_FORCEREDRAWLISTENER_H diff --git a/src/engine/framework/Framework.cpp b/src/engine/framework/Framework.cpp index 08c46f6..fa1b964 100644 --- a/src/engine/framework/Framework.cpp +++ b/src/engine/framework/Framework.cpp @@ -14,16 +14,27 @@ #endif #include "engine/eventbus/EventBus.h" -#include "engine/eventbus/internal/event/EmptyEvent.hpp" +#include "engine/eventbus/internal/event/ForceRedrawEvent.hpp" -#include +#include "engine/utils/ordered_map.hpp" #include +#include +#include +#include "backends/imgui_impl_glfw.h" +#include "backends/imgui_impl_opengl3.h" #include "engine/animation/Player.h" +#include "engine/eventbus/internal/listener/ForceRedrawListener.hpp" using EventBus = cmaterial::event::EventBus; namespace cmaterial { + /** + * @brief + * @details Initialize CMaterial Engine. + * @details This should be called at the beginning. + * @return Statement for initialize + */ Framework::error Framework::initialize() { if (!glfwInit()) return GLFW_INIT_FAILED; @@ -51,27 +62,63 @@ namespace cmaterial { hiddenImgui = ImGui::CreateContext(fontAtlas); ImGui::SetCurrentContext(hiddenImgui); + EventBus::addListener(new event::internal::ForceRedrawListener(&isForceRedraw)); + isInitialized = true; return OK; } + /** + * @brief Start CMaterial engine. + * @return Statement for result + */ Framework::error Framework::run() { if (!isInitialized) return NOT_INIT; - EventBus::postEvent(new event::internal::EmptyEvent); + GLFWmonitor* primary = glfwGetPrimaryMonitor(); + const GLFWvidmode* mode = glfwGetVideoMode(primary); + double targetHz = (mode && mode->refreshRate > 0) ? mode->refreshRate : 60.0; + double frameDuration = 1.0 / targetHz; + + double nextFrameTime = glfwGetTime(); + + bool isNotFirstRender = false; + + EventBus::postEvent(new event::internal::ForceRedrawEvent); while (!glfwWindowShouldClose(hiddenWindow) && !windows.empty()) { bool isEventBusy = EventBus::dispatch(); - bool isAnimationBusy = animation::Player::update(); - if (!(isEventBusy || isAnimationBusy)) + auto playingAnimations = animation::Player::update(); + bool isAnimationBusy = !playingAnimations->empty(); + + if (!(isEventBusy || isAnimationBusy)) { + double now = glfwGetTime(); + + if (now < nextFrameTime) { + std::this_thread::sleep_for(std::chrono::milliseconds(1)); // who will have 1000+ Hz monitor? 1 ms should be fine in all the time + continue; + } + + nextFrameTime += frameDuration; + + if (nextFrameTime < now) + nextFrameTime = now + frameDuration; + glfwWaitEvents(); + } else { + if (!isNotFirstRender) + isNotFirstRender = true; + else + glfwPollEvents(); + } ImFontAtlasUpdateNewFrame(fontAtlas, ++globalFrameCount, true); for (std::pair &pair : windows) { bool isSizeChange = pair.second->_isSizeChange; + bool isWindowBusy = false; pair.second->update(); if (pair.second->isDead) { @@ -82,15 +129,24 @@ namespace cmaterial { if (!isSizeChange && !pair.second->isHovered()) { if (!pair.second->isInitialized) pair.second->isInitialized = true; - else continue; } - pair.second->drawWindow(!isAnimationBusy); - } + if (isAnimationBusy) { + for (auto animation : *playingAnimations) { + auto node = animation->parent; + while (node->parent != nullptr) { + node = node->parent; + } + if (node == pair.second) { + isWindowBusy = true; + goto render; + } + } + continue; + } - if (!deadWindows.empty()) { - glfwMakeContextCurrent(hiddenWindow); - ImGui::SetCurrentContext(hiddenImgui); + render: + pair.second->drawWindow(!(isForceRedraw || isWindowBusy)); } for (std::string &name : deadWindows) { @@ -98,11 +154,23 @@ namespace cmaterial { windows.erase(name); delete win; } + + if (!deadWindows.empty()) { + glfwMakeContextCurrent(hiddenWindow); + ImGui::SetCurrentContext(hiddenImgui); + } + + deadWindows.clear(); + isForceRedraw = false; } return OK; } + /** + * @brief Add a new window to the CMaterial engine. + * @param window Pointer of the @code IWindow@endcode + */ void Framework::addWindow(window::IWindow *window) { window->initialize(hiddenWindow, fontAtlas); windows.insert({window->name, window}); diff --git a/src/engine/framework/Framework.h b/src/engine/framework/Framework.h index 88adc63..fe63b0a 100644 --- a/src/engine/framework/Framework.h +++ b/src/engine/framework/Framework.h @@ -8,6 +8,7 @@ #include #include "GLFW/glfw3.h" +#include "engine/utils/ordered_map.hpp" #include "engine/window/IWindow.h" @@ -33,11 +34,12 @@ namespace cmaterial { private: bool isInitialized = false; int globalFrameCount = 0; + bool isForceRedraw = false; GLFWwindow* hiddenWindow = nullptr; ImGuiContext* hiddenImgui = nullptr; ImFontAtlas* fontAtlas = nullptr; - std::unordered_map windows; + utils::ordered_map windows; std::vector deadWindows; }; } diff --git a/src/engine/utils/INode.h b/src/engine/utils/INode.h new file mode 100644 index 0000000..09e0904 --- /dev/null +++ b/src/engine/utils/INode.h @@ -0,0 +1,19 @@ +// +// Created by Earth_Studio on 2026/5/6. +// + +#ifndef CMATERIAL_INODE_H +#define CMATERIAL_INODE_H + + +namespace cmaterial::utils { + class INode{ + public: + virtual ~INode() = default; + INode * parent = nullptr; + }; +} + + + +#endif //CMATERIAL_INODE_H diff --git a/src/engine/utils/ordered_map.hpp b/src/engine/utils/ordered_map.hpp new file mode 100644 index 0000000..b7de810 --- /dev/null +++ b/src/engine/utils/ordered_map.hpp @@ -0,0 +1,92 @@ +// +// Created by Earth_Studio on 2026/5/1. +// + +#ifndef CMATERIAL_ORDERED_MAP_H +#define CMATERIAL_ORDERED_MAP_H + + + +#include +#include +#include + +namespace cmaterial::utils { + template + class ordered_map { + public: + using ValueType = std::pair; + using ListIter = typename std::list::iterator; + + std::pair insert(const K& key, V value) { + auto it = lookup.find(key); + if (it != lookup.end()) { + return {it->second, false}; + } + + data.emplace_back(key, value); + ListIter lastIt = std::prev(data.end()); + + lookup[key] = lastIt; + return {lastIt, true}; + } + + std::pair insert(const ValueType& value) { + return insert(value.first, value.second); + } + + std::pair insert(ValueType&& value) { + auto it = lookup.find(value.first); + if (it != lookup.end()) return {it->second, false}; + + data.emplace_back(std::move(value)); + ListIter lastIt = std::prev(data.end()); + lookup[lastIt->first] = lastIt; + return {lastIt, true}; + } + + V& operator[](const K& key) { + auto it = lookup.find(key); + if (it == lookup.end()) { + return insert(key, V{}).first->second; + } + return it->second->second; + } + + size_t erase(const K& key) { + auto it = lookup.find(key); + if (it == lookup.end()) return 0; + + data.erase(it->second); + lookup.erase(it); + return 1; + } + + auto begin() noexcept { return data.begin(); } + auto end() noexcept { return data.end(); } + auto begin() const noexcept { return data.begin(); } + auto end() const noexcept { return data.end(); } + + bool contains(const K& key) const { return lookup.contains(key); } + bool empty() const noexcept { return lookup.empty(); } + size_t size() const noexcept { return lookup.size(); } + + void clear() noexcept { + lookup.clear(); + data.clear(); + } + + auto find(const K& key) { + auto it = lookup.find(key); + return (it == lookup.end()) ? data.end() : it->second; + } + + private: + std::list data; + std::unordered_map lookup; + }; +} + + + +#endif //CMATERIAL_ORDERED_MAP_H diff --git a/src/engine/window/IWindow.cpp b/src/engine/window/IWindow.cpp index cfd3793..53ab086 100644 --- a/src/engine/window/IWindow.cpp +++ b/src/engine/window/IWindow.cpp @@ -11,8 +11,6 @@ #include "GLFW/glfw3.h" #include "engine/eventbus/EventBus.h" -#include "engine/eventbus/internal/event/EmptyEvent.hpp" -#include "imgui_internal.h" namespace cmaterial::window { void window_size_callback(GLFWwindow* window, int width, int height) { @@ -65,6 +63,12 @@ namespace cmaterial::window { postInit(io); } + /** + * @brief + * @details The core update logic of the window. + * @details If you TRULY have a compelling reason that you must use it, you can override it completely. + * @details But in most cases, you should override @code postUpdate()@endcode instead of this. + */ void IWindow::update() { if (glfwWindowShouldClose(glfwWindow)) isDead = true; @@ -81,6 +85,31 @@ namespace cmaterial::window { postUpdate(); } + void IWindow::addStyle(ImGuiStyleVar styleVar, float value) { + styles[styleVar] = value; + } + + void IWindow::removeStyle(ImGuiStyleVar styleVar) { + styles.erase(styleVar); + } + + /** + * @brief Draw Window. + * + * @details + * We all know ImGui is Immediate Mode, so its logic and render are forcibly bound; you cannot trigger logic or render + * independently. HOWEVER, to be portable across different platforms, ImGui splits itself into two parts: the core + * **library** and the **backend**. In other words, the ImGui core is responsible for calculating vertex data, which + * it then submits to the backend for rendering. This is where the magic happens: although ImGui's rendering and + * logic are forcibly bound, rendering MUST actually go through the backend submission. The REAL rendering is + * ultimately done by the **backend**, and the vertex computation overhead is actually tiny compared to full + * rendering. So, by calling ImGui::Render() to let the ImGui core execute the complete rendering pipeline — but + * WITHOUT submitting to the backend for actual rendering — we can achieve a complete DECOUPLING of logic and + * rendering! Although the CPU will inevitably still calculate the vertices, we have successfully and completely + * decoupled rendering from logic, and the **possibilities** from here are INFINITE! + * + * @param isVirtual If true, CMaterial will not actually render anything, just update internal ImGui logic. + */ void IWindow::drawWindow(bool isVirtual) { if (!isVirtual) glfwMakeContextCurrent(glfwWindow); @@ -95,7 +124,35 @@ namespace cmaterial::window { ImGui::SetNextWindowPos(ImVec2(0, 0)); ImGui::SetNextWindowSize(io->DisplaySize); - this->render(io); + for (auto style : styles) { + ImGui::PushStyleVar(style.first, style.second); + } + + ImGui::PushStyleColor(ImGuiCol_WindowBg, backgroundColor); + + if (ImGui::Begin(this->name.c_str(), nullptr, windowFlags)) { + this->render(io); + + for (auto &pair: components) { + if (pair.second->getIsDead()) { + deadComponents.push_back(pair.first); + continue; + } + pair.second->drawComponent(io); + } + + for (const std::string &name: deadComponents) { + component::IComponent *component = components[name]; + components.erase(name); + delete component; + } + + deadComponents.clear(); + } + ImGui::End(); + + ImGui::PopStyleColor(); + ImGui::PopStyleVar(styles.size()); ImGui::Render(); @@ -111,8 +168,15 @@ namespace cmaterial::window { } void IWindow::addComponent(component::IComponent* comp) { - if (comp && !comp->name.empty()) + if (comp && !comp->name.empty()) { + comp->parent = this; components[comp->name] = comp; + } + } + + void IWindow::removeComponent(component::IComponent *comp) { + comp->parent = nullptr; + components.erase(comp->name); } bool IWindow::isHovered() const { diff --git a/src/engine/window/IWindow.h b/src/engine/window/IWindow.h index 6e8a382..5716149 100644 --- a/src/engine/window/IWindow.h +++ b/src/engine/window/IWindow.h @@ -13,26 +13,67 @@ #include "GLFW/glfw3.h" #include "engine/component/IComponent.h" +#include "engine/utils/ordered_map.hpp" #include "imgui.h" namespace cmaterial::window { - class IWindow { + /** + * @brief The base of the window. + * + * @details --- Extend Hook --- + * + * @details @code virtual postInit()@endcode : The custom logic of the window initialization. + * @details @code virtual postUpdate()@endcode : The custom logic of the window update. + * @details @code virtual render()@endcode : The content of the window. Design your window here. + * + * @details --- Property --- + * @details @code std::string name@endcode : The name of the window. + * @details @code int width, height@endcode : The width and height of the window. + * @details @code ImGuiWindowFlags windowFlags@endcode : The flags of the ImGuiWindow. If you don't know what they + * are, DON'T touch them. + * @details @code ImVec4 backgroundColor@endcode : The background color of the window. Use + * @code ImVec4(r, g, b, alpha)@endcode to change it. + * + * @details --- DANGER ZONE --- + * + * @details @code virtual update()@endcode : The core update logic of the window. + * If you TRULY have a compelling reason that you must use it, you can override it completely. + * But in most cases, you should override @code postUpdate()@endcode instead of this. + * + * @warning You should extend it to make a custom Window. NEVER USE THE INTERFACE DIRECTLY! + */ + class IWindow : public utils::INode { public: IWindow(const std::string &name, int width, int height); virtual ~IWindow(); void initialize(GLFWwindow* window, ImFontAtlas* fontAtlas); - void drawWindow(bool isVirtual); // isVirtual: Is only force ImGui update private states? + void drawWindow(bool isVirtual); + /** + * The custom logic of the window initialization. + */ virtual void postInit(ImGuiIO *io) {}; + /** + * The custom logic of the window update. + */ virtual void postUpdate() {}; virtual void update(); - virtual void render(ImGuiIO* io) = 0; + /** + * The custom logic of the window initialization. + */ + virtual void render(ImGuiIO* io) {}; + void addComponent(component::IComponent *comp); + void addStyle(ImGuiStyleVar styleVar, float value); + void removeStyle(ImGuiStyleVar styleVar); + void removeComponent(component::IComponent *comp); std::string name; int width, height; + ImGuiWindowFlags windowFlags = ImGuiWindowFlags_NoDecoration | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoSavedSettings; + ImVec4 backgroundColor = ImVec4(0.0f, 0.0f, 0.0f, 1.0f); bool isDead = false; bool isInitialized = false; @@ -47,8 +88,9 @@ namespace cmaterial::window { ImGuiIO* io = nullptr; ImFontAtlas* fontAtlas = nullptr; - std::unordered_map components; + utils::ordered_map components; std::vector deadComponents; + std::unordered_map styles; }; } diff --git a/src/main.cpp b/src/main.cpp index e5f2ff4..d800637 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -2,33 +2,50 @@ // Created by Earth_Studio on 2026/4/12. // +#include "content/component/MultiLayerButton/MultiLayerButton.h" #include "engine/framework/Framework.h" #include "content/component/BasicButton/BasicButton.h" #include "content/component/CreatorButton/CreatorButton.h" +#include "content/component/material/Button/Button.h" #include "content/logic/listener/WindowLogic.h" #include "content/window/BasicWindow/BasicWindow.h" +using namespace cmaterial; + int main() { - cmaterial::Framework app; + // Before you start to write application, you must initialize the Framework first: + Framework app; app.initialize(); - cmaterial::event::EventBus::addListener(new cmaterial::event::WindowLogic(&app)); + // Add your Listener: + event::EventBus::addListener(new event::WindowLogic(&app)); - cmaterial::window::BasicWindow* window1 = new cmaterial::window::BasicWindow("window1", 300, 100); - cmaterial::window::BasicWindow* window2 = new cmaterial::window::BasicWindow("window2", 300, 100); + // Create your windows: + window::BasicWindow* window1 = new window::BasicWindow("Milestone Single Test", 300, 100); + window::BasicWindow* window2 = new window::BasicWindow("Hybrid Final Test", 300, 100); - cmaterial::component::BasicButton* button1 = new cmaterial::component::BasicButton(); + // Create your components: + component::BasicButton* button1 = new component::BasicButton(); button1->name = "buttonInWindow1"; - cmaterial::component::CreatorButton* button2 = new cmaterial::component::CreatorButton(); + component::CreatorButton* button2 = new component::CreatorButton(); button2->name = "buttonInWindow2"; + component::MultiLayerButton* multiLayerButton = new component::MultiLayerButton(); + multiLayerButton->name = "MultiLayer"; + component::material::Button* md3Button = new component::material::Button(); + md3Button->name = "MD3 Button"; + + // To inject components in an exist window: app.addWindow(window1); window1->addComponent(button1); + window1->addComponent(multiLayerButton); app.addWindow(window2); window2->addComponent(button2); + window2->addComponent(md3Button); + // Finally, run your app by doing this: app.run(); return 0; } \ No newline at end of file diff --git a/version.rc b/version.rc index 0085c10..40d7387 100644 --- a/version.rc +++ b/version.rc @@ -37,6 +37,6 @@ BEGIN END BLOCK "VarFileInfo" BEGIN - VALUE "Translation", 0x0409, 0x04E4 // 英语美国 , 多字节->Unicode + VALUE "Translation", 0x0409, 0x04E4 END END \ No newline at end of file