diff --git a/src/batcher.rs b/src/batcher.rs index 2195660..a1c2687 100644 --- a/src/batcher.rs +++ b/src/batcher.rs @@ -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, max_slots: u32, ) -> RenderJob { profiling::scope!("build_render_job"); diff --git a/src/dpi.rs b/src/dpi.rs index f528e99..4cf78ff 100644 --- a/src/dpi.rs +++ b/src/dpi.rs @@ -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 = Vector; pub type PhysicalSize = Size; pub type PhysicalRect = Rect; +pub type ScaleFactor = Scale; + pub type NormalizedPoint = Point; pub type NormalizedRect = Rect; pub type NormalizedQuad = Quad; @@ -53,96 +56,6 @@ where } } -pub trait ConvertToLogical { - type Output; - fn to_logical(&self, scale_factor: F) -> Self::Output; -} - -pub trait ConvertToPhysical { - type Output; - fn to_physical(&self, scale_factor: F) -> Self::Output; -} - -#[inline] -pub fn validate_scale_factor(scale_factor: F) -> bool { - scale_factor.is_sign_positive() && scale_factor.is_normal() -} - -impl ConvertToLogical for PhysicalPoint -where - T: Copy + std::ops::Div + ToPrimitive, -{ - type Output = LogicalPoint; - - #[inline] - fn to_logical(&self, scale_factor: F) -> Self::Output { - 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 ConvertToLogical for PhysicalSize -where - T: Copy + std::ops::Div + ToPrimitive, -{ - type Output = LogicalSize; - - #[inline] - fn to_logical(&self, scale_factor: F) -> Self::Output { - 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 ConvertToLogical for PhysicalRect -where - T: Copy + std::ops::Div + ToPrimitive, -{ - type Output = LogicalRect; - - #[inline] - fn to_logical(&self, scale_factor: F) -> Self::Output { - 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 ConvertToPhysical for LogicalPoint -where - T: Copy + std::ops::Div + ToPrimitive, -{ - type Output = PhysicalPoint; - - #[inline] - fn to_physical(&self, scale_factor: F) -> Self::Output { - 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 ConvertToPhysical for LogicalRect -where - T: Copy + std::ops::Div + ToPrimitive, -{ - type Output = PhysicalRect; - - #[inline] - fn to_physical(&self, scale_factor: F) -> Self::Output { - 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; diff --git a/src/draw_commands.rs b/src/draw_commands.rs index 06a54d9..69e7ce5 100644 --- a/src/draw_commands.rs +++ b/src/draw_commands.rs @@ -56,8 +56,8 @@ impl DrawCommandRecorder { self.current_viewport = viewport; } - pub fn set_viewport_from_size(&mut self, size: LogicalSize) { - self.set_viewport(LogicalRect::from_size(size).cast()); + pub fn set_viewport_from_size(&mut self, size: LogicalSize) { + self.set_viewport(LogicalRect::from_size(size)); } pub fn set_draw_layer(&mut self, layer: i32, sublayer: i32) { diff --git a/src/fonts.rs b/src/fonts.rs index ec37a5e..6ff8195 100644 --- a/src/fonts.rs +++ b/src/fonts.rs @@ -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 { - let hash = calculate_hash(&(&job, OrderedFloat(pixels_per_point))); + pub fn layout(&mut self, job: LayoutJob, scale_factor: ScaleFactor) -> Rc { + 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) -> 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; diff --git a/src/fonts/glyph_key.rs b/src/fonts/glyph_key.rs index 46bf36a..353d25d 100644 --- a/src/fonts/glyph_key.rs +++ b/src/fonts/glyph_key.rs @@ -8,19 +8,19 @@ pub struct GlyphKey { glyph_id: swash::GlyphId, style_id: StyleId, x_bin: SubpixelBin<4>, - pixels_per_point: OrderedFloat, + scale_factor: OrderedFloat, } impl GlyphKey { pub fn from_glyph( glyph: &Glyph, style_id: StyleId, - pixels_per_point: f32, + scale_factor: f32, ) -> (Self, PhysicalPoint) { // 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, ) diff --git a/src/fonts/rasterizer.rs b/src/fonts/rasterizer.rs index e9543a7..d44a249 100644 --- a/src/fonts/rasterizer.rs +++ b/src/fonts/rasterizer.rs @@ -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, color: Srgba, - pixels_per_point: f32, + scale_factor: ScaleFactor, ) -> 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, - pixels_per_point: f32, + scale_factor: ScaleFactor, ) -> impl Iterator> + 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, )) }) } diff --git a/src/pob.rs b/src/pob.rs index 1718d29..b217a11 100644 --- a/src/pob.rs +++ b/src/pob.rs @@ -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) { self.input_state - .set_mouse_pos(pos.to_logical(self.window_state.scale_factor())); + .set_mouse_pos(pos / self.window_state.scale_factor()); } } diff --git a/src/pob/api/rendering.rs b/src/pob/api/rendering.rs index 6d4fc9b..7264a78 100644 --- a/src/pob/api/rendering.rs +++ b/src/pob/api/rendering.rs @@ -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::(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()), diff --git a/src/pob/api/window.rs b/src/pob/api/window.rs index e61c1ef..c475ead 100644 --- a/src/pob/api/window.rs +++ b/src/pob/api/window.rs @@ -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 { let ctx = l.app_data_ref::().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::().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 { let ctx = l.app_data_ref::().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), } diff --git a/src/renderer.rs b/src/renderer.rs index ed249e7..dfb122a 100644 --- a/src/renderer.rs +++ b/src/renderer.rs @@ -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, pub batches: Vec, pub textures_delta: TexturesDelta, - pub scale_factor: f32, + pub scale_factor: ScaleFactor, } #[derive(Debug)] @@ -255,7 +255,7 @@ impl Renderer { render_pass: &mut wgpu::RenderPass<'static>, render_job: &RenderJob, screen_size: PhysicalSize, - pixels_per_point: f32, + scale_factor: ScaleFactor, ) { 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::(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::() - .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, - pixels_per_point: f32, + scale_factor: ScaleFactor, ) { 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 diff --git a/src/stage.rs b/src/stage.rs index e7b76a2..8b3dc6d 100644 --- a/src/stage.rs +++ b/src/stage.rs @@ -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, pub can_elide: bool, pub request_redraw: bool, - pub scale_factor: f32, + pub scale_factor: ScaleFactor, } pub enum ActiveStage { diff --git a/src/window.rs b/src/window.rs index 96aed9f..c8be59d 100644 --- a/src/window.rs +++ b/src/window.rs @@ -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, pub window: Option>, pub size: PhysicalSize, - scale_factor: f32, - pub scale_factor_override: Option, + scale_factor: ScaleFactor, + scale_factor_override: Option>, pending_window_title: std::cell::Cell>, 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 { - self.size.to_logical(self.scale_factor()) + pub fn logical_size(&self) -> LogicalSize { + self.size.cast() / self.scale_factor() } - pub fn scale_factor(&self) -> f32 { + pub fn scale_factor(&self) -> ScaleFactor { 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 { + self.scale_factor_override.map(|s| s.get()) + } + + pub fn set_scale_factor_override(&mut self, scale_factor: Option) { + self.scale_factor_override = scale_factor.map(ScaleFactor::new); } pub fn focus(&self) {