Core Concepts
01 - Conceptos Fundamentales y Arquitectura
Este documento define el paradigma de modo retenido de X4UI, las decisiones de diseño que sustentan su árbol de componentes, el ciclo de vida determinista, la gestión de estado reactivo y los criterios de optimización mediante banderas sucias (dirty flags).
1. El Paradigma de X4UI y Qué Soluciona
En el sistema vanilla de Minecraft (GuiScreen), el código de interfaz es imperativo e inmediato: cada fotograma recalcula posiciones, dibuja primitivas crudas y mezcla la lógica de negocio con el renderizado. Esto provoca acoplamiento fuerte, fugas de estado al redimensionar la ventana y código difícil de mantener.
X4UI adopta un paradigma de modo retenido tipo DOM:
- Separación entre estructura y dibujo: Los componentes se instancian una sola vez en
initComponents()y se organizan en un árbol jerárquico (rootPanel). - Layout perezoso: Las coordenadas y dimensiones se recalculan únicamente cuando cambia la estructura o la resolución, nunca en cada fotograma por defecto.
- Vistas reactivas y pasivas (Dumb Views): Los datos residen en contenedores observables (
State<T>) o enUIStateBus; la vista se limita a suscribirse y reflejar cambios. - Limpieza automática de memoria: Al destruir un componente o cerrar la pantalla, X4UI desvincula sus suscripciones reactivas y libera animaciones asociadas.
2. Árbol Jerárquico de Componentes
Cada elemento visual hereda de GuiComponent (patrón Composite). La raíz de toda pantalla es rootPanel, un GuiPanel que cubre el área lógica de la ventana:
rootPanel (GuiPanel)
├── headerPanel (GuiPanel.row)
│ ├── GuiLabel
│ ├── spacer (GuiPanel.spacer)
│ └── GuiButton ("X")
├── contentPanel (GuiScrollPanel)
│ ├── card1 (GuiPanel.card)
│ └── card2 (GuiPanel.card)
└── footerPanel (GuiPanel.row)
└── GuiSliderInt
Operaciones sobre el Árbol
GuiPanel panel = GuiPanel.column(10, 6).withPercentWidth(1.0f);
GuiButton btn = panel.add(GuiButton.of("Aceptar", () -> {}), b -> b.withPercentWidth(0.5f));
panel.removeChild(btn); // Separa btn e invoca onDetached()
panel.clearChildren(); // Separa y destruye todos los hijos
3. Ciclo de Vida de GuiComponent
El ciclo de vida sigue seis etapas deterministas:
- Construcción: Asignación de propiedades iniciales en el constructor o mediante API fluida (
withPercentWidth,withMargin,withLayer). - Adjunción (
onAttached()): Se ejecuta al agregarse a un contenedor padre. - Actualización (
update(float deltaTime)): Se ejecuta antes de renderizar. Si existen banderas sucias de diseño (requestLayout()), resuelve dimensiones porcentuales y posicionamiento delILayoutManager, propagándolo hacia los hijos. - Renderizado (
render(IGraphics gfx, int mouseX, int mouseY, float partialTicks)):- Invoca
renderSelf(gfx, mouseX, mouseY, partialTicks). - Si existe bandera sucia de render (
requestRender()), reordena los hijos porlayer(Z-index). - Invoca
renderChildren(gfx, ...)aplicando recorte (clipping) cuando corresponde.
- Invoca
- Separación (
onDetached()): Se ejecuta al remover el componente de su padre. - Destrucción (
destroy()/onDestroy()):- Desvincula automáticamente todos los listeners enlazados mediante
bindState()omapState(). - Libera animaciones en
GuiAnimatory se propaga recursivamente a los hijos.
- Desvincula automáticamente todos los listeners enlazados mediante
4. Propagación de Eventos
Los eventos de mouse (mouseClicked, mouseReleased, mouseDragged, mouseScrolled) y teclado (keyTyped) recorren el árbol respetando visibilidad y orden de capas (layer):
- Los componentes en capas superiores (
layermayor) reciben prioridad de captura. - Cuando un componente consume el evento (retorna
true), detiene la propagación hacia capas inferiores.
5. Estado Reactivo (State<T>) y Bus de Estados (UIStateBus)
State<T>
com.x4yi.x4ui.common.State<T> es un contenedor observable seguro para hilos (volatile + serialización de notificaciones en set(T) para evitar condiciones de carrera entre hilos Netty/I/O y el hilo principal) y compatible con servidor dedicado. Deduplica notificaciones mediante Objects.equals() y aísla excepciones por listener para que un fallo en un suscriptor no interrumpa a los demás:
State<Integer> score = new State<>(0);
// Vinculación segura ligada al ciclo de vida del componente
label.bindState(score, val -> label.setText("Puntos: " + val));
score.set(10); // Actualiza la etiqueta automáticamente
UIStateBus
Permite compartir estado entre módulos o sincronizar datos desde el servidor sin acoplar referencias directas. Soporta tres alcances:
Scope.SCREEN: se limpia automáticamente al cerrar la pantalla (GuiBaseScreen.onGuiClosed()). Es el alcance utilizado porsyncedState(key, valorInicial).Scope.SESSION: persiste entre pantallas abiertas y se limpia al desconectarse del servidor.Scope.GLOBAL: persiste durante toda la ejecución del cliente.
String key = UIStateBus.scopedKey("machine:10,64,10", "energy");
State<Integer> energy = UIStateBus.getOrCreate(key, 0, UIStateBus.Scope.SCREEN);
6. Sistema de Temas (ITheme y ThemeRegistry)
La apariencia visual está desacoplada de la lógica de componentes mediante ITheme. DefaultTheme.INSTANCE provee una paleta oscura sólida y minimalista. Los componentes heredan el tema de su cadena de ancestros o utilizan ThemeRegistry.getCurrentTheme() como respaldo:
ThemeRegistry.registerTheme("custom_dark", customTheme);
rootPanel.setTheme(ThemeRegistry.getTheme("custom_dark"));
7. Optimización mediante Dirty Flags, ScreenHost y Caché de Coordenadas
requestLayout(): marca que las dimensiones o la jerarquía estructural cambiaron; el layout se recalculará una única vez en el siguienteupdate().requestRender(): solicita reordenar las capas visuales (layer).- Caché de Coordenadas Absolutas:
GuiComponentcacheaabsX/absYe invalida en cascada solo al mutarx,yoparent, evitando recorrer toda la cadena de padres en cada hit-test o dibujo. ScreenHostUnificado:GuiBaseScreenyGuiBaseContainerdelegan la lógica compartida aScreenHost— seguimiento y expiración unificada de RPCs,deltaTime, tooltips multilínea cacheados, animación opcional de apertura independiente de FPS (setAnimateOpen(boolean)) y limpieza automática enonGuiClosed().- Composición sin Casts:
GuiComponent.add(T child)yadd(T child, Consumer<T> config)(delegados también enGuiScrollPanel) retornan el tipo exacto del hijo para evitar casts manuales. - Las mutaciones puramente visuales (color, opacidad, texto cuando no altera tamaño estructural) no requieren
requestLayout().
8. Qué Evitar al Crear una GUI
| Antipatrón | Causa Técnica del Problema | Solución Correcta |
|---|---|---|
Llamar addChild() dentro de renderSelf() o render() | Crea componentes infinitos por fotograma y satura memoria/GC | Instanciar la jerarquía en initComponents() |
Llamar requestLayout() incondicionalmente cada tick | Anula la optimización perezosa y fuerza recálculo completo en cada frame | Invocar solo ante cambios reales de tamaño, visibilidad o hijos |
Suscribirse manualmente con state.addListener(...) sin limpiar | Retiene referencias fuertes al GuiComponent y provoca fugas de memoria | Usar component.bindState(state, callback) |
| Ejecutar I/O o red síncrona en callbacks de botones | Congela el hilo principal del cliente Minecraft | Delegar en MediaPipeline, CompletableFuture o UINetwork |
01 - Core Concepts & Architecture
This document defines X4UI’s retained-mode paradigm, the design decisions behind its component tree, deterministic lifecycle, reactive state management, and dirty-flag optimization model.
1. The X4UI Paradigm & What It Solves
Vanilla Minecraft’s GuiScreen relies on immediate-mode imperative code: every frame recalculates positions, emits raw OpenGL geometry, and mixes business logic with rendering. This causes tight coupling, lost UI state on window resize, and high maintenance overhead.
X4UI adopts a DOM-like retained-mode paradigm:
- Structure decoupled from rendering: Components are instantiated once in
initComponents()and arranged in a persistent tree (rootPanel). - Lazy layout resolution: Coordinates and sizes are recalculated only when structure or viewport dimensions change, never unconditionally per frame.
- Passive, reactive views (Dumb Views): Data lives in observable containers (
State<T>) orUIStateBus; views subscribe to state and reflect updates automatically. - Lifecycle-managed cleanup: Destroying a component or closing a screen automatically unbinds reactive listeners and clears associated animations.
2. Hierarchical Component Tree
Every visual element extends GuiComponent (Composite pattern). The root of every screen is rootPanel, a GuiPanel spanning the logical viewport:
rootPanel (GuiPanel)
├── headerPanel (GuiPanel.row)
│ ├── GuiLabel
│ ├── spacer (GuiPanel.spacer)
│ └── GuiButton ("X")
├── contentPanel (GuiScrollPanel)
│ ├── card1 (GuiPanel.card)
│ └── card2 (GuiPanel.card)
└── footerPanel (GuiPanel.row)
└── GuiSliderInt
Tree Operations
GuiPanel panel = GuiPanel.column(10, 6).withPercentWidth(1.0f);
GuiButton btn = panel.add(GuiButton.of("Accept", () -> {}), b -> b.withPercentWidth(0.5f));
panel.removeChild(btn); // Detaches btn and invokes onDetached()
panel.clearChildren(); // Detaches and destroys all children
3. Component Lifecycle (GuiComponent)
The lifecycle follows six deterministic stages:
- Construction: Initial properties are set via constructor or fluent API (
withPercentWidth,withMargin,withLayer). - Attachment (
onAttached()): Invoked when added to a parent container. - Update (
update(float deltaTime)): Executed before rendering. If layout dirty flags (requestLayout()) are active, resolves percentage dimensions and delegates positioning toILayoutManager, propagating down to children. - Rendering (
render(IGraphics gfx, int mouseX, int mouseY, float partialTicks)):- Calls
renderSelf(gfx, mouseX, mouseY, partialTicks). - If render dirty flag (
requestRender()) is set, sorts children bylayer(Z-index). - Calls
renderChildren(gfx, ...)with scissor clipping when enabled.
- Calls
- Detachment (
onDetached()): Invoked when removed from the parent. - Destruction (
destroy()/onDestroy()):- Automatically unbinds all listeners registered via
bindState()ormapState(). - Releases weak references in
GuiAnimatorand propagates recursively to children.
- Automatically unbinds all listeners registered via
4. Event Propagation
Mouse events (mouseClicked, mouseReleased, mouseDragged, mouseScrolled) and keyboard events (keyTyped) traverse the tree respecting visibility and layer ordering:
- Higher-layer components receive capture priority.
- Returning
trueconsumes the event and halts propagation to lower layers.
5. Reactive State (State<T>) & State Bus (UIStateBus)
State<T>
com.x4yi.x4ui.common.State<T> is a thread-safe, dedicated-server-compatible observable container (volatile storage + serialized update delivery in set(T) to prevent races between Netty/I/O threads and the main client thread). It deduplicates updates using Objects.equals() and isolates per-listener exceptions so one failing subscriber cannot block the rest:
State<Integer> score = new State<>(0);
// Lifecycle-safe binding tied to the component
label.bindState(score, val -> label.setText("Score: " + val));
score.set(10); // Updates the label automatically
UIStateBus
Enables decoupled cross-module state sharing and server-to-client data sync without direct object references. Supports three scopes:
Scope.SCREEN: automatically cleared on screen close (GuiBaseScreen.onGuiClosed()). Used bysyncedState(key, initialValue).Scope.SESSION: survives screen closes and is cleared on server disconnect.Scope.GLOBAL: persists for the entire client session.
String key = UIStateBus.scopedKey("machine:10,64,10", "energy");
State<Integer> energy = UIStateBus.getOrCreate(key, 0, UIStateBus.Scope.SCREEN);
6. Theme System (ITheme & ThemeRegistry)
Visual styling is decoupled from component logic through ITheme. DefaultTheme.INSTANCE provides a solid, minimalist dark palette. Components inherit the theme from their ancestor chain or fall back to ThemeRegistry.getCurrentTheme():
ThemeRegistry.registerTheme("custom_dark", customTheme);
rootPanel.setTheme(ThemeRegistry.getTheme("custom_dark"));
7. Dirty-Flag Optimization, ScreenHost & Absolute Coordinate Caching
requestLayout(): marks that dimensions or structural hierarchy changed; layout runs once on the nextupdate().requestRender(): requests resorting of visuallayers.- Absolute Coordinate Cache:
GuiComponentcachesabsX/absYand invalidates them in cascade only whenx,y, orparentmutates, avoiding repeated parent-chain walks during hit-testing and drawing. - Unified
ScreenHost:GuiBaseScreenandGuiBaseContainerdelegate shared lifecycle logic toScreenHost— unified RPC tracking and expiration sweeps, framedeltaTime, cached multi-line tooltips, optional FPS-independent opening zoom (setAnimateOpen(boolean)), and cleanup ononGuiClosed(). - Cast-Free Composition:
GuiComponent.add(T child)andadd(T child, Consumer<T> config)(also delegated inGuiScrollPanel) return the exact child type so fluent wiring requires no casts. - Purely visual mutations (color, alpha, or text changes that do not alter structural bounds) do not require
requestLayout().
8. What to Avoid When Building a GUI
| Anti-Pattern | Technical Root Cause | Correct Approach |
|---|---|---|
Calling addChild() inside renderSelf() or render() | Allocates unbounded components every frame and exhausts memory/GC | Instantiate hierarchy in initComponents() |
Calling requestLayout() unconditionally every tick | Defeats lazy layout and forces full tree recalculation every frame | Call only when dimensions, visibility, or children actually change |
Subscribing via state.addListener(...) without unsubscribing | Retains strong references to closed GuiComponent instances (memory leak) | Use component.bindState(state, callback) |
| Running blocking I/O or network calls in button callbacks | Freezes the Minecraft client main thread | Delegate to MediaPipeline, CompletableFuture, or UINetwork |