From b00c65fc55445f59cc771822ca44feb10f67c55a Mon Sep 17 00:00:00 2001 From: Jay Oster Date: Wed, 1 Sep 2021 20:53:08 -0700 Subject: [PATCH] Properly clip pixel buffer when larger than surface texture (#190) - Fixes #186 --- src/lib.rs | 10 ++++------ src/renderers.rs | 22 ++++++++++++---------- 2 files changed, 16 insertions(+), 16 deletions(-) diff --git a/src/lib.rs b/src/lib.rs index f137062..cb3dd15 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -464,13 +464,11 @@ impl Pixels { ); let pos = self.scaling_matrix_inverse * pos; + let offset_width = pixels_width.min(physical_width) / 2.0; + let offset_height = pixels_height.min(physical_height) / 2.0; - let pos = ( - pos.x / pos.w + pixels_width / 2.0, - -pos.y / pos.w + pixels_height / 2.0, - ); - let pixel_x = pos.0.floor() as isize; - let pixel_y = pos.1.floor() as isize; + let pixel_x = (pos.x / pos.w + offset_width).floor() as isize; + let pixel_y = (-pos.y / pos.w + offset_height).floor() as isize; if pixel_x < 0 || pixel_x >= self.context.texture_extent.width as isize diff --git a/src/renderers.rs b/src/renderers.rs index c22fa83..a088447 100644 --- a/src/renderers.rs +++ b/src/renderers.rs @@ -253,26 +253,28 @@ impl ScalingMatrix { let scaled_width = texture_width * scale; let scaled_height = texture_height * scale; - // Update transformation matrix + // Create a transformation matrix let sw = scaled_width / screen_width; let sh = scaled_height / screen_height; + let tx = (texture_width / screen_width - 1.0).max(0.0); + let ty = (1.0 - texture_height / screen_height).min(0.0); #[rustfmt::skip] let transform: [f32; 16] = [ sw, 0.0, 0.0, 0.0, 0.0, -sh, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, - 0.0, 0.0, 0.0, 1.0, + tx, ty, 0.0, 1.0, ]; // Create a clipping rectangle - let x = (screen_width - scaled_width) / 2.0; - let y = (screen_height - scaled_height) / 2.0; - let clip_rect = ( - x as u32, - y as u32, - scaled_width as u32, - scaled_height as u32, - ); + let clip_rect = { + let scaled_width = scaled_width.min(screen_width); + let scaled_height = scaled_height.min(screen_height); + let x = ((screen_width - scaled_width) / 2.0) as u32; + let y = ((screen_height - scaled_height) / 2.0) as u32; + + (x, y, scaled_width as u32, scaled_height as u32) + }; ScalingMatrix { transform: Mat4::from(transform),