1use glam::Vec2;
4use std::{fmt, sync::Arc, time::Duration};
5
6#[derive(Clone, Copy, Debug, PartialEq, Eq)]
8pub enum SpriteError {
9 InvalidRegion,
11 EmptyName,
13 EmptyClip,
15 ZeroDuration,
17 DurationOverflow,
19}
20
21impl fmt::Display for SpriteError {
22 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
23 f.write_str(match self {
24 Self::InvalidRegion => "sprite region must have nonzero dimensions and u32 endpoints",
25 Self::EmptyName => "animation clip must have a nonblank name",
26 Self::EmptyClip => "animation clip must contain at least one frame",
27 Self::ZeroDuration => "animation frame duration must be nonzero",
28 Self::DurationOverflow => "animation clip duration exceeds Duration::MAX",
29 })
30 }
31}
32impl std::error::Error for SpriteError {}
33
34#[derive(Clone, Copy, Debug, PartialEq, Eq)]
37pub struct SpriteRegion {
38 x: u32,
39 y: u32,
40 width: u32,
41 height: u32,
42}
43
44impl SpriteRegion {
45 pub fn new(x: u32, y: u32, width: u32, height: u32) -> Result<Self, SpriteError> {
48 if width == 0
49 || height == 0
50 || x.checked_add(width).is_none()
51 || y.checked_add(height).is_none()
52 {
53 return Err(SpriteError::InvalidRegion);
54 }
55 Ok(Self {
56 x,
57 y,
58 width,
59 height,
60 })
61 }
62 pub fn x(self) -> u32 {
64 self.x
65 }
66 pub fn y(self) -> u32 {
68 self.y
69 }
70 pub fn width(self) -> u32 {
72 self.width
73 }
74 pub fn height(self) -> u32 {
76 self.height
77 }
78 pub fn fits(self, width: u32, height: u32) -> bool {
80 self.x + self.width <= width && self.y + self.height <= height
81 }
82}
83
84#[derive(Clone, Copy, Debug, PartialEq)]
87pub struct SpriteTransform {
88 pub position: Vec2,
90 pub size: Vec2,
92 pub origin: Vec2,
95 pub rotation: f32,
97 pub flip_x: bool,
99 pub flip_y: bool,
101}
102
103impl Default for SpriteTransform {
104 fn default() -> Self {
105 Self {
106 position: Vec2::ZERO,
107 size: Vec2::ONE,
108 origin: Vec2::ZERO,
109 rotation: 0.0,
110 flip_x: false,
111 flip_y: false,
112 }
113 }
114}
115
116impl SpriteTransform {
117 pub fn is_valid(self) -> bool {
120 self.position.is_finite()
121 && self.size.is_finite()
122 && self.size.min_element() > 0.0
123 && self.origin.is_finite()
124 && self.rotation.is_finite()
125 && self.rotation.to_degrees().is_finite()
126 }
127}
128
129#[derive(Clone, Copy, Debug, PartialEq, Eq)]
131pub struct SpriteFrame {
132 pub region: SpriteRegion,
134 pub duration: Duration,
136}
137
138#[derive(Clone, Copy, Debug, PartialEq, Eq)]
140pub enum PlaybackMode {
141 Loop,
143 Once,
145}
146
147#[derive(Debug)]
149pub struct AnimationClip {
150 name: String,
151 frames: Vec<SpriteFrame>,
152 ends: Vec<Duration>,
153 duration: Duration,
154 mode: PlaybackMode,
155}
156
157impl AnimationClip {
158 pub fn new(
161 name: impl Into<String>,
162 frames: Vec<SpriteFrame>,
163 mode: PlaybackMode,
164 ) -> Result<Self, SpriteError> {
165 let name = name.into();
166 if name.trim().is_empty() {
167 return Err(SpriteError::EmptyName);
168 }
169 if frames.is_empty() {
170 return Err(SpriteError::EmptyClip);
171 }
172 let mut duration = Duration::ZERO;
173 let mut ends = Vec::with_capacity(frames.len());
174 for frame in &frames {
175 if frame.duration.is_zero() {
176 return Err(SpriteError::ZeroDuration);
177 }
178 duration = duration
179 .checked_add(frame.duration)
180 .ok_or(SpriteError::DurationOverflow)?;
181 ends.push(duration);
182 }
183 Ok(Self {
184 name,
185 frames,
186 ends,
187 duration,
188 mode,
189 })
190 }
191 pub fn name(&self) -> &str {
193 &self.name
194 }
195 pub fn frames(&self) -> &[SpriteFrame] {
197 &self.frames
198 }
199 pub fn duration(&self) -> Duration {
201 self.duration
202 }
203 pub fn mode(&self) -> PlaybackMode {
205 self.mode
206 }
207}
208
209#[derive(Clone, Debug)]
213pub struct AnimationCompleted {
214 pub clip: Arc<AnimationClip>,
216}
217
218#[derive(Clone, Debug)]
222pub struct AnimationPlayer {
223 clip: Arc<AnimationClip>,
224 elapsed: Duration,
225 paused: bool,
226 finished: bool,
227}
228
229impl AnimationPlayer {
230 pub fn new(clip: impl Into<Arc<AnimationClip>>) -> Self {
232 Self {
233 clip: clip.into(),
234 elapsed: Duration::ZERO,
235 paused: false,
236 finished: false,
237 }
238 }
239 pub fn play(&mut self, clip: impl Into<Arc<AnimationClip>>) {
241 *self = Self::new(clip);
242 }
243 pub fn reset(&mut self) {
245 self.elapsed = Duration::ZERO;
246 self.finished = false;
247 }
248 pub fn pause(&mut self) {
250 self.paused = true;
251 }
252 pub fn resume(&mut self) {
254 self.paused = false;
255 }
256 pub fn is_paused(&self) -> bool {
258 self.paused
259 }
260 pub fn is_finished(&self) -> bool {
262 self.finished
263 }
264 pub fn clip(&self) -> &Arc<AnimationClip> {
266 &self.clip
267 }
268 pub fn elapsed(&self) -> Duration {
270 self.elapsed
271 }
272 pub fn frame_index(&self) -> usize {
275 self.clip
276 .ends
277 .partition_point(|end| *end <= self.elapsed)
278 .min(self.clip.frames.len() - 1)
279 }
280 pub fn frame(&self) -> &SpriteFrame {
282 &self.clip.frames[self.frame_index()]
283 }
284 pub fn advance(&mut self, dt: Duration) -> Option<AnimationCompleted> {
289 if self.paused || self.finished || dt.is_zero() {
290 return None;
291 }
292 let next = self.elapsed.as_nanos() + dt.as_nanos();
294 let duration = self.clip.duration.as_nanos();
295 let next = match self.clip.mode {
296 PlaybackMode::Loop => next % duration,
297 PlaybackMode::Once if next >= duration => {
298 self.elapsed = self.clip.duration;
299 self.finished = true;
300 return Some(AnimationCompleted {
301 clip: Arc::clone(&self.clip),
302 });
303 }
304 PlaybackMode::Once => next,
305 };
306 self.elapsed = Duration::new((next / 1_000_000_000) as u64, (next % 1_000_000_000) as u32);
307 None
308 }
309}
310
311#[cfg(test)]
312mod tests;