Merge main into screen-cursor-centre

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Ludovic Marie
2026-10-27 22:33:03 +01:00
371 changed files with 20449 additions and 2758 deletions
@@ -0,0 +1,464 @@
//! The system clipboard and the text-editing shortcuts of 26.3:
//! `KeyboardHandler.getClipboard`/`setClipboard`, `InputWithModifiers.isSelectAll`,
//! `isCopy`, `isPaste` and `isCut`, `StringUtil.filterText` and
//! `ChatFormatting.stripFormatting`.
use winit::keyboard::{Key, KeyCode, PhysicalKey};
/// A text-editing shortcut (`InputWithModifiers.isSelectAll`, `isCopy`,
/// `isPaste`, `isCut`).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum EditShortcut {
SelectAll,
Copy,
Paste,
Cut,
}
/// The letter a key stands for in shortcuts (`KeyEvent.shortcutKey`, SDL's
/// keycode): the layout's letter, or the key's US-layout letter when the
/// layout's is not a Latin one (SDL's default `latin_letters` keycode option).
pub fn shortcut_letter(logical: &Key, physical: PhysicalKey) -> Option<char> {
if let Key::Character(s) = logical {
let mut chars = s.chars();
if let (Some(c), None) = (chars.next(), chars.next())
&& c.is_ascii_alphabetic()
{
return Some(c.to_ascii_lowercase());
}
}
let PhysicalKey::Code(code) = physical else {
return None;
};
Some(match code {
KeyCode::KeyA => 'a',
KeyCode::KeyC => 'c',
KeyCode::KeyV => 'v',
KeyCode::KeyX => 'x',
_ => return None,
})
}
/// `InputWithModifiers.isSelectAll`/`isCopy`/`isPaste`/`isCut`: A, C, V or X
/// with the edit modifier (`InputQuirks.EDIT_SHORTCUT_KEY_MODIFIER`: Cmd on
/// macOS, Ctrl elsewhere) and neither Shift nor Alt.
pub fn edit_shortcut(
letter: Option<char>,
edit_modifier: bool,
shift: bool,
alt: bool,
) -> Option<EditShortcut> {
if !edit_modifier || shift || alt {
return None;
}
Some(match letter? {
'a' => EditShortcut::SelectAll,
'c' => EditShortcut::Copy,
'v' => EditShortcut::Paste,
'x' => EditShortcut::Cut,
_ => return None,
})
}
/// `StringUtil.isAllowedChatCharacter`.
pub fn is_allowed_chat_character(c: char) -> bool {
c != '§' && c >= ' ' && c != '\u{7f}'
}
/// `StringUtil.filterText`: the allowed characters, and line breaks where
/// the field takes several lines.
pub fn filter_text(input: &str, multiline: bool) -> String {
input
.chars()
.filter(|&c| is_allowed_chat_character(c) || (multiline && c == '\n'))
.collect()
}
/// `ChatFormatting.stripFormatting`: `§` followed by a format code removed.
pub fn strip_formatting(input: &str) -> String {
let mut out = String::with_capacity(input.len());
let mut chars = input.chars().peekable();
while let Some(c) = chars.next() {
if c == '§'
&& chars.peek().is_some_and(
|n| matches!(n.to_ascii_lowercase(), '0'..='9' | 'a'..='f' | 'k'..='o' | 'r'),
)
{
chars.next();
continue;
}
out.push(c);
}
out
}
/// `TextFieldHelper.getClipboardContents`: formatting and carriage returns
/// removed (signs).
pub fn helper_clipboard_contents(clipboard: &str) -> String {
strip_formatting(&clipboard.replace('\r', ""))
}
/// A clipboard: the system's, or an in-memory one in tests.
pub trait Clipboard {
/// `KeyboardHandler.getClipboard`: empty when there is no text.
fn get(&mut self) -> String;
/// `KeyboardHandler.setClipboard`: empty text is not copied.
fn set(&mut self, text: &str);
}
/// The system clipboard (`ClipboardManager`). On Wayland, arboard uses the
/// data-control protocol and falls back to X11 (XWayland) on compositors
/// without it. When no system clipboard can be reached, text copied in the
/// game can still be pasted in the game.
#[derive(Default)]
pub struct SystemClipboard {
system: Option<arboard::Clipboard>,
/// The text Horizon last copied (`horizon-ctl status`).
copied: Option<String>,
}
impl SystemClipboard {
/// The text last copied by the game.
pub fn copied(&self) -> Option<&str> {
self.copied.as_deref()
}
fn system(&mut self) -> Option<&mut arboard::Clipboard> {
if self.system.is_none() {
self.system = arboard::Clipboard::new().ok();
}
self.system.as_mut()
}
}
impl Clipboard for SystemClipboard {
fn get(&mut self) -> String {
let Some(system) = self.system() else {
return self.copied.clone().unwrap_or_default();
};
match system.get_text() {
Ok(text) => text,
Err(arboard::Error::ContentNotAvailable) => String::new(),
Err(_) => {
// A lost connection (a restarted compositor): reconnect next time.
self.system = None;
String::new()
}
}
}
fn set(&mut self, text: &str) {
if text.is_empty() {
return;
}
self.copied = Some(text.to_owned());
if let Some(system) = self.system()
&& system.set_text(text.to_owned()).is_err()
{
self.system = None;
}
}
}
/// A clipboard in memory.
#[derive(Default, Debug)]
pub struct MemoryClipboard(pub String);
impl Clipboard for MemoryClipboard {
fn get(&mut self) -> String {
self.0.clone()
}
fn set(&mut self, text: &str) {
if !text.is_empty() {
self.0 = text.to_owned();
}
}
}
/// A text field with a cursor and a selection (`EditBox`).
pub trait Editable {
/// Select All: the cursor at the end, the selection from the start.
fn select_all(&mut self);
/// `getHighlighted`.
fn selected_text(&self) -> String;
/// `insertText`, with the field's own filter and length limit. True when
/// the value changed.
fn insert(&mut self, text: &str) -> bool;
}
/// `EditBox.keyPressed`'s shortcuts. True when the value changed.
pub fn apply(
field: &mut dyn Editable,
shortcut: EditShortcut,
clipboard: &mut dyn Clipboard,
) -> bool {
match shortcut {
EditShortcut::SelectAll => {
field.select_all();
false
}
EditShortcut::Copy => {
clipboard.set(&field.selected_text());
false
}
EditShortcut::Paste => field.insert(&clipboard.get()),
EditShortcut::Cut => {
clipboard.set(&field.selected_text());
field.insert("")
}
}
}
/// Which append-only field a Select All covers: a name and an index (a
/// sign line, a book page).
pub type FieldId = (&'static str, usize);
/// The selection of Horizon's append-only fields, whose cursor stays at the
/// end: Select All selects the whole value, which the next copy, cut, paste,
/// typed text or backspace replaces. It is forgotten as soon as the field or
/// its value changes.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct AppendSelection(Option<(FieldId, String)>);
impl AppendSelection {
/// Whether `value` of field `id` is wholly selected.
pub fn covers(&self, id: FieldId, value: &str) -> bool {
self.0.as_ref().is_some_and(|(i, v)| *i == id && v == value)
}
/// Select the whole `value` of field `id`, as Select All does.
pub fn select(&mut self, id: FieldId, value: &str) {
self.0 = Some((id, value.to_owned()));
}
/// Before typing or a backspace: an all-selected value is cleared (true).
pub fn take(&mut self, id: FieldId, value: &mut String) -> bool {
let covered = self.covers(id, value);
self.0 = None;
if covered {
value.clear();
}
covered
}
/// A shortcut in an append-only field. `insert` adds pasted text to a
/// value the field's own way and says whether it accepted it (a field
/// that rejects it keeps its value, as `TextFieldHelper.insertText`).
/// True when the value changed.
pub fn apply(
&mut self,
id: FieldId,
value: &mut String,
shortcut: EditShortcut,
clipboard: &mut dyn Clipboard,
insert: impl FnOnce(&mut String, &str) -> bool,
) -> bool {
let covered = self.covers(id, value);
match shortcut {
EditShortcut::SelectAll => {
self.select(id, value);
false
}
EditShortcut::Copy => {
if covered {
clipboard.set(value);
}
false
}
EditShortcut::Cut => {
self.0 = None;
if !covered {
return false;
}
clipboard.set(value);
let changed = !value.is_empty();
value.clear();
changed
}
EditShortcut::Paste => {
self.0 = None;
let text = clipboard.get();
let mut next = if covered {
String::new()
} else {
value.clone()
};
if !insert(&mut next, &text) || next == *value {
return false;
}
*value = next;
true
}
}
}
}
/// `EditBox.insertText` for a field without a cursor: the filtered text,
/// cut to the room left by `max_chars`.
pub fn append_limited(value: &mut String, text: &str, max_chars: usize) -> bool {
let room = max_chars.saturating_sub(value.chars().count());
if room == 0 {
return false;
}
value.extend(filter_text(text, false).chars().take(room));
true
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn shortcuts_need_the_edit_modifier_alone() {
let c = Some('c');
assert_eq!(
edit_shortcut(c, true, false, false),
Some(EditShortcut::Copy)
);
assert_eq!(
edit_shortcut(Some('v'), true, false, false),
Some(EditShortcut::Paste)
);
assert_eq!(
edit_shortcut(Some('x'), true, false, false),
Some(EditShortcut::Cut)
);
assert_eq!(
edit_shortcut(Some('a'), true, false, false),
Some(EditShortcut::SelectAll)
);
assert_eq!(edit_shortcut(c, false, false, false), None);
assert_eq!(edit_shortcut(c, true, true, false), None);
assert_eq!(edit_shortcut(c, true, false, true), None);
assert_eq!(edit_shortcut(Some('b'), true, false, false), None);
}
#[test]
fn the_layout_letter_decides_and_non_latin_layouts_use_the_position() {
let q = PhysicalKey::Code(KeyCode::KeyQ);
// AZERTY: the key at Q's position types an A.
assert_eq!(shortcut_letter(&Key::Character("a".into()), q), Some('a'));
// Russian: the key at C's position types с.
let c = PhysicalKey::Code(KeyCode::KeyC);
assert_eq!(shortcut_letter(&Key::Character("с".into()), c), Some('c'));
assert_eq!(shortcut_letter(&Key::Character("C".into()), q), Some('c'));
}
#[test]
fn filter_text_keeps_line_breaks_only_for_multiline_fields() {
let s = "a\u{7}b§c\nd\re\u{80}";
assert_eq!(filter_text(s, false), "abcde\u{80}");
assert_eq!(filter_text(s, true), "abc\nde\u{80}");
assert_eq!(strip_formatting("§aRed§r §zx§"), "Red §zx§");
assert_eq!(helper_clipboard_contents("§lone\r\ntwo"), "one\ntwo");
// TextFieldHelper.getClipboardContents runs before insertText's filter.
assert_eq!(
filter_text(&helper_clipboard_contents("§aHello"), false),
"Hello"
);
}
struct Field {
value: String,
cursor: usize,
highlight: usize,
}
impl Editable for Field {
fn select_all(&mut self) {
self.cursor = self.value.len();
self.highlight = 0;
}
fn selected_text(&self) -> String {
let (a, b) = (
self.cursor.min(self.highlight),
self.cursor.max(self.highlight),
);
self.value[a..b].to_owned()
}
fn insert(&mut self, text: &str) -> bool {
let (a, b) = (
self.cursor.min(self.highlight),
self.cursor.max(self.highlight),
);
self.value.replace_range(a..b, text);
self.cursor = a + text.len();
self.highlight = self.cursor;
true
}
}
#[test]
fn edit_box_shortcuts() {
let mut clip = MemoryClipboard("old".into());
let mut f = Field {
value: "hello".into(),
cursor: 5,
highlight: 5,
};
// Nothing selected: copying leaves the clipboard alone (setClipboard skips "").
apply(&mut f, EditShortcut::Copy, &mut clip);
assert_eq!(clip.0, "old");
apply(&mut f, EditShortcut::SelectAll, &mut clip);
apply(&mut f, EditShortcut::Copy, &mut clip);
assert_eq!(clip.0, "hello");
assert!(apply(&mut f, EditShortcut::Cut, &mut clip));
assert_eq!(f.value, "");
assert!(apply(&mut f, EditShortcut::Paste, &mut clip));
assert!(apply(&mut f, EditShortcut::Paste, &mut clip));
assert_eq!(f.value, "hellohello");
}
#[test]
fn append_only_fields_select_everything_or_nothing() {
let id = ("search", 0);
let mut clip = MemoryClipboard("stone".into());
let mut sel = AppendSelection::default();
let mut value = String::from("dirt");
let insert = |v: &mut String, t: &str| append_limited(v, t, 6);
// Without Select All, copy and cut do nothing and paste appends.
sel.apply(id, &mut value, EditShortcut::Copy, &mut clip, insert);
assert_eq!(clip.0, "stone");
assert!(!sel.apply(id, &mut value, EditShortcut::Cut, &mut clip, insert));
assert!(sel.apply(id, &mut value, EditShortcut::Paste, &mut clip, insert));
assert_eq!(value, "dirtst");
// Select All then paste replaces the value.
sel.apply(id, &mut value, EditShortcut::SelectAll, &mut clip, insert);
assert!(sel.apply(id, &mut value, EditShortcut::Paste, &mut clip, insert));
assert_eq!(value, "stone");
// Select All then cut empties it and copies it.
sel.apply(id, &mut value, EditShortcut::SelectAll, &mut clip, insert);
clip.0 = "x".into();
assert!(sel.apply(id, &mut value, EditShortcut::Cut, &mut clip, insert));
assert_eq!((value.as_str(), clip.0.as_str()), ("", "stone"));
// A selection is forgotten once the value changes or another field is used.
value = "ab".into();
sel.apply(id, &mut value, EditShortcut::SelectAll, &mut clip, insert);
assert!(!sel.covers(("other", 0), &value));
value.push('c');
assert!(!sel.take(id, &mut value));
assert_eq!(value, "abc");
sel.apply(id, &mut value, EditShortcut::SelectAll, &mut clip, insert);
assert!(sel.take(id, &mut value));
assert_eq!(value, "");
}
#[test]
fn a_rejected_paste_keeps_the_selected_value() {
// TextFieldHelper.insertText: a line too wide is not set at all.
let id = ("sign", 1);
let mut clip = MemoryClipboard("far too long".into());
let mut sel = AppendSelection::default();
let mut value = String::from("ok");
sel.apply(
id,
&mut value,
EditShortcut::SelectAll,
&mut clip,
|_, _| true,
);
let fits = |v: &mut String, t: &str| {
let next = format!("{v}{t}");
next.len() <= 5 && {
*v = next;
true
}
};
assert!(!sel.apply(id, &mut value, EditShortcut::Paste, &mut clip, fits));
assert_eq!(value, "ok");
}
}
File diff suppressed because it is too large Load Diff
+67
View File
@@ -0,0 +1,67 @@
//! KeyboardInput direction and LocalPlayer input-speed arithmetic for 26.3.
//! Item-use and sneak multipliers come from the player's current state; this
//! module does not implement sprint eligibility, poses or the input lifecycle.
fn length(v: [f32; 2]) -> f32 {
f64::from(v[0] * v[0] + v[1] * v[1]).sqrt() as f32
}
fn scale(v: [f32; 2], factor: f32) -> [f32; 2] {
[v[0] * factor, v[1] * factor]
}
pub fn keyboard_direction(forward: bool, backward: bool, left: bool, right: bool) -> [f32; 2] {
let impulse = |positive: bool, negative: bool| {
if positive == negative {
0.0
} else if positive {
1.0
} else {
-1.0
}
};
let v = [impulse(left, right), impulse(forward, backward)];
let magnitude = length(v);
if magnitude < 1.0e-4 {
[0.0, 0.0]
} else {
[v[0] / magnitude, v[1] / magnitude]
}
}
/// LocalPlayer.modifyInput with already selected multipliers. `item_use` is
/// Some only when using an item and not riding; `sneaking` only when moving
/// slowly. Zero input returns before either multiplier is applied.
pub fn modify_input(input: [f32; 2], item_use: Option<f32>, sneaking: Option<f32>) -> [f32; 2] {
if input[0] * input[0] + input[1] * input[1] == 0.0 {
return input;
}
let mut v = scale(input, 0.98);
if let Some(multiplier) = item_use {
v = scale(v, multiplier);
}
if let Some(multiplier) = sneaking {
v = scale(v, multiplier);
}
square_movement(v)
}
fn square_movement(v: [f32; 2]) -> [f32; 2] {
let magnitude = length(v);
if magnitude <= 0.0 {
return v;
}
let unit = scale(v, 1.0 / magnitude);
let x = unit[0].abs();
let y = unit[1].abs();
let ratio = if y > x { x / y } else { y / x };
let distance = f64::from(1.0 + ratio * ratio).sqrt() as f32;
let speed = magnitude * distance;
// Java Math.min propagates NaN, unlike Rust's f32::min.
scale(
unit,
if speed.is_nan() || speed < 1.0 {
speed
} else {
1.0
},
)
}
@@ -0,0 +1,186 @@
//! The mouse-key portion of Minecraft.handleKeybinds. Events only count clicks;
//! the client tick consumes them before player movement and CLIENT_TICK_END.
#[derive(Default)]
pub struct InteractionInput {
clicks: [u32; 3],
}
#[derive(Clone, Copy)]
pub enum Button {
Attack,
Use,
Pick,
}
pub trait InteractionWorld {
fn using_item(&self) -> bool;
fn release_using(&mut self);
fn start_attack(&mut self) -> bool;
fn start_use(&mut self);
fn pick(&mut self);
fn use_delay(&self) -> u32;
fn continue_attack(&mut self, down: bool);
}
/// Minecraft.startUseItem dispatches one hit result per hand. A passing
/// entity interaction falls back to the item, without trying a block behind it.
pub trait TargetUseWorld {
fn use_entity(&mut self) -> bool;
fn use_block(&mut self) -> bool;
fn use_item(&mut self);
}
pub fn use_on_target(world: &mut impl TargetUseWorld, entity: bool) {
let consumed = if entity {
world.use_entity()
} else {
world.use_block()
};
if !consumed {
world.use_item();
}
}
impl InteractionInput {
pub fn press(&mut self, button: Button) {
self.clicks[button as usize] += 1;
}
pub fn tick(&mut self, world: &mut impl InteractionWorld, attack_down: bool, use_down: bool) {
let [attack, use_item, pick] = std::mem::take(&mut self.clicks);
let mut instant = false;
if world.using_item() {
if !use_down {
world.release_using();
}
// Vanilla drains all three click queues while using an item,
// including the tick that releases it.
} else {
for _ in 0..attack {
instant |= world.start_attack();
}
for _ in 0..use_item {
world.start_use();
}
for _ in 0..pick {
world.pick();
}
}
if use_down && world.use_delay() == 0 && !world.using_item() {
world.start_use();
}
world.continue_attack(!instant && attack_down);
}
}
#[cfg(test)]
mod tests {
use super::*;
#[derive(Default)]
struct World {
using: bool,
destroying: bool,
delay: u32,
begin_using: bool,
events: Vec<&'static str>,
}
impl InteractionWorld for World {
fn using_item(&self) -> bool {
self.using
}
fn release_using(&mut self) {
self.events.push("release");
self.using = false;
}
fn start_attack(&mut self) -> bool {
self.events.push("attack");
false
}
fn start_use(&mut self) {
if !self.destroying {
self.events.push("use");
self.delay = 4;
self.using = self.begin_using;
}
}
fn pick(&mut self) {
self.events.push("pick");
}
fn use_delay(&self) -> u32 {
self.delay
}
fn continue_attack(&mut self, _: bool) {
self.events.push("continue");
}
}
#[test]
fn quick_clicks_wait_for_a_tick_and_follow_keybind_order() {
let mut input = InteractionInput::default();
let mut world = World::default();
input.press(Button::Use);
input.press(Button::Pick);
input.press(Button::Attack);
assert!(world.events.is_empty());
// Both edges can arrive between ticks; the press still acts once.
input.tick(&mut world, false, false);
assert_eq!(world.events, ["attack", "use", "pick", "continue"]);
world.events.clear();
input.tick(&mut world, false, false);
assert_eq!(
world.events,
["continue"],
"no spurious release or repeated click"
);
}
#[test]
fn releasing_actual_item_use_discards_clicks_for_that_tick() {
let mut input = InteractionInput::default();
let mut world = World {
using: true,
..Default::default()
};
for button in [Button::Attack, Button::Use, Button::Pick] {
input.press(button);
}
input.tick(&mut world, true, false);
assert_eq!(world.events, ["release", "continue"]);
}
#[test]
fn holding_use_respects_the_delay_and_active_digging() {
let mut input = InteractionInput::default();
let mut world = World {
destroying: true,
..Default::default()
};
input.press(Button::Use);
input.tick(&mut world, true, true);
assert_eq!(world.events, ["continue"]);
world.destroying = false;
world.events.clear();
input.tick(&mut world, false, true);
assert_eq!(world.events, ["use", "continue"]);
world.events.clear();
input.tick(&mut world, false, true);
assert_eq!(world.events, ["continue"]);
}
#[test]
fn a_quick_use_click_releases_on_the_following_tick() {
let mut input = InteractionInput::default();
let mut world = World {
begin_using: true,
..Default::default()
};
input.press(Button::Use);
input.tick(&mut world, false, false);
assert_eq!(world.events, ["use", "continue"]);
assert!(world.using);
world.events.clear();
input.tick(&mut world, false, false);
assert_eq!(world.events, ["release", "continue"]);
}
}
@@ -0,0 +1,265 @@
//! InputConstants key tables of 26.3 (SDL scancodes), generated from the
//! pinned client by `VanillaOptionsTableExporter`.
/// Keyboard keys: (SDL scancode, key name).
pub const KEYBOARD: &[(i32, &str)] = &[
(0, "key.keyboard.unknown"),
(4, "key.keyboard.a"),
(5, "key.keyboard.b"),
(6, "key.keyboard.c"),
(7, "key.keyboard.d"),
(8, "key.keyboard.e"),
(9, "key.keyboard.f"),
(10, "key.keyboard.g"),
(11, "key.keyboard.h"),
(12, "key.keyboard.i"),
(13, "key.keyboard.j"),
(14, "key.keyboard.k"),
(15, "key.keyboard.l"),
(16, "key.keyboard.m"),
(17, "key.keyboard.n"),
(18, "key.keyboard.o"),
(19, "key.keyboard.p"),
(20, "key.keyboard.q"),
(21, "key.keyboard.r"),
(22, "key.keyboard.s"),
(23, "key.keyboard.t"),
(24, "key.keyboard.u"),
(25, "key.keyboard.v"),
(26, "key.keyboard.w"),
(27, "key.keyboard.x"),
(28, "key.keyboard.y"),
(29, "key.keyboard.z"),
(30, "key.keyboard.1"),
(31, "key.keyboard.2"),
(32, "key.keyboard.3"),
(33, "key.keyboard.4"),
(34, "key.keyboard.5"),
(35, "key.keyboard.6"),
(36, "key.keyboard.7"),
(37, "key.keyboard.8"),
(38, "key.keyboard.9"),
(39, "key.keyboard.0"),
(40, "key.keyboard.enter"),
(41, "key.keyboard.escape"),
(42, "key.keyboard.backspace"),
(43, "key.keyboard.tab"),
(44, "key.keyboard.space"),
(45, "key.keyboard.minus"),
(46, "key.keyboard.equal"),
(47, "key.keyboard.left.bracket"),
(48, "key.keyboard.right.bracket"),
(49, "key.keyboard.backslash"),
(50, "key.keyboard.world.2"),
(51, "key.keyboard.semicolon"),
(52, "key.keyboard.apostrophe"),
(53, "key.keyboard.grave.accent"),
(54, "key.keyboard.comma"),
(55, "key.keyboard.period"),
(56, "key.keyboard.slash"),
(57, "key.keyboard.caps.lock"),
(58, "key.keyboard.f1"),
(59, "key.keyboard.f2"),
(60, "key.keyboard.f3"),
(61, "key.keyboard.f4"),
(62, "key.keyboard.f5"),
(63, "key.keyboard.f6"),
(64, "key.keyboard.f7"),
(65, "key.keyboard.f8"),
(66, "key.keyboard.f9"),
(67, "key.keyboard.f10"),
(68, "key.keyboard.f11"),
(69, "key.keyboard.f12"),
(70, "key.keyboard.print.screen"),
(71, "key.keyboard.scroll.lock"),
(72, "key.keyboard.pause"),
(73, "key.keyboard.insert"),
(74, "key.keyboard.home"),
(75, "key.keyboard.page.up"),
(76, "key.keyboard.delete"),
(77, "key.keyboard.end"),
(78, "key.keyboard.page.down"),
(79, "key.keyboard.right"),
(80, "key.keyboard.left"),
(81, "key.keyboard.down"),
(82, "key.keyboard.up"),
(83, "key.keyboard.num.lock"),
(84, "key.keyboard.keypad.divide"),
(85, "key.keyboard.keypad.multiply"),
(86, "key.keyboard.keypad.subtract"),
(87, "key.keyboard.keypad.add"),
(88, "key.keyboard.keypad.enter"),
(89, "key.keyboard.keypad.1"),
(90, "key.keyboard.keypad.2"),
(91, "key.keyboard.keypad.3"),
(92, "key.keyboard.keypad.4"),
(93, "key.keyboard.keypad.5"),
(94, "key.keyboard.keypad.6"),
(95, "key.keyboard.keypad.7"),
(96, "key.keyboard.keypad.8"),
(97, "key.keyboard.keypad.9"),
(98, "key.keyboard.keypad.0"),
(99, "key.keyboard.keypad.period"),
(100, "key.keyboard.world.1"),
(101, "key.keyboard.application"),
(102, "key.keyboard.power"),
(103, "key.keyboard.keypad.equal"),
(104, "key.keyboard.f13"),
(105, "key.keyboard.f14"),
(106, "key.keyboard.f15"),
(107, "key.keyboard.f16"),
(108, "key.keyboard.f17"),
(109, "key.keyboard.f18"),
(110, "key.keyboard.f19"),
(111, "key.keyboard.f20"),
(112, "key.keyboard.f21"),
(113, "key.keyboard.f22"),
(114, "key.keyboard.f23"),
(115, "key.keyboard.f24"),
(116, "key.keyboard.execute"),
(117, "key.keyboard.help"),
(118, "key.keyboard.menu"),
(119, "key.keyboard.select"),
(120, "key.keyboard.stop"),
(121, "key.keyboard.again"),
(122, "key.keyboard.undo"),
(123, "key.keyboard.cut"),
(124, "key.keyboard.copy"),
(125, "key.keyboard.paste"),
(126, "key.keyboard.find"),
(127, "key.keyboard.mute"),
(128, "key.keyboard.volume.up"),
(129, "key.keyboard.volume.down"),
(133, "key.keyboard.keypad.comma"),
(134, "key.keyboard.keypad.equals.as400"),
(135, "key.keyboard.international1"),
(136, "key.keyboard.international2"),
(137, "key.keyboard.international3"),
(138, "key.keyboard.international4"),
(139, "key.keyboard.international5"),
(140, "key.keyboard.international6"),
(141, "key.keyboard.international7"),
(142, "key.keyboard.international8"),
(143, "key.keyboard.international9"),
(144, "key.keyboard.lang1"),
(145, "key.keyboard.lang2"),
(146, "key.keyboard.lang3"),
(147, "key.keyboard.lang4"),
(148, "key.keyboard.lang5"),
(149, "key.keyboard.lang6"),
(150, "key.keyboard.lang7"),
(151, "key.keyboard.lang8"),
(152, "key.keyboard.lang9"),
(153, "key.keyboard.alternate.erase"),
(154, "key.keyboard.sys.req"),
(155, "key.keyboard.cancel"),
(156, "key.keyboard.clear"),
(157, "key.keyboard.prior"),
(158, "key.keyboard.enter2"),
(159, "key.keyboard.separator"),
(160, "key.keyboard.out"),
(161, "key.keyboard.oper"),
(162, "key.keyboard.clear.again"),
(163, "key.keyboard.crsel"),
(164, "key.keyboard.exsel"),
(176, "key.keyboard.keypad.00"),
(177, "key.keyboard.keypad.000"),
(178, "key.keyboard.thousands.separator"),
(179, "key.keyboard.decimal.separator"),
(180, "key.keyboard.currency.unit"),
(181, "key.keyboard.currency.subunit"),
(182, "key.keyboard.keypad.left.parenthesis"),
(183, "key.keyboard.keypad.right.parenthesis"),
(184, "key.keyboard.keypad.left.brace"),
(185, "key.keyboard.keypad.right.brace"),
(186, "key.keyboard.keypad.tab"),
(187, "key.keyboard.keypad.backspace"),
(188, "key.keyboard.keypad.a"),
(189, "key.keyboard.keypad.b"),
(190, "key.keyboard.keypad.c"),
(191, "key.keyboard.keypad.d"),
(192, "key.keyboard.keypad.e"),
(193, "key.keyboard.keypad.f"),
(194, "key.keyboard.keypad.xor"),
(195, "key.keyboard.keypad.power"),
(196, "key.keyboard.keypad.percent"),
(197, "key.keyboard.keypad.less"),
(198, "key.keyboard.keypad.greater"),
(199, "key.keyboard.keypad.ampersand"),
(200, "key.keyboard.keypad.double.ampersand"),
(201, "key.keyboard.keypad.vertical.bar"),
(202, "key.keyboard.keypad.double.vertical.bar"),
(203, "key.keyboard.keypad.colon"),
(204, "key.keyboard.keypad.hash"),
(205, "key.keyboard.keypad.space"),
(206, "key.keyboard.keypad.at"),
(207, "key.keyboard.keypad.exclamation"),
(208, "key.keyboard.keypad.memory.store"),
(209, "key.keyboard.keypad.memory.recall"),
(210, "key.keyboard.keypad.memory.clear"),
(211, "key.keyboard.keypad.memory.add"),
(212, "key.keyboard.keypad.memory.subtract"),
(213, "key.keyboard.keypad.memory.multiply"),
(214, "key.keyboard.keypad.memory.divide"),
(215, "key.keyboard.keypad.plus.minus"),
(216, "key.keyboard.keypad.clear"),
(217, "key.keyboard.keypad.clear.entry"),
(218, "key.keyboard.keypad.binary"),
(219, "key.keyboard.keypad.octal"),
(220, "key.keyboard.keypad.decimal"),
(221, "key.keyboard.keypad.hexadecimal"),
(224, "key.keyboard.left.control"),
(225, "key.keyboard.left.shift"),
(226, "key.keyboard.left.alt"),
(227, "key.keyboard.left.win"),
(228, "key.keyboard.right.control"),
(229, "key.keyboard.right.shift"),
(230, "key.keyboard.right.alt"),
(231, "key.keyboard.right.win"),
(257, "key.keyboard.mode"),
(258, "key.keyboard.sleep"),
(259, "key.keyboard.wake"),
(260, "key.keyboard.channel.up"),
(261, "key.keyboard.channel.down"),
(262, "key.keyboard.media.play"),
(263, "key.keyboard.media.pause"),
(264, "key.keyboard.media.record"),
(265, "key.keyboard.media.fast.forward"),
(266, "key.keyboard.media.rewind"),
(267, "key.keyboard.media.next.track"),
(268, "key.keyboard.media.previous.track"),
(269, "key.keyboard.media.stop"),
(270, "key.keyboard.media.eject"),
(271, "key.keyboard.media.play.pause"),
(272, "key.keyboard.media.select"),
(273, "key.keyboard.ac.new"),
(274, "key.keyboard.ac.open"),
(275, "key.keyboard.ac.close"),
(276, "key.keyboard.ac.exit"),
(277, "key.keyboard.ac.save"),
(278, "key.keyboard.ac.print"),
(279, "key.keyboard.ac.properties"),
(280, "key.keyboard.ac.search"),
(281, "key.keyboard.ac.home"),
(282, "key.keyboard.ac.back"),
(283, "key.keyboard.ac.forward"),
(284, "key.keyboard.ac.stop"),
(285, "key.keyboard.ac.refresh"),
(286, "key.keyboard.ac.bookmarks"),
(287, "key.keyboard.soft.left"),
(288, "key.keyboard.soft.right"),
(289, "key.keyboard.call"),
(290, "key.keyboard.end.call"),
];
/// Mouse buttons: (button number, key name).
pub const MOUSE: &[(i32, &str)] = &[
(1, "key.mouse.left"),
(2, "key.mouse.middle"),
(3, "key.mouse.right"),
(4, "key.mouse.4"),
(5, "key.mouse.5"),
(6, "key.mouse.6"),
(7, "key.mouse.7"),
(8, "key.mouse.8"),
];
+457
View File
@@ -0,0 +1,457 @@
//! Key mappings (Options.keyMappings): vanilla names, categories and
//! defaults, `key_<name>:key.keyboard.x` persistence, display names, and the
//! translation of rebound physical keys back to the default keys the game
//! logic listens for.
use std::collections::BTreeMap;
use winit::{event::MouseButton, keyboard::KeyCode};
/// (name, default key, category) in Options.keyMappings order.
pub const MAPPINGS: &[(&str, &str, &str)] = &[
("key.attack", "key.mouse.left", "gameplay"),
("key.use", "key.mouse.right", "gameplay"),
("key.forward", "key.keyboard.w", "movement"),
("key.left", "key.keyboard.a", "movement"),
("key.back", "key.keyboard.s", "movement"),
("key.right", "key.keyboard.d", "movement"),
("key.jump", "key.keyboard.space", "movement"),
("key.sneak", "key.keyboard.left.shift", "movement"),
("key.sprint", "key.keyboard.left.control", "movement"),
("key.drop", "key.keyboard.q", "inventory"),
("key.inventory", "key.keyboard.e", "inventory"),
("key.chat", "key.keyboard.t", "multiplayer"),
("key.playerlist", "key.keyboard.tab", "multiplayer"),
("key.pickItem", "key.mouse.middle", "gameplay"),
("key.command", "key.keyboard.slash", "multiplayer"),
("key.friends", "key.keyboard.o", "multiplayer"),
("key.socialInteractions", "key.keyboard.p", "multiplayer"),
("key.toggleGui", "key.keyboard.f1", "misc"),
(
"key.toggleSpectatorShaderEffects",
"key.keyboard.f4",
"misc",
),
("key.screenshot", "key.keyboard.f2", "misc"),
("key.togglePerspective", "key.keyboard.f5", "misc"),
("key.smoothCamera", "key.keyboard.unknown", "misc"),
("key.fullscreen", "key.keyboard.f11", "misc"),
("key.spectatorOutlines", "key.keyboard.unknown", "spectator"),
("key.spectatorHotbar", "key.mouse.middle", "spectator"),
("key.swapOffhand", "key.keyboard.f", "inventory"),
("key.saveToolbarActivator", "key.keyboard.c", "creative"),
("key.loadToolbarActivator", "key.keyboard.x", "creative"),
("key.advancements", "key.keyboard.l", "misc"),
("key.quickActions", "key.keyboard.g", "misc"),
("key.debug.overlay", "key.keyboard.f3", "debug"),
("key.debug.modifier", "key.keyboard.f3", "debug"),
("key.hotbar.1", "key.keyboard.1", "inventory"),
("key.hotbar.2", "key.keyboard.2", "inventory"),
("key.hotbar.3", "key.keyboard.3", "inventory"),
("key.hotbar.4", "key.keyboard.4", "inventory"),
("key.hotbar.5", "key.keyboard.5", "inventory"),
("key.hotbar.6", "key.keyboard.6", "inventory"),
("key.hotbar.7", "key.keyboard.7", "inventory"),
("key.hotbar.8", "key.keyboard.8", "inventory"),
("key.hotbar.9", "key.keyboard.9", "inventory"),
("key.debug.reloadChunk", "key.keyboard.a", "debug"),
("key.debug.showHitboxes", "key.keyboard.b", "debug"),
("key.debug.clearChat", "key.keyboard.d", "debug"),
("key.debug.crash", "key.keyboard.c", "debug"),
("key.debug.showChunkBorders", "key.keyboard.g", "debug"),
("key.debug.showAdvancedTooltips", "key.keyboard.h", "debug"),
("key.debug.copyRecreateCommand", "key.keyboard.i", "debug"),
("key.debug.spectate", "key.keyboard.n", "debug"),
("key.debug.switchGameMode", "key.keyboard.f4", "debug"),
("key.debug.debugOptions", "key.keyboard.f6", "debug"),
("key.debug.focusPause", "key.keyboard.p", "debug"),
("key.debug.dumpDynamicTextures", "key.keyboard.s", "debug"),
("key.debug.reloadResourcePacks", "key.keyboard.t", "debug"),
("key.debug.profiling", "key.keyboard.l", "debug"),
("key.debug.copyLocation", "key.keyboard.c", "debug"),
("key.debug.dumpVersion", "key.keyboard.v", "debug"),
("key.debug.profilingChart", "key.keyboard.1", "debug"),
("key.debug.fpsCharts", "key.keyboard.2", "debug"),
("key.debug.networkCharts", "key.keyboard.3", "debug"),
("key.debug.lightmapTexture", "key.keyboard.4", "debug"),
("key.debug.improvedTransparency", "key.keyboard.x", "debug"),
];
/// Mappings Options builds as `ToggleKeyMapping` (hold or toggle by option).
pub fn is_toggle(name: &str) -> bool {
matches!(name, "key.sneak" | "key.sprint" | "key.use" | "key.attack")
}
/// KeyMapping.Category sort order.
pub const CATEGORIES: [&str; 8] = [
"movement",
"misc",
"multiplayer",
"gameplay",
"inventory",
"creative",
"spectator",
"debug",
];
/// InputConstants key names <-> winit physical keys.
const KEYS: &[(&str, KeyCode)] = &[
("key.keyboard.a", KeyCode::KeyA),
("key.keyboard.b", KeyCode::KeyB),
("key.keyboard.c", KeyCode::KeyC),
("key.keyboard.d", KeyCode::KeyD),
("key.keyboard.e", KeyCode::KeyE),
("key.keyboard.f", KeyCode::KeyF),
("key.keyboard.g", KeyCode::KeyG),
("key.keyboard.h", KeyCode::KeyH),
("key.keyboard.i", KeyCode::KeyI),
("key.keyboard.j", KeyCode::KeyJ),
("key.keyboard.k", KeyCode::KeyK),
("key.keyboard.l", KeyCode::KeyL),
("key.keyboard.m", KeyCode::KeyM),
("key.keyboard.n", KeyCode::KeyN),
("key.keyboard.o", KeyCode::KeyO),
("key.keyboard.p", KeyCode::KeyP),
("key.keyboard.q", KeyCode::KeyQ),
("key.keyboard.r", KeyCode::KeyR),
("key.keyboard.s", KeyCode::KeyS),
("key.keyboard.t", KeyCode::KeyT),
("key.keyboard.u", KeyCode::KeyU),
("key.keyboard.v", KeyCode::KeyV),
("key.keyboard.w", KeyCode::KeyW),
("key.keyboard.x", KeyCode::KeyX),
("key.keyboard.y", KeyCode::KeyY),
("key.keyboard.z", KeyCode::KeyZ),
("key.keyboard.1", KeyCode::Digit1),
("key.keyboard.2", KeyCode::Digit2),
("key.keyboard.3", KeyCode::Digit3),
("key.keyboard.4", KeyCode::Digit4),
("key.keyboard.5", KeyCode::Digit5),
("key.keyboard.6", KeyCode::Digit6),
("key.keyboard.7", KeyCode::Digit7),
("key.keyboard.8", KeyCode::Digit8),
("key.keyboard.9", KeyCode::Digit9),
("key.keyboard.0", KeyCode::Digit0),
("key.keyboard.enter", KeyCode::Enter),
("key.keyboard.escape", KeyCode::Escape),
("key.keyboard.backspace", KeyCode::Backspace),
("key.keyboard.tab", KeyCode::Tab),
("key.keyboard.space", KeyCode::Space),
("key.keyboard.minus", KeyCode::Minus),
("key.keyboard.equal", KeyCode::Equal),
("key.keyboard.left.bracket", KeyCode::BracketLeft),
("key.keyboard.right.bracket", KeyCode::BracketRight),
("key.keyboard.backslash", KeyCode::Backslash),
("key.keyboard.semicolon", KeyCode::Semicolon),
("key.keyboard.apostrophe", KeyCode::Quote),
("key.keyboard.grave.accent", KeyCode::Backquote),
("key.keyboard.comma", KeyCode::Comma),
("key.keyboard.period", KeyCode::Period),
("key.keyboard.slash", KeyCode::Slash),
("key.keyboard.caps.lock", KeyCode::CapsLock),
("key.keyboard.f1", KeyCode::F1),
("key.keyboard.f2", KeyCode::F2),
("key.keyboard.f3", KeyCode::F3),
("key.keyboard.f4", KeyCode::F4),
("key.keyboard.f5", KeyCode::F5),
("key.keyboard.f6", KeyCode::F6),
("key.keyboard.f7", KeyCode::F7),
("key.keyboard.f8", KeyCode::F8),
("key.keyboard.f9", KeyCode::F9),
("key.keyboard.f10", KeyCode::F10),
("key.keyboard.f11", KeyCode::F11),
("key.keyboard.f12", KeyCode::F12),
("key.keyboard.print.screen", KeyCode::PrintScreen),
("key.keyboard.scroll.lock", KeyCode::ScrollLock),
("key.keyboard.pause", KeyCode::Pause),
("key.keyboard.insert", KeyCode::Insert),
("key.keyboard.home", KeyCode::Home),
("key.keyboard.page.up", KeyCode::PageUp),
("key.keyboard.delete", KeyCode::Delete),
("key.keyboard.end", KeyCode::End),
("key.keyboard.page.down", KeyCode::PageDown),
("key.keyboard.right", KeyCode::ArrowRight),
("key.keyboard.left", KeyCode::ArrowLeft),
("key.keyboard.down", KeyCode::ArrowDown),
("key.keyboard.up", KeyCode::ArrowUp),
("key.keyboard.num.lock", KeyCode::NumLock),
("key.keyboard.keypad.divide", KeyCode::NumpadDivide),
("key.keyboard.keypad.multiply", KeyCode::NumpadMultiply),
("key.keyboard.keypad.subtract", KeyCode::NumpadSubtract),
("key.keyboard.keypad.add", KeyCode::NumpadAdd),
("key.keyboard.keypad.enter", KeyCode::NumpadEnter),
("key.keyboard.keypad.1", KeyCode::Numpad1),
("key.keyboard.keypad.2", KeyCode::Numpad2),
("key.keyboard.keypad.3", KeyCode::Numpad3),
("key.keyboard.keypad.4", KeyCode::Numpad4),
("key.keyboard.keypad.5", KeyCode::Numpad5),
("key.keyboard.keypad.6", KeyCode::Numpad6),
("key.keyboard.keypad.7", KeyCode::Numpad7),
("key.keyboard.keypad.8", KeyCode::Numpad8),
("key.keyboard.keypad.9", KeyCode::Numpad9),
("key.keyboard.keypad.0", KeyCode::Numpad0),
("key.keyboard.keypad.period", KeyCode::NumpadDecimal),
("key.keyboard.keypad.equal", KeyCode::NumpadEqual),
("key.keyboard.menu", KeyCode::ContextMenu),
("key.keyboard.left.control", KeyCode::ControlLeft),
("key.keyboard.left.shift", KeyCode::ShiftLeft),
("key.keyboard.left.alt", KeyCode::AltLeft),
("key.keyboard.left.win", KeyCode::SuperLeft),
("key.keyboard.right.control", KeyCode::ControlRight),
("key.keyboard.right.shift", KeyCode::ShiftRight),
("key.keyboard.right.alt", KeyCode::AltRight),
("key.keyboard.right.win", KeyCode::SuperRight),
];
pub fn key_code(name: &str) -> Option<KeyCode> {
KEYS.iter().find(|(n, _)| *n == name).map(|(_, k)| *k)
}
pub fn key_name(code: KeyCode) -> Option<&'static str> {
KEYS.iter().find(|(_, k)| *k == code).map(|(n, _)| *n)
}
pub fn mouse_name(button: MouseButton) -> String {
match button {
MouseButton::Left => "key.mouse.left".into(),
MouseButton::Right => "key.mouse.right".into(),
MouseButton::Middle => "key.mouse.middle".into(),
MouseButton::Back => "key.mouse.4".into(),
MouseButton::Forward => "key.mouse.5".into(),
MouseButton::Other(n) => format!("key.mouse.{}", n + 1),
}
}
pub fn mouse_button(name: &str) -> Option<MouseButton> {
Some(match name {
"key.mouse.left" => MouseButton::Left,
"key.mouse.right" => MouseButton::Right,
"key.mouse.middle" => MouseButton::Middle,
"key.mouse.4" => MouseButton::Back,
"key.mouse.5" => MouseButton::Forward,
_ => return None,
})
}
pub use horizon_client_core::key_display::display_name;
/// Current bindings by mapping name.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct KeyBinds {
keys: BTreeMap<&'static str, String>,
}
impl Default for KeyBinds {
fn default() -> Self {
Self {
keys: MAPPINGS
.iter()
.map(|(n, d, _)| (*n, (*d).to_owned()))
.collect(),
}
}
}
/// Each default key once, in order: two mappings that share a default key
/// (Advancements and the debug profiler both on L) are one press of it, not
/// two (the second would close the screen the first opened). Vanilla clicks
/// both mappings, but the profiler one only acts with F3 held.
fn distinct<T: PartialEq>(keys: Vec<T>) -> Vec<T> {
let mut out = Vec::with_capacity(keys.len());
for k in keys {
if !out.contains(&k) {
out.push(k);
}
}
out
}
impl KeyBinds {
pub fn get(&self, name: &str) -> &str {
self.keys
.get(name)
.map_or("key.keyboard.unknown", String::as_str)
}
pub fn default_of(name: &str) -> &'static str {
MAPPINGS
.iter()
.find(|m| m.0 == name)
.map_or("key.keyboard.unknown", |m| m.1)
}
pub fn is_default(&self, name: &str) -> bool {
self.get(name) == Self::default_of(name)
}
pub fn set(&mut self, name: &str, key: &str) {
if let Some((n, _, _)) = MAPPINGS.iter().find(|m| m.0 == name) {
self.keys.insert(n, key.to_owned());
}
}
pub fn saved(&self) -> Vec<(&'static str, String)> {
MAPPINGS
.iter()
.map(|(n, _, _)| (*n, self.get(n).to_owned()))
.collect()
}
pub fn reset_all(&mut self) {
*self = Self::default();
}
/// Mappings sharing `name`'s key (KeyMapping.same), for conflict marks.
pub fn conflicts(&self, name: &str) -> Vec<&'static str> {
let key = self.get(name);
if key == "key.keyboard.unknown" {
return Vec::new();
}
MAPPINGS
.iter()
.filter(|(n, _, _)| {
*n != name && self.get(n) == key && (!self.is_default(n) || !self.is_default(name))
})
.map(|(n, _, _)| *n)
.collect()
}
/// The mapping a physical input triggers (first in list order).
pub fn mapping_for(&self, key: &str) -> Option<&'static str> {
self.mappings_for(key).next()
}
/// Every mapping a physical input triggers, in list order: like
/// `KeyMapping.set`/`click`, one key drives all the mappings bound to it.
pub fn mappings_for<'a>(&'a self, key: &'a str) -> impl Iterator<Item = &'static str> + 'a {
MAPPINGS
.iter()
.map(|m| m.0)
.filter(move |n| self.get(n) == key)
}
/// Translate a physical key into the default key of the mapping it is
/// bound to, so game code written against vanilla defaults follows the
/// player's bindings. `None` means the key now does nothing; mouse
/// mappings bound to keys come back as `Err(button)`. The first of
/// [`KeyBinds::translate_all`].
pub fn translate(&self, key: KeyCode) -> Option<Result<KeyCode, MouseButton>> {
self.translate_all(key).into_iter().next()
}
/// The default keys of every mapping `key` is bound to (empty when it
/// now does nothing), so a key bound to two mappings (forward and
/// sprint) drives both, as `KeyMapping.set` does.
pub fn translate_all(&self, key: KeyCode) -> Vec<Result<KeyCode, MouseButton>> {
let Some(name) = key_name(key) else {
return vec![Ok(key)];
};
let bound: Vec<_> = self
.mappings_for(name)
.filter_map(|mapping| {
let default = Self::default_of(mapping);
match key_code(default) {
Some(code) => Some(Ok(code)),
None => mouse_button(default).map(Err),
}
})
.collect();
if !bound.is_empty() {
return distinct(bound);
}
// An unbound key whose default meaning was moved elsewhere is inert.
if MAPPINGS
.iter()
.any(|(n, d, _)| *d == name && !self.is_default(n))
{
return Vec::new();
}
vec![Ok(key)]
}
/// Translate a mouse button the same way (keys bound to mouse buttons).
pub fn translate_mouse(&self, button: MouseButton) -> Option<Result<KeyCode, MouseButton>> {
self.translate_mouse_all(button).into_iter().next()
}
/// [`KeyBinds::translate_all`] for a mouse button.
pub fn translate_mouse_all(&self, button: MouseButton) -> Vec<Result<KeyCode, MouseButton>> {
let name = mouse_name(button);
let bound: Vec<_> = self
.mappings_for(&name)
.filter_map(|mapping| {
let default = Self::default_of(mapping);
match mouse_button(default) {
Some(b) => Some(Err(b)),
None => key_code(default).map(Ok),
}
})
.collect();
if !bound.is_empty() {
return distinct(bound);
}
if MAPPINGS
.iter()
.any(|(n, d, _)| *d == name && !self.is_default(n))
{
return Vec::new();
}
vec![Err(button)]
}
/// `AbstractContainerScreen.checkHotbarMouseClicked`: off hand, then hotbar.
pub fn container_mouse_key(&self, button: MouseButton, creative: bool) -> Option<KeyCode> {
let name = mouse_name(button);
if matches!(button, MouseButton::Left | MouseButton::Right)
|| (creative && self.get("key.pickItem") == name)
{
return None;
}
std::iter::once("key.swapOffhand")
.chain(
MAPPINGS
.iter()
.map(|m| m.0)
.filter(|n| n.starts_with("key.hotbar.")),
)
.find(|mapping| self.get(mapping) == name)
.and_then(|mapping| key_code(Self::default_of(mapping)))
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn container_mouse_hotkeys_follow_slot_bindings_and_pick_item_priority() {
for button in [MouseButton::Back, MouseButton::Forward, MouseButton::Middle] {
for (mapping, default, _) in MAPPINGS.iter().filter(|m| m.0.starts_with("key.hotbar."))
{
let mut keys = KeyBinds::default();
keys.set(mapping, &mouse_name(button));
assert_eq!(keys.container_mouse_key(button, false), key_code(default));
assert_eq!(
keys.container_mouse_key(button, true),
if button == MouseButton::Middle {
None
} else {
key_code(default)
}
);
}
}
let mut keys = KeyBinds::default();
keys.set("key.hotbar.1", "key.mouse.4");
keys.set("key.swapOffhand", "key.mouse.4");
assert_eq!(
keys.container_mouse_key(MouseButton::Back, false),
Some(KeyCode::KeyF)
);
keys.set("key.hotbar.2", "key.mouse.left");
assert_eq!(keys.container_mouse_key(MouseButton::Left, false), None);
assert_eq!(keys.container_mouse_key(MouseButton::Right, false), None);
assert_eq!(keys.container_mouse_key(MouseButton::Forward, false), None);
}
#[test]
fn rebinding_translates_to_defaults() {
let mut k = KeyBinds::default();
assert_eq!(k.translate(KeyCode::KeyW), Some(Ok(KeyCode::KeyW)));
// Forward on the up arrow, inventory on W.
k.set("key.forward", "key.keyboard.up");
k.set("key.inventory", "key.keyboard.w");
assert_eq!(k.translate(KeyCode::ArrowUp), Some(Ok(KeyCode::KeyW)));
assert_eq!(k.translate(KeyCode::KeyW), Some(Ok(KeyCode::KeyE)));
// E's default meaning moved and nothing else uses it.
assert_eq!(k.translate(KeyCode::KeyE), None);
// Attack on a key.
k.set("key.attack", "key.keyboard.r");
assert_eq!(k.translate(KeyCode::KeyR), Some(Err(MouseButton::Left)));
assert_eq!(k.translate_mouse(MouseButton::Left), None);
assert_eq!(k.translate(KeyCode::Escape), Some(Ok(KeyCode::Escape)));
assert!(k.conflicts("key.forward").is_empty());
k.set("key.jump", "key.keyboard.up");
assert_eq!(k.conflicts("key.forward"), ["key.jump"]);
}
#[test]
fn display_names() {
assert_eq!(display_name("key.keyboard.w").plain(), "W");
assert_eq!(display_name("key.keyboard.slash").plain(), "/");
}
}
@@ -0,0 +1,209 @@
//! The down/click state of `KeyMapping` and `ToggleKeyMapping` (sneak,
//! sprint, attack and use can be toggled instead of held).
/// One mapping's runtime state. `toggle` is `Some(restore)` for a
/// `ToggleKeyMapping` (with its `shouldRestore` flag), `None` for a plain one.
#[derive(Clone, Debug)]
pub struct KeyState {
pub is_down: bool,
click_count: i32,
released_by_screen_when_down: bool,
toggle: Option<bool>,
keyboard: bool,
}
impl KeyState {
pub fn plain() -> Self {
Self {
is_down: false,
click_count: 0,
released_by_screen_when_down: false,
toggle: None,
keyboard: true,
}
}
/// A `ToggleKeyMapping`; `keyboard` is whether the bound key is a keyboard key.
pub fn toggle(should_restore: bool, keyboard: bool) -> Self {
Self {
toggle: Some(should_restore),
keyboard,
..Self::plain()
}
}
/// `KeyMapping.click`: one more pending click.
pub fn click(&mut self) {
self.click_count += 1;
}
/// `consumeClick`.
pub fn consume_click(&mut self) -> bool {
if self.click_count == 0 {
false
} else {
self.click_count -= 1;
true
}
}
/// `setDown`; `needs_toggle` is the mapping's option value.
pub fn set_down(&mut self, down: bool, needs_toggle: bool) {
if self.toggle.is_some() && needs_toggle {
if down {
self.is_down = !self.is_down;
}
} else {
self.is_down = down;
}
}
/// `shouldSetOnIngameFocus` for a keyboard-bound, bound key.
pub fn should_set_on_ingame_focus(&self, needs_toggle: bool) -> bool {
self.keyboard && (self.toggle.is_none() || !needs_toggle)
}
/// `release` (a screen opened): drops pending clicks and the held state.
pub fn release(&mut self, needs_toggle: bool) {
if self.toggle.is_some() {
// ToggleKeyMapping.release does not clear pending clicks.
if needs_toggle && self.is_down || self.released_by_screen_when_down {
self.released_by_screen_when_down = true;
}
self.reset();
} else {
self.click_count = 0;
self.set_down(false, needs_toggle);
}
}
/// `ToggleKeyMapping.reset`.
pub fn reset(&mut self) {
self.is_down = false;
}
/// Clicks not yet consumed.
pub fn pending_clicks(&self) -> i32 {
self.click_count
}
/// `shouldRestoreStateOnScreenClosed` (clears the remembered release).
pub fn should_restore_state_on_screen_closed(&mut self, needs_toggle: bool) -> bool {
let Some(restore) = self.toggle else {
return false;
};
let result = restore && needs_toggle && self.keyboard && self.released_by_screen_when_down;
self.released_by_screen_when_down = false;
result
}
}
/// A keyboard event (`KeyEvent.Action`): SDL reports a held key's repeats
/// as their own action.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum KeyAction {
Release,
Press,
Repeat,
}
/// Sneak.
pub const SNEAK: usize = 0;
/// Sprint.
pub const SPRINT: usize = 1;
/// Attack (mouse).
pub const ATTACK: usize = 2;
/// The `ToggleKeyMapping`s `Options` builds: sneak and sprint (keyboard,
/// restored after a screen), attack (mouse, restored) and use (mouse, not
/// restored), and the handlers that drive them. `needs_toggle` is each
/// mapping's toggle option, read at every event as vanilla does.
#[derive(Clone, Debug)]
pub struct ToggleKeys(pub [KeyState; 4]);
impl Default for ToggleKeys {
fn default() -> Self {
Self([
KeyState::toggle(true, true),
KeyState::toggle(true, true),
KeyState::toggle(true, false),
KeyState::toggle(false, false),
])
}
}
impl ToggleKeys {
pub fn is_down(&self, slot: usize) -> bool {
self.0[slot].is_down
}
/// `KeyboardHandler.keyPress` for a key bound to `slot`: a release sets
/// the mapping up (`KeyMapping.set(key, false)`); a press or a repeat
/// with no screen open sets it down and clicks it.
pub fn key(&mut self, slot: usize, action: KeyAction, screen_open: bool, needs_toggle: bool) {
match action {
KeyAction::Release => self.0[slot].set_down(false, needs_toggle),
KeyAction::Press | KeyAction::Repeat if !screen_open => {
self.0[slot].set_down(true, needs_toggle);
self.0[slot].click();
}
_ => {}
}
}
/// `MouseHandler.onButton` for a button bound to `slot`: only without a
/// screen or overlay.
pub fn button(&mut self, slot: usize, pressed: bool, screen_open: bool, needs_toggle: bool) {
if !screen_open {
self.0[slot].set_down(pressed, needs_toggle);
if pressed {
self.0[slot].click();
}
}
}
/// `Gui.setScreen` with a screen: `KeyMapping.releaseAll`.
pub fn screen_opened(&mut self, needs_toggle: [bool; 4]) {
for (key, option) in self.0.iter_mut().zip(needs_toggle) {
key.release(option);
}
}
/// `Gui.setScreen(null)` in a level:
/// `KeyMapping.restoreToggleStatesOnScreenClosed`.
pub fn screen_closed(&mut self, needs_toggle: [bool; 4]) {
for (key, option) in self.0.iter_mut().zip(needs_toggle) {
if key.should_restore_state_on_screen_closed(option) {
key.set_down(true, option);
}
}
}
/// `LocalPlayer.respawn`: `KeyMapping.resetToggleKeys`.
pub fn respawn(&mut self) {
for key in &mut self.0 {
key.reset();
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn toggle_flips_on_press_and_ignores_release() {
let mut k = KeyState::toggle(true, true);
k.set_down(true, true);
assert!(k.is_down);
k.set_down(false, true);
assert!(k.is_down);
k.set_down(true, true);
assert!(!k.is_down);
}
#[test]
fn screens_block_presses_but_not_releases() {
let mut keys = ToggleKeys::default();
keys.key(SNEAK, KeyAction::Press, true, false);
assert!(!keys.is_down(SNEAK));
keys.key(SNEAK, KeyAction::Press, false, false);
assert!(keys.is_down(SNEAK));
keys.key(SNEAK, KeyAction::Release, true, false);
assert!(!keys.is_down(SNEAK));
keys.key(SPRINT, KeyAction::Press, false, true);
keys.respawn();
assert!(!keys.is_down(SPRINT));
}
#[test]
fn screen_release_restores_toggled_state() {
let mut k = KeyState::toggle(true, true);
k.set_down(true, true);
k.release(true);
assert!(!k.is_down);
assert!(k.should_restore_state_on_screen_closed(true));
assert!(!k.should_restore_state_on_screen_closed(true));
}
}
+14
View File
@@ -0,0 +1,14 @@
//! The client's input layer, below gameplay and screens: key bindings and their
//! names, toggle keys, mouse settings, controllers, the clipboard and window
//! options. horizon-client re-exports each module under its old path
//! (`horizon_client::keybinds`, ...).
#![forbid(unsafe_code)]
pub mod clipboard;
pub mod gamepad;
pub mod input;
pub mod interaction_input;
pub mod key_names;
pub mod keybinds;
pub mod keymapping;
pub mod mouse;
pub mod window;
+529
View File
@@ -0,0 +1,529 @@
//! Mouse look and scrolling of 26.3: `MouseHandler` (accumulated movement,
//! sensitivity curve, cinematic smoothing, inversion), `SmoothDouble`,
//! `ScrollWheelHandler` and `Entity.turn`.
/// `SmoothDouble`.
#[derive(Clone, Debug, Default)]
pub struct SmoothDouble {
target_value: f64,
remaining_value: f64,
last_amount: f64,
}
impl SmoothDouble {
pub fn get_new_delta_value(&mut self, target_delta: f64, time: f64) -> f64 {
self.target_value += target_delta;
let mut delta = self.target_value - self.remaining_value;
let new_last_amount = self.last_amount + 0.5 * (delta - self.last_amount);
let delta_sign = java_signum(delta);
if delta_sign * delta > delta_sign * self.last_amount {
delta = new_last_amount;
}
self.last_amount = new_last_amount;
self.remaining_value += delta * time;
delta * time
}
pub fn reset(&mut self) {
*self = Self::default();
}
}
/// `Math.signum(double)`.
pub fn java_signum(v: f64) -> f64 {
if v == 0.0 || v.is_nan() {
v
} else {
v.signum()
}
}
/// `ScrollWheelHandler`.
#[derive(Clone, Debug, Default)]
pub struct ScrollWheelHandler {
accumulated_x: f64,
accumulated_y: f64,
}
impl ScrollWheelHandler {
/// `onMouseScroll`: whole wheel steps `(x, y)` once enough has accumulated.
pub fn on_mouse_scroll(&mut self, x: f64, y: f64) -> (i32, i32) {
if self.accumulated_x != 0.0 && java_signum(x) != java_signum(self.accumulated_x) {
self.accumulated_x = 0.0;
}
if self.accumulated_y != 0.0 && java_signum(y) != java_signum(self.accumulated_y) {
self.accumulated_y = 0.0;
}
self.accumulated_x += x;
self.accumulated_y += y;
// Java's double-to-int cast saturates and maps NaN to zero, like Rust's.
let wheel_x = self.accumulated_x as i32;
let wheel_y = self.accumulated_y as i32;
if wheel_x == 0 && wheel_y == 0 {
return (0, 0);
}
self.accumulated_x -= f64::from(wheel_x);
self.accumulated_y -= f64::from(wheel_y);
(wheel_x, wheel_y)
}
/// `getNextScrollWheelSelection`.
pub fn next_selection(wheel: f64, current_selected: i32, limit: i32) -> i32 {
let step = java_signum(wheel) as i32;
let mut current = (current_selected - step).max(-1);
while current < 0 {
current += limit;
}
while current >= limit {
current -= limit;
}
current
}
}
/// `MouseHandler.onScroll` with the spectator menu closed. Only vertical whole
/// wheel steps adjust `Abilities.flyingSpeed`; horizontal scrolling does not.
pub fn spectator_flying_speed(speed: f32, vertical_steps: i32) -> f32 {
(speed + vertical_steps as f32 * 0.005).clamp(0.0, 0.2)
}
/// Entity rotation as `Entity.turn` keeps it.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Rotation {
pub x_rot: f32,
pub y_rot: f32,
pub x_rot_o: f32,
pub y_rot_o: f32,
}
impl Rotation {
fn set_x_rot(&mut self, x_rot: f32) {
if x_rot.is_finite() {
self.x_rot = (x_rot % 360.0).clamp(-90.0, 90.0);
}
}
fn set_y_rot(&mut self, y_rot: f32) {
if y_rot.is_finite() {
self.y_rot = y_rot;
}
}
/// `Entity.turn(xo, yo)`: mouse deltas in, 0.15 degrees per unit, pitch clamped.
pub fn turn(&mut self, xo: f64, yo: f64) {
let x_delta = (yo as f32) * 0.15;
let y_delta = (xo as f32) * 0.15;
self.set_x_rot(self.x_rot + x_delta);
self.set_y_rot(self.y_rot + y_delta);
self.set_x_rot(mth_clamp(self.x_rot, -90.0, 90.0));
self.x_rot_o += x_delta;
self.y_rot_o += y_delta;
self.x_rot_o = mth_clamp(self.x_rot_o, -90.0, 90.0);
}
}
/// `Mth.clamp(float, float, float)`.
pub fn mth_clamp(value: f32, min: f32, max: f32) -> f32 {
if value < min {
min
} else if value.is_nan() || max.is_nan() {
f32::NAN
} else {
value.min(max)
}
}
/// The options `turnPlayer` reads.
#[derive(Clone, Copy, Debug)]
pub struct LookOptions {
pub sensitivity: f64,
pub smooth_camera: bool,
/// First-person camera and the player is scoping (spyglass).
pub scoping: bool,
pub invert_x: bool,
pub invert_y: bool,
}
/// The input state of `MouseHandler` that drives the camera and the hotbar.
#[derive(Clone, Debug)]
pub struct MouseLook {
xpos: f64,
ypos: f64,
ignore_first_move: bool,
smooth_turn_x: SmoothDouble,
smooth_turn_y: SmoothDouble,
accumulated_dx: f64,
accumulated_dy: f64,
pub scroll: ScrollWheelHandler,
last_handle_movement_time: f64,
}
impl Default for MouseLook {
fn default() -> Self {
Self {
xpos: 0.0,
ypos: 0.0,
ignore_first_move: true,
smooth_turn_x: SmoothDouble::default(),
smooth_turn_y: SmoothDouble::default(),
accumulated_dx: 0.0,
accumulated_dy: 0.0,
scroll: ScrollWheelHandler::default(),
// Double.MIN_VALUE
last_handle_movement_time: 4.9e-324,
}
}
}
impl MouseLook {
/// `setIgnoreFirstMove`.
pub fn set_ignore_first_move(&mut self) {
self.ignore_first_move = true;
}
/// `onMove`: relative motion counts while the pointer is grabbed, absolute
/// motion otherwise.
pub fn on_move(
&mut self,
xpos: f64,
ypos: f64,
xrel: f64,
yrel: f64,
window_active: bool,
grabbed: bool,
) {
if self.ignore_first_move {
self.xpos = xpos;
self.ypos = ypos;
self.ignore_first_move = false;
} else {
if window_active {
if grabbed {
self.accumulated_dx += xrel;
self.accumulated_dy += yrel;
} else {
self.accumulated_dx += xpos - self.xpos;
self.accumulated_dy += ypos - self.ypos;
}
}
self.xpos = xpos;
self.ypos = ypos;
}
}
/// `onMove` with the pointer grabbed, for relative motion an agent makes
/// (`horizon-ctl mouse-move`): added to the frame's accumulated movement.
pub fn add_motion(&mut self, dx: f64, dy: f64) {
self.accumulated_dx += dx;
self.accumulated_dy += dy;
}
/// Movement accumulated since the last frame (for screens' mouse-moved events).
pub fn accumulated(&self) -> (f64, f64) {
(self.accumulated_dx, self.accumulated_dy)
}
/// `handleAccumulatedMovement` for a frame at `time` seconds: the
/// `(xo, yo)` passed to `Entity.turn` when the pointer is grabbed and the
/// window is active. The accumulators are cleared either way.
pub fn handle_accumulated_movement(
&mut self,
time: f64,
window_active: bool,
grabbed_with_player: bool,
look: LookOptions,
) -> Option<(f64, f64)> {
let mousea = time - self.last_handle_movement_time;
self.last_handle_movement_time = time;
let turn = (window_active && grabbed_with_player).then(|| self.turn_player(mousea, look));
self.accumulated_dx = 0.0;
self.accumulated_dy = 0.0;
turn
}
fn turn_player(&mut self, mousea: f64, look: LookOptions) -> (f64, f64) {
let (sensitivity_mod, sens) = sensitivity_scales(look.sensitivity);
let (xo, yo) = if look.smooth_camera {
(
self.smooth_turn_x
.get_new_delta_value(self.accumulated_dx * sens, mousea * sens),
self.smooth_turn_y
.get_new_delta_value(self.accumulated_dy * sens, mousea * sens),
)
} else if look.scoping {
self.smooth_turn_x.reset();
self.smooth_turn_y.reset();
(
self.accumulated_dx * sensitivity_mod,
self.accumulated_dy * sensitivity_mod,
)
} else {
self.smooth_turn_x.reset();
self.smooth_turn_y.reset();
(self.accumulated_dx * sens, self.accumulated_dy * sens)
};
(
if look.invert_x { -xo } else { xo },
if look.invert_y { -yo } else { yo },
)
}
/// `onScroll` for the in-game case (no screen, player present): the wheel
/// value `wheel` the hotbar or spectator speed reacts to, and the raw
/// wheel steps. `None` when no whole step has accumulated.
pub fn on_scroll(
&mut self,
xoffset: f64,
yoffset: f64,
discrete: bool,
wheel_sensitivity: f64,
) -> Option<(i32, (i32, i32))> {
let scale = |v: f64| (if discrete { java_signum(v) } else { v }) * wheel_sensitivity;
let (x, y) = self.scroll.on_mouse_scroll(scale(xoffset), scale(yoffset));
if x == 0 && y == 0 {
return None;
}
let wheel = if y == 0 { -x } else { y };
Some((wheel, (x, y)))
}
}
/// `MouseHandler.turnPlayer`'s scales: `sensitivityMod = (s*0.6F+0.2F)^3`
/// and `sens = sensitivityMod * 8`.
fn sensitivity_scales(sensitivity: f64) -> (f64, f64) {
let ss = sensitivity * f64::from(0.6f32) + f64::from(0.2f32);
let sensitivity_mod = ss * ss * ss;
(sensitivity_mod, sensitivity_mod * 8.0)
}
/// Degrees `Entity.turn` turns per unit of mouse motion: 0.15 x `sens`
/// (`sensitivityMod` while scoping). With the cinematic camera the same total
/// is reached, spread over the following frames.
pub fn degrees_per_count(look: LookOptions) -> f64 {
let (sensitivity_mod, sens) = sensitivity_scales(look.sensitivity);
let scale = if look.scoping && !look.smooth_camera {
sensitivity_mod
} else {
sens
};
0.15 * scale
}
/// The mouse motion that turns the view by `dyaw` and `dpitch` degrees with
/// these options, the inverted axes included.
pub fn motion_for_turn(dyaw: f64, dpitch: f64, look: LookOptions) -> (f64, f64) {
let per_count = degrees_per_count(look);
let flip = |inverted: bool| if inverted { -1.0 } else { 1.0 };
(
dyaw / per_count * flip(look.invert_x),
dpitch / per_count * flip(look.invert_y),
)
}
/// Ease-in-out (a half cosine) over `t` in 0..=1: how much of a spread-out
/// turn is done at that point of its time.
pub fn ease_in_out(t: f64) -> f64 {
let t = t.clamp(0.0, 1.0);
0.5 - 0.5 * (std::f64::consts::PI * t).cos()
}
/// `MouseHandler.grabMouse` / `releaseMouse`: the mouse position is the
/// window's centre whenever the pointer's grab state changes, so a screen
/// opened from gameplay starts with the cursor in the middle. A release of
/// an already free pointer (or a grab of an already grabbed one) leaves the
/// position where it is, as vanilla does.
pub fn mouse_position_after_grab_change(
grab: bool,
was_grabbed: bool,
size: [u32; 2],
scale: f32,
) -> Option<(f32, f32)> {
if grab == was_grabbed {
None
} else {
Some((size[0] as f32 / 2.0 / scale, size[1] as f32 / 2.0 / scale))
}
}
#[cfg(test)]
mod tests {
use super::*;
const PLAIN: LookOptions = LookOptions {
sensitivity: 0.5,
smooth_camera: false,
scoping: false,
invert_x: false,
invert_y: false,
};
/// One frame of motion `(dx, dy)` through `onMove`'s grabbed path,
/// `handleAccumulatedMovement` and `Entity.turn`.
fn frame(look: &mut MouseLook, rot: &mut Rotation, time: f64, d: (f64, f64), o: LookOptions) {
look.add_motion(d.0, d.1);
if let Some((xo, yo)) = look.handle_accumulated_movement(time, true, true, o) {
rot.turn(xo, yo);
}
}
fn rotation() -> Rotation {
Rotation {
x_rot: 0.0,
y_rot: 0.0,
x_rot_o: 0.0,
y_rot_o: 0.0,
}
}
#[test]
fn turn_player_matches_the_vanilla_formula() {
// MouseHandler.turnPlayer: ss = sensitivity*0.6F + 0.2F, sens = ss^3 * 8,
// then Entity.turn: yRot += (float)xo * 0.15F, xRot += (float)yo * 0.15F.
for sensitivity in [0.0, 0.25, 0.5, 0.75, 1.0] {
for (dx, dy) in [(1.0, 0.0), (37.0, -12.5), (-400.0, 250.0)] {
let o = LookOptions {
sensitivity,
..PLAIN
};
let ss = sensitivity * f64::from(0.6f32) + f64::from(0.2f32);
let sens = ss * ss * ss * 8.0;
let mut look = MouseLook::default();
let mut rot = rotation();
frame(&mut look, &mut rot, 1.0, (dx, dy), o);
let yaw = (dx * sens) as f32 * 0.15;
let pitch = ((dy * sens) as f32 * 0.15).clamp(-90.0, 90.0);
assert_eq!(
(rot.y_rot, rot.x_rot),
(yaw, pitch),
"s {sensitivity} d {dx},{dy}"
);
}
}
}
#[test]
fn inverted_and_scoping_turns() {
let mut look = MouseLook::default();
let mut rot = rotation();
let o = LookOptions {
invert_y: true,
..PLAIN
};
frame(&mut look, &mut rot, 1.0, (0.0, 10.0), o);
assert!(rot.x_rot < 0.0, "inverted Y looks up: {}", rot.x_rot);
// Scoping drops the factor 8.
let scoped = LookOptions {
scoping: true,
..PLAIN
};
assert!((degrees_per_count(PLAIN) / degrees_per_count(scoped) - 8.0).abs() < 1e-12);
}
#[test]
fn motion_for_turn_round_trips_through_turn_player() {
for o in [
PLAIN,
LookOptions {
sensitivity: 0.9,
invert_x: true,
invert_y: true,
..PLAIN
},
LookOptions {
scoping: true,
..PLAIN
},
] {
let (dx, dy) = motion_for_turn(73.5, -21.25, o);
let mut look = MouseLook::default();
let mut rot = rotation();
frame(&mut look, &mut rot, 1.0, (dx, dy), o);
assert!((rot.y_rot - 73.5).abs() < 1e-3, "{o:?}: {}", rot.y_rot);
assert!((rot.x_rot + 21.25).abs() < 1e-3, "{o:?}: {}", rot.x_rot);
}
}
#[test]
fn cinematic_camera_spreads_the_same_motion_over_frames() {
// SmoothDouble: the first frame turns part of the way, later frames
// without new motion carry on towards the same total.
let o = LookOptions {
smooth_camera: true,
..PLAIN
};
let (dx, _) = motion_for_turn(30.0, 0.0, o);
let mut look = MouseLook::default();
let mut rot = rotation();
frame(&mut look, &mut rot, 0.0, (0.0, 0.0), o);
frame(&mut look, &mut rot, 1.0 / 60.0, (dx, 0.0), o);
let first = rot.y_rot;
assert!(first > 0.0 && first < 30.0, "{first}");
for i in 2..600 {
frame(&mut look, &mut rot, f64::from(i) / 60.0, (0.0, 0.0), o);
}
assert!((rot.y_rot - 30.0).abs() < 0.05, "{}", rot.y_rot);
}
#[test]
fn ease_in_out_starts_and_ends_slowly() {
assert_eq!(ease_in_out(0.0), 0.0);
assert!((ease_in_out(0.5) - 0.5).abs() < 1e-12);
assert!((ease_in_out(1.0) - 1.0).abs() < 1e-12);
assert!(ease_in_out(0.1) < 0.1 && ease_in_out(0.9) > 0.9);
assert_eq!(ease_in_out(2.0), 1.0);
}
#[test]
fn default_sensitivity_turns_point_fifteen_degrees_per_count_at_one() {
let mut look = MouseLook::default();
look.on_move(0.0, 0.0, 0.0, 0.0, true, true);
look.on_move(1.0, 0.0, 1.0, 0.0, true, true);
let (xo, _) = look
.handle_accumulated_movement(
1.0,
true,
true,
LookOptions {
sensitivity: 0.5,
smooth_camera: false,
scoping: false,
invert_x: false,
invert_y: false,
},
)
.unwrap();
let mut rot = Rotation {
x_rot: 0.0,
y_rot: 0.0,
x_rot_o: 0.0,
y_rot_o: 0.0,
};
rot.turn(xo, 0.0);
assert!((rot.y_rot - 0.15 * 1.0).abs() < 1e-6, "{}", rot.y_rot);
}
#[test]
fn scroll_accumulates_fractions() {
let mut look = MouseLook::default();
assert_eq!(look.on_scroll(0.0, 0.4, false, 1.0), None);
assert_eq!(look.on_scroll(0.0, 0.7, false, 1.0), Some((1, (0, 1))));
}
#[test]
fn the_mouse_position_is_the_centre_when_the_grab_changes() {
// A grab of a free pointer and a release of a grabbed one both put
// the position at the window's centre (`MouseHandler.grabMouse`,
// `MouseHandler.releaseMouse`).
assert_eq!(
mouse_position_after_grab_change(true, false, [1920, 1080], 1.0),
Some((960.0, 540.0))
);
assert_eq!(
mouse_position_after_grab_change(false, true, [1920, 1080], 2.0),
Some((480.0, 270.0))
);
// Without a change of the grab state the position stays where it is.
assert_eq!(
mouse_position_after_grab_change(false, false, [1920, 1080], 1.0),
None
);
assert_eq!(
mouse_position_after_grab_change(true, true, [1920, 1080], 1.0),
None
);
}
}
+451
View File
@@ -0,0 +1,451 @@
//! Window sizing and frame pacing of 26.3: `Window.calculateScale` and
//! `setGuiScale`, `MouseHandler`'s scaled positions, `FramerateLimitTracker`,
//! `FramerateLimiter`, the vsync present-mode choice and the fullscreen
//! request/state pair.
/// `Window.calculateScale`: the largest scale that leaves at least 320x240
/// GUI pixels, capped by `max_scale` (0 = automatic); an odd result is bumped
/// to even when unicode is enforced.
pub fn calculate_scale(framebuffer: [i32; 2], max_scale: i32, enforce_unicode: bool) -> i32 {
let [width, height] = framebuffer;
let mut scale = 1;
while scale != max_scale
&& scale < width
&& scale < height
&& width / (scale + 1) >= 320
&& height / (scale + 1) >= 240
{
scale += 1;
}
if enforce_unicode && scale % 2 != 0 {
scale += 1;
}
scale
}
/// `Window.setGuiScale`: the GUI-scaled size of a framebuffer.
pub fn gui_scaled_size(framebuffer: [i32; 2], gui_scale: i32) -> [i32; 2] {
let scaled = |v: i32| (f64::from(v) / f64::from(gui_scale)).ceil() as i32;
[scaled(framebuffer[0]), scaled(framebuffer[1])]
}
/// `MouseHandler.getScaledXPos`/`getScaledYPos`.
pub fn scaled_pos(pos: f64, gui_scaled: i32, screen: i32) -> f64 {
pos * f64::from(gui_scaled) / f64::from(screen)
}
/// `InactivityFpsLimit`.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum InactivityFpsLimit {
Minimized,
Afk,
}
/// `FramerateLimitTracker.FramerateThrottleReason`.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ThrottleReason {
None,
WindowIconified,
LongAfk,
ShortAfk,
OutOfLevelMenu,
}
/// What `FramerateLimitTracker` looks at.
#[derive(Clone, Copy, Debug)]
pub struct FrameContext {
pub inactivity: InactivityFpsLimit,
pub iconified: bool,
pub focused: bool,
pub exclusive_fullscreen: bool,
pub now_ms: i64,
pub latest_input_ms: i64,
pub has_level: bool,
pub has_screen: bool,
pub has_overlay: bool,
}
/// `getThrottleReason`.
pub fn throttle_reason(c: FrameContext) -> ThrottleReason {
if !c.iconified && (c.focused || !c.exclusive_fullscreen) {
if c.inactivity == InactivityFpsLimit::Afk {
let afk = c.now_ms - c.latest_input_ms;
if afk > 600_000 {
return ThrottleReason::LongAfk;
}
if afk > 60_000 {
return ThrottleReason::ShortAfk;
}
}
if c.has_level || (!c.has_screen && !c.has_overlay) {
ThrottleReason::None
} else {
ThrottleReason::OutOfLevelMenu
}
} else {
ThrottleReason::WindowIconified
}
}
/// `getFramerateLimit`.
pub fn framerate_limit(option_limit: i32, c: FrameContext) -> i32 {
match throttle_reason(c) {
ThrottleReason::None => option_limit,
ThrottleReason::WindowIconified | ThrottleReason::LongAfk => 10,
ThrottleReason::ShortAfk => option_limit.min(30),
ThrottleReason::OutOfLevelMenu => 60,
}
}
/// `isHeavilyThrottled`.
pub fn heavily_throttled(reason: ThrottleReason) -> bool {
matches!(
reason,
ThrottleReason::WindowIconified | ThrottleReason::LongAfk
)
}
/// Present modes the renderer can choose between.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum PresentMode {
Fifo,
Mailbox,
Immediate,
}
/// `GpuSurface.PresentMode.getSupportedVsyncMode`: vsync means Fifo only,
/// otherwise the first of Immediate, Mailbox, Fifo that is supported.
pub fn vsync_present_mode(supported: &[PresentMode], vsync: bool) -> Option<PresentMode> {
let preferred: &[PresentMode] = if vsync {
&[PresentMode::Fifo]
} else {
&[
PresentMode::Immediate,
PresentMode::Mailbox,
PresentMode::Fifo,
]
};
preferred.iter().copied().find(|m| supported.contains(m))
}
/// The present mode for the VSync option and Horizon's present-mode setting
/// (`None` for Auto). VSync on always means Fifo, in a window and in
/// fullscreen alike, as in vanilla; the setting chooses only while VSync is
/// off, when the surface supports it, and otherwise vanilla's choice applies.
pub fn chosen_present_mode(
supported: &[PresentMode],
vsync: bool,
setting: Option<PresentMode>,
) -> Option<PresentMode> {
setting
.filter(|m| !vsync && supported.contains(m))
.or_else(|| vsync_present_mode(supported, vsync))
}
/// `FramerateLimiter.limitDisplayFPS` with an injectable clock so the sleep
/// and spin decisions are testable.
#[derive(Clone, Debug)]
pub struct FramerateLimiter {
last_frame_time: i64,
average_overshoot_ns: i64,
last_framerate_limit: i32,
}
/// Time source of the limiter.
pub trait LimiterClock {
fn nanos(&mut self) -> i64;
/// `LockSupport.parkNanos`.
fn park(&mut self, nanos: i64);
/// `Thread.onSpinWait`.
fn spin(&mut self);
/// `Thread.interrupted`: an interrupted limiter skips that sleep.
fn interrupted(&mut self) -> bool {
false
}
}
/// The real clock: `System.nanoTime` from a fixed origin, sleeping for
/// `LockSupport.parkNanos` and a CPU spin hint for `Thread.onSpinWait`.
#[derive(Clone, Copy, Debug)]
pub struct SystemClock {
origin: std::time::Instant,
}
impl Default for SystemClock {
fn default() -> Self {
Self {
origin: std::time::Instant::now(),
}
}
}
impl LimiterClock for SystemClock {
fn nanos(&mut self) -> i64 {
i64::try_from(self.origin.elapsed().as_nanos()).unwrap_or(i64::MAX)
}
fn park(&mut self, nanos: i64) {
std::thread::sleep(std::time::Duration::from_nanos(nanos.max(0) as u64));
}
fn spin(&mut self) {
std::hint::spin_loop();
}
}
/// The real clock without busy waiting: where vanilla spins on
/// `Thread.onSpinWait` for the last half millisecond, this sleeps in short
/// steps, so a capped frame rate leaves the core idle.
#[derive(Clone, Copy, Debug, Default)]
pub struct SleepingClock(pub SystemClock);
impl LimiterClock for SleepingClock {
fn nanos(&mut self) -> i64 {
self.0.nanos()
}
fn park(&mut self, nanos: i64) {
self.0.park(nanos);
}
fn spin(&mut self) {
std::thread::sleep(std::time::Duration::from_micros(50));
}
}
/// `Minecraft.runTick`'s frame-limiter step: only limits below 260
/// (the "unlimited" setting) pace frames.
pub fn end_frame(
limiter: &mut FramerateLimiter,
framerate_limit: i32,
clock: &mut impl LimiterClock,
) {
if framerate_limit < 260 {
limiter.limit_display_fps(framerate_limit, clock);
}
}
impl FramerateLimiter {
pub fn new(now_ns: i64) -> Self {
Self::with_state(now_ns, 0, 0)
}
/// The limiter's static state: `lastFrameTime`, `averageOvershootNs`
/// and `lastFramerateLimit`.
pub fn with_state(
last_frame_time: i64,
average_overshoot_ns: i64,
last_framerate_limit: i32,
) -> Self {
Self {
last_frame_time,
average_overshoot_ns,
last_framerate_limit,
}
}
pub fn average_overshoot_ns(&self) -> i64 {
self.average_overshoot_ns
}
pub fn last_framerate_limit(&self) -> i32 {
self.last_framerate_limit
}
pub fn limit_display_fps(&mut self, framerate_limit: i32, clock: &mut impl LimiterClock) {
let target_time_per_frame = 1_000_000_000 / i64::from(framerate_limit);
let target_time_ns = self.last_frame_time + target_time_per_frame;
if framerate_limit != self.last_framerate_limit {
self.average_overshoot_ns = 0;
self.last_framerate_limit = framerate_limit;
}
loop {
let remaining = target_time_ns - clock.nanos();
if remaining <= 0 {
break;
}
if remaining > self.average_overshoot_ns + 500_000 {
let sleep_start = clock.nanos();
let expected = remaining - self.average_overshoot_ns - 500_000;
if !clock.interrupted() {
clock.park(expected);
let duration = clock.nanos() - sleep_start;
let overshoot = duration - expected;
if overshoot > 0 && overshoot < 25_000_000 {
self.average_overshoot_ns = (0.1 * overshoot as f64
+ 0.9 * self.average_overshoot_ns as f64)
as i64;
self.average_overshoot_ns = self.average_overshoot_ns.min(2_000_000);
}
}
} else {
clock.spin();
}
}
self.last_frame_time = clock.nanos();
}
pub fn last_frame_time(&self) -> i64 {
self.last_frame_time
}
}
/// blaze3d `Window`'s `fullscreenRequested` / `fullscreen` pair. The window
/// system has the last word: a change it makes on its own (a compositor
/// shortcut, a window rule) is adopted by the Fullscreen option
/// (`Window.updateFullscreenState` -> `Minecraft.fullscreenStateChanged`), and
/// the window is only asked to change when the option itself changes
/// (`Window.updateFullscreenIfChanged`), never re-forced to the option.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct FullscreenState {
/// The state the window system last reported (`Window.fullscreen`).
actual: bool,
/// The state last asked of the window system, or adopted from it.
requested: bool,
}
impl FullscreenState {
/// A window created windowed or, when `requested`, asked to be fullscreen.
pub fn new(requested: bool) -> Self {
Self {
actual: false,
requested,
}
}
/// `Window.updateFullscreenIfChanged`: the state to ask of the window
/// when the option `wanted` differs from what was last asked or adopted.
pub fn request(&mut self, wanted: bool) -> Option<bool> {
(wanted != self.requested).then(|| {
self.requested = wanted;
wanted
})
}
/// `Window.updateFullscreenState`: the window now reports `now`; returns
/// it when it changed, for the option to adopt.
pub fn observe(&mut self, now: bool) -> Option<bool> {
(now != self.actual).then(|| {
self.actual = now;
self.requested = now;
now
})
}
}
/// Horizon's icon for the window's title bar and the task bar (X11 and Windows; Wayland takes
/// it from the `horizon.desktop` entry, macOS from the app bundle). `None` if it can't be read.
pub fn icon() -> Option<winit::window::Icon> {
let mut decoder = png::Decoder::new(std::io::Cursor::new(horizon_theme::ICON_PNG));
decoder.set_transformations(png::Transformations::EXPAND | png::Transformations::STRIP_16);
let mut reader = decoder.read_info().ok()?;
let mut bytes = vec![0; reader.output_buffer_size()?];
let info = reader.next_frame(&mut bytes).ok()?;
if info.color_type != png::ColorType::Rgba {
return None;
}
bytes.truncate(info.buffer_size());
winit::window::Icon::from_rgba(bytes, info.width, info.height).ok()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn the_window_icon_decodes() {
assert!(icon().is_some());
}
#[test]
fn fullscreen_follows_the_option_only_when_it_changes() {
let mut f = FullscreenState::new(false);
// Settings applied again with nothing changed: the window is left alone.
assert_eq!(f.request(false), None);
// The compositor makes the window fullscreen on its own: the option adopts it,
// and applying the settings afterwards does not undo it.
assert_eq!(f.observe(true), Some(true));
assert_eq!(f.request(true), None);
assert_eq!(f.observe(true), None);
// F11: one request, not repeated while the compositor catches up.
assert_eq!(f.request(false), Some(false));
assert_eq!(f.request(false), None);
assert_eq!(f.observe(false), Some(false));
assert_eq!(f.request(false), None);
}
#[test]
fn fullscreen_requests_changed_before_the_compositor_answers() {
// Created fullscreen from options.txt.
let mut f = FullscreenState::new(true);
assert_eq!(f.request(true), None);
assert_eq!(f.observe(true), Some(true));
// Toggled twice before any configure: the second request cancels the first.
assert_eq!(f.request(false), Some(false));
assert_eq!(f.request(true), Some(true));
assert_eq!(f.observe(true), None);
// A compositor that refuses leaves the option where the player put it.
assert_eq!(f.request(false), Some(false));
assert_eq!(f.request(false), None);
}
struct Virtual {
now: i64,
oversleep: i64,
}
impl LimiterClock for Virtual {
fn nanos(&mut self) -> i64 {
self.now
}
fn park(&mut self, nanos: i64) {
self.now += nanos + self.oversleep;
}
fn spin(&mut self) {
self.now += 1000;
}
}
#[test]
fn scale_matches_the_320_by_240_rule() {
assert_eq!(calculate_scale([854, 480], 0, false), 2);
assert_eq!(calculate_scale([1920, 1080], 0, false), 4);
assert_eq!(calculate_scale([1920, 1080], 3, false), 3);
assert_eq!(calculate_scale([1920, 1080], 3, true), 4);
assert_eq!(gui_scaled_size([1921, 1081], 4), [481, 271]);
}
#[test]
fn limiter_paces_frames_at_the_target() {
let mut limiter = FramerateLimiter::new(0);
let mut clock = Virtual {
now: 1_000_000,
oversleep: 200_000,
};
limiter.limit_display_fps(100, &mut clock);
assert!(clock.now >= 10_000_000);
assert!(clock.now < 10_000_000 + 1_000_000);
}
#[test]
fn vsync_only_uses_fifo() {
let all = [
PresentMode::Mailbox,
PresentMode::Fifo,
PresentMode::Immediate,
];
assert_eq!(vsync_present_mode(&all, true), Some(PresentMode::Fifo));
assert_eq!(
vsync_present_mode(&all, false),
Some(PresentMode::Immediate)
);
assert_eq!(
vsync_present_mode(&[PresentMode::Fifo], false),
Some(PresentMode::Fifo)
);
}
#[test]
fn vsync_on_waits_for_the_display_whatever_the_present_mode() {
use PresentMode::*;
let all = [Mailbox, Fifo, Immediate];
for setting in [None, Some(Fifo), Some(Mailbox), Some(Immediate)] {
assert_eq!(chosen_present_mode(&all, true, setting), Some(Fifo));
}
assert_eq!(chosen_present_mode(&all, false, None), Some(Immediate));
assert_eq!(
chosen_present_mode(&all, false, Some(Mailbox)),
Some(Mailbox)
);
assert_eq!(chosen_present_mode(&all, false, Some(Fifo)), Some(Fifo));
// Metal has no Mailbox: vanilla's choice instead.
assert_eq!(
chosen_present_mode(&[Fifo, Immediate], false, Some(Mailbox)),
Some(Immediate)
);
}
}