1use crate::Rect;
3use std::sync::{
4 Arc,
5 atomic::{AtomicU32, Ordering},
6};
7static NEXT_IMAGE_ID: AtomicU32 = AtomicU32::new(1);
8#[derive(Clone, Debug, PartialEq)]
10pub struct Image {
11 pub(crate) id: u32,
12 pub(crate) width: u32,
13 pub(crate) height: u32,
14 pub(crate) msdf_px_range: f32,
15 pub(crate) pixels: Arc<[u8]>,
16}
17impl Image {
18 pub fn rgba(width: u32, height: u32, pixels: Vec<u8>) -> Option<Self> {
20 Self::new_inner(width, height, 0.0, pixels)
21 }
22 pub fn msdf(width: u32, height: u32, px_range: f32, pixels: Vec<u8>) -> Option<Self> {
25 if !px_range.is_finite() || px_range <= 0.0 {
26 return None;
27 }
28 Self::new_inner(width, height, px_range, pixels)
29 }
30 fn new_inner(width: u32, height: u32, msdf_px_range: f32, pixels: Vec<u8>) -> Option<Self> {
31 if width == 0 || height == 0 || width > 1022 || height > 1022 {
32 return None;
33 }
34 let length = (width as usize)
35 .checked_mul(height as usize)?
36 .checked_mul(4)?;
37 if pixels.len() != length {
38 return None;
39 }
40 let id = NEXT_IMAGE_ID
41 .try_update(Ordering::Relaxed, Ordering::Relaxed, |id| id.checked_add(1))
42 .ok()?;
43 Some(Self {
44 id,
45 width,
46 height,
47 msdf_px_range,
48 pixels: pixels.into(),
49 })
50 }
51 pub fn msdf_px_range(&self) -> f32 {
52 self.msdf_px_range
53 }
54 pub fn width(&self) -> u32 {
55 self.width
56 }
57 pub fn height(&self) -> u32 {
58 self.height
59 }
60 pub fn pixels(&self) -> &[u8] {
61 &self.pixels
62 }
63 pub fn id(&self) -> u32 {
64 self.id
65 }
66}
67#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
68pub enum ImageFit {
69 #[default]
70 Cover,
71 Contain,
72}
73pub fn fit_image(bounds: Rect, width: u32, height: u32, fit: ImageFit) -> Option<(Rect, [f32; 4])> {
75 if width == 0
76 || height == 0
77 || !bounds.width.is_finite()
78 || !bounds.height.is_finite()
79 || bounds.width <= 0.0
80 || bounds.height <= 0.0
81 {
82 return None;
83 }
84 let iw = width as f32;
85 let ih = height as f32;
86 match fit {
87 ImageFit::Contain => {
88 let scale = (bounds.width / iw).min(bounds.height / ih);
89 let w = iw * scale;
90 let h = ih * scale;
91 Some((
92 Rect {
93 x: bounds.x + (bounds.width - w) / 2.0,
94 y: bounds.y + (bounds.height - h) / 2.0,
95 width: w,
96 height: h,
97 },
98 [0.0, 0.0, 1.0, 1.0],
99 ))
100 }
101 ImageFit::Cover => {
102 let scale = (bounds.width / iw).max(bounds.height / ih);
103 let u = bounds.width / (iw * scale);
104 let v = bounds.height / (ih * scale);
105 Some((
106 bounds,
107 [
108 (1.0 - u) / 2.0,
109 (1.0 - v) / 2.0,
110 (1.0 + u) / 2.0,
111 (1.0 + v) / 2.0,
112 ],
113 ))
114 }
115 }
116}
117
118#[cfg(test)]
119#[path = "media.spec.rs"]
120mod tests;