pub struct Ui { /* private fields */ }Expand description
Reuse one instance across frames. Errors reject a command atomically. Budgets: 1024 commands/widgets, 32 KiB UTF-8, 196608 vertices and 16 clip levels.
Implementations§
Source§impl Ui
impl Ui
Sourcepub fn compose<R>(
&mut self,
build: impl FnOnce(&mut UiComposition<'_>) -> Result<R, UiError>,
) -> Result<R, UiError>
pub fn compose<R>( &mut self, build: impl FnOnce(&mut UiComposition<'_>) -> Result<R, UiError>, ) -> Result<R, UiError>
Submit an atomic group through a restricted UiComposition.
On an ordinary submission/callback error, restore commands, text, vertex
estimates, clips, inspection copy/metadata and modal/widget registrations.
Prior focus, capture and UiInteraction are preserved: input is not
delivered within the group. Success commits all submissions and returns
the callback’s value. The first submission error wins over a later error.
Nested errors may be handled locally; see UiComposition::compose.
Rollback truncates append-only arenas and reconstructs at most 1024 widgets from retained commands. Existing duplicate-ID checking makes reconstruction at worst quadratic in that fixed widget bound. No heap scratch, arena clones or unbounded undo log are needed, including for repeated modal replacements. Each active group saves a 16-entry clip array and scalar checkpoints, with a maximum nesting depth of 16.
The drop guard also restores UI during Rust panic unwinding; it does not catch panics, handle abort/allocation failure or undo callback/formatter side effects outside this UI. Do not paint, deliver input or perform game actions indirectly from a callback. Compose before finishing/painting.
This headless result-card recipe exercises both success and a rejected oversized body. A small explicit fallback retains the same readable primary action. Start with room for that fallback; if prior groups use all budgets, even a fallback can reject and its error must be handled. Game rules/feedback run later from accepted actions, on actual ticks.
use ferravex_render::ui::{ButtonStyle, TextStyle, Ui, UiError, UiRect,
UiLabel, Viewport, PANEL, text_layout::LineLimit};
let mut ui = Ui::new(); // Reuse across frames.
ui.set_inspection_enabled(true); // Optional host diagnostics.
let viewport = Viewport::responsive([320., 240.], [0.; 4])?;
let card = UiRect { min: [12.; 2], size: [296., 216.] };
let title = UiRect { min: [24., 24.], size: [272., 28.] };
let body = UiRect { min: [24., 64.], size: [272., 90.] };
let action = UiRect { min: [24., 172.], size: [272., 44.] };
let oversized = "x".repeat(32769); // Inject a rejected result payload.
for (copy, rejected) in [("DELIVERY COMPLETE", false), (&oversized, true)] {
ui.begin(viewport);
let result = ui.compose(|card_ui| {
card_ui.modal(900)?;
card_ui.panel(card, PANEL)?;
card_ui.label(title, "RESULTS", TextStyle::default())?;
card_ui.wrapped_text(body, copy, TextStyle::default(), LineLimit::Clip(5))?;
card_ui.hud_button(901, action, "CONTINUE", true, ButtonStyle::default())
});
assert_eq!(result.is_err(), rejected);
if result.is_err() {
ui.compose(|fallback| {
fallback.modal(900)?;
fallback.panel(card, PANEL)?;
fallback.label(title, "RESULTS UNAVAILABLE", TextStyle::default())?;
fallback.hud_button(901, action, "CONTINUE", true, ButtonStyle::default())
})?;
}
ui.finish(true); // Deliver input only after choosing the full group.
let primary = ui.inspect().unwrap().find(|e| e.id == Some(901)).unwrap();
assert_eq!(primary.label, UiLabel::Full("CONTINUE"));
assert!(primary.enabled && primary.interaction_registered);
assert_eq!(primary.visible_bounds, Some(action));
ui.paint();
}pub fn new() -> Ui
Sourcepub fn reserved_bytes(&self) -> usize
pub fn reserved_bytes(&self) -> usize
Reserved CPU storage, including this value; excludes the renderer’s shared stream.
Sourcepub fn set_inspection_enabled(&mut self, enabled: bool)
pub fn set_inspection_enabled(&mut self, enabled: bool)
Opt in before begin; enabling allocates bounded supplemental storage
once. Inspection starts at the next begin, so shortened labels from an
earlier submission are never misreported as full. Disabling immediately
drops this storage. Default-off instances retain the original arenas and
submission behavior, with only one added optional pointer in Ui.
Ordinary text/button copy borrows the existing paint arena. Only shortened
label/hud_button source uses an extra 32 KiB UTF-8 arena and at most
1024 metadata entries. Overflow yields UiLabel::Unavailable, without
changing command acceptance. begin clears all inspection copy and IDs.
Sourcepub fn inspect(&self) -> Option<UiInspection<'_>>
pub fn inspect(&self) -> Option<UiInspection<'_>>
Inspect accepted submissions without consuming input or modifying paint. Rejected commands never appear. The latest modal blocker is synthesized from existing modal state; earlier buttons remain with registration false. No snapshot history or action-execution API is provided.
Runnable native/headless host recipe: compose actual UI, locate a visible action by its full label, project its clipped geometry for host diagnostics, then explicitly export into a bounded caller buffer. Hosts choose where (or whether) to publish these diagnostics; there is no global/Wasm export.
use ferravex_render::{input::host_frame, ui::{ButtonStyle, Ui,
UiLabel, UiRect, UiRole, Viewport}};
let viewport = Viewport::fit([400., 200.], [100.; 2], [0.; 4]).unwrap();
let mut ui = Ui::new();
ui.set_inspection_enabled(true); // Setup, outside the frame loop.
host_frame(0., 400, 200, || {
ui.begin(viewport);
ui.push_clip(UiRect { min: [20., 30.], size: [10., 20.] }).unwrap();
ui.hud_button(7, UiRect { min: [10., 20.], size: [80., 40.] },
"RESUME EXPEDITION", true, ButtonStyle::default()).unwrap();
ui.finish(true);
let action = ui.inspect().unwrap().find(|e| e.role == UiRole::Button
&& e.label == UiLabel::Full("RESUME EXPEDITION")).unwrap();
assert_eq!(action.id, Some(7));
let visible = action.visible_bounds.unwrap();
assert_eq!(visible, UiRect { min: [20., 30.], size: [10., 20.] });
assert!(visible.contains([25., 40.])); // Same half-open hit geometry.
let pixel = std::array::from_fn::<_, 2, _>(|i|
viewport.pixels().min[i] + [25., 40.][i] * viewport.scale());
assert_eq!(pixel, [150., 80.]);
ui.paint(); // Inspection leaves the normal paint path intact.
let mut diagnostic = [0_u8; 2048];
let written = ui.write_inspection(&mut diagnostic).unwrap();
let json = std::str::from_utf8(&diagnostic[..written]).unwrap();
assert!(json.contains("RESUME EXPEDITION"));
assert!(json.contains("\"visible_bounds\":[20,30,10,20]"));
});Sourcepub fn write_inspection(
&self,
output: &mut [u8],
) -> Result<usize, UiInspectionExportError>
pub fn write_inspection( &self, output: &mut [u8], ) -> Result<usize, UiInspectionExportError>
Write diagnostic JSON schema 1 (UTF-8, no terminator) to caller storage.
Its elements follow inspect; IDs are decimal strings (lossless u64
in JavaScript), rectangles are [x,y,width,height] in
logical units. Unavailable labels are null with label_required_bytes.
This is a diagnostic format, not scene/save/replay or an action protocol.
Two bounded passes determine required bytes before writing: insufficient
output returns its exact requirement and leaves the entire buffer intact.
The tail after the returned byte count is unchanged. Disabled inspection
returns Disabled, rather than misleadingly exporting an empty scene.
pub fn begin(&mut self, viewport: Viewport)
Sourcepub fn modal(&mut self, blocker: u64) -> Result<(), UiError>
pub fn modal(&mut self, blocker: u64) -> Result<(), UiError>
Discard lower widgets from interaction while preserving their paint order. Queue a full-screen panel after this call and before modal buttons.
Sourcepub fn set_auto_focus(&mut self, enabled: bool)
pub fn set_auto_focus(&mut self, enabled: bool)
Menus may accept the first button immediately; gameplay overlays can require explicit navigation/pointer focus so a shared gamepad action keeps its role.
pub fn focused(&self) -> Option<u64>
Sourcepub fn hovered(&self) -> Option<u64>
pub fn hovered(&self) -> Option<u64>
Enabled widget under the pointer as of the last finished frame (the
same hover that Self::paint highlights). Used by ui::kit visuals.
Sourcepub fn viewport(&self) -> Viewport
pub fn viewport(&self) -> Viewport
Viewport passed to the most recent Self::begin.
pub fn activated(&self, id: u64) -> bool
Sourcepub fn interaction(&self) -> UiInteraction
pub fn interaction(&self) -> UiInteraction
Inspect after finishing UI, before translating this frame’s scene input.
Repeated reads/finishes in one host frame retain the aggregate, including
across begin; the next host frame’s finish resets transient fields.
No allocations or input consumption occur here. See UiInteraction
for routing policy and the runnable tick-queue recipe below.
This headless recipe uses injected primary touches in logical pixels.
Its one-slot queue rejects new requests while full (no overwrite). A real
host passes its fresh pointer press/position at the same point; mouse
polling can use is_mouse_button_pressed(MouseButton::Left). Do not read
a tick-buffered fire action here. Buy/drop are requests: rules and feedback
run only when the actual tick accepts them. Reset the queue on restart.
use ferravex_core::session::GameSession;
use ferravex_render::{Vec2, input::{ActionKind, Binding, InputCode,
PlayerInput, host_frame, touch, touch_event},
ui::{ButtonStyle, Ui, UiRect, Viewport}};
#[derive(Clone, Copy, Debug, PartialEq)]
enum Command { Buy, Drop([f32; 2]) }
let mut ui = Ui::new();
let mut player = PlayerInput::transient("ui-world-recipe");
player.action("jump", "Jump", ActionKind::Button,
vec![Binding::digital(InputCode::Key(32))]).unwrap();
let viewport = Viewport::responsive([320., 240.], [0.; 4]).unwrap();
let mut session = GameSession::try_new(64., 4, true).unwrap();
let mut pending = None; // Bounded one-slot command queue.
let mut executed = Vec::new(); // Test observation, not the command queue.
for (id, position, elapsed) in [
(1, [30., 30.], 0.), // Buy: zero ticks; no scene drop.
(2, [180., 160.], 0.), // Queue full: this request is rejected.
(3, [180., 160.], 1. / 64.), // First actual tick executes Buy.
(4, [180., 160.], 1. / 64.), // World drop executes once.
] {
for phase in [touch::Phase::Start, touch::Phase::End] {
touch_event(touch::Event { id, phase,
position: Vec2::from(position) });
}
host_frame(elapsed as f32, 320, 240, || {
player.sample(true); // Sample globals/gameplay without ticking.
ui.begin(viewport);
ui.button(10, UiRect { min: [20.; 2], size: [100., 44.] },
"BUY", true, ButtonStyle::default()).unwrap();
ui.finish_player(&mut player, true);
let ownership = ui.interaction();
let request = if ui.activated(10) { Some(Command::Buy) }
else if !ownership.input_blocked && !ownership.pointer_consumed {
Some(Command::Drop(position)) // This host's fresh press.
} else { None };
if pending.is_none() { pending = request; } // Explicit full policy.
let frame = session.advance(elapsed);
for _ in frame.ticks() { // Only actually executed updates consume.
let [_jump] = player.take_tick(["jump"]);
if let Some(command) = pending.take() { executed.push(command); }
}
ui.paint();
});
}
assert_eq!(executed, [Command::Buy, Command::Drop([180., 160.])]);
assert_eq!(pending, None);Sourcepub fn cancel(&mut self)
pub fn cancel(&mut self)
Cancel activation but retain an owned gesture’s tail until release, so closing/removing UI cannot turn that release into a scene action. Focus loss/overflow reset ownership because the journal can no longer prove it.
pub fn push_clip(&mut self, rect: Rect) -> Result<(), UiError>
pub fn pop_clip(&mut self)
pub fn panel(&mut self, rect: Rect, color: Color) -> Result<(), UiError>
Sourcepub fn gradient(
&mut self,
rect: Rect,
left: Color,
right: Color,
) -> Result<(), UiError>
pub fn gradient( &mut self, rect: Rect, left: Color, right: Color, ) -> Result<(), UiError>
Horizontal color/alpha gradient; clipping preserves the original interpolation.
Sourcepub fn text_fmt(
&mut self,
rect: Rect,
style: TextStyle,
args: Arguments<'_>,
) -> Result<(), UiError>
pub fn text_fmt( &mut self, rect: Rect, style: TextStyle, args: Arguments<'_>, ) -> Result<(), UiError>
Format directly into the persistent UTF-8 arena; no temporary String.
pub fn text( &mut self, rect: Rect, text: &str, style: TextStyle, ) -> Result<(), UiError>
Sourcepub fn wrapped_text(
&mut self,
rect: Rect,
text: &str,
style: TextStyle,
limit: LineLimit,
) -> Result<TextBlockMetrics, UiError>
pub fn wrapped_text( &mut self, rect: Rect, text: &str, style: TextStyle, limit: LineLimit, ) -> Result<TextBlockMetrics, UiError>
Queue measured word-wrapped copy at fixed style.size, with an explicit
line limit. style.wrap is ignored; color, alignment and shadow are kept.
The returned metrics match WrappedText::measure before geometric
clipping: rect and the current clip can still cut a partial last line.
Use the measured height for a content-sized block, or a line limit of
floor(rect.size[1] / style.size) to keep complete line slots in a card.
The full source is copied into the existing 32 KiB arena, even when lines
are hidden. Only retained glyphs (including the suffix) reserve vertices.
Invalid styles/rectangles or exhausted budgets reject the whole command;
an empty/zero-line block still uses one command, like Self::text.
use ferravex_render::ui::{TextStyle, Ui, UiRect, Viewport};
use ferravex_render::ui::text_layout::LineLimit;
let mut ui = Ui::new();
ui.begin(Viewport::responsive([320., 240.], [0.; 4])?);
let report = ui.wrapped_text(
UiRect { min: [16., 24.], size: [288., 36.] },
"BRIEFING\nCollect the keys.\nReturn to the gate.",
TextStyle::default(), LineLimit::Ellipsis(2),
)?;
assert_eq!((report.visible_lines, report.hidden_lines), (2, 1));
assert!(report.is_truncated());
ui.paint();Sourcepub fn label(
&mut self,
rect: Rect,
text: &str,
style: TextStyle,
) -> Result<(), UiError>
pub fn label( &mut self, rect: Rect, text: &str, style: TextStyle, ) -> Result<(), UiError>
A single-line HUD label that keeps style.size and ellipsizes overflow.
Alignment and shadow are honored; wrap is ignored. Newlines truncate.
The visible prefix is copied directly into the reusable text arena, so
even a very long source label consumes only its visible text budget.
Use Viewport::responsive to keep this size in host logical pixels.
use ferravex_render::ui::{Anchor, TextStyle, Ui, Viewport};
let mut ui = Ui::new(); // Keep this outside the frame loop.
let viewport = Viewport::responsive([320., 240.], [0., 20., 0., 0.])?;
ui.begin(viewport);
let score = Anchor::TopRight.place(viewport.bounds().inset([12.; 4])?, [180., 24.])?;
ui.label(score, "COLLECT THE REMAINING CRYSTALS", TextStyle::default())?;A button with an ellipsized, fixed-size label and the same clipped
hit/focus rectangle as Self::button. Eight logical pixels on each side
are reserved for padding; on tiny rectangles text clips to the button.
The full label is retained only when inspection is opted in and its
separate bounded arena has room; otherwise hosts keep accessibility copy.
use ferravex_render::ui::{ButtonStyle, Ui, Viewport, hud_slots};
let mut ui = Ui::new(); // Reuse between frames.
let viewport = Viewport::responsive([320., 240.], [0.; 4])?;
ui.begin(viewport);
let labels = ["RESUME EXPEDITION", "RESTART FROM CHECKPOINT", "QUIT"];
// Two 144px columns; the third action wraps, retaining a 44px row height.
for (index, rect) in hud_slots(viewport.bounds().inset([12.; 4])?, 3, 140., 44., 8.)?.enumerate() {
ui.hud_button(index as u64, rect, labels[index], true, ButtonStyle::default())?;
}Sourcepub fn finish_player(&mut self, player: &mut PlayerInput, enabled: bool)
pub fn finish_player(&mut self, player: &mut PlayerInput, enabled: bool)
Finish layout before input. Block while the host’s settings editor is open. Keyboard Tab/arrows/Enter, gamepad D-pad/A and one captured touch are supported. Include a player’s remapped global confirm action and selected gamepad.
pub fn finish(&mut self, enabled: bool)
Sourcepub fn finish_with_gamepad(&mut self, enabled: bool, pad: u8)
pub fn finish_with_gamepad(&mut self, enabled: bool, pad: u8)
Use the player profile’s selected pad (0..4).
Source§impl Ui
impl Ui
Sourcepub fn card(
&mut self,
layout: &CardLayout<'_>,
scroll: Option<&ScrollState>,
) -> Result<CardReport, UiError>
pub fn card( &mut self, layout: &CardLayout<'_>, scroll: Option<&ScrollState>, ) -> Result<CardReport, UiError>
Standalone atomic card submission. See the module’s executed recipe;
use CardLayout::submit inside a larger atomic composition.
Source§impl Ui
impl Ui
Sourcepub fn stat_rows(
&mut self,
bounds: Rect,
rows: &[StatRow<'_>],
style: StatRowsStyle,
) -> Result<StatRowsReport, UiError>
pub fn stat_rows( &mut self, bounds: Rect, rows: &[StatRow<'_>], style: StatRowsStyle, ) -> Result<StatRowsReport, UiError>
Measure and atomically submit a stat list. See StatRowsLayout for
measurement, overflow policy and the executable result-summary recipe.
use ferravex_render::ui::{Ui, UiError, UiRect, Viewport};
use ferravex_render::ui::stats::{StatRow, StatRowsStyle};
let mut ui = Ui::new();
ui.begin(Viewport::responsive([320., 240.], [0.; 4])?);
let rows = [StatRow { label: "TIME", value: "1:00.001", description: None }];
let bounds = UiRect { min: [16.; 2], size: [288., 18.] };
assert_eq!(ui.stat_rows(bounds, &rows, StatRowsStyle::default())?.hidden_rows, 0);
// The restricted facade provides the same helper inside a result card.
ui.compose(|card| card.stat_rows(bounds, &rows, StatRowsStyle::default()))?;Source§impl Ui
impl Ui
Queue a button with consistent selected/disabled visuals using the
existing Self::button interaction and storage budgets.
Enabled/unselected uses style unchanged. Selected uses style.focus
as fill and style.fill as text and focus-border color, keeping focus
distinguishable from selection. Disabled uses style.disabled as fill
and blends text RGB halfway toward that fill, preserving text alpha.
Custom palettes should keep fill and focus colors contrasting.
All original style fields are validated, including inactive colors.
Rebuild with options each frame; no extra commands or widgets are added.
use ferravex_render::ui::{ButtonOptions, ButtonStyle, Ui, UiRect, Viewport};
let mut ui = Ui::new();
ui.begin(Viewport::responsive([320., 240.], [0.; 4])?);
ui.button_with_options(
1, UiRect { min: [20.; 2], size: [120., 40.] }, "EASY",
ButtonOptions { selected: true, ..Default::default() },
ButtonStyle::default(),
)?;
ui.finish(true); // Process input after all widgets have been queued.
let chose_easy = ui.activated(1);
ui.paint();Ellipsized, fixed-size-label counterpart of Self::button_with_options.
Uses Self::hud_button’s padding, clipping and bounded text arena.
use ferravex_render::ui::{ButtonOptions, ButtonStyle, Ui, UiRect, Viewport};
let mut ui = Ui::new();
ui.begin(Viewport::responsive([320., 240.], [0.; 4])?);
ui.hud_button_with_options(
1, UiRect { min: [20.; 2], size: [120., 40.] }, "CONTINUE EXPEDITION",
ButtonOptions { enabled: false, selected: false }, ButtonStyle::default(),
)?;
ui.finish(true);
assert!(!ui.activated(1));
ui.paint();