sim_logic/rendering/screen/
image.rs1use std::{error::Error, fmt};
4
5use bevy_ecs::prelude::Component;
6use sim_engine::{Color, Layer, LogicalScreenPosition, LogicalScreenVector};
7
8use crate::assets::ImageAssetId;
9
10use super::{ScreenRectangleVisual, ScreenVisualError};
11
12#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Hash)]
14pub enum ImageFilter {
15 #[default]
17 Nearest,
18 Linear,
20}
21
22#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
27pub struct ImageRegion {
28 x: u32,
29 y: u32,
30 width: u32,
31 height: u32,
32}
33
34impl ImageRegion {
35 pub fn new(x: u32, y: u32, width: u32, height: u32) -> Result<Self, ImageVisualError> {
41 let region = Self {
42 x,
43 y,
44 width,
45 height,
46 };
47 region.validate()?;
48 Ok(region)
49 }
50
51 pub const fn x(self) -> u32 {
53 self.x
54 }
55
56 pub const fn y(self) -> u32 {
58 self.y
59 }
60
61 pub const fn width(self) -> u32 {
63 self.width
64 }
65
66 pub const fn height(self) -> u32 {
68 self.height
69 }
70
71 fn validate(self) -> Result<(), ImageVisualError> {
72 if self.width == 0
73 || self.height == 0
74 || self.x.checked_add(self.width).is_none()
75 || self.y.checked_add(self.height).is_none()
76 {
77 return Err(ImageVisualError::InvalidRegion {
78 x: self.x,
79 y: self.y,
80 width: self.width,
81 height: self.height,
82 });
83 }
84 Ok(())
85 }
86
87 fn validate_image(self, image: ImageAssetId) -> Result<(), ImageVisualError> {
88 self.validate()?;
89 if self.x + self.width > image.width() || self.y + self.height > image.height() {
90 return Err(ImageVisualError::RegionOutOfBounds {
91 region: self,
92 image,
93 });
94 }
95 Ok(())
96 }
97}
98
99#[derive(Debug, Clone, Copy, PartialEq, Component)]
114pub struct ScreenImageVisual {
115 rotation: f32,
116 image: ImageAssetId,
117 source_region: Option<ImageRegion>,
118 filter: ImageFilter,
119 rectangle: ScreenRectangleVisual,
120}
121
122impl ScreenImageVisual {
123 pub const fn rotation(&self) -> f32 {
126 self.rotation
127 }
128
129 pub fn set_rotation(&mut self, radians: f32) -> Result<(), ImageVisualError> {
132 if !radians.is_finite() {
133 return Err(ScreenVisualError::InvalidRotation { value: radians }.into());
134 }
135 self.rotation = radians.rem_euclid(std::f32::consts::TAU);
136 Ok(())
137 }
138
139 pub fn contains_pointer(&self, sample: crate::input::PointerSample) -> bool {
142 if !self.clip().contains_pointer(sample) {
143 return false;
144 }
145 let size = self.size().to_vec2();
146 let min = self.position().to_vec2();
147 let p = sample.position().to_vec2();
148 let x = f64::from(p.x()) - (f64::from(min.x()) + f64::from(size.x()) * 0.5);
149 let y = f64::from(p.y()) - (f64::from(min.y()) + f64::from(size.y()) * 0.5);
150 let (sin, cos) = f64::from(self.rotation).sin_cos();
151 let local_x = x * cos + y * sin + f64::from(size.x()) * 0.5;
152 let local_y = -x * sin + y * cos + f64::from(size.y()) * 0.5;
153 local_x >= 0.0
154 && local_y >= 0.0
155 && local_x < f64::from(size.x())
156 && local_y < f64::from(size.y())
157 }
158 pub const fn clip(&self) -> super::ScreenClip {
160 self.rectangle.clip()
161 }
162
163 pub fn set_clip(&mut self, clip: super::ScreenClip) {
165 self.rectangle.set_clip(clip);
166 }
167 pub fn new(
173 image: ImageAssetId,
174 position: LogicalScreenPosition,
175 size: LogicalScreenVector,
176 ) -> Result<Self, ImageVisualError> {
177 Ok(Self {
178 rotation: 0.0,
179 image,
180 source_region: None,
181 filter: ImageFilter::Nearest,
182 rectangle: ScreenRectangleVisual::new(position, size, Color::WHITE)?,
183 })
184 }
185
186 pub const fn image(&self) -> ImageAssetId {
188 self.image
189 }
190
191 pub const fn source_region(&self) -> Option<ImageRegion> {
193 self.source_region
194 }
195
196 pub const fn filter(&self) -> ImageFilter {
198 self.filter
199 }
200
201 pub const fn position(&self) -> LogicalScreenPosition {
203 self.rectangle.position()
204 }
205
206 pub const fn size(&self) -> LogicalScreenVector {
208 self.rectangle.size()
209 }
210
211 pub const fn tint(&self) -> Color {
213 self.rectangle.color()
214 }
215
216 pub const fn layer(&self) -> Layer {
218 self.rectangle.layer()
219 }
220
221 pub const fn draw_order_depth(&self) -> f32 {
223 self.rectangle.draw_order_depth()
224 }
225
226 pub fn set_image(&mut self, image: ImageAssetId) -> Result<(), ImageVisualError> {
232 if let Some(region) = self.source_region {
233 region.validate_image(image)?;
234 }
235 self.image = image;
236 Ok(())
237 }
238
239 pub fn set_source_region(
244 &mut self,
245 region: Option<ImageRegion>,
246 ) -> Result<(), ImageVisualError> {
247 if let Some(region) = region {
248 region.validate_image(self.image)?;
249 }
250 self.source_region = region;
251 Ok(())
252 }
253
254 pub fn set_filter(&mut self, filter: ImageFilter) {
256 self.filter = filter;
257 }
258
259 pub fn set_geometry(
264 &mut self,
265 position: LogicalScreenPosition,
266 size: LogicalScreenVector,
267 ) -> Result<(), ImageVisualError> {
268 self.rectangle.set_geometry(position, size)?;
269 Ok(())
270 }
271
272 pub fn set_position(
274 &mut self,
275 position: LogicalScreenPosition,
276 ) -> Result<(), ImageVisualError> {
277 self.rectangle.set_position(position)?;
278 Ok(())
279 }
280
281 pub fn set_size(&mut self, size: LogicalScreenVector) -> Result<(), ImageVisualError> {
283 self.rectangle.set_size(size)?;
284 Ok(())
285 }
286
287 pub fn set_tint(&mut self, tint: Color) -> Result<(), ImageVisualError> {
291 self.rectangle.set_color(tint)?;
292 Ok(())
293 }
294
295 pub fn set_layer(&mut self, layer: Layer) {
297 self.rectangle.set_layer(layer);
298 }
299
300 pub fn set_draw_order_depth(&mut self, depth: f32) -> Result<(), ImageVisualError> {
304 self.rectangle.set_draw_order_depth(depth)?;
305 Ok(())
306 }
307
308 pub(crate) fn validate(&self) -> Result<(), ImageVisualError> {
309 self.rectangle.validate()?;
310 if let Some(region) = self.source_region {
311 region.validate_image(self.image)?;
312 }
313 Ok(())
314 }
315}
316
317#[derive(Debug, Clone, Copy, PartialEq)]
319#[non_exhaustive]
320pub enum ImageVisualError {
321 Screen(ScreenVisualError),
323 InvalidRegion {
325 x: u32,
327 y: u32,
329 width: u32,
331 height: u32,
333 },
334 RegionOutOfBounds {
336 region: ImageRegion,
338 image: ImageAssetId,
340 },
341}
342
343impl From<ScreenVisualError> for ImageVisualError {
344 fn from(source: ScreenVisualError) -> Self {
345 Self::Screen(source)
346 }
347}
348
349impl fmt::Display for ImageVisualError {
350 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
351 match self {
352 Self::Screen(source) => {
353 write!(formatter, "invalid screen image presentation: {source}")
354 }
355 Self::InvalidRegion {
356 x,
357 y,
358 width,
359 height,
360 } => write!(
361 formatter,
362 "image source region ({x}, {y}, {width}, {height}) needs positive extents and non-overflowing texel bounds"
363 ),
364 Self::RegionOutOfBounds { region, image } => write!(
365 formatter,
366 "image source region {region:?} exceeds image dimensions {} by {}",
367 image.width(),
368 image.height()
369 ),
370 }
371 }
372}
373
374impl Error for ImageVisualError {
375 fn source(&self) -> Option<&(dyn Error + 'static)> {
376 match self {
377 Self::Screen(source) => Some(source),
378 _ => None,
379 }
380 }
381}
382
383#[cfg(test)]
384#[path = "image_tests.rs"]
385mod tests;