Use euclid::Scale to convert between physical and logical coord spaces

This commit is contained in:
meehl committed 2026-08-24 23:57:19 +02:00
1 parent 8ba72fd7df
commit 8d17f8e64f
12 files changed
+70 -155

No files matched your search

+2 -2
View File
@@ -1,7 +1,7 @@
use ahash::HashMap;
use crate::{
dpi::LogicalRect,
dpi::{LogicalRect, ScaleFactor},
draw_commands::DrawCommand,
renderer::{
Batch, RenderJob, Vertex,
@@ -68,7 +68,7 @@ impl BatchBuilder {
pub fn build_render_job(
commands: &[DrawCommand],
textures_delta: TexturesDelta,
scale_factor: f32,
scale_factor: ScaleFactor<f32>,
max_slots: u32,
) -> RenderJob {
profiling::scope!("build_render_job");
+4 -91
View File
@@ -1,6 +1,7 @@
use crate::math::{Point, Quad, Rect, Size, Vector};
use core::f32;
use num_traits::{Float, NumCast, ToPrimitive};
use euclid::Scale;
use num_traits::{Float, ToPrimitive};
pub struct LogicalScreenSpace;
pub struct PhysicalScreenSpace;
@@ -17,6 +18,8 @@ pub type PhysicalVector<T> = Vector<T, PhysicalScreenSpace>;
pub type PhysicalSize<T> = Size<T, PhysicalScreenSpace>;
pub type PhysicalRect<T> = Rect<T, PhysicalScreenSpace>;
pub type ScaleFactor<F> = Scale<F, LogicalScreenSpace, PhysicalScreenSpace>;
pub type NormalizedPoint = Point<f32, Normalized>;
pub type NormalizedRect = Rect<f32, Normalized>;
pub type NormalizedQuad = Quad<f32, Normalized>;
@@ -53,96 +56,6 @@ where
}
}
pub trait ConvertToLogical {
type Output<V>;
fn to_logical<V: NumCast, F: Float>(&self, scale_factor: F) -> Self::Output<V>;
}
pub trait ConvertToPhysical {
type Output<V>;
fn to_physical<V: NumCast, F: Float>(&self, scale_factor: F) -> Self::Output<V>;
}
#[inline]
pub fn validate_scale_factor<F: Float>(scale_factor: F) -> bool {
scale_factor.is_sign_positive() && scale_factor.is_normal()
}
impl<T> ConvertToLogical for PhysicalPoint<T>
where
T: Copy + std::ops::Div<Output = T> + ToPrimitive,
{
type Output<V> = LogicalPoint<V>;
#[inline]
fn to_logical<V: NumCast, F: Float>(&self, scale_factor: F) -> Self::Output<V> {
assert!(validate_scale_factor(scale_factor));
let x = F::from(self.x).unwrap() / scale_factor;
let y = F::from(self.y).unwrap() / scale_factor;
LogicalPoint::new(x, y).cast()
}
}
impl<T> ConvertToLogical for PhysicalSize<T>
where
T: Copy + std::ops::Div<Output = T> + ToPrimitive,
{
type Output<V> = LogicalSize<V>;
#[inline]
fn to_logical<V: NumCast, F: Float>(&self, scale_factor: F) -> Self::Output<V> {
assert!(validate_scale_factor(scale_factor));
let width = F::from(self.width).unwrap() / scale_factor;
let height = F::from(self.height).unwrap() / scale_factor;
LogicalSize::new(width, height).cast()
}
}
impl<T> ConvertToLogical for PhysicalRect<T>
where
T: Copy + std::ops::Div<Output = T> + ToPrimitive,
{
type Output<V> = LogicalRect<V>;
#[inline]
fn to_logical<V: NumCast, F: Float>(&self, scale_factor: F) -> Self::Output<V> {
assert!(validate_scale_factor(scale_factor));
let min = self.min.to_logical(scale_factor);
let max = self.max.to_logical(scale_factor);
LogicalRect::new(min, max)
}
}
impl<T> ConvertToPhysical for LogicalPoint<T>
where
T: Copy + std::ops::Div<Output = T> + ToPrimitive,
{
type Output<V> = PhysicalPoint<V>;
#[inline]
fn to_physical<V: NumCast, F: Float>(&self, scale_factor: F) -> Self::Output<V> {
assert!(validate_scale_factor(scale_factor));
let x = F::from(self.x).unwrap() * scale_factor;
let y = F::from(self.y).unwrap() * scale_factor;
PhysicalPoint::new(x, y).cast()
}
}
impl<T> ConvertToPhysical for LogicalRect<T>
where
T: Copy + std::ops::Div<Output = T> + ToPrimitive,
{
type Output<V> = PhysicalRect<V>;
#[inline]
fn to_physical<V: NumCast, F: Float>(&self, scale_factor: F) -> Self::Output<V> {
assert!(validate_scale_factor(scale_factor));
let min = self.min.to_physical(scale_factor);
let max = self.max.to_physical(scale_factor);
PhysicalRect::new(min, max)
}
}
pub trait Uv {
fn default_uv() -> Self;
fn white_uv() -> Self;
+2 -2
View File
@@ -56,8 +56,8 @@ impl DrawCommandRecorder {
self.current_viewport = viewport;
}
pub fn set_viewport_from_size(&mut self, size: LogicalSize<u32>) {
self.set_viewport(LogicalRect::from_size(size).cast());
pub fn set_viewport_from_size(&mut self, size: LogicalSize<f32>) {
self.set_viewport(LogicalRect::from_size(size));
}
pub fn set_draw_layer(&mut self, layer: i32, sublayer: i32) {
+7 -7
View File
@@ -1,6 +1,6 @@
use crate::{
color::Srgba,
dpi::LogicalVector,
dpi::{LogicalVector, ScaleFactor},
fonts::{
atlas::FontAtlas, glyph_key::SubpixelBin, layout::PositionedGlyph,
layout_cache::LayoutCache, rasterizer::GlyphRasterizer,
@@ -176,7 +176,7 @@ impl Fonts {
&mut self.atlas,
&run,
LogicalVector::new(horizontal_offset, 0.0),
1.0,
ScaleFactor::identity(),
)
.for_each(|_| {});
}
@@ -184,21 +184,21 @@ impl Fonts {
}
}
pub fn layout(&mut self, job: LayoutJob, pixels_per_point: f32) -> Rc<Layout> {
let hash = calculate_hash(&(&job, OrderedFloat(pixels_per_point)));
pub fn layout(&mut self, job: LayoutJob, scale_factor: ScaleFactor<f32>) -> Rc<Layout> {
let hash = calculate_hash(&(&job, OrderedFloat(scale_factor.get())));
if let Some(cached_layout) = self.layout_cache.get(hash) {
return cached_layout;
}
let layout = Rc::new(self.build_layout(job, pixels_per_point));
let layout = Rc::new(self.build_layout(job, scale_factor));
self.layout_cache.insert(hash, Rc::clone(&layout));
layout
}
fn build_layout(&mut self, job: LayoutJob, pixels_per_point: f32) -> Layout {
fn build_layout(&mut self, job: LayoutJob, scale_factor: ScaleFactor<f32>) -> Layout {
let default_style = TextStyle::default();
let style = TextStyle {
font_family: job.font_family,
@@ -255,7 +255,7 @@ impl Fonts {
&mut self.atlas,
&run,
glyph_offset,
pixels_per_point,
scale_factor,
) {
let Some(glyph) = rasterized_glyph else {
continue;
+5 -5
View File
@@ -8,19 +8,19 @@ pub struct GlyphKey {
glyph_id: swash::GlyphId,
style_id: StyleId,
x_bin: SubpixelBin<4>,
pixels_per_point: OrderedFloat<f32>,
scale_factor: OrderedFloat<f32>,
}
impl GlyphKey {
pub fn from_glyph(
glyph: &Glyph,
style_id: StyleId,
pixels_per_point: f32,
scale_factor: f32,
) -> (Self, PhysicalPoint<i32>) {
// Use subpixel binning for x coordinate
let (x, x_bin) = SubpixelBin::<4>::new(glyph.x * pixels_per_point);
let (x, x_bin) = SubpixelBin::<4>::new(glyph.x * scale_factor);
// No binning for y coordinate, just rounding
let y = (glyph.y * pixels_per_point).round() as i32;
let y = (glyph.y * scale_factor).round() as i32;
let glyph_pos = PhysicalPoint::new(x, y);
(
@@ -28,7 +28,7 @@ impl GlyphKey {
glyph_id: glyph.id as u16,
style_id,
x_bin,
pixels_per_point: OrderedFloat(pixels_per_point),
scale_factor: OrderedFloat(scale_factor),
},
glyph_pos,
)
+9 -9
View File
@@ -1,8 +1,8 @@
use crate::{
color::Srgba,
dpi::{
ConvertToLogical, LogicalRect, LogicalVector, NormalizedRect, PhysicalPoint, PhysicalRect,
PhysicalVector,
LogicalRect, LogicalVector, NormalizedRect, PhysicalPoint, PhysicalRect, PhysicalVector,
ScaleFactor,
},
fonts::{atlas::FontAtlas, glyph_key::GlyphKey},
math::Size,
@@ -71,7 +71,7 @@ impl RasterizedGlyph {
cached: CachedGlyph,
position: PhysicalPoint<i32>,
color: Srgba,
pixels_per_point: f32,
scale_factor: ScaleFactor<f32>,
) -> Self {
let glyph_rect = PhysicalRect::from_origin_and_size(
position + cached.baseline_offset,
@@ -79,7 +79,7 @@ impl RasterizedGlyph {
);
RasterizedGlyph {
rect: glyph_rect.to_logical(pixels_per_point),
rect: glyph_rect.cast() / scale_factor,
uv: cached.uv,
texture_layer_idx: cached.texture_layer_idx,
color,
@@ -161,11 +161,11 @@ impl GlyphRasterizer {
glyph_run: &'run GlyphRun<'_, Srgba>,
// additional offset relative to layout origin
glyph_offset: LogicalVector<f32>,
pixels_per_point: f32,
scale_factor: ScaleFactor<f32>,
) -> impl Iterator<Item = Option<RasterizedGlyph>> + use<'slf, 'run, 'atlas> {
let run = glyph_run.run();
let color = glyph_run.style().brush;
let font_size = run.font_size() * pixels_per_point;
let font_size = run.font_size() * scale_factor.get();
let normalized_coords = run.normalized_coords();
let skew = run.synthesis().skew(); // skew angle for faux italic
@@ -192,11 +192,11 @@ impl GlyphRasterizer {
glyph.x += glyph_offset.x;
glyph.y += glyph_offset.y;
let (glyph_key, glyph_pos) = GlyphKey::from_glyph(&glyph, style_id, pixels_per_point);
let (glyph_key, glyph_pos) = GlyphKey::from_glyph(&glyph, style_id, scale_factor.get());
if let Some(cached_glyph) = cached_glyphs.get(&glyph_key) {
return cached_glyph.map(|cached| {
RasterizedGlyph::from_cached(cached, glyph_pos, color, pixels_per_point)
RasterizedGlyph::from_cached(cached, glyph_pos, color, scale_factor)
});
}
@@ -234,7 +234,7 @@ impl GlyphRasterizer {
cached_glyph,
glyph_pos,
color,
pixels_per_point,
scale_factor,
))
})
}
+2 -2
View File
@@ -6,7 +6,7 @@ use winit::window::Window;
use crate::{
args::Args,
dpi::{ConvertToLogical, PhysicalPoint},
dpi::PhysicalPoint,
draw_commands::DrawCommandRecorder,
fonts::Fonts,
input::{InputState, key_as_str, mousebutton_as_str},
@@ -80,7 +80,7 @@ impl Context {
fn set_mouse_pos(&mut self, pos: PhysicalPoint<f32>) {
self.input_state
.set_mouse_pos(pos.to_logical(self.window_state.scale_factor()));
.set_mouse_pos(pos / self.window_state.scale_factor());
}
}
+4 -7
View File
@@ -1,6 +1,6 @@
use crate::{
color::Srgba,
dpi::{ConvertToLogical, ConvertToPhysical, LogicalPoint},
dpi::LogicalPoint,
fonts::{Alignment, FontStyle, LayoutJob},
math::{Point, Quad, Rect, Size},
pob::Context,
@@ -357,13 +357,10 @@ unsafe extern "C-unwind" fn draw_string(state: *mut ffi::lua_State) -> c_int {
}
// Align layout origin with the physical pixel grid to reduce blurriness
let pixels_per_point = ctx.window_state.scale_factor();
let position = position
.to_physical::<f32, _>(pixels_per_point)
.round()
.to_logical(pixels_per_point);
let scale_factor = ctx.window_state.scale_factor();
let position = (position * scale_factor).round() / scale_factor;
let layout = ctx.fonts.borrow_mut().layout(job, pixels_per_point);
let layout = ctx.fonts.borrow_mut().layout(job, scale_factor);
for glyph in &layout.glyphs {
ctx.recorder.draw_glyph(
glyph.rect.translate(position.to_vector()),
+7 -5
View File
@@ -10,7 +10,7 @@ pub fn get_screen_size(l: &Lua, _: ()) -> LuaResult<(u32, u32)> {
let PhysicalSize { width, height, .. } = ctx.window_state.size;
(width, height)
} else {
let LogicalSize { width, height, .. } = ctx.window_state.logical_size();
let LogicalSize { width, height, .. } = ctx.window_state.logical_size().cast();
(width, height)
};
Ok(size)
@@ -19,7 +19,7 @@ pub fn get_screen_size(l: &Lua, _: ()) -> LuaResult<(u32, u32)> {
pub fn get_screen_scale(l: &Lua, _: ()) -> LuaResult<f32> {
let ctx = l.app_data_ref::<Context>().unwrap();
let scale_factor = ctx.window_state.scale_factor();
Ok(scale_factor)
Ok(scale_factor.get())
}
pub fn set_window_title(l: &Lua, title: String) -> LuaResult<()> {
@@ -37,8 +37,10 @@ pub fn set_foreground(l: &Lua, _: ()) -> LuaResult<()> {
pub fn set_dpi_scale_override(l: &Lua, percent: i32) -> LuaResult<()> {
let mut ctx = l.app_data_mut::<Context>().unwrap();
match percent {
0 => ctx.window_state.scale_factor_override = None,
p if p > 0 => ctx.window_state.scale_factor_override = Some(p as f32 / 100.0),
0 => ctx.window_state.set_scale_factor_override(None),
p if p > 0 => ctx
.window_state
.set_scale_factor_override(Some(p as f32 / 100.0)),
_ => {}
}
Ok(())
@@ -46,7 +48,7 @@ pub fn set_dpi_scale_override(l: &Lua, percent: i32) -> LuaResult<()> {
pub fn get_dpi_scale_override(l: &Lua, _: ()) -> LuaResult<i32> {
let ctx = l.app_data_ref::<Context>().unwrap();
match ctx.window_state.scale_factor_override {
match ctx.window_state.scale_factor_override() {
Some(scale_factor) => Ok((scale_factor * 100.0) as i32),
None => Ok(0),
}
+9 -14
View File
@@ -1,8 +1,8 @@
use crate::{
color::Srgba,
dpi::{
ConvertToLogical, ConvertToPhysical, LogicalPoint, LogicalRect, LogicalSize,
NormalizedPoint, PhysicalRect, PhysicalSize,
LogicalPoint, LogicalRect, LogicalSize, NormalizedPoint, PhysicalRect, PhysicalSize,
ScaleFactor,
},
math::Point,
renderer::{
@@ -52,7 +52,7 @@ pub struct RenderJob {
pub indices: Vec<u32>,
pub batches: Vec<Batch>,
pub textures_delta: TexturesDelta,
pub scale_factor: f32,
pub scale_factor: ScaleFactor<f32>,
}
#[derive(Debug)]
@@ -255,7 +255,7 @@ impl Renderer {
render_pass: &mut wgpu::RenderPass<'static>,
render_job: &RenderJob,
screen_size: PhysicalSize<u32>,
pixels_per_point: f32,
scale_factor: ScaleFactor<f32>,
) {
profiling::scope!("render");
@@ -282,15 +282,10 @@ impl Renderer {
render_pass.set_bind_group(1, bind_group, &[]);
// scissor
let phys_clip_rect = batch
.clip_rect
.to_physical::<f32, _>(pixels_per_point)
.round();
let phys_clip_rect = batch.clip_rect * scale_factor;
let scissor = phys_clip_rect
// NOTE: can't cast to u32 directly because negative values cause a panic
.cast::<i32>()
.intersection(&screen_rect.to_i32())
.map(|s| s.to_u32());
.intersection(&screen_rect.cast())
.map(|s| s.round().to_u32());
// skip batch if scissor doesn't intersect screen
let Some(scissor) = scissor else {
@@ -420,12 +415,12 @@ impl Renderer {
queue: &wgpu::Queue,
render_job: &RenderJob,
screen_size: PhysicalSize<u32>,
pixels_per_point: f32,
scale_factor: ScaleFactor<f32>,
) {
profiling::scope!("update_buffers");
let uniform_buffer_content = Globals {
screen_size: screen_size.to_logical(pixels_per_point),
screen_size: screen_size.cast() / scale_factor,
};
// update globals uniform buffer
+2 -2
View File
@@ -3,7 +3,7 @@ use std::sync::Arc;
use winit::window::Window;
use crate::{
dpi::{PhysicalPoint, PhysicalSize},
dpi::{PhysicalPoint, PhysicalSize, ScaleFactor},
draw_commands::DrawCommand,
installer::Installer,
pob::PathOfBuilding,
@@ -55,7 +55,7 @@ pub struct StageFrameOutput {
pub draw_commands: Vec<DrawCommand>,
pub can_elide: bool,
pub request_redraw: bool,
pub scale_factor: f32,
pub scale_factor: ScaleFactor<f32>,
}
pub enum ActiveStage {
+17 -9
View File
@@ -1,6 +1,6 @@
use crate::{
clipboard::Clipboard,
dpi::{ConvertToLogical, LogicalSize, PhysicalSize},
dpi::{LogicalSize, PhysicalSize, ScaleFactor},
};
use raw_window_handle::HasDisplayHandle;
use std::sync::Arc;
@@ -11,8 +11,8 @@ pub struct WindowState {
clipboard: Option<Clipboard>,
pub window: Option<Arc<Window>>,
pub size: PhysicalSize<u32>,
scale_factor: f32,
pub scale_factor_override: Option<f32>,
scale_factor: ScaleFactor<f32>,
scale_factor_override: Option<ScaleFactor<f32>>,
pending_window_title: std::cell::Cell<Option<String>>,
pub is_hovered: bool,
pub is_focused: bool,
@@ -23,7 +23,7 @@ impl Default for WindowState {
Self {
window: None,
size: Default::default(),
scale_factor: 1.0,
scale_factor: ScaleFactor::identity(),
scale_factor_override: None,
pending_window_title: std::cell::Cell::new(None),
clipboard: None,
@@ -41,7 +41,7 @@ impl WindowState {
let winit::dpi::PhysicalSize { width, height } = window.inner_size();
self.size = PhysicalSize::new(width, height);
self.scale_factor = window.scale_factor() as f32;
self.scale_factor = ScaleFactor::new(window.scale_factor() as f32);
let raw_display_handle = window.display_handle().ok().map(|h| h.as_raw());
self.clipboard = Some(Clipboard::new(raw_display_handle));
@@ -56,16 +56,24 @@ impl WindowState {
}
}
pub fn logical_size(&self) -> LogicalSize<u32> {
self.size.to_logical(self.scale_factor())
pub fn logical_size(&self) -> LogicalSize<f32> {
self.size.cast() / self.scale_factor()
}
pub fn scale_factor(&self) -> f32 {
pub fn scale_factor(&self) -> ScaleFactor<f32> {
self.scale_factor_override.unwrap_or(self.scale_factor)
}
pub fn set_scale_factor(&mut self, scale_factor: f32) {
self.scale_factor = scale_factor;
self.scale_factor = ScaleFactor::new(scale_factor);
}
pub fn scale_factor_override(&self) -> Option<f32> {
self.scale_factor_override.map(|s| s.get())
}
pub fn set_scale_factor_override(&mut self, scale_factor: Option<f32>) {
self.scale_factor_override = scale_factor.map(ScaleFactor::new);
}
pub fn focus(&self) {