diff --git a/src/draw_commands.rs b/src/draw_commands.rs index b1f8304..06a54d9 100644 --- a/src/draw_commands.rs +++ b/src/draw_commands.rs @@ -92,8 +92,15 @@ impl DrawCommandRecorder { None => (TextureId::default(), NormalizedQuad::white_uv(), 0), }; + let positions = rect.translate(self.current_viewport.min.to_vector()); + + // cull if outside of viewport + if !positions.intersects(&self.current_viewport) { + return; + } + self.push(DrawCommand { - positions: rect.translate(self.current_viewport.min.to_vector()).into(), + positions: positions.into(), uvs, color: self.current_draw_color, texture_id, @@ -118,8 +125,15 @@ impl DrawCommandRecorder { None => (TextureId::default(), NormalizedQuad::white_uv(), 0), }; + let positions = quad.translate(self.current_viewport.min.to_vector()); + + // cull if outside of viewport + if !positions.aabb_intersects_rect(&self.current_viewport) { + return; + } + self.push(DrawCommand { - positions: quad.translate(self.current_viewport.min.to_vector()), + positions, uvs, color: self.current_draw_color, texture_id, @@ -136,14 +150,19 @@ impl DrawCommandRecorder { layer_idx: u32, is_absolute_position: bool, ) { - let rect = if is_absolute_position { + let positions = if is_absolute_position { rect } else { rect.translate(self.current_viewport.min.to_vector()) }; + // cull if outside of viewport + if !positions.intersects(&self.current_viewport) { + return; + } + self.push(DrawCommand { - positions: rect.into(), + positions: positions.into(), uvs: uv.into(), color, // font atlas always lives at default texture ID diff --git a/src/math/quad.rs b/src/math/quad.rs index 8796f87..96746f3 100644 --- a/src/math/quad.rs +++ b/src/math/quad.rs @@ -1,5 +1,6 @@ use crate::math::{Corners, Point, Rect, Size, Vector}; use bytemuck::{Pod, Zeroable}; +use euclid::approxord::{max, min}; use euclid::num::Zero; use std::fmt; use std::hash::Hash; @@ -135,3 +136,25 @@ where ) } } + +impl Quad +where + T: Copy + PartialOrd, +{ + /// Returns the axis-aligned bounding box containing this quad. + #[inline] + pub fn aabb(&self) -> Rect { + let min_x = min(min(min(self.p0.x, self.p1.x), self.p2.x), self.p3.x); + let max_x = max(max(max(self.p0.x, self.p1.x), self.p2.x), self.p3.x); + let min_y = min(min(min(self.p0.y, self.p1.y), self.p2.y), self.p3.y); + let max_y = max(max(max(self.p0.y, self.p1.y), self.p2.y), self.p3.y); + + Rect::new(Point::new(min_x, min_y), Point::new(max_x, max_y)) + } + + /// Tests intersection between this quad's AABB and a rectangle. + #[inline] + pub fn aabb_intersects_rect(&self, rect: &Rect) -> bool { + self.aabb().intersects(rect) + } +}