ZenitUI
Retained-mode C++20 UI framework
Loading...
Searching...
No Matches
UIContext.hpp
Go to the documentation of this file.
1#pragma once
2
28
29#include "Common.hpp"
30#include "CoreTypes.hpp"
31#include "Geometry2D.hpp"
32#include "FilterRegistry.hpp"
33#include "Theme.hpp"
34#include "TextEngine.hpp"
35#include "UIEnums.hpp"
36
37#include <span>
38#include <any>
39
40namespace ZenitUI
41{
45
46 class Layout;
47
48 namespace ZMarkup
49 {
50 class Registry;
51 }
52
67
82
93
106 {
107 public:
108 virtual ~IRenderer() = default;
109
112
123 virtual void drawGeometry(std::span<const Vertex2D> vertices,
124 std::span<const uint32_t> indices,
125 TextureHandle tex = {}) = 0;
127
130
132 virtual void fillRect(Rect r, Color c)
133 {
134 const auto m = Geometry2D::buildQuad(r, c);
135 if (!m.empty())
136 drawGeometry(m.vertexSpan(), m.indexSpan());
137 }
138
140 virtual void fillRoundedRect(Rect r, float radiusPx, Color c)
141 {
142 const auto m = Geometry2D::buildRoundedRectFill(r, radiusPx, c);
143 if (!m.empty())
144 drawGeometry(m.vertexSpan(), m.indexSpan());
145 }
146
148 virtual void fillCircle(Vec2 center, float radius, Color c)
149 {
150 const auto m = Geometry2D::buildCircle(center, radius, c);
151 if (!m.empty())
152 drawGeometry(m.vertexSpan(), m.indexSpan());
153 }
154
161 virtual void strokeRect(Rect r, float thickness, Color c)
162 {
163 const auto m = Geometry2D::buildRectStroke(r, thickness, c);
164 if (!m.empty())
165 drawGeometry(m.vertexSpan(), m.indexSpan());
166 }
167
174 virtual void strokeRoundedRect(Rect r, float radiusPx, float thickness, Color c)
175 {
176 const auto m = Geometry2D::buildRoundedRectStroke(r, radiusPx, thickness, c);
177 if (!m.empty())
178 drawGeometry(m.vertexSpan(), m.indexSpan());
179 }
180
184 virtual void fillBorder(Rect r, EdgeInsets sides, Color c)
185 {
186 const auto m = Geometry2D::buildBorder(r, sides, c);
187 if (!m.empty())
188 drawGeometry(m.vertexSpan(), m.indexSpan());
189 }
190
191
194
196 virtual void drawTexture(TextureHandle t, Rect src, Rect dst, Color tint)
197 {
198 const auto m = Geometry2D::buildTexturedQuad(t, src, dst, tint);
199 if (!m.empty())
200 drawGeometry(m.vertexSpan(), m.indexSpan(), t);
201 }
202
204 virtual void drawNineSlice(TextureHandle t, NineSlice s, Rect dst, Color tint)
205 {
206 const auto m = Geometry2D::buildNineSlice(t, s, dst, tint);
207 if (!m.empty())
208 drawGeometry(m.vertexSpan(), m.indexSpan(), t);
209 }
210
217 virtual TextureHandle createTexture(int /*w*/, int /*h*/, const uint8_t * /*rgbaPixels*/ = nullptr)
218 {
219 return {};
220 }
221
227 virtual void updateTexture(TextureHandle /*t*/, Rect /*region*/, const uint8_t * /*rgbaPixels*/) {}
228
230 virtual void destroyTexture(TextureHandle /*t*/) {}
231
233
236
238 virtual void pushTransform(const Transform2D &t) = 0;
239
241 virtual void popTransform() = 0;
242
244 virtual void pushEffect(EffectHandle e) = 0;
245
247 virtual void popEffect() = 0;
248
256 virtual void setBlendMode(BlendMode /*mode*/) {}
257
264 virtual void pushClip(Rect r) = 0;
265
267 virtual void popClip() = 0;
268
270 virtual Rect getClipRect() const = 0;
272
275
277 virtual TargetHandle createTarget(int w, int h) = 0;
278
280 virtual void destroyTarget(TargetHandle t) = 0;
281
288 virtual void pushTarget(TargetHandle t) = 0;
289
291 virtual void popTarget() = 0;
292
294 virtual void drawTarget(TargetHandle t, Rect dst, Color tint) = 0;
295
302 virtual void drawTarget(TargetHandle t, Rect /*src*/, Rect dst, Color tint)
303 {
304 drawTarget(t, dst, tint);
305 }
306
308 virtual void clearTarget(TargetHandle t, Color c) = 0;
309
311 virtual bool inTarget() const = 0;
312
314
317
323 virtual EffectHandle createEffect(std::string_view /*fsSource*/,
324 std::string_view /*vsSource*/ = {})
325 {
326 return {};
327 }
328
330 virtual void destroyEffect(EffectHandle /*e*/) {}
331
333
336
338 virtual void setEffectFloat(EffectHandle e, const char *name, float value) = 0;
339
341 virtual void setEffectVec2(EffectHandle e, const char *name, Vec2 value) = 0;
342
344 virtual void setEffectVec3(EffectHandle e, const char *name, Vec3 value) = 0;
345
347 virtual void setEffectVec4f(EffectHandle e, const char *name, Vec4 value) = 0;
348
350 virtual void setEffectVec4(EffectHandle e, const char *name, Color value) = 0;
351
353
356
358 virtual bool supports(Feature f) const = 0;
359
362
364 virtual void beginFrame() = 0;
365
367 virtual void endFrame() = 0;
368
370 virtual void setDpiScale(float scale) = 0;
372 };
373
383 {
384 public:
385 virtual ~IPlatform() = default;
386
388 virtual Vec2 viewportSize() = 0;
389
397 virtual PointerState pointer() = 0;
398
400 virtual double time() = 0;
401
404
412
414 virtual float dpiScale() = 0;
415
417 virtual EdgeInsets safeArea() = 0;
418
420 virtual void setClipboardText(const std::string &text) = 0;
421
423 virtual std::string getClipboardText() = 0;
424
426 virtual void setCursor(CursorShape /*cursor*/) {}
427
434 virtual void setTextInputRect(Rect /*inputRect*/, float /*cursorXOffset*/ = 0.0f) {}
435 };
436
449 {
450 public:
451 virtual ~IAssetProvider() = default;
452
454 virtual TextureHandle getTexture(std::string_view name) = 0;
455
457 virtual EffectHandle getEffect(std::string_view name) = 0;
458
460 virtual TextureHandle loadTexture(std::string_view /*name*/, std::string_view /*path*/)
461 {
462 return {};
463 }
464
466 virtual TextureHandle loadTextureFromMemory(std::string_view /*name*/,
467 const void * /*data*/,
468 size_t /*size*/)
469 {
470 return {};
471 }
472
474 virtual void unloadTexture(std::string_view /*name*/) {}
475
477 virtual EffectHandle loadEffect(std::string_view /*name*/,
478 std::string_view /*fsPath*/,
479 std::string_view /*vsPath*/ = {})
480 {
481 return {};
482 }
483
485 virtual EffectHandle loadEffectFromMemory(std::string_view /*name*/,
486 std::string_view /*fsSource*/,
487 std::string_view /*vsSource*/ = {})
488 {
489 return {};
490 }
491
497 EffectHandle loadEffectAsset(std::string_view name,
498 std::string_view baseDir,
499 std::string_view fileStem,
500 ShaderLanguage lang)
501 {
502 std::string dir(baseDir);
503 if (!dir.empty() && dir.back() != '/' && dir.back() != '\\')
504 dir.push_back('/');
505
506 std::string path;
507 switch (lang)
508 {
510 path = dir + std::string(fileStem) + ".fs";
511 break;
513 path = dir + "es300/" + std::string(fileStem) + ".fs";
514 break;
516 path = dir + "spv/" + std::string(fileStem) + ".frag.spv";
517 break;
519 path = dir + "hlsl/" + std::string(fileStem) + ".hlsl";
520 break;
522 path = dir + "msl/" + std::string(fileStem) + ".metal";
523 break;
525 path = dir + "wgsl/" + std::string(fileStem) + ".wgsl";
526 break;
528 default:
529 return {};
530 }
531 return loadEffect(name, path);
532 }
533
535 virtual void unloadEffect(std::string_view /*name*/) {}
536 };
537
543 {
544 uint32_t targetsCreated{0};
545 uint32_t targetsDestroyed{0};
546 uint32_t liveTargets{0};
547 uint32_t pushTargetCalls{0};
548 uint32_t filterPasses{0};
549
550 void beginFrame()
551 {
552 targetsCreated = 0;
553 targetsDestroyed = 0;
554 pushTargetCalls = 0;
555 filterPasses = 0;
556 }
557
558 void resetAll()
559 {
560 beginFrame();
561 liveTargets = 0;
562 }
563 };
564
570 {
571 public:
572 static constexpr int BUCKET_SIZE = 64;
573 static constexpr int MAX_DIM = 4096;
574
575 static int bucketDim(int v)
576 {
577 int rounded = ((v + BUCKET_SIZE - 1) / BUCKET_SIZE) * BUCKET_SIZE;
578 return rounded < MAX_DIM ? rounded : MAX_DIM;
579 }
580
581 TargetHandle acquire(IRenderer &r, int w, int h, RenderStats *stats = nullptr)
582 {
583 if (w <= 0 || h <= 0)
584 return {};
585
586 const bool useSubRect = r.supports(Feature::TargetSubRect);
587 const int reqW = useSubRect ? bucketDim(w) : w;
588 const int reqH = useSubRect ? bucketDim(h) : h;
589
590 // Ricerca LIFO di un target libero con le dimensioni richieste/arrotondate.
591 for (auto it = entries_.rbegin(); it != entries_.rend(); ++it)
592 {
593 if (!it->inUse && it->handle.width == reqW && it->handle.height == reqH)
594 {
595 it->inUse = true;
596 it->lastUsedFrame = frameIndex_;
597 return it->handle;
598 }
599 }
600
601 TargetHandle hnd = r.createTarget(reqW, reqH);
602 if (!hnd.valid())
603 return {};
604
605 entries_.push_back({hnd, true, frameIndex_});
606 if (stats)
607 {
608 stats->targetsCreated++;
609 stats->liveTargets++;
610 }
611 return hnd;
612 }
613
614 void release(TargetHandle t)
615 {
616 if (!t.valid())
617 return;
618 for (auto it = entries_.rbegin(); it != entries_.rend(); ++it)
619 {
620 if (it->handle.id == t.id)
621 {
622 it->inUse = false;
623 it->lastUsedFrame = frameIndex_;
624 return;
625 }
626 }
627 }
628
629 void trim(IRenderer &r, RenderStats *stats = nullptr, int graceFrames = 120)
630 {
631 const uint64_t grace = graceFrames > 0 ? static_cast<uint64_t>(graceFrames) : 1u;
632 for (auto it = entries_.begin(); it != entries_.end();)
633 {
634 if (!it->inUse && (frameIndex_ - it->lastUsedFrame) >= grace)
635 {
636 r.destroyTarget(it->handle);
637 if (stats)
638 {
639 stats->targetsDestroyed++;
640 if (stats->liveTargets > 0)
641 stats->liveTargets--;
642 }
643 it = entries_.erase(it);
644 }
645 else
646 {
647 ++it;
648 }
649 }
650 frameIndex_++;
651 }
652
653 void clear(IRenderer &r, RenderStats *stats = nullptr)
654 {
655 for (auto &e : entries_)
656 {
657 if (e.handle.valid())
658 {
659 r.destroyTarget(e.handle);
660 if (stats)
661 {
662 stats->targetsDestroyed++;
663 if (stats->liveTargets > 0)
664 stats->liveTargets--;
665 }
666 }
667 }
668 entries_.clear();
669 frameIndex_ = 0;
670 generation_++;
671 }
672
673 size_t liveCount() const { return entries_.size(); }
674
676 uint64_t generation() const { return generation_; }
677
679 uint64_t frameIndex() const { return frameIndex_; }
680
681 private:
682 struct Entry
683 {
684 TargetHandle handle{};
685 bool inUse{false};
686 uint64_t lastUsedFrame{0};
687 };
688 std::vector<Entry> entries_;
689 uint64_t frameIndex_{0};
690 uint64_t generation_{1};
691 };
692
698 {
699 std::any data;
700 std::string typeTag;
701 };
702
708 {
709 std::weak_ptr<Layout> source;
710 std::weak_ptr<Layout> ghost;
711 DragPayload payload;
712 Vec2 startPos{0.0f, 0.0f};
713 Vec2 currentPos{0.0f, 0.0f};
714 Vec2 grabOffset{0.0f, 0.0f};
715 Layout *hoverTarget{nullptr};
716 bool pending{false};
717 bool active{false};
718 };
719
724 struct UIContext
725 {
726
727 UIContext() = default;
728 ~UIContext();
729
730 UIContext(const UIContext &) = delete;
731 UIContext &operator=(const UIContext &) = delete;
732 UIContext(UIContext &&) = delete;
733 UIContext &operator=(UIContext &&) = delete;
734
735 // ---- Backends ----
736 IRenderer *renderer{nullptr};
737 IPlatform *platform{nullptr};
738 IAssetProvider *assets{nullptr};
739
748 UIContext **ownerSlot = nullptr)
749 {
751 renderer = r;
752 platform = p;
753 assets = a;
754 backendOwnerSlot_ = ownerSlot;
755 activeCursor = CursorShape::Default;
756 cursorInitialized_ = false;
758 if (backendOwnerSlot_)
759 *backendOwnerSlot_ = this;
760 }
761
766 {
767 if (renderer)
768 {
769 textEngine.clearAtlas(*renderer);
770 targetPool.clear(*renderer, &renderStats);
771 }
772 renderer = nullptr;
773 platform = nullptr;
774 assets = nullptr;
775 activeCursor = CursorShape::Default;
776 cursorInitialized_ = false;
778 if (backendOwnerSlot_)
779 {
780 *backendOwnerSlot_ = nullptr;
781 backendOwnerSlot_ = nullptr;
782 }
783 }
784
785 // ---- Unified Asset Management (Fonts, Textures, Shaders) ----
786
788 FontHandle loadFont(std::string_view name, std::string_view path)
789 {
790 return textEngine.loadFont(name, path);
791 }
792
794 FontHandle loadFontFromMemory(std::string_view name, const void *data, size_t size)
795 {
796 return textEngine.loadFontFromMemory(name, data, size);
797 }
798
800 void unloadFont(std::string_view name)
801 {
802 textEngine.unloadFont(name);
803 }
804
806 FontHandle getFont(std::string_view name) const
807 {
808 return textEngine.getFont(name);
809 }
810
813 {
814 textEngine.setDefaultFont(h);
815 }
816
819 {
820 return textEngine.defaultFont();
821 }
822
824 TextureHandle loadTexture(std::string_view name, std::string_view path)
825 {
826 return assets ? assets->loadTexture(name, path) : TextureHandle{};
827 }
828
830 TextureHandle loadTextureFromMemory(std::string_view name, const void *data, size_t size)
831 {
832 return assets ? assets->loadTextureFromMemory(name, data, size) : TextureHandle{};
833 }
834
836 void unloadTexture(std::string_view name)
837 {
838 if (assets)
839 assets->unloadTexture(name);
840 }
841
843 TextureHandle getTexture(std::string_view name) const
844 {
845 return assets ? assets->getTexture(name) : TextureHandle{};
846 }
847
849 EffectHandle loadEffect(std::string_view name,
850 std::string_view fsPath,
851 std::string_view vsPath = {})
852 {
853 return assets ? assets->loadEffect(name, fsPath, vsPath) : EffectHandle{};
854 }
855
857 EffectHandle loadEffectFromMemory(std::string_view name,
858 std::string_view fsSource,
859 std::string_view vsSource = {})
860 {
861 return assets ? assets->loadEffectFromMemory(name, fsSource, vsSource) : EffectHandle{};
862 }
863
868 EffectHandle loadEffectAsset(std::string_view name,
869 std::string_view baseDir,
870 std::string_view fileStem)
871 {
872 if (!assets || !renderer)
873 return {};
874 return assets->loadEffectAsset(name, baseDir, fileStem, renderer->shaderLanguage());
875 }
876
878 void unloadEffect(std::string_view name)
879 {
880 if (assets)
881 assets->unloadEffect(name);
882 }
883
885 EffectHandle getEffect(std::string_view name) const
886 {
887 return assets ? assets->getEffect(name) : EffectHandle{};
888 }
889
890 // ---- Per-frame state ----
891 PointerState pointer;
892 float dt{0.0f};
893 double time{0.0};
894 float dpiScale{1.0f};
895 EdgeInsets safeArea;
896 ModifierState modifiers;
897 bool wheelConsumedThisFrame{false};
898 std::array<bool, (size_t)MouseButton::Count> buttonConsumed{};
899 Vec2 viewport{1280.0f, 720.0f};
900
902 void consumeClick(MouseButton b) { buttonConsumed[(size_t)b] = true; }
904 bool wasConsumed(MouseButton b) const { return buttonConsumed[(size_t)b]; }
905
906 InputEvents inputEvents;
907 std::weak_ptr<Layout> focusedNode;
908 std::weak_ptr<Layout> pointerCapture;
909
913
921
923 const ZMarkup::Registry *markupRegistryPtr() const noexcept { return markupRegistry_.get(); }
924
925 uint32_t viewportGeneration{0};
926
928 void invalidateStyles() { viewportGeneration++; }
929
930 // ---- Hit-test and click routing ----
931 Layout *topmostConsumer{nullptr};
932 Layout *hoverTarget{nullptr};
933 Layout *pressTarget{nullptr};
934 Layout *releaseTarget{nullptr};
935
936 CursorShape activeCursor{CursorShape::Default};
937
939 bool isPressTarget(const Layout *n) const { return pressTarget == n; }
941 bool isValidClick() const
942 {
943 return pressTarget && releaseTarget && pressTarget == releaseTarget;
944 }
945
946 // ---- Drag & Drop ----
947 ActiveDrag activeDrag;
948 float dragThreshold{5.0f};
949 std::function<std::shared_ptr<Layout>(const DragPayload &)> dragGhostFactory;
950
952 bool isDragging() const noexcept { return activeDrag.active; }
954 bool hasPendingDrag() const noexcept { return activeDrag.pending; }
957
959 std::shared_ptr<Layout> dragGhost() const { return dragGhost_; }
960
963 {
964 const CursorShape resolved = (shape == CursorShape::Auto) ? CursorShape::Default : shape;
965 if (cursorInitialized_ && activeCursor == resolved)
966 return;
967 activeCursor = resolved;
968 cursorInitialized_ = true;
969 if (platform)
970 platform->setCursor(resolved);
971 }
972
974 void setTextInputRect(Rect inputRect, float cursorXOffset = 0.0f)
975 {
976 const bool valid = (inputRect.width > 0.0f && inputRect.height > 0.0f);
977 if (!valid && !imeRectInitialized_)
978 {
979 imeRectInitialized_ = true;
980 return;
981 }
982 if (valid)
983 imeRectUpdatedThisFrame_ = true;
984
985 const Rect norm = valid ? inputRect : Rect{0.0f, 0.0f, 0.0f, 0.0f};
986 const float normCursor = valid ? cursorXOffset : 0.0f;
987 if (imeRectInitialized_ &&
988 std::abs(activeImeRect_.x - norm.x) < 0.5f &&
989 std::abs(activeImeRect_.y - norm.y) < 0.5f &&
990 std::abs(activeImeRect_.width - norm.width) < 0.5f &&
991 std::abs(activeImeRect_.height - norm.height) < 0.5f &&
992 std::abs(activeImeCursorOffset_ - normCursor) < 0.5f)
993 {
994 return;
995 }
996 activeImeRect_ = norm;
997 activeImeCursorOffset_ = normCursor;
998 imeRectInitialized_ = true;
999 if (platform)
1000 platform->setTextInputRect(norm, normCursor);
1001 }
1002
1005 {
1006 activeImeRect_ = {0.0f, 0.0f, 0.0f, 0.0f};
1007 activeImeCursorOffset_ = 0.0f;
1008 imeRectInitialized_ = false;
1009 imeRectUpdatedThisFrame_ = false;
1010 }
1011
1012 // ---- Portals ----
1013 std::vector<std::weak_ptr<Layout>> activePortals;
1014 std::vector<std::weak_ptr<Layout>> framePortals;
1015
1016 std::mt19937 rng;
1017
1018 // ---- Render instrumentation & target pool ----
1019 RenderStats renderStats;
1020 TargetPool targetPool;
1021
1022 // ---- Screen-space culling clip stack across off-screen targets ----
1023 std::vector<Rect> cullingClipStack;
1024 std::vector<float> targetScaleStack_;
1025
1028 {
1029 if (!cullingClipStack.empty())
1030 return cullingClipStack.front();
1031 return renderer ? renderer->getClipRect()
1032 : Rect{0.0f, 0.0f, viewport.x, viewport.y};
1033 }
1034
1036 void pushLayerTarget(TargetHandle t, float targetScale = 1.0f)
1037 {
1038 if (!renderer)
1039 return;
1040 cullingClipStack.push_back(getCullingClip());
1041 targetScaleStack_.push_back(targetScale);
1042 textEngine.setTargetDpiScale(targetScale);
1043 renderer->pushTarget(t);
1044 renderStats.pushTargetCalls++;
1045 }
1046
1049 {
1050 if (!renderer)
1051 return;
1052 renderer->popTarget();
1053 if (!cullingClipStack.empty())
1054 cullingClipStack.pop_back();
1055 if (!targetScaleStack_.empty())
1056 targetScaleStack_.pop_back();
1057 textEngine.setTargetDpiScale(targetScaleStack_.empty() ? 1.0f : targetScaleStack_.back());
1058 }
1059
1069 void beginFrame(float delta_time)
1070 {
1071 dt = delta_time;
1072 time += delta_time;
1073 wheelConsumedThisFrame = false;
1074 buttonConsumed.fill(false);
1075 topmostConsumer = nullptr;
1076 hoverTarget = nullptr;
1077 releaseTarget = nullptr;
1078 cullingClipStack.clear();
1079 targetScaleStack_.clear();
1080 textEngine.setTargetDpiScale(1.0f);
1081 renderStats.beginFrame();
1082 activePortals = std::move(framePortals);
1083 framePortals.clear();
1084 if (platform)
1085 {
1086 Vec2 newVp = platform->viewportSize();
1087 EdgeInsets newSafe = platform->safeArea();
1088 if (newVp.x != viewport.x || newVp.y != viewport.y ||
1089 newSafe != safeArea)
1090 {
1091 viewportGeneration++;
1092 }
1093 viewport = newVp;
1094 safeArea = newSafe;
1095 pointer = platform->pointer();
1096 modifiers = platform->modifiers();
1097 inputEvents = platform->pollInputEvents();
1098 dpiScale = platform->dpiScale();
1099 textEngine.setDpiScale(dpiScale);
1100 if (renderer)
1101 {
1102 renderer->setDpiScale(dpiScale);
1103 }
1104 }
1105 }
1106
1109 {
1110 if (renderer)
1111 targetPool.trim(*renderer, &renderStats);
1112 }
1113
1115 void requestFocus(std::shared_ptr<Layout> n);
1116
1118 void mount(Layout &root);
1119 void mount(const std::shared_ptr<Layout> &root)
1120 {
1121 if (root)
1122 mount(*root);
1123 }
1124
1126 void unmount(Layout &root);
1127 void unmount(const std::shared_ptr<Layout> &root)
1128 {
1129 if (root)
1130 unmount(*root);
1131 }
1132
1134 void unmount();
1135
1137 Layout *mountedRoot() const { return primaryRoot_; }
1138
1141
1143 void runFrame(float dt);
1144
1147
1149 void runFrame(Layout &root, float dt);
1150
1152 void renderFrame(Layout &root);
1153
1155 void releaseFocus() { focusedNode.reset(); }
1157 bool hasFocus(const Layout *n) const
1158 {
1159 auto sp = focusedNode.lock();
1160 return sp && sp.get() == n;
1161 }
1162
1163 private:
1164 friend class Layout;
1165
1166 void registerRoot(Layout *root)
1167 {
1168 if (!root)
1169 return;
1170 if (std::find(attachedRoots_.begin(), attachedRoots_.end(), root) == attachedRoots_.end())
1171 attachedRoots_.push_back(root);
1172 }
1173
1174 void unregisterRoot(Layout *root)
1175 {
1176 if (primaryRoot_ == root)
1177 primaryRoot_ = nullptr;
1178 auto it = std::find(attachedRoots_.begin(), attachedRoots_.end(), root);
1179 if (it != attachedRoots_.end())
1180 attachedRoots_.erase(it);
1181 }
1182
1183 std::vector<Layout *> attachedRoots_;
1184 Layout *primaryRoot_{nullptr};
1185 UIContext **backendOwnerSlot_{nullptr};
1186 std::shared_ptr<ZMarkup::Registry> markupRegistry_;
1187 bool cursorInitialized_{false};
1188 Rect activeImeRect_{0.0f, 0.0f, 0.0f, 0.0f};
1189 float activeImeCursorOffset_{0.0f};
1190 bool imeRectInitialized_{false};
1191 bool imeRectUpdatedThisFrame_{false};
1192 std::shared_ptr<Layout> dragGhost_;
1193 };
1194
1196}
Centralized standard library includes used throughout ZenitUI.
Small value types shared by the layout, rendering and input layers.
Post-processing filter registry and the filter execution context.
Shared zero-allocation 2D tessellation helpers for IRenderer backends.
Backend-independent text shaping (HarfBuzz), glyph rasterization (FreeType), dynamic atlas packing,...
Global stylesheet storage and rule matching.
Small enumerations describing layout strategy and interaction state.
Per-context map from CSS filter name to FilterDef.
Definition FilterRegistry.hpp:130
Abstract name-based lookup and runtime lifecycle for textures and shaders.
Definition UIContext.hpp:449
virtual TextureHandle loadTexture(std::string_view, std::string_view)
Optional runtime hook to load a 2D texture from disk under name.
Definition UIContext.hpp:460
virtual void unloadEffect(std::string_view)
Optional runtime hook to unload a shader effect by logical name.
Definition UIContext.hpp:535
virtual EffectHandle loadEffect(std::string_view, std::string_view, std::string_view={})
Optional runtime hook to load a fragment (and optional vertex) shader from disk under name.
Definition UIContext.hpp:477
virtual TextureHandle getTexture(std::string_view name)=0
Look up a loaded 2D texture by logical name; returns {0} if not found.
virtual EffectHandle getEffect(std::string_view name)=0
Look up a loaded shader effect by logical name; returns {0} if not found.
EffectHandle loadEffectAsset(std::string_view name, std::string_view baseDir, std::string_view fileStem, ShaderLanguage lang)
Load a shader effect by stem fileStem under baseDir, resolving the file extension from lang (e....
Definition UIContext.hpp:497
virtual EffectHandle loadEffectFromMemory(std::string_view, std::string_view, std::string_view={})
Optional runtime hook to load a shader effect from in-memory source strings.
Definition UIContext.hpp:485
virtual void unloadTexture(std::string_view)
Optional runtime hook to unload a texture by logical name.
Definition UIContext.hpp:474
virtual TextureHandle loadTextureFromMemory(std::string_view, const void *, size_t)
Optional runtime hook to load a 2D texture from encoded image bytes in memory.
Definition UIContext.hpp:466
Abstract windowing, timing, input, and clipboard backend.
Definition UIContext.hpp:383
virtual void setCursor(CursorShape)
Request the OS/windowing system to display the given cursor shape.
Definition UIContext.hpp:426
virtual EdgeInsets safeArea()=0
Return screen safe-area insets in logical pixels (notches, rounded corners, system bars).
virtual ModifierState modifiers()=0
Return the current state of modifier keys (shift, ctrl, alt, super).
virtual PointerState pointer()=0
Return the current pointer position (logical pixels), scroll wheel delta, and button states.
virtual void setClipboardText(const std::string &text)=0
Copy UTF-8 text to the operating system clipboard.
virtual float dpiScale()=0
Return the physical-to-logical DPI scale factor (e.g.
virtual std::string getClipboardText()=0
Read UTF-8 text from the operating system clipboard (empty string if unavailable).
virtual double time()=0
Return a monotonic clock timestamp in seconds.
virtual InputEvents pollInputEvents()=0
Drain and return keyboard events queued since the previous frame.
virtual void setTextInputRect(Rect, float=0.0f)
Inform the OS IME of the active text-input rect and caret offset (in logical window coordinates) so c...
Definition UIContext.hpp:434
virtual Vec2 viewportSize()=0
Return the current window/surface dimensions in logical pixels.
Abstract 2D rendering backend.
Definition UIContext.hpp:106
virtual void popEffect()=0
Pop the active shader effect and restore the previous one (if any).
virtual void popTarget()=0
Finish drawing into the active target and restore the previous target (or main framebuffer) and stack...
virtual TextureHandle createTexture(int, int, const uint8_t *=nullptr)
Allocate a dynamic RGBA8 2D texture of w x h pixels.
Definition UIContext.hpp:217
virtual void strokeRoundedRect(Rect r, float radiusPx, float thickness, Color c)
Stroke a rounded border strictly inside r (CSS border-box).
Definition UIContext.hpp:174
virtual void fillCircle(Vec2 center, float radius, Color c)
Fill a circle centered at center with the given logical radius.
Definition UIContext.hpp:148
virtual void endFrame()=0
Called at the end of Layout::renderFrame after all draw calls and portals have rendered.
virtual void drawTarget(TargetHandle t, Rect dst, Color tint)=0
Composite the entire render target t into logical destination rect dst, multiplied by tint.
virtual bool supports(Feature f) const =0
Query whether this backend implements an optional Feature.
virtual bool inTarget() const =0
Return true while a pushTarget is active without a matching popTarget.
virtual Rect getClipRect() const =0
Return the active screen-space clip rectangle in logical pixels (used for culling).
virtual void clearTarget(TargetHandle t, Color c)=0
Clear render target t to solid color c.
virtual EffectHandle createEffect(std::string_view, std::string_view={})
Compile and allocate a shader effect from GLSL/backend source strings.
Definition UIContext.hpp:323
virtual void drawTarget(TargetHandle t, Rect, Rect dst, Color tint)
Composite sub-rectangle src (target pixels) of t into logical rect dst.
Definition UIContext.hpp:302
virtual void fillBorder(Rect r, EdgeInsets sides, Color c)
Draw a rectangular ring with per-edge widths in a single indexed draw call.
Definition UIContext.hpp:184
virtual void destroyTarget(TargetHandle t)=0
Release a render target previously allocated by createTarget.
virtual void pushEffect(EffectHandle e)=0
Bind shader effect e and push it onto the effect stack (used when Feature::Effects is supported).
virtual void drawTexture(TextureHandle t, Rect src, Rect dst, Color tint)
Draw sub-rectangle src (texture pixels) of texture t into logical rect dst, multiplied by tint.
Definition UIContext.hpp:196
virtual void destroyEffect(EffectHandle)
Release a shader effect previously created by createEffect.
Definition UIContext.hpp:330
virtual ShaderLanguage shaderLanguage() const
Return the shading language expected by IAssetProvider::loadEffect on this renderer.
Definition UIContext.hpp:361
virtual void beginFrame()=0
Called at the start of Layout::renderFrame before any draw calls (e.g.
virtual void drawNineSlice(TextureHandle t, NineSlice s, Rect dst, Color tint)
Draw texture t stretched into dst using the 9-slice insets s (fixed corners, stretched edges/center).
Definition UIContext.hpp:204
virtual void pushTransform(const Transform2D &t)=0
Push a 2D pivot-based transform onto the transform stack.
virtual void destroyTexture(TextureHandle)
Release a dynamic texture previously created by createTexture.
Definition UIContext.hpp:230
virtual void setEffectFloat(EffectHandle e, const char *name, float value)=0
Set a float uniform named name on effect e.
virtual void pushClip(Rect r)=0
Push a local-space clip rectangle r, intersecting it with the current clip.
virtual void updateTexture(TextureHandle, Rect, const uint8_t *)
Upload tightly-packed RGBA8 pixels into sub-rectangle region of texture t.
Definition UIContext.hpp:227
virtual void setEffectVec4f(EffectHandle e, const char *name, Vec4 value)=0
Set a vec4 uniform named name on effect e.
virtual void setEffectVec4(EffectHandle e, const char *name, Color value)=0
Set a normalized RGBA vec4 uniform (0..1 per channel) named name on effect e.
virtual void strokeRect(Rect r, float thickness, Color c)
Stroke a rectangular border strictly inside r (CSS border-box).
Definition UIContext.hpp:161
virtual void fillRect(Rect r, Color c)
Fill an axis-aligned rectangle r with solid color c.
Definition UIContext.hpp:132
virtual void setBlendMode(BlendMode)
Switch the active color-blending mode.
Definition UIContext.hpp:256
virtual void pushTarget(TargetHandle t)=0
Redirect subsequent draw calls to target t and clear it to transparent black.
virtual void fillRoundedRect(Rect r, float radiusPx, Color c)
Fill a rectangle r with corner radius radiusPx (clamped to half the shorter side).
Definition UIContext.hpp:140
virtual void setDpiScale(float scale)=0
Notify the renderer of the active logical-to-physical DPI scale factor for the current frame.
virtual TargetHandle createTarget(int w, int h)=0
Allocate an off-screen RGBA render target of w x h pixels (used when Feature::NestedTargets is suppor...
virtual void setEffectVec2(EffectHandle e, const char *name, Vec2 value)=0
Set a vec2 uniform named name on effect e.
virtual void drawGeometry(std::span< const Vertex2D > vertices, std::span< const uint32_t > indices, TextureHandle tex={})=0
Draw an indexed triangle list in logical screen coordinates.
virtual void setEffectVec3(EffectHandle e, const char *name, Vec3 value)=0
Set a vec3 uniform named name on effect e.
virtual void popClip()=0
Pop the current clip rectangle and restore the previous scissor region.
virtual void popTransform()=0
Pop the most recently pushed transform from the stack.
The base node type: tree, style, layout, input, scroll, render.
Definition Layout.hpp:154
Shared, bucket-sized render-target pool owned by UIContext (§4.9 Step c).
Definition UIContext.hpp:570
uint64_t generation() const
Monotonic generation counter incremented whenever clear() destroys all targets.
Definition UIContext.hpp:676
uint64_t frameIndex() const
Current frame counter advanced once per trim() call.
Definition UIContext.hpp:679
Per-context font store, HarfBuzz shaper, FreeType glyph atlas, and layout engine.
Definition TextEngine.hpp:142
Per-context stylesheet: rules, keyframes, and root style.
Definition Theme.hpp:164
Tag → factory map plus the prefab table (either per-UIContext or standalone/global).
Definition ZMarkup.hpp:215
NineSliceMesh buildNineSlice(TextureHandle t, NineSlice s, Rect dst, Color tint)
Build a 9-slice mesh (up to 9 quads, single indexed draw call).
Definition Geometry2D.hpp:185
RectStrokeMesh buildRectStroke(Rect r, float thickness, Color c)
Build a CSS border-box rectangular stroke strictly inside r without corner overdraw.
Definition Geometry2D.hpp:240
RoundedFillMesh buildRoundedRectFill(Rect r, float radiusPx, Color c)
Build a filled rounded rectangle (fast-paths to a 4-vertex quad when radiusPx <= 0....
Definition Geometry2D.hpp:323
BorderMesh buildBorder(Rect r, EdgeInsets sides, Color c)
Build per-edge rectangular borders in a single indexed draw call.
Definition Geometry2D.hpp:282
CircleMesh buildCircle(Vec2 center, float radius, Color c)
Build a filled circle with adaptive segment count (16..kCircleMaxSegments).
Definition Geometry2D.hpp:417
QuadMesh buildQuad(Rect r, Color c)
Build a solid-color axis-aligned quad.
Definition Geometry2D.hpp:146
RoundedStrokeMesh buildRoundedRectStroke(Rect r, float radiusPx, float thickness, Color c)
Build a CSS border-box rounded stroke mesh strictly inside r.
Definition Geometry2D.hpp:379
QuadMesh buildTexturedQuad(TextureHandle t, Rect src, Rect dst, Color tint)
Build a textured quad mapping pixel sub-rect src onto logical dst.
Definition Geometry2D.hpp:162
ShaderLanguage
Shading language consumed by an IRenderer that supports Feature::Effects.
Definition UIContext.hpp:73
MouseButton
Mouse buttons tracked by the input system.
Definition CoreTypes.hpp:361
BlendMode
Color-blending mode used by IRenderer draw calls.
Definition UIContext.hpp:88
CursorShape
Standard OS cursor shapes requested via ZStyle cursor: and IPlatform::setCursor.
Definition UIEnums.hpp:61
Feature
Optional renderer capabilities queried via IRenderer::supports.
Definition UIContext.hpp:62
@ MSL
Apple Metal Shading Language (.metal).
Definition UIContext.hpp:79
@ WGSL
WebGPU Shading Language (.wgsl).
Definition UIContext.hpp:80
@ SPIRV
Precompiled Vulkan / SDL_GPU SPIR-V binaries (.frag.spv).
Definition UIContext.hpp:77
@ None
Backend does not execute custom shaders.
Definition UIContext.hpp:74
@ GLSL300ES
OpenGL ES 3.0 / WebGL 2 GLSL.
Definition UIContext.hpp:76
@ GLSL330
OpenGL 3.3 Core GLSL (.fs / .vs, Raylib & SDL3 GL convention).
Definition UIContext.hpp:75
@ HLSL
Direct3D HLSL (.hlsl).
Definition UIContext.hpp:78
@ Replace
Overwrite destination RGBA directly without blending (single-quad filter passes).
Definition UIContext.hpp:91
@ Premultiplied
Premultiplied-alpha compositing for multi-draw cached FBO layers.
Definition UIContext.hpp:90
@ Alpha
Standard straight-alpha compositing (default).
Definition UIContext.hpp:89
@ Auto
Inherit or fall back to Default.
Definition UIEnums.hpp:62
@ Default
Standard arrow cursor.
Definition UIEnums.hpp:63
@ NestedTargets
Supports off-screen render targets (createTarget, pushTarget, popTarget, drawTarget).
Definition UIContext.hpp:64
@ TargetSubRect
Supports sub-rectangle blitting via drawTarget(t, src, dst, tint) for pooled targets.
Definition UIContext.hpp:65
@ Effects
Supports fragment shaders (pushEffect, popEffect, setEffect*).
Definition UIContext.hpp:63
Per-context state tracking a pending or active drag operation.
Definition UIContext.hpp:708
8-bit-per-channel RGBA color, non-premultiplied.
Definition CoreTypes.hpp:78
Opaque user payload carried during an active drag-and-drop operation.
Definition UIContext.hpp:698
std::string typeTag
User-defined discriminator (e.g. "list-item", "card", "file").
Definition UIContext.hpp:700
Four-sided edge inset (used for padding, margin, borders).
Definition CoreTypes.hpp:62
Opaque handle to a shader/effect owned by the asset provider.
Definition CoreTypes.hpp:142
Opaque handle to a font loaded by TextEngine.
Definition CoreTypes.hpp:135
One frame's worth of keyboard input.
Definition CoreTypes.hpp:437
Keyboard modifier snapshot.
Definition CoreTypes.hpp:390
Nine-slice inset values for scalable textures.
Definition CoreTypes.hpp:163
Pointer position, wheel delta, and per-button state for one frame.
Definition CoreTypes.hpp:378
Axis-aligned rectangle in screen coordinates.
Definition CoreTypes.hpp:46
Per-frame and live render-target / filter counters (Proposal 9, Step 0).
Definition UIContext.hpp:543
Opaque handle to an off-screen render target.
Definition CoreTypes.hpp:155
Opaque handle to a GPU/software texture owned by the asset provider.
Definition CoreTypes.hpp:127
2D affine transform stored as pivot + translate + rotation + scale.
Definition CoreTypes.hpp:178
bool wasConsumed(MouseButton b) const
true if b was already consumed this frame.
Definition UIContext.hpp:904
void setDefaultFont(FontHandle h)
Set the fallback font used when a node specifies no font or an unknown font name.
Definition UIContext.hpp:812
void mount(Layout &root)
Attach a root Layout subtree to this context and set it as the primary root.
void detachBackend()
Flush pooled render targets while the renderer is still valid and clear backend pointers.
Definition UIContext.hpp:765
std::shared_ptr< Layout > dragGhost() const
Return the currently active drag ghost node, or nullptr if none.
Definition UIContext.hpp:959
FilterRegistry filters
Per-context post-processing filter definitions (preloaded with builtins).
Definition UIContext.hpp:910
EffectHandle loadEffect(std::string_view name, std::string_view fsPath, std::string_view vsPath={})
Load a fragment (and optional vertex) shader from disk under logical name.
Definition UIContext.hpp:849
void requestFocus(std::shared_ptr< Layout > n)
Set n as the focused node; null clears focus.
void unmount()
Detach the currently mounted primary root, if any.
void consumeClick(MouseButton b)
Mark b as consumed; subsequent handlers in the same frame will skip it.
Definition UIContext.hpp:902
TextureHandle loadTexture(std::string_view name, std::string_view path)
Load a 2D texture from disk under logical name.
Definition UIContext.hpp:824
bool hasPendingDrag() const noexcept
true while a press on a draggable node is waiting to cross dragThreshold.
Definition UIContext.hpp:954
FontHandle defaultFont() const
Return the current default font handle ({0} if none).
Definition UIContext.hpp:818
void renderFrame()
Render the mounted primary root (beginFrame, draw, endFrame).
TextureHandle loadTextureFromMemory(std::string_view name, const void *data, size_t size)
Load a 2D texture from encoded image bytes (PNG/JPG/BMP/...) under logical name.
Definition UIContext.hpp:830
void unmount(Layout &root)
Detach a previously mounted root Layout subtree from this context.
TextureHandle getTexture(std::string_view name) const
Look up a loaded 2D texture by logical name ({0} if not found).
Definition UIContext.hpp:843
void runFrame(float dt)
Run one full update/measure/arrange frame on the mounted primary root.
void unloadFont(std::string_view name)
Unload a font by logical name.
Definition UIContext.hpp:800
void releaseFocus()
Clear focus.
Definition UIContext.hpp:1155
Rect getCullingClip() const
Active screen-space clip rect used by Layout::draw() for off-screen culling.
Definition UIContext.hpp:1027
void clearDragState()
Reset all pending/active drag state and destroy any active drag ghost without invoking callbacks.
void invalidateStyles()
Force style-cache invalidation across the tree.
Definition UIContext.hpp:928
FontHandle getFont(std::string_view name) const
Look up a loaded font by logical name ({0} if not found).
Definition UIContext.hpp:806
void applyCursor(CursorShape shape)
Apply shape to the active platform backend, deduplicating unchanged requests.
Definition UIContext.hpp:962
void unloadEffect(std::string_view name)
Unload a shader effect by logical name.
Definition UIContext.hpp:878
void endFrame()
End-of-frame housekeeping (trims idle pooled render targets).
Definition UIContext.hpp:1108
bool isValidClick() const
true if press and release targets agree (a valid click).
Definition UIContext.hpp:941
void attachBackend(IRenderer *r, IPlatform *p, IAssetProvider *a, UIContext **ownerSlot=nullptr)
Attach renderer, platform, and asset backends to this context.
Definition UIContext.hpp:747
void unloadTexture(std::string_view name)
Unload a 2D texture by logical name.
Definition UIContext.hpp:836
FontHandle loadFont(std::string_view name, std::string_view path)
Load a TTF/OTF font from disk under logical name.
Definition UIContext.hpp:788
TextEngine textEngine
Per-context FreeType/HarfBuzz shaper, glyph atlas, and layout cache.
Definition UIContext.hpp:912
void resetImeRectState()
Clear cached IME rect state (e.g.
Definition UIContext.hpp:1004
void detachAllRoots()
Detach every root currently attached to this context.
FontHandle loadFontFromMemory(std::string_view name, const void *data, size_t size)
Load a TTF/OTF font from memory under logical name (copies bytes).
Definition UIContext.hpp:794
Vec2 viewport
Current logical viewport dimensions.
Definition UIContext.hpp:899
ZMarkup::Registry & markupRegistry()
Return this context's isolated ZMarkup::Registry, lazily initialized with built-in widgets.
void runFrame(Layout &root, float dt)
Run one full update/measure/arrange frame on root using this context.
Theme theme
Per-context stylesheet (rules, keyframes, and :root style).
Definition UIContext.hpp:911
const ZMarkup::Registry * markupRegistryPtr() const noexcept
Return this context's ZMarkup::Registry if initialized, or nullptr without allocating.
Definition UIContext.hpp:923
void renderFrame(Layout &root)
Render root (beginFrame, draw, endFrame) using this context.
bool isDragging() const noexcept
true while a drag gesture has crossed dragThreshold and is active.
Definition UIContext.hpp:952
void setTextInputRect(Rect inputRect, float cursorXOffset=0.0f)
Forward the active text-input IME rect to the platform, deduplicating unchanged rects.
Definition UIContext.hpp:974
EffectHandle getEffect(std::string_view name) const
Look up a loaded shader effect by logical name ({0} if not found).
Definition UIContext.hpp:885
void beginFrame(float delta_time)
Advance the frame: pull platform state and reset one-shot flags.
Definition UIContext.hpp:1069
EffectHandle loadEffectFromMemory(std::string_view name, std::string_view fsSource, std::string_view vsSource={})
Load a shader effect from in-memory source strings under logical name.
Definition UIContext.hpp:857
EffectHandle loadEffectAsset(std::string_view name, std::string_view baseDir, std::string_view fileStem)
Load a shader effect by stem fileStem under baseDir, automatically resolving the file extension for t...
Definition UIContext.hpp:868
bool hasFocus(const Layout *n) const
true if n is the current focused node.
Definition UIContext.hpp:1157
void popLayerTarget()
Pop an off-screen target pushed via pushLayerTarget.
Definition UIContext.hpp:1048
void pushLayerTarget(TargetHandle t, float targetScale=1.0f)
Push an off-screen target while preserving the root screen-space culling clip.
Definition UIContext.hpp:1036
Layout * mountedRoot() const
Return the primary root set by mount(), or nullptr if none.
Definition UIContext.hpp:1137
bool isPressTarget(const Layout *n) const
true if n is the current press target.
Definition UIContext.hpp:939
2D vector with component-wise arithmetic.
Definition CoreTypes.hpp:25
3D vector.
Definition CoreTypes.hpp:34
4D vector with an implicit w = 1 default.
Definition CoreTypes.hpp:40