From 6a218432ec6871edb09ad56253a1f291c78797fc Mon Sep 17 00:00:00 2001 From: John Giorshev Date: Thu, 2 Jan 2025 14:24:08 -0500 Subject: [PATCH] add ClippingRect type --- src/sdl2/render.rs | 49 ++++++++++++++++++++++++++++++++++------------ 1 file changed, 37 insertions(+), 12 deletions(-) diff --git a/src/sdl2/render.rs b/src/sdl2/render.rs index e18e9a0..c3abe5a 100644 --- a/src/sdl2/render.rs +++ b/src/sdl2/render.rs @@ -406,6 +406,15 @@ impl RenderTarget for Window { type Context = WindowContext; } +pub enum ClippingRect { + /// a non-zero area clipping rect + Some(Rect), + /// a clipping rect with zero area + Zero, + /// the absence of a clipping rect + None, +} + /// Methods for the `WindowCanvas`. impl Canvas { /// Gets a reference to the associated window of the Canvas @@ -1099,31 +1108,47 @@ impl Canvas { } /// Sets the clip rectangle for rendering on the specified target. - /// - /// If the rectangle is `None`, clipping will be disabled. #[doc(alias = "SDL_RenderSetClipRect")] - pub fn set_clip_rect>>(&mut self, rect: R) { - let rect = rect.into(); - // as_ref is important because we need rect to live until the end of the FFI call, but map_or consumes an Option - let ptr = rect.as_ref().map_or(ptr::null(), |rect| rect.raw()); - let ret = unsafe { sys::SDL_RenderSetClipRect(self.context.raw, ptr) }; + pub fn set_clip_rect(&mut self, arg: ClippingRect) { + let ret = match arg { + ClippingRect::Some(r) => { + unsafe { sys::SDL_RenderSetClipRect(self.context.raw, r.raw()) } + } + ClippingRect::Zero => { + let r = sys::SDL_Rect { + x: 0, + y: 0, + w: 0, + h: 0, + }; + let r: *const sys::SDL_Rect = &r; + unsafe { sys::SDL_RenderSetClipRect(self.context.raw, r) } + } + ClippingRect::None => { + unsafe { sys::SDL_RenderSetClipRect(self.context.raw, ptr::null()) } + } + }; if ret != 0 { panic!("Could not set clip rect: {}", get_error()) } } /// Gets the clip rectangle for the current target. - /// - /// Returns `None` if clipping is disabled. #[doc(alias = "SDL_RenderGetClipRect")] - pub fn clip_rect(&self) -> Option { + pub fn clip_rect(&self) -> ClippingRect { + let clip_enabled = unsafe { sys::SDL_RenderIsClipEnabled(self.context.raw) }; + + if let sys::SDL_bool::SDL_FALSE = clip_enabled { + return ClippingRect::None; + } + let mut raw = mem::MaybeUninit::uninit(); unsafe { sys::SDL_RenderGetClipRect(self.context.raw, raw.as_mut_ptr()) }; let raw = unsafe { raw.assume_init() }; if raw.w == 0 || raw.h == 0 { - None + ClippingRect::Zero } else { - Some(Rect::from_ll(raw)) + ClippingRect::Some(Rect::from_ll(raw)) } }