pub struct PlayerInput { /* private fields */ }Implementations§
Source§impl PlayerInput
impl PlayerInput
Sourcepub fn format_visible_hint<'a>(
&self,
name: &str,
labels: &[VisibleTouchLabel<'_>],
buffer: &'a mut [u8],
) -> Result<&'a str, VisibleHintError>
pub fn format_visible_hint<'a>( &self, name: &str, labels: &[VisibleTouchLabel<'_>], buffer: &'a mut [u8], ) -> Result<&'a str, VisibleHintError>
Like Self::format_visible_hint_for, selecting Self::current_device.
Neither hint method samples input or consumes tick edges.
use ferravex_render::input::{ActionKind, Binding, InputCode, PlayerInput};
let mut input = PlayerInput::transient("visible-current");
input.action("jump", "Jump", ActionKind::Button,
vec![Binding::digital(InputCode::Key(32))])?;
assert_eq!(input.format_visible_hint("jump", &[], &mut [0; 16])?, "Space");Sourcepub fn format_visible_hint_for<'a>(
&self,
name: &str,
device: Option<HintDevice>,
labels: &[VisibleTouchLabel<'_>],
buffer: &'a mut [u8],
) -> Result<&'a str, VisibleHintError>
pub fn format_visible_hint_for<'a>( &self, name: &str, device: Option<HintDevice>, labels: &[VisibleTouchLabel<'_>], buffer: &'a mut [u8], ) -> Result<&'a str, VisibleHintError>
Format current bindings with labels for the touch controls actually drawn
by the caller. A supplied label must name an output of an installed slot;
stale/hidden suffix slots and duplicate (slot, code) pairs are errors.
There are at most 32 labels, each 1..=96 UTF-8 bytes without controls.
The caller establishes visibility; geometry alone cannot prove it.
Omitted touch codes remain explicit Touch N (not visible) or
Touch look N (gesture; not visible), rather than Unbound. Named stick
axes append (stick X/Y) and relative look axes (gesture X/Y).
Multiple visible slots emitting one code are listed in descriptor order.
Binding order, duplicates, scales, device filtering and zero omission
follow Self::format_hint_for. No cross-device fallback is performed.
Supply only labels drawn now: pass an empty slice when authored labels
are hidden by a custom overlay, or labels matching your resolved custom
drawing. Self::touch_customized alone does not establish visibility.
Installing new layouts, remapping, capture/import and resetting bindings
are reflected on every read. No labels or borrowed data are retained.
Formatting allocates nothing and uses two bounded passes over at most
MAX_BINDINGS * 32 entries, plus bounded descriptor validation. Unknown
actions fail first. All failures preserve the whole byte buffer; capacity
errors report exact UTF-8 bytes, and success preserves the unused tail.
This headless first-party recipe draws GAS in task 278’s resolved slot 0
region before advertising that label; it is not a browser playtest.
Hidden slot 1 emits no channel, even if an action is bound to Touch 14.
use ferravex_render::{input::{ActionKind, Binding, HintDevice, InputCode,
PlayerInput, VisibleTouchLabel, host_frame, touch::{Output, Region},
touch_layout::{TouchLayout, TouchSlot, MinimumTouchSize}},
ui::{UiRect, Viewport}, draw_rectangle, draw_text, set_default_camera,
Color, WHITE};
let layout = TouchLayout::from_viewport(
Viewport::responsive([320., 480.], [0.; 4]).unwrap(), &[
TouchSlot::rect(0, UiRect { min: [240., 400.], size: [64.; 2] },
Output::Button(6)), TouchSlot::hidden(1),
], MinimumTouchSize::Require(44.))?;
let mut input = PlayerInput::transient("visible-recipe");
input.set_touch_layout(layout.controls())?;
let drawing = layout.resolve(input.touch_settings(), [320., 480.])?;
host_frame(0., 320, 480, || {
set_default_camera();
let Region::Rect(r) = drawing.controls()[0].region else { unreachable!() };
draw_rectangle(r.x, r.y, r.w, r.h, Color::new(0.1, 0.3, 0.4, 1.));
draw_text("GAS", r.x + 8., r.y + 32., 14., WHITE);
});
input.action("gas", "Accelerate", ActionKind::Axis,
vec![Binding::digital(InputCode::Touch(6))])?;
let labels = [VisibleTouchLabel { slot: 0, code: InputCode::Touch(6), label: "GAS" }];
let mut text = [0; 128];
assert_eq!(input.format_visible_hint_for("gas", Some(HintDevice::Touch),
&labels, &mut text)?, "GAS");
input.rebind("gas", vec![Binding::digital(InputCode::Touch(14))])?;
assert_eq!(input.format_visible_hint_for("gas", Some(HintDevice::Touch),
&labels, &mut text)?, "Touch 14 (not visible)");Sourcepub fn format_hint<'a>(
&self,
name: &str,
buffer: &'a mut [u8],
) -> Result<&'a str, HintError>
pub fn format_hint<'a>( &self, name: &str, buffer: &'a mut [u8], ) -> Result<&'a str, HintError>
Format bindings for Self::current_device into caller-owned storage,
without allocating, polling the host or consuming edges/motion. There is
no cross-device fallback: a missing binding for this family is Unbound.
See Self::format_hint_for for formatting and capacity rules.
use ferravex_render::input::{ActionKind, Binding, InputCode, PlayerInput};
let mut input = PlayerInput::transient("jump-hint");
input.action("jump", "Jump", ActionKind::Button,
vec![Binding::digital(InputCode::Key(32))]).unwrap();
let mut text = [0; 128];
assert_eq!(input.format_hint("jump", &mut text).unwrap(), "Space");
input.rebind("jump", vec![Binding::digital(InputCode::Key(106))]).unwrap();
assert_eq!(input.format_hint("jump", &mut text).unwrap(), "J");Sourcepub fn format_hint_for<'a>(
&self,
name: &str,
device: Option<HintDevice>,
buffer: &'a mut [u8],
) -> Result<&'a str, HintError>
pub fn format_hint_for<'a>( &self, name: &str, device: Option<HintDevice>, buffer: &'a mut [u8], ) -> Result<&'a str, HintError>
Format the current validated bindings for one family, or all families
with None, in authored order separated by /. Zero-scale bindings
are omitted; an empty selection yields Unbound. Other scales append
x<scale> when not one, preserving negative directions/inversions.
Duplicates are retained. Deadzones are not printed. Labels are ASCII;
pad/touch numbers identify channels rather than hardware glyphs/regions.
Reads ActionMap::action_descriptor on each call, so rebind, capture,
config import and reset are reflected immediately. A persistent profile
loads on its first sample; before that, hints show registered defaults.
Hints remain inspectable while paused, unfocused or in controls. They do
not claim the action/context is enabled, the pad connected, or a touch
region installed. Use Self::gameplay_active to gate a gameplay HUD.
Work is bounded by action lookup and two passes over at most
MAX_BINDINGS entries; storage is the caller’s byte slice. The returned
string borrows only that slice. Unknown names return an input error;
insufficient capacity reports the exact required byte count without
modifying any bytes. Success leaves bytes beyond the string unchanged.
use ferravex_render::input::{ActionKind, Binding, InputCode, PlayerInput};
let mut input = PlayerInput::transient("all-hints");
input.action("jump", "Jump", ActionKind::Button, vec![
Binding::digital(InputCode::Key(32)),
Binding::digital(InputCode::PadButton(0)),
Binding::digital(InputCode::Touch(3)),
]).unwrap();
let mut text = [0; 128];
assert_eq!(input.format_hint_for("jump", None, &mut text).unwrap(),
"Space / Pad 0 / Touch 3");
let device = input.current_device();
assert_eq!(input.format_hint_for("jump", Some(device), &mut text).unwrap(), "Space");Source§impl PlayerInput
impl PlayerInput
Sourcepub fn draw_settings(&mut self)
pub fn draw_settings(&mut self)
Draw after the game’s HUD. F2, the browser Controls button or controller Home opens this editor. Tab/arrows and Enter or the D-pad/A navigate it.
Sourcepub fn draw_controls(&mut self)
pub fn draw_controls(&mut self)
Draw the controls editor and customized touch controls without the default pause banner. Use this when the game paints its own start, pause or result screen; input gating remains unchanged.
Panels narrower than 530 logical pixels show one action’s full name and
all nonzero bindings in wrapped 14px text. Long content continues on the
next numbered page; </> page through every line without ellipsis or
reduced type. Key/pad capture, Done and Reset remain available on each
page. The minimum panel is 280 by 300 logical pixels (304 by 324 including
its normal outer margins); smaller hosts may clip the panel.
use ferravex_render::input::{PlayerInput, Preset};
let mut input = PlayerInput::preset("my-game", Preset::TopDown);
input.set_paused(true);
// Paint the game's pause card, then the controls editor above it.
input.draw_controls();
assert!(input.paused());Source§impl PlayerInput
impl PlayerInput
Sourcepub fn new(owner: &str) -> PlayerInput
pub fn new(owner: &str) -> PlayerInput
Build a named profile, register actions, then sample once per render frame. Configuration is loaded lazily after registration on the first sample.
Sourcepub fn transient(owner: &str) -> PlayerInput
pub fn transient(owner: &str) -> PlayerInput
Session-only profile for tests, tools and hosts that own their storage.
pub fn action( &mut self, name: &str, label: &str, kind: ActionKind, bindings: Vec<Binding>, ) -> Result<usize, InputError>
pub fn global_action( &mut self, name: &str, label: &str, kind: ActionKind, bindings: Vec<Binding>, ) -> Result<usize, InputError>
Restrict relative mouse look to dragging a button, leaving touch/stick look independent. None is suitable for pointer-locked first-person games.
pub fn bindings(&self, name: &str) -> Option<&[Binding]>
Sourcepub fn add_default_binding(
&mut self,
name: &str,
binding: Binding,
) -> Result<(), InputError>
pub fn add_default_binding( &mut self, name: &str, binding: Binding, ) -> Result<(), InputError>
Extend an authored profile before its first sample. The binding also becomes part of Reset defaults; saved mappings load after registration.
Sourcepub fn set_default_bindings(
&mut self,
name: &str,
bindings: Vec<Binding>,
) -> Result<(), InputError>
pub fn set_default_bindings( &mut self, name: &str, bindings: Vec<Binding>, ) -> Result<(), InputError>
Replace authored defaults before the first sample (for a custom profile).
pub fn preferences(&self) -> Preferences
pub fn preferences_error(&self) -> Option<StorageError>
pub fn set_preferences(&mut self, next: Preferences) -> Result<(), StorageError>
pub fn save_preferences(&mut self) -> Result<(), StorageError>
pub fn reset_preferences(&mut self) -> Result<(), StorageError>
pub fn settings(&self) -> ControlSettings
pub fn set_settings( &mut self, settings: ControlSettings, ) -> Result<(), InputError>
pub fn status(&self) -> ControlsStatus
Sourcepub fn sample_play(&mut self)
pub fn sample_play(&mut self)
Single-player convenience: a global pause action toggles simulation.
Repeated calls in a render frame cannot replay the pause edge. Network
clients should call Self::sample directly and continue their clocks.
Sourcepub fn set_paused(&mut self, paused: bool)
pub fn set_paused(&mut self, paused: bool)
Set the single-player pause state immediately, discarding pending gameplay
edges/motion and touch gestures. Held buttons must release before firing.
Self::sample_play preserves this state; an explicit Self::sample
call still controls its own gameplay enablement (for example, networking).
pub fn paused(&self) -> bool
pub fn controls_open(&self) -> bool
pub fn gameplay_active(&self) -> bool
pub fn touch_active(&self) -> bool
pub fn touch_seen(&self) -> bool
Sourcepub fn current_device(&self) -> HintDevice
pub fn current_device(&self) -> HintDevice
Last device family observed by Self::sample, initially keyboard/mouse.
Fresh key/button presses, nonzero mouse motion/wheel and touch starts/moves
select their family, including in menus. Only the selected controller
counts, after reconnect/focus suppression has cleared. Stick activity
must cross max(0.25, pad_deadzone) or change sign above that threshold;
drift, releases and unchanged holds do not steal the hints.
A controller slot/connection epoch change or focus/overflow reset restores the last non-controller family on the next new render-frame sample. Discarded events are ignored. This is a presentation preference, not a device-availability or action-enabled query; it never consumes input.
use ferravex_render::input::PlayerInput;
let mut input = PlayerInput::transient("current-device");
let initial = input.current_device();
input.sample(false); // Menus can sample without advancing gameplay.
assert_eq!(input.current_device(), initial);pub fn simulation_dt(&self, dt: f32) -> f32
pub fn set_touch_layout(&mut self, layout: &[Control]) -> Result<(), InputError>
pub fn touch_customized(&self) -> bool
pub fn touch_settings(&self) -> TouchLayoutSettings
pub fn set_touch_settings( &mut self, next: TouchLayoutSettings, ) -> Result<(), StorageError>
pub fn touch_stick(&self, x: u8, y: u8) -> Option<(Vec2, Vec2)>
pub fn value(&self, name: &str) -> f32
pub fn held(&self, name: &str) -> bool
Sourcepub fn take(&mut self, name: &str) -> Action
pub fn take(&mut self, name: &str) -> Action
Digital edges remain pending across zero-tick render frames until taken.
pub fn pressed(&mut self, name: &str) -> bool
Sourcepub fn take_tick<const N: usize>(&mut self, names: [&str; N]) -> [Action; N]
pub fn take_tick<const N: usize>(&mut self, names: [&str; N]) -> [Action; N]
Capture the requested actions for one simulation tick without allocating. Share the returned array between systems: reading it does not consume anything further. Duplicate names receive the same snapshot, and unknown names are neutral. Only the named actions are consumed.
Call Self::sample once per render frame, then call this once inside
each fixed-tick iteration. Held values persist for catch-up ticks; pending
presses, releases and relative motion appear only in the first snapshot.
Zero-tick frames retain gameplay edges. Global actions still expire at the
next sampled render frame and should usually be handled before ticking.
Like Self::take, this does not poll the host or advance time. Multiple
taps before a tick coalesce into pressed/released flags, not a count.
use ferravex_render::input::{ActionKind, Binding, InputCode, PlayerInput};
let mut input = PlayerInput::transient("tick-example");
input.action("jump", "Jump", ActionKind::Button,
vec![Binding::digital(InputCode::Key(32))]).unwrap();
// In the render loop, sample even on frames with no simulation ticks.
input.sample(true);
let fixed_steps = 3;
for _ in 0..fixed_steps {
let [jump] = input.take_tick(["jump"]);
// Pass this same `jump` to physics, animation, and gameplay this tick.
if jump.pressed { /* start jumping */ }
}Sourcepub fn cursor(&mut self, dt: f32, speed: f32) -> Vec2
pub fn cursor(&mut self, dt: f32, speed: f32) -> Vec2
Mouse/touch position with a movement-stick cursor for pointing games. Real pointer movement takes over immediately; no synthetic mouse action is generated. Call once per render frame using logical pixels/second.
pub fn cursor_is_virtual(&self) -> bool
pub fn movement(&self) -> Vec2
Sourcepub fn look(&mut self, dt: f32) -> Vec2
pub fn look(&mut self, dt: f32) -> Vec2
Local right/down look radians. Call once per render frame before building fixed-tick commands; the simulation receives the resulting absolute aim.
pub fn rebind( &mut self, name: &str, bindings: Vec<Binding>, ) -> Result<(), InputError>
pub fn export_config(&self) -> Result<Vec<u8>, InputError>
pub fn import_config( &mut self, bytes: &[u8], ) -> Result<AppliedConfig, InputError>
pub fn save(&mut self) -> bool
pub fn load(&mut self)
pub fn reset_defaults(&mut self)
pub fn set_controls_open(&mut self, open: bool)
pub fn begin_capture( &mut self, name: &str, device: CaptureDevice, ) -> Result<(), InputError>
Sourcepub fn sample(&mut self, enabled: bool)
pub fn sample(&mut self, enabled: bool)
Sample the host event journal at most once per render frame. Repeated calls may change gameplay enablement, and observe focus/modal changes, but never replay the frame’s events. Call after the host pumps events.
false disables gameplay actions while leaving global menu actions
available. Disabling clears queued gameplay input and touch gestures;
buttons held during the pause must release before firing on resume.
Consume gameplay edges with Self::take_tick only when a tick runs.