hit: the pointer meets laid device pixels through one grid, and the scale rule has one owner

Finding hit-seam-at-fractional-scale. covers() puts the point and every edge on the device grid (k times the
logical value, held to 1/1024 px) and tests half-open, so the first pixel past an edge is outside at scales 1.25,
1.5, 1.75, 2.5 and 3.0. render::device_scale is the one usable-scale rule; the wheel's copy in pointer.rs is
deleted (finding public-surface-and-scale-rule-twice, scale half). Test: first and last pixel of every leaf of
odd-width rows, corner and centre, at 1, 1.25, 1.5, 1.75, 2, 2.5 and 3.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Meta Vens 2026-11-29 05:40:47 +01:00
commit 6985991b4b
4 changed files with 121 additions and 30 deletions

View file

@ -1,6 +1,7 @@
//! Hit-testing: which node a point reaches, read from the geometry render placed and nothing else.
//! The point is in the space `Placed` is in (logical px, or cells), so this file applies no scale,
//! scroll or clip of its own: render already did, and `Placed::visible` is what the user could see.
//! The point is in the space `Placed` is in (logical px, or cells), so this file applies no scroll or
//! clip of its own: render already did, and `Placed::visible` is what the user could see. `k` (device px
//! per logical px, from `render::device_scale`) only puts point and edges on the device grid layout laid.
//! Paint order is the only layer order: the last placed node under the point wins, overlays are last,
//! and a modal overlay shuts out everything painted before it.
@ -51,12 +52,23 @@ pub(super) enum Reach {
Scrim(usize),
}
/// Half-open: a node's right and bottom edges belong to its neighbour.
fn covers(rect: Rect, (x, y): (f32, f32)) -> bool {
x >= rect.x && x < rect.x + rect.w && y >= rect.y && y < rect.y + rect.h
/// A coordinate on the device grid, held to 1/1024 px. Layout lays whole device pixels, render divides
/// them by the scale, and a pointer is that logical coordinate again: `k` times it is the device pixel
/// only up to the rounding error of dividing and multiplying back, which at a fractional scale is enough to
/// put the first pixel past an edge inside it. The grid is coarser than that error and finer than any
/// pixel, so an edge and a pointer that mean the same device position compare equal.
fn on_device(logical: f32, k: f32) -> f32 {
const GRID: f32 = 1024.0;
(logical * k * GRID).round() / GRID
}
pub(super) fn reach(rendered: &Rendered, laid: &LaidTree, index: &HashMap<&NodeId, &Node>, point: (f32, f32)) -> Option<Reach> {
/// Half-open on the device grid: a node's right and bottom edges belong to its neighbour.
fn covers(rect: Rect, (x, y): (f32, f32), k: f32) -> bool {
let (x, y) = (on_device(x, k), on_device(y, k));
x >= on_device(rect.x, k) && x < on_device(rect.x + rect.w, k) && y >= on_device(rect.y, k) && y < on_device(rect.y + rect.h, k)
}
pub(super) fn reach(rendered: &Rendered, laid: &LaidTree, index: &HashMap<&NodeId, &Node>, point: (f32, f32), k: f32) -> Option<Reach> {
// The last modal overlay root in paint order: nothing painted before it is reachable, and what
// is painted after it (its own subtree, then any later overlay) is.
let modal = laid
@ -67,7 +79,7 @@ pub(super) fn reach(rendered: &Rendered, laid: &LaidTree, index: &HashMap<&NodeI
// A non-modal overlay's root is only where its content is anchored: it is the viewport or the
// anchor's rect, not something drawn, so a press that misses the content goes on through it.
let transparent = |i: usize| laid.nodes[i].parent.is_none() && matches!(index.get(&laid.nodes[i].id), Some(Node::Overlay(_)));
let top = rendered.placed.iter().enumerate().skip(floor).rev().find(|(i, placed)| !transparent(*i) && placed.visible.is_some_and(|seen| covers(seen, point)));
let top = rendered.placed.iter().enumerate().skip(floor).rev().find(|(i, placed)| !transparent(*i) && placed.visible.is_some_and(|seen| covers(seen, point, k)));
match (top, modal) {
(Some((i, _)), _) => Some(Reach::Node(i)),
(None, Some(m)) => Some(Reach::Scrim(m)),
@ -77,8 +89,8 @@ pub(super) fn reach(rendered: &Rendered, laid: &LaidTree, index: &HashMap<&NodeI
/// The topmost node drawn at `point` (a modal's scrim when nothing in the modal is there), read
/// from the last good frame: what the user saw when they pressed.
pub fn hit_test(rendered: &Rendered, laid: &LaidTree, index: &HashMap<&NodeId, &Node>, point: (f32, f32)) -> Option<Hit> {
Some(match reach(rendered, laid, index, point)? {
pub fn hit_test(rendered: &Rendered, laid: &LaidTree, index: &HashMap<&NodeId, &Node>, point: (f32, f32), k: f32) -> Option<Hit> {
Some(match reach(rendered, laid, index, point, k)? {
Reach::Scrim(m) => Hit { node: laid.nodes[m].id.clone(), kind: HitKind::Scrim },
Reach::Node(i) => Hit { node: laid.nodes[i].id.clone(), kind: HitKind::Node },
})
@ -98,8 +110,8 @@ fn control_of(node: &Node) -> Option<Control> {
/// The node `point` activates: the nearest activatable node at or above the topmost one under it
/// (a Button's label hits the Button), or a modal's scrim. A point on a Box, on text outside a
/// control or on a non-modal overlay's root targets nothing.
pub fn target(rendered: &Rendered, laid: &LaidTree, index: &HashMap<&NodeId, &Node>, point: (f32, f32)) -> Option<Target> {
let mut at = match reach(rendered, laid, index, point)? {
pub fn target(rendered: &Rendered, laid: &LaidTree, index: &HashMap<&NodeId, &Node>, point: (f32, f32), k: f32) -> Option<Target> {
let mut at = match reach(rendered, laid, index, point, k)? {
Reach::Scrim(m) => return Some(Target { node: laid.nodes[m].id.clone(), control: Control::Scrim }),
Reach::Node(i) => Some(i),
};

View file

@ -12,7 +12,7 @@ use crate::command::{Activation, ActivationKind, Commands};
use crate::diagnostic::Diagnostic;
use crate::layout::{LaidTree, Metrics, Rect};
use crate::port::{IdSource, Ledger, StatePort};
use crate::render::{Rendered, ScrollOffsets, clamp};
use crate::render::{Rendered, ScrollOffsets, clamp, device_scale};
use crate::time::Timestamp;
/// The last good frame and how it was drawn: what every event is judged against.
@ -28,6 +28,13 @@ pub struct Seen<'a> {
pub line: f32,
}
impl Seen<'_> {
/// Device px per logical px, which is what a pointer is multiplied by to land on laid pixels.
fn k(&self) -> f32 {
device_scale(self.metrics, self.scale)
}
}
/// The owners an event writes through: activation, drafts and scroll positions.
pub struct Owners<'a> {
pub commands: &'a mut Commands,
@ -106,7 +113,7 @@ impl Input {
self.cancel(surface, owners.drafts);
let index = seen.tree.index();
let mut said = Vec::new();
self.pointer.press = target(seen.rendered, seen.laid, &index, at).and_then(|hit| match (hit.control, index.get(&hit.node)) {
self.pointer.press = target(seen.rendered, seen.laid, &index, at, seen.k()).and_then(|hit| match (hit.control, index.get(&hit.node)) {
(Control::Slider, Some(Node::Slider(slider))) => {
let value = placed_rect(seen.rendered, &hit.node).and_then(|rect| slider_value(slider, rect, at.0))?;
// A slider that takes no change takes no press: nothing is drafted, so nothing is left unsent.
@ -145,7 +152,7 @@ impl Input {
None => return Vec::new(),
},
Some(Press::Target(pressed)) => {
if target(seen.rendered, seen.laid, &seen.tree.index(), at).as_ref() != Some(&pressed) {
if target(seen.rendered, seen.laid, &seen.tree.index(), at, seen.k()).as_ref() != Some(&pressed) {
return Vec::new();
}
match pressed.control {
@ -170,10 +177,11 @@ impl Input {
/// modal only the modal's own subtree is reachable. Offsets are held in device px (Pixels) or cells.
fn wheel(at: (f32, f32), delta: (f32, f32), unit: WheelUnit, seen: &Seen<'_>, scroll: &mut ScrollOffsets) {
let index = seen.tree.index();
let Some(Reach::Node(start) | Reach::Scrim(start)) = reach(seen.rendered, seen.laid, &index, at) else { return };
let (to_device, line) = match seen.metrics {
Metrics::Cells => (1.0, 1.0),
Metrics::Pixels => (if seen.scale.is_finite() && seen.scale > 0.0 { seen.scale } else { 1.0 }, seen.line),
let Some(Reach::Node(start) | Reach::Scrim(start)) = reach(seen.rendered, seen.laid, &index, at, seen.k()) else { return };
let to_device = seen.k();
let line = match seen.metrics {
Metrics::Cells => 1.0,
Metrics::Pixels => seen.line,
};
let per = match unit {
WheelUnit::Units => to_device,

View file

@ -72,12 +72,18 @@ pub struct Rendered {
pub diagnostics: Vec<Diagnostic>,
}
/// Device px per logical px: the scale in Pixels when it is finite and positive, else 1; always 1 in
/// Cells. The one owner of the rule: render divides by it, and input multiplies by it.
pub(crate) fn device_scale(metrics: Metrics, scale: f32) -> f32 {
match metrics {
Metrics::Pixels if scale.is_finite() && scale > 0.0 => scale,
_ => 1.0,
}
}
pub fn render(tree: &BoundTree, laid: &LaidTree, input: &RenderInput, text: &mut dyn Measure) -> Rendered {
let nodes = tree.index();
let k = match input.metrics {
Metrics::Pixels if input.scale.is_finite() && input.scale > 0.0 => input.scale,
_ => 1.0,
};
let k = device_scale(input.metrics, input.scale);
let mut ids = HashMap::new();
for (i, node) in laid.nodes.iter().enumerate() {
ids.entry(&node.id).or_insert(i);

View file

@ -300,8 +300,20 @@ fn index_of(rig: &Rig) -> std::collections::HashMap<&NodeId, &Node> {
rig.tree.index()
}
/// Device px per logical px, as input holds it.
fn device_k(rig: &Rig) -> f32 {
match rig.metrics {
Metrics::Pixels => rig.scale,
Metrics::Cells => 1.0,
}
}
fn hit_node(rig: &Rig, at: (f32, f32)) -> Option<String> {
hit_test(&rig.rendered, &rig.laid, &index_of(rig), at).map(|hit| hit.node.as_str().to_string())
hit_test(&rig.rendered, &rig.laid, &index_of(rig), at, device_k(rig)).map(|hit| hit.node.as_str().to_string())
}
fn rig_target(rig: &Rig, at: (f32, f32)) -> Option<thing_core::input::Target> {
target(&rig.rendered, &rig.laid, &index_of(rig), at, device_k(rig))
}
// ----- hit-testing agrees with the laid geometry -----
@ -329,13 +341,13 @@ fn a_rect_is_half_open_so_a_shared_edge_belongs_to_the_second_node() {
let (a, b) = (rig.rect("a"), rig.rect("b"));
assert_eq!(a.y + a.h, b.y, "{mode:?}: the buttons touch");
let edge = (a.x + 0.5, b.y);
assert!(target(&rig.rendered, &rig.laid, &index_of(&rig), edge).is_some_and(|hit| hit.node.as_str() == "b"), "{mode:?}");
assert!(rig_target(&rig, edge).is_some_and(|hit| hit.node.as_str() == "b"), "{mode:?}");
let last = (a.x + 0.5, b.y - 0.25);
assert!(target(&rig.rendered, &rig.laid, &index_of(&rig), last).is_some_and(|hit| hit.node.as_str() == "a"), "{mode:?}");
assert!(rig_target(&rig, last).is_some_and(|hit| hit.node.as_str() == "a"), "{mode:?}");
let under = (b.x + 0.5, b.y + b.h);
assert_eq!(target(&rig.rendered, &rig.laid, &index_of(&rig), under), None, "{mode:?}: the bottom edge is outside");
assert_eq!(rig_target(&rig, under), None, "{mode:?}: the bottom edge is outside");
let beyond = (a.x + a.w, a.y + 0.5);
assert_ne!(target(&rig.rendered, &rig.laid, &index_of(&rig), beyond).map(|hit| hit.node), Some(nid("a")), "{mode:?}: the right edge is outside");
assert_ne!(rig_target(&rig, beyond).map(|hit| hit.node), Some(nid("a")), "{mode:?}: the right edge is outside");
}
}
@ -368,14 +380,67 @@ fn a_node_outside_its_clip_is_not_hit_where_its_rect_reaches_past_the_clip() {
assert!(tall.y + tall.h > frame.y + frame.h, "{mode:?}: the button runs past the clip");
let below = (tall.x + 0.5, frame.y + frame.h + 0.5);
assert!(below.1 < tall.y + tall.h);
assert_eq!(target(&rig.rendered, &rig.laid, &index_of(&rig), below), None, "{mode:?}");
assert_eq!(rig_target(&rig, below), None, "{mode:?}");
assert_ne!(hit_node(&rig, below).as_deref(), Some("tall"), "{mode:?}");
// Inside the clip it is hit.
let inside_clip = target(&rig.rendered, &rig.laid, &index_of(&rig), inside(frame));
let inside_clip = rig_target(&rig, inside(frame));
assert_eq!(inside_clip.map(|hit| hit.node.as_str().to_string()).as_deref(), Some("tall"), "{mode:?}");
}
}
// ----- the edge of a node, at a scale that does not divide -----
/// Rows of odd widths and heights, so edges fall between whole logical px at a fractional scale.
fn seam_surface() -> SurfaceDocument {
let row = |id: &str, h: f64, widths: &[f64]| {
let mut row = column(id, None, Overflow::Visible, widths.iter().enumerate().map(|(i, w)| fixed(&format!("{id}-{i}"), *w, h)).collect());
if let Node::Box(b) = &mut row {
b.style.direction = Direction::Row;
b.style.size = size2(Dimension::Percent(Scalar { value: 100.0 }), px(h));
b.style.justify_content = ContentAlign::Start;
}
row
};
surface(
column("root", None, Overflow::Visible, vec![
row("r0", 7.0, &[9.0, 14.0, 5.0, 31.0]),
row("r1", 13.0, &[11.0, 3.0, 17.0]),
row("r2", 5.0, &[6.0, 6.0, 6.0, 6.0, 7.0]),
row("r3", 19.0, &[23.0, 29.0, 13.0]),
]),
vec![],
)
}
#[test]
fn the_first_device_pixel_past_a_nodes_right_or_bottom_edge_is_not_the_node_at_every_scale() {
let scales = [1.0, 1.25, 1.5, 1.75, 2.0, 2.5, 3.0];
let modes = scales.map(|scale| (Metrics::Pixels, scale)).into_iter().chain([(Metrics::Cells, 1.0)]);
for mode in modes {
let rig = Rig::new(MemState::new(), &seam_surface(), mode);
let k = device_k(&rig);
let mut leaves = 0;
for node in rig.laid.nodes.iter().filter(|node| node.id.as_str().contains('-')) {
leaves += 1;
let (id, r) = (node.id.as_str(), node.rect);
assert!(r.w >= 1.0 && r.h >= 1.0 && r.x.fract() == 0.0 && r.y.fract() == 0.0, "{mode:?} {id}: laid in whole device px, {r:?}");
// Device pixels, as a host at this scale reports a pointer: the pixel's corner and its centre.
let at = |dx: f32, dy: f32, off: f32| ((dx + off) / k, (dy + off) / k);
for off in [0.0, 0.5] {
let last = at(r.x + r.w - 1.0, r.y + r.h - 1.0, off);
assert_eq!(hit_node(&rig, last).as_deref(), Some(id), "{mode:?} {id} the last pixel of the node, +{off}");
let right = at(r.x + r.w, r.y, off);
assert_ne!(hit_node(&rig, right).as_deref(), Some(id), "{mode:?} {id} the pixel right of the node, +{off}");
let below = at(r.x, r.y + r.h, off);
assert_ne!(hit_node(&rig, below).as_deref(), Some(id), "{mode:?} {id} the pixel below the node, +{off}");
let first = at(r.x, r.y, off);
assert_eq!(hit_node(&rig, first).as_deref(), Some(id), "{mode:?} {id} the first pixel of the node, +{off}");
}
}
assert_eq!(leaves, 15, "{mode:?}");
}
}
// ----- a non-modal overlay -----
fn nonmodal_surface(anchor: Anchor) -> SurfaceDocument {
@ -492,7 +557,7 @@ fn a_click_hits_the_row_drawn_there_after_a_scroll_and_not_a_row_scrolled_out()
let over = (pane.x + 0.5, gone.rect.y + 0.5);
assert!(over.1 < pane.y, "{mode:?}: the scrolled-out row is above the pane");
assert_ne!(hit_node(&rig, over).as_deref(), Some(first.as_str()), "{mode:?}");
assert_eq!(target(&rig.rendered, &rig.laid, &index_of(&rig), over), None, "{mode:?}");
assert_eq!(rig_target(&rig, over), None, "{mode:?}");
}
}