#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct FontHandle(pub usize);
#[derive(Debug, Clone, Copy, PartialEq)]
#[non_exhaustive]
pub struct TextStyle {
pub font: Option<FontHandle>,
pub size: f32,
pub sizing: TextSizing,
}
impl Default for TextStyle {
fn default() -> Self {
Self {
font: None,
size: 14.0,
sizing: TextSizing::Screen,
}
}
}
impl TextStyle {
pub fn new(size: f32) -> Self {
Self {
font: None,
size,
sizing: TextSizing::Screen,
}
}
pub fn with_font(mut self, font: FontHandle) -> Self {
self.font = Some(font);
self
}
pub fn with_size(mut self, size: f32) -> Self {
self.size = size;
self
}
pub fn with_sizing(mut self, sizing: TextSizing) -> Self {
self.sizing = sizing;
self
}
pub fn resolve_screen_size_at(
&self,
anchor: &crate::overlay::OverlayOrigin,
viewport: [f32; 2],
pixels_per_point: f32,
view: &glam::Mat4,
proj: &glam::Mat4,
world_origin: glam::DVec3,
) -> Option<TextFit> {
let TextSizing::World(world) = self.sizing else {
return Some(TextFit {
size: self.size,
opacity: 1.0,
});
};
let view_proj = *proj * *view;
let point = match anchor {
crate::overlay::OverlayOrigin::World(p) => (*p - world_origin).as_vec3(),
crate::overlay::OverlayOrigin::Viewport(a) => {
let at = [a.x.coord(viewport[0]), a.y.coord(viewport[1])];
screen_point_on_plane(&view_proj, at, viewport, world, world_origin)?
}
};
let per_unit = plane_px_per_unit(&view_proj, world.plane, point, viewport)?;
let fit = world.fit(self.size, per_unit)?;
let ppp = pixels_per_point.max(1.0e-6);
Some(TextFit {
size: TextSizing::step_px(fit.size * ppp) / ppp,
opacity: fit.opacity,
})
}
}
#[derive(Debug, Clone, Copy, PartialEq, Default)]
#[non_exhaustive]
pub enum TextSizing {
#[default]
Screen,
World(WorldTextSize),
}
impl TextSizing {
pub const STEP: f32 = 1.04;
pub fn step_px(px: f32) -> f32 {
if !(px > 0.0) || !px.is_finite() {
return px.max(0.0);
}
let steps = ((px / 48.0).ln() / Self::STEP.ln()).round();
48.0 * Self::STEP.powf(steps)
}
}
#[derive(Debug, Clone, Copy, PartialEq)]
#[non_exhaustive]
pub struct WorldTextSize {
pub plane: crate::overlay::WorldPlane,
pub elevation: f32,
pub min_px: Option<f32>,
pub max_px: Option<f32>,
pub fade_px: Option<[f32; 2]>,
}
impl Default for WorldTextSize {
fn default() -> Self {
Self {
plane: crate::overlay::WorldPlane::Xy,
elevation: 0.0,
min_px: None,
max_px: None,
fade_px: None,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq)]
#[non_exhaustive]
pub struct TextFit {
pub size: f32,
pub opacity: f32,
}
impl WorldTextSize {
pub fn new(plane: crate::overlay::WorldPlane) -> Self {
Self {
plane,
..Self::default()
}
}
pub fn with_elevation(mut self, elevation: f32) -> Self {
self.elevation = elevation;
self
}
pub fn with_min_px(mut self, px: f32) -> Self {
self.min_px = Some(px);
self
}
pub fn with_max_px(mut self, px: f32) -> Self {
self.max_px = Some(px);
self
}
pub fn with_fade_px(mut self, gone: f32, full: f32) -> Self {
self.fade_px = Some([gone, full]);
self
}
pub fn fit(&self, height: f32, px_per_unit: f32) -> Option<TextFit> {
let raw = height * px_per_unit;
if !raw.is_finite() {
return None;
}
let mut size = raw;
if let Some(max) = self.max_px {
size = size.min(max);
}
if let Some(min) = self.min_px {
size = size.max(min);
}
let opacity = match self.fade_px {
Some([gone, full]) if full > gone => ((raw - gone) / (full - gone)).clamp(0.0, 1.0),
Some([gone, _]) => {
if raw > gone {
1.0
} else {
0.0
}
}
None => 1.0,
};
Some(TextFit { size, opacity })
}
}
pub fn plane_px_per_unit(
view_proj: &glam::Mat4,
plane: crate::overlay::WorldPlane,
point: glam::Vec3,
viewport: [f32; 2],
) -> Option<f32> {
let c = *view_proj * point.extend(1.0);
if !(c.w > 1.0e-12) {
return None;
}
let d = |axis: glam::Vec3| {
let a = *view_proj * axis.extend(0.0);
glam::Vec2::new(
(a.x * c.w - c.x * a.w) / (c.w * c.w) * viewport[0] * 0.5,
(a.y * c.w - c.y * a.w) / (c.w * c.w) * viewport[1] * 0.5,
)
};
let du = d(plane.x_axis());
let dv = d(plane.y_axis());
let area = (du.x * dv.y - du.y * dv.x).abs();
let per_unit = area.sqrt();
(per_unit.is_finite() && per_unit > 0.0).then_some(per_unit)
}
fn screen_point_on_plane(
view_proj: &glam::Mat4,
at: [f32; 2],
viewport: [f32; 2],
world: WorldTextSize,
world_origin: glam::DVec3,
) -> Option<glam::Vec3> {
let inv = view_proj.inverse();
let ndc = glam::Vec2::new(
at[0] / viewport[0].max(1.0e-6) * 2.0 - 1.0,
1.0 - at[1] / viewport[1].max(1.0e-6) * 2.0,
);
let a = inv.project_point3(ndc.extend(0.3));
let b = inv.project_point3(ndc.extend(0.7));
let dir = b - a;
let n = world.plane.normal();
let denom = dir.dot(n);
if denom.abs() < 1.0e-12 {
return None;
}
let offset = world.elevation - world_origin.dot(n.as_dvec3()) as f32;
let t = (offset - a.dot(n)) / denom;
let p = a + dir * t;
p.is_finite().then_some(p)
}
#[cfg(test)]
mod tests {
use super::*;
use crate::overlay::{OverlayOrigin, WorldPlane};
fn ortho(upp: f32, px: [f32; 2]) -> (glam::Mat4, glam::Mat4) {
let hw = px[0] * 0.5 * upp;
let hh = px[1] * 0.5 * upp;
let proj = glam::Mat4::orthographic_rh(-hw, hw, -hh, hh, 0.1, 100.0);
let view = glam::Mat4::look_at_rh(
glam::Vec3::new(1.0, 2.0, 10.0),
glam::Vec3::new(1.0, 2.0, 0.0),
glam::Vec3::Y,
);
(view, proj)
}
#[test]
fn world_text_is_its_height_times_the_pixels_per_unit_and_clamped() {
let px = [640.0, 360.0];
let style = TextStyle::new(2.0).with_sizing(TextSizing::World(
WorldTextSize::new(WorldPlane::Xy)
.with_min_px(10.0)
.with_max_px(48.0),
));
let anchor = OverlayOrigin::World(glam::DVec3::new(1.5, 2.5, 0.0));
for (per_unit, expect) in [(4.0_f32, 10.0_f32), (12.0, 24.0), (40.0, 48.0)] {
let (view, proj) = ortho(1.0 / per_unit, px);
let measured = plane_px_per_unit(
&(proj * view),
WorldPlane::Xy,
glam::Vec3::new(1.5, 2.5, 0.0),
px,
)
.unwrap();
assert!(
(measured - per_unit).abs() / per_unit < 1.0e-4,
"{measured}"
);
let exact = match style.sizing {
TextSizing::World(w) => w.fit(style.size, measured).unwrap(),
TextSizing::Screen => unreachable!(),
};
assert!(
(exact.size - expect).abs() < 1.0e-3,
"{per_unit}: {exact:?}"
);
let drawn = style
.resolve_screen_size_at(&anchor, px, 2.0, &view, &proj, glam::DVec3::ZERO)
.unwrap();
assert!((drawn.size - expect).abs() <= expect * 0.021, "{drawn:?}");
let device = drawn.size * 2.0;
assert!((TextSizing::step_px(device) - device).abs() < 1.0e-3);
}
let free = WorldTextSize::new(WorldPlane::Xy);
for per_unit in [3.0_f32, 17.0, 90.0] {
assert_eq!(free.fit(2.0, per_unit).unwrap().size, 2.0 * per_unit);
}
}
#[test]
fn fade_runs_on_the_unclamped_size() {
let w = WorldTextSize::new(WorldPlane::Xy)
.with_min_px(10.0)
.with_fade_px(4.0, 8.0);
assert_eq!(
w.fit(1.0, 2.0).unwrap(),
TextFit {
size: 10.0,
opacity: 0.0
}
);
assert_eq!(
w.fit(1.0, 6.0).unwrap(),
TextFit {
size: 10.0,
opacity: 0.5
}
);
assert_eq!(
w.fit(1.0, 20.0).unwrap(),
TextFit {
size: 20.0,
opacity: 1.0
}
);
}
#[test]
fn steps_are_a_ratio_ladder_through_48() {
assert_eq!(TextSizing::step_px(48.0), 48.0);
assert!((TextSizing::step_px(49.0) - 48.0 * 1.04).abs() < 1.0e-3);
let mut px = 6.0_f32;
while px < 400.0 {
let s = TextSizing::step_px(px);
assert!((s - px).abs() <= px * 0.0201, "{px} -> {s}");
px += 0.37;
}
}
#[test]
fn a_viewport_anchor_measures_where_its_ray_meets_the_plane() {
let px = [400.0, 300.0];
let proj = glam::Mat4::perspective_rh(0.8, px[0] / px[1], 0.1, 100.0);
let view = glam::Mat4::look_at_rh(
glam::Vec3::new(0.0, -6.0, 6.0),
glam::Vec3::ZERO,
glam::Vec3::Z,
);
let world = WorldTextSize::new(WorldPlane::Xy);
let centre = OverlayOrigin::Viewport(crate::overlay::Alignment::new(
crate::overlay::AnchorX::Middle,
crate::overlay::AnchorY::Middle,
));
let style = TextStyle::new(1.0).with_sizing(TextSizing::World(world));
let a = style
.resolve_screen_size_at(¢re, px, 1.0, &view, &proj, glam::DVec3::ZERO)
.unwrap();
let b = style
.resolve_screen_size_at(
&OverlayOrigin::World(glam::DVec3::ZERO),
px,
1.0,
&view,
&proj,
glam::DVec3::ZERO,
)
.unwrap();
assert!((a.size - b.size).abs() < 1.0e-2, "{a:?} {b:?}");
}
}