horizon-ctl: mouse-move and eased turns through the player's mouse path
mouse-move DX DY (MCP mouse_move) adds relative motion to MouseHandler's accumulated movement, so the next frame turns the player with turnPlayer's sensitivity curve ((s*0.6F+0.2F)^3*8, no 8 while scoping), the inverted axes and the cinematic camera, then Entity.turn. The motion counts as a grabbed pointer in an active window until the real pointer is grabbed or released again. turn and look-at (and look-at-block/look-at-entity) take --over SECONDS: the turn becomes that motion fed over the time with ease-in-out (the shorter way round for look-at), replying once the last of it has been turned. Without --over they still jump. turn is now an MCP tool. stop cancels a turn in progress. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -111,6 +111,11 @@ const BLOCK_XYZ: [Param; 3] = [
|
||||
p("y", Ty::Int, "block Y"),
|
||||
p("z", Ty::Int, "block Z"),
|
||||
];
|
||||
const OVER: Param = flag(
|
||||
"over",
|
||||
Ty::Num,
|
||||
"turn with mouse motion spread over this many seconds (eased), as a player would",
|
||||
);
|
||||
const FACE: Ty = Ty::Enum(&["down", "up", "north", "south", "west", "east"]);
|
||||
|
||||
macro_rules! cmd {
|
||||
@@ -200,16 +205,22 @@ pub const COMMANDS: &[Cmd] = &[
|
||||
cmd!("look", Move, "look YAW PITCH", "set the view direction in degrees",
|
||||
"Yaw 0 faces south (+Z), 90 west (-X), 180 north, -90 east; pitch 90 looks straight down.",
|
||||
["horizon-ctl look 90 10"], &[p("yaw", Ty::Num, "yaw in degrees"), p("pitch", Ty::Num, "pitch in degrees (-90 up .. 90 down)")], mcp: true, local: false),
|
||||
cmd!("turn", Move, "turn DYAW DPITCH", "rotate the view by an amount", "", ["horizon-ctl turn 45 0"],
|
||||
&[p("dyaw", Ty::Num, "yaw change"), p("dpitch", Ty::Num, "pitch change")], mcp: false, local: false),
|
||||
cmd!("look-at", Move, "look-at X Y Z | look-at block X Y Z [FACE] | look-at entity ID", "turn to face a point, a block (a visible face of it) or an entity",
|
||||
"look-at block aims at a face the crosshair can reach and fails when none is visible.",
|
||||
["horizon-ctl look-at 10.5 65 3.5", "horizon-ctl look-at block 10 64 3 up", "horizon-ctl look-at entity 42"],
|
||||
&XYZ, mcp: true, local: false),
|
||||
cmd!("look-at-block", Move, "look-at-block X Y Z [FACE]", "aim the crosshair at a block (same as look-at block)", "",
|
||||
["horizon-ctl look-at-block 10 64 3"], &[BLOCK_XYZ[0], BLOCK_XYZ[1], BLOCK_XYZ[2], opt("face", FACE, "which face to aim at")], mcp: true, local: false, wire: "look-at block"),
|
||||
cmd!("look-at-entity", Move, "look-at-entity ID", "face an entity (same as look-at entity)", "",
|
||||
["horizon-ctl look-at-entity 42"], &[p("id", Ty::Int, "entity id from entities")], mcp: true, local: false, wire: "look-at entity"),
|
||||
cmd!("turn", Move, "turn DYAW DPITCH [--over S]", "rotate the view by an amount",
|
||||
"Without --over the view jumps. With --over S the turn is mouse motion fed over S seconds with ease-in-out, through the same path as a real mouse (sensitivity, inverted axes, cinematic camera), and the reply comes once it is done.",
|
||||
["horizon-ctl turn 45 0", "horizon-ctl turn -90 10 --over 0.5"],
|
||||
&[p("dyaw", Ty::Num, "yaw change in degrees"), p("dpitch", Ty::Num, "pitch change in degrees"), OVER], mcp: true, local: false),
|
||||
cmd!("mouse-move", Move, "mouse-move DX DY", "move the mouse: relative motion that turns the view like a player's mouse",
|
||||
"DX and DY are mouse units (pixels of relative motion) added to the frame's accumulated movement and turned by MouseHandler.turnPlayer: degrees = units x 0.15 x (sensitivity x 0.6 + 0.2)^3 x 8 (without the 8 while scoping), inverted axes and the cinematic camera included. Positive DX turns right, positive DY looks down. Works in the world with no screen open; replies with yaw and pitch after the frame that turned.",
|
||||
["horizon-ctl mouse-move 100 0", "horizon-ctl mouse-move -25 40"],
|
||||
&[p("dx", Ty::Num, "horizontal motion (positive turns right)"), p("dy", Ty::Num, "vertical motion (positive looks down)")], mcp: true, local: false),
|
||||
cmd!("look-at", Move, "look-at X Y Z | look-at block X Y Z [FACE] | look-at entity ID [--over S]", "turn to face a point, a block (a visible face of it) or an entity",
|
||||
"look-at block aims at a face the crosshair can reach and fails when none is visible. --over S turns there with mouse motion over S seconds (the shorter way round) instead of jumping.",
|
||||
["horizon-ctl look-at 10.5 65 3.5", "horizon-ctl look-at block 10 64 3 up", "horizon-ctl look-at entity 42 --over 0.4"],
|
||||
&[XYZ[0], XYZ[1], XYZ[2], OVER], mcp: true, local: false),
|
||||
cmd!("look-at-block", Move, "look-at-block X Y Z [FACE] [--over S]", "aim the crosshair at a block (same as look-at block)", "",
|
||||
["horizon-ctl look-at-block 10 64 3", "horizon-ctl look-at-block 10 64 3 up --over 0.3"], &[BLOCK_XYZ[0], BLOCK_XYZ[1], BLOCK_XYZ[2], opt("face", FACE, "which face to aim at"), OVER], mcp: true, local: false, wire: "look-at block"),
|
||||
cmd!("look-at-entity", Move, "look-at-entity ID [--over S]", "face an entity (same as look-at entity)", "",
|
||||
["horizon-ctl look-at-entity 42"], &[p("id", Ty::Int, "entity id from entities"), OVER], mcp: true, local: false, wire: "look-at entity"),
|
||||
cmd!("tp", Move, "tp X Y Z", "teleport the player", "", ["horizon-ctl tp 0 80 0"], &XYZ, mcp: true, local: false),
|
||||
// Act
|
||||
cmd!("break", Act, "break X Y Z [--timeout S]", "mine a block, holding the attack button until it breaks",
|
||||
@@ -541,6 +552,21 @@ mod tests {
|
||||
)
|
||||
.is_err()
|
||||
);
|
||||
let turn = find("turn").unwrap();
|
||||
assert_eq!(
|
||||
line_for(turn, &json!({ "dyaw": -90, "dpitch": 10.5, "over": 0.5 })).unwrap(),
|
||||
["turn", "-90", "10.5", "--over", "0.5"]
|
||||
);
|
||||
let mouse = find("mouse-move").unwrap();
|
||||
assert_eq!(tool_name(mouse), "mouse_move");
|
||||
assert_eq!(
|
||||
line_for(mouse, &json!({ "dx": -25, "dy": 40 })).unwrap(),
|
||||
["mouse-move", "-25", "40"]
|
||||
);
|
||||
assert_eq!(
|
||||
line_for(block, &json!({ "x": 1, "y": 2, "z": 3, "over": 0.3 })).unwrap(),
|
||||
["look-at", "block", "1", "2", "3", "--over", "0.3"]
|
||||
);
|
||||
let button = find("click-button").unwrap();
|
||||
assert_eq!(
|
||||
line_for(button, &json!({ "label": "Create New World" })).unwrap(),
|
||||
|
||||
@@ -633,6 +633,9 @@ struct Game<'a> {
|
||||
fullscreen: horizon_client::window::FullscreenState,
|
||||
/// MouseHandler's accumulated look and wheel state.
|
||||
mouse: MouseLook,
|
||||
/// An agent moved the mouse (`mouse-move`) since the pointer was last
|
||||
/// grabbed or released: its motion turns the view like a grabbed pointer.
|
||||
agent_pointer: bool,
|
||||
/// `Options.smoothCamera` (cinematic camera), not persisted.
|
||||
smooth_camera: bool,
|
||||
/// Sneak, sprint, attack and use as ToggleKeyMappings.
|
||||
@@ -2988,20 +2991,28 @@ impl Game<'_> {
|
||||
self.left = self.toggles.is_down(2);
|
||||
self.right = self.toggles.is_down(3);
|
||||
}
|
||||
/// `MouseHandler.handleAccumulatedMovement` and `Entity.turn`, once per frame.
|
||||
fn apply_mouse_look(&mut self) {
|
||||
let look = LookOptions {
|
||||
/// The options `MouseHandler.turnPlayer` reads.
|
||||
fn look_options(&self) -> LookOptions {
|
||||
LookOptions {
|
||||
sensitivity: f64::from(self.settings.sensitivity),
|
||||
smooth_camera: self.smooth_camera,
|
||||
scoping: self.scoping(),
|
||||
invert_x: self.settings.invert_x,
|
||||
invert_y: self.settings.invert_y,
|
||||
};
|
||||
}
|
||||
}
|
||||
/// `MouseHandler.handleAccumulatedMovement` and `Entity.turn`, once per frame.
|
||||
/// An agent moving the mouse (`mouse-move`) counts as a grabbed pointer in
|
||||
/// an active window, as it cannot grab the real one.
|
||||
fn apply_mouse_look(&mut self) {
|
||||
let look = self.look_options();
|
||||
let time = self.started.elapsed().as_secs_f64();
|
||||
let grabbed = self.captured && self.screen == Screen::Playing && self.player.is_some();
|
||||
if let Some((xo, yo)) =
|
||||
self.mouse
|
||||
.handle_accumulated_movement(time, self.focused, grabbed, look)
|
||||
let pointer = self.captured || self.agent_pointer;
|
||||
let grabbed = pointer && self.screen == Screen::Playing && self.player.is_some();
|
||||
let active = self.focused || self.agent_pointer;
|
||||
if let Some((xo, yo)) = self
|
||||
.mouse
|
||||
.handle_accumulated_movement(time, active, grabbed, look)
|
||||
{
|
||||
let mut rotation = Rotation {
|
||||
x_rot: self.pitch,
|
||||
@@ -3024,6 +3035,8 @@ impl Game<'_> {
|
||||
) || self.book.is_some())
|
||||
}
|
||||
fn capture(&mut self, capture: bool) {
|
||||
// The real pointer takes over from an agent's.
|
||||
self.agent_pointer = false;
|
||||
let Some(window) = &self.window else { return };
|
||||
if capture {
|
||||
self.mouse.set_ignore_first_move();
|
||||
@@ -8897,6 +8910,7 @@ pub fn run() -> Result<()> {
|
||||
modifiers: winit::keyboard::ModifiersState::empty(),
|
||||
fullscreen: horizon_client::window::FullscreenState::new(false),
|
||||
mouse: MouseLook::default(),
|
||||
agent_pointer: false,
|
||||
smooth_camera: false,
|
||||
toggles: Default::default(),
|
||||
was_playing: false,
|
||||
|
||||
@@ -34,7 +34,9 @@ pub(super) const HELP: &[&str] = &[
|
||||
"move DIR SECONDS [--sprint] [--sneak] [--jump] walk forward|back|left|right",
|
||||
"jump jump once",
|
||||
"goto X Y Z [--near R] [--sprint] [--direct] [--timeout S] walk to a position along a path",
|
||||
"look-at X Y Z | look-at block X Y Z [FACE] | look-at entity ID",
|
||||
"look-at X Y Z | look-at block X Y Z [FACE] | look-at entity ID [--over S]",
|
||||
"turn DYAW DPITCH --over S rotate the view with mouse motion spread over S seconds",
|
||||
"mouse-move DX DY relative mouse motion, turned like a player's mouse",
|
||||
"attack [ID] swing at the target (after looking at entity ID)",
|
||||
"break X Y Z [--timeout S] mine a block until it breaks; reports drops and pickups",
|
||||
"place X Y Z [--item ITEM] place the held (or given) item at a position",
|
||||
@@ -69,7 +71,7 @@ pub(super) struct Args<'a> {
|
||||
pub flags: HashMap<&'a str, Option<&'a str>>,
|
||||
}
|
||||
/// Options that take a value (`--timeout 10` or `--timeout=10`).
|
||||
const VALUE_FLAGS: &[&str] = &["timeout", "near", "item", "radius", "hold", "face"];
|
||||
const VALUE_FLAGS: &[&str] = &["timeout", "near", "item", "radius", "hold", "face", "over"];
|
||||
|
||||
pub(super) fn parse_args<'a>(words: &[&'a str]) -> Args<'a> {
|
||||
let mut args = Args::default();
|
||||
@@ -257,9 +259,27 @@ struct Task {
|
||||
name: &'static str,
|
||||
}
|
||||
|
||||
/// Mouse motion an agent feeds over frames (`mouse-move`, `turn --over`,
|
||||
/// `look-at --over`): eased, through `MouseHandler`'s accumulated movement.
|
||||
struct Glide {
|
||||
/// The whole motion, in mouse units, and how much has been fed.
|
||||
total: (f64, f64),
|
||||
fed: (f64, f64),
|
||||
started: Instant,
|
||||
over: Duration,
|
||||
/// The frame count when motion was last fed: the reply waits for the
|
||||
/// frame that turns the view with it.
|
||||
fed_frame: u64,
|
||||
deadline: Instant,
|
||||
reply: Sender<String>,
|
||||
/// What `look-at` aimed at, reported once the turn is done.
|
||||
aim: Option<&'static str>,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
pub(super) struct Agent {
|
||||
task: Option<Task>,
|
||||
glide: Option<Glide>,
|
||||
}
|
||||
|
||||
pub(super) enum Handled {
|
||||
@@ -975,14 +995,32 @@ impl Game<'_> {
|
||||
};
|
||||
self.start_task("goto", TaskKind::Goto(Box::new(goto)), reply, timeout)
|
||||
}
|
||||
"mouse-move" => {
|
||||
self.turning()?;
|
||||
let motion = (a.f64(0, "DX")?, a.f64(1, "DY")?);
|
||||
self.start_glide(motion, 0.0, None, reply)
|
||||
}
|
||||
"turn" if a.has("over") => {
|
||||
self.turning()?;
|
||||
let (dyaw, dpitch) = (a.f64(0, "DYAW")?, a.f64(1, "DPITCH")?);
|
||||
let motion =
|
||||
horizon_client::mouse::motion_for_turn(dyaw, dpitch, self.look_options());
|
||||
self.start_glide(motion, a.num("over", 0.0)?, None, reply)
|
||||
}
|
||||
"look-at" => {
|
||||
self.need_world()?;
|
||||
match a.pos.first().copied() {
|
||||
let over = a.has("over").then(|| a.num("over", 0.0)).transpose()?;
|
||||
if over.is_some() {
|
||||
self.turning()?;
|
||||
}
|
||||
let before = (self.yaw, self.pitch);
|
||||
let (aim, value) = match a.pos.first().copied() {
|
||||
Some("block") => {
|
||||
let pos = a.block_pos(1)?;
|
||||
let face = a.pos.get(4).map(|f| face_dir(f)).transpose()?;
|
||||
let hit = self.aim_block(pos, face)?;
|
||||
ok(
|
||||
(
|
||||
"block",
|
||||
json!({ "ok": true, "yaw": self.yaw, "pitch": self.pitch, "face": face_name(hit) }),
|
||||
)
|
||||
}
|
||||
@@ -995,16 +1033,31 @@ impl Game<'_> {
|
||||
.ok_or_else(|| format!("no entity {id}"))?;
|
||||
let c = m.center();
|
||||
self.face_point(c)?;
|
||||
ok(
|
||||
(
|
||||
"entity",
|
||||
json!({ "ok": true, "yaw": self.yaw, "pitch": self.pitch, "target": self.looking_at() }),
|
||||
)
|
||||
}
|
||||
_ => {
|
||||
let at = [a.f64(0, "X")?, a.f64(1, "Y")?, a.f64(2, "Z")?];
|
||||
self.face_point(at)?;
|
||||
ok(json!({ "ok": true, "yaw": self.yaw, "pitch": self.pitch }))
|
||||
(
|
||||
"point",
|
||||
json!({ "ok": true, "yaw": self.yaw, "pitch": self.pitch }),
|
||||
)
|
||||
}
|
||||
}
|
||||
};
|
||||
let Some(over) = over else {
|
||||
return ok(value);
|
||||
};
|
||||
// Turn there with the mouse instead: the shorter way round.
|
||||
let target = (self.yaw, self.pitch);
|
||||
(self.yaw, self.pitch) = before;
|
||||
let dyaw = f64::from(target.0 - before.0 + 180.0).rem_euclid(360.0) - 180.0;
|
||||
let dpitch = f64::from(target.1 - before.1);
|
||||
let motion =
|
||||
horizon_client::mouse::motion_for_turn(dyaw, dpitch, self.look_options());
|
||||
self.start_glide(motion, over, Some(aim), reply)
|
||||
}
|
||||
"attack" => {
|
||||
self.playing()?;
|
||||
@@ -1334,6 +1387,13 @@ impl Game<'_> {
|
||||
);
|
||||
t.name
|
||||
});
|
||||
let turning = self.agent.glide.take().map(|g| {
|
||||
let _ = g.reply.send(
|
||||
json!({ "error": "cancelled by stop", "cancelled": true }).to_string(),
|
||||
);
|
||||
"turn"
|
||||
});
|
||||
let cancelled = cancelled.or(turning);
|
||||
self.release_agent_keys();
|
||||
ok(json!({ "ok": true, "cancelled": cancelled }))
|
||||
}
|
||||
@@ -1358,8 +1418,106 @@ impl Game<'_> {
|
||||
Err(format!("no {item} in the inventory").into())
|
||||
}
|
||||
|
||||
/// Mouse motion turns the view only in the world with no screen open
|
||||
/// (`MouseHandler` turns the player while the mouse is grabbed).
|
||||
fn turning(&self) -> Result<()> {
|
||||
self.playing()?;
|
||||
if self.agent.glide.is_some() {
|
||||
return Err("already turning; wait for it or send stop".into());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn start_glide(
|
||||
&mut self,
|
||||
total: (f64, f64),
|
||||
over: f64,
|
||||
aim: Option<&'static str>,
|
||||
reply: &Sender<String>,
|
||||
) -> Result<Handled> {
|
||||
if !over.is_finite() || !(0.0..=60.0).contains(&over) {
|
||||
return Err("--over takes 0 to 60 seconds".into());
|
||||
}
|
||||
if !(total.0.is_finite() && total.1.is_finite()) {
|
||||
return Err("the motion must be finite".into());
|
||||
}
|
||||
let now = Instant::now();
|
||||
let over = Duration::from_secs_f64(over);
|
||||
self.agent.glide = Some(Glide {
|
||||
total,
|
||||
fed: (0.0, 0.0),
|
||||
started: now,
|
||||
over,
|
||||
fed_frame: self.frames,
|
||||
deadline: now + over + Duration::from_secs(10),
|
||||
reply: reply.clone(),
|
||||
aim,
|
||||
});
|
||||
self.advance_glide();
|
||||
Ok(Handled::Deferred)
|
||||
}
|
||||
|
||||
/// Feed the motion due by now (eased over the glide's time); reply once
|
||||
/// all of it has been turned by a frame.
|
||||
fn advance_glide(&mut self) {
|
||||
let Some(mut g) = self.agent.glide.take() else {
|
||||
return;
|
||||
};
|
||||
let done = |game: &Self, extra: Value| {
|
||||
let mut v = json!({
|
||||
"ok": true,
|
||||
"yaw": game.yaw,
|
||||
"pitch": game.pitch,
|
||||
"motion": [g.total.0, g.total.1],
|
||||
});
|
||||
if let (Value::Object(m), Value::Object(e)) = (&mut v, extra) {
|
||||
m.extend(e);
|
||||
}
|
||||
v
|
||||
};
|
||||
if let Err(e) = self.playing() {
|
||||
let _ = g.reply.send(
|
||||
json!({ "error": format!("stopped turning: {e}"), "yaw": self.yaw, "pitch": self.pitch })
|
||||
.to_string(),
|
||||
);
|
||||
return;
|
||||
}
|
||||
let now = Instant::now();
|
||||
let t = if g.over.is_zero() {
|
||||
1.0
|
||||
} else {
|
||||
now.duration_since(g.started).as_secs_f64() / g.over.as_secs_f64()
|
||||
};
|
||||
let f = horizon_client::mouse::ease_in_out(t);
|
||||
let due = (g.total.0 * f, g.total.1 * f);
|
||||
let step = (due.0 - g.fed.0, due.1 - g.fed.1);
|
||||
if step != (0.0, 0.0) {
|
||||
self.mouse.add_motion(step.0, step.1);
|
||||
self.agent_pointer = true;
|
||||
g.fed = due;
|
||||
g.fed_frame = self.frames;
|
||||
}
|
||||
if t >= 1.0 && self.frames > g.fed_frame {
|
||||
let extra = match g.aim {
|
||||
Some("block") | Some("entity") => json!({ "target": self.looking_at() }),
|
||||
_ => json!({}),
|
||||
};
|
||||
let _ = g.reply.send(done(self, extra).to_string());
|
||||
return;
|
||||
}
|
||||
if now >= g.deadline {
|
||||
let _ = g.reply.send(
|
||||
json!({ "error": "no frame was drawn to turn the view", "yaw": self.yaw, "pitch": self.pitch })
|
||||
.to_string(),
|
||||
);
|
||||
return;
|
||||
}
|
||||
self.agent.glide = Some(g);
|
||||
}
|
||||
|
||||
/// Advance the running agent task; reply when it ends.
|
||||
pub(super) fn advance_agent(&mut self) {
|
||||
self.advance_glide();
|
||||
let Some(mut task) = self.agent.task.take() else {
|
||||
return;
|
||||
};
|
||||
|
||||
@@ -202,6 +202,13 @@ impl MouseLook {
|
||||
}
|
||||
}
|
||||
|
||||
/// `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)
|
||||
@@ -226,9 +233,7 @@ impl MouseLook {
|
||||
}
|
||||
|
||||
fn turn_player(&mut self, mousea: f64, look: LookOptions) -> (f64, f64) {
|
||||
let ss = look.sensitivity * f64::from(0.6f32) + f64::from(0.2f32);
|
||||
let sensitivity_mod = ss * ss * ss;
|
||||
let sens = sensitivity_mod * 8.0;
|
||||
let (sensitivity_mod, sens) = sensitivity_scales(look.sensitivity);
|
||||
let (xo, yo) = if look.smooth_camera {
|
||||
(
|
||||
self.smooth_turn_x
|
||||
@@ -274,9 +279,172 @@ impl MouseLook {
|
||||
}
|
||||
}
|
||||
|
||||
/// `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()
|
||||
}
|
||||
|
||||
#[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();
|
||||
|
||||
Reference in New Issue
Block a user