1use std::collections::BTreeMap;
21use std::fmt;
22use std::time::Duration;
23
24use nadir_assets::Handle;
25use nadir_core::{GenArena, Rect, Vec2};
26use nadir_ecs::{Component, Entity};
27use nadir_render::{Atlas, AtlasSprite, Texture};
28
29#[derive(Clone, Copy, Debug, PartialEq)]
35#[non_exhaustive]
36pub struct ClipFrame {
37 pub texture: Handle<Texture>,
39 pub uv: Rect,
41 pub duration: Duration,
43 pub placement: Option<Placement>,
48}
49
50#[derive(Clone, Copy, Debug, PartialEq)]
53pub struct Placement {
54 pub size: Vec2,
56 pub pivot: Vec2,
58}
59
60impl ClipFrame {
61 pub const fn new(texture: Handle<Texture>, uv: Rect, duration: Duration) -> Self {
64 Self {
65 texture,
66 uv,
67 duration,
68 placement: None,
69 }
70 }
71
72 pub fn from_atlas(
80 texture: Handle<Texture>,
81 sprite: &AtlasSprite,
82 frame: usize,
83 duration: Duration,
84 ) -> Option<Self> {
85 let pivot = sprite.pivot()?;
86 let frame = sprite.frame(frame)?;
87 Some(Self {
88 texture,
89 uv: frame.uv(),
90 duration,
91 placement: Some(Placement {
92 size: frame.size().as_vec2(),
93 pivot: frame.pivot_in(pivot),
94 }),
95 })
96 }
97}
98
99#[derive(Clone, Debug, PartialEq, Eq)]
101#[non_exhaustive]
102pub enum ClipError {
103 NoFrames,
105 FrameLastsZero {
107 index: usize,
109 },
110 TooLong,
112 NameTaken(String),
114 WrongPages {
116 needed: usize,
118 given: usize,
120 },
121}
122
123impl fmt::Display for ClipError {
124 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
125 match self {
126 Self::NoFrames => write!(f, "a clip needs a frame"),
127 Self::FrameLastsZero { index } => write!(f, "frame {index} of a clip lasts zero"),
128 Self::TooLong => write!(f, "a clip's frames last longer than a Duration holds"),
129 Self::NameTaken(name) => write!(f, "there is a clip named `{name}` already"),
130 Self::WrongPages { needed, given } => write!(
131 f,
132 "the atlas has {needed} pages, and {given} textures were given for them"
133 ),
134 }
135 }
136}
137
138impl std::error::Error for ClipError {}
139
140#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
142pub enum Playback {
143 #[default]
145 Loop,
146 Once,
149}
150
151#[derive(Clone, Debug, PartialEq)]
153pub struct Clip {
154 frames: Vec<ClipFrame>,
155 ends: Vec<Duration>,
157 playback: Playback,
158}
159
160impl Clip {
161 pub fn new(frames: Vec<ClipFrame>, playback: Playback) -> Self {
169 match Self::try_new(frames, playback) {
170 Ok(clip) => clip,
171 Err(error) => panic!("{error}"),
172 }
173 }
174
175 pub fn try_new(frames: Vec<ClipFrame>, playback: Playback) -> Result<Self, ClipError> {
182 if frames.is_empty() {
183 return Err(ClipError::NoFrames);
184 }
185 let mut ends = Vec::with_capacity(frames.len());
186 let mut end = Duration::ZERO;
187 for (index, frame) in frames.iter().enumerate() {
188 if frame.duration.is_zero() {
189 return Err(ClipError::FrameLastsZero { index });
190 }
191 end = end.checked_add(frame.duration).ok_or(ClipError::TooLong)?;
192 ends.push(end);
193 }
194 Ok(Self {
195 frames,
196 ends,
197 playback,
198 })
199 }
200
201 pub fn frames(&self) -> &[ClipFrame] {
203 &self.frames
204 }
205
206 pub fn playback(&self) -> Playback {
208 self.playback
209 }
210
211 pub fn duration(&self) -> Duration {
213 *self.ends.last().expect("a clip has a frame")
214 }
215
216 pub fn frame_at(&self, elapsed: Duration) -> usize {
222 let at = match self.playback {
223 Playback::Loop => from_nanos(elapsed.as_nanos() % self.duration().as_nanos()),
224 Playback::Once if elapsed >= self.duration() => return self.frames.len() - 1,
225 Playback::Once => elapsed,
226 };
227 self.ends.partition_point(|&end| end <= at)
228 }
229}
230
231fn from_nanos(nanos: u128) -> Duration {
233 let seconds = u64::try_from(nanos / 1_000_000_000).expect("less than a Duration holds");
234 Duration::new(seconds, (nanos % 1_000_000_000) as u32)
235}
236
237pub struct Clips {
244 clips: GenArena<Named>,
245 names: BTreeMap<String, Handle<Clip>>,
246 atlases: Vec<AtlasClips>,
249}
250
251struct AtlasClips {
254 pages: Vec<Handle<Texture>>,
255 clips: Vec<Handle<Clip>>,
256 holds: u32,
257}
258
259struct Named {
261 clip: Clip,
262 name: Option<String>,
263}
264
265impl Clips {
266 pub fn new() -> Self {
268 Self {
269 clips: GenArena::new(),
270 names: BTreeMap::new(),
271 atlases: Vec::new(),
272 }
273 }
274
275 pub fn add(&mut self, clip: Clip) -> Handle<Clip> {
277 Handle::new(self.clips.insert(Named { clip, name: None }))
278 }
279
280 pub fn add_named(
286 &mut self,
287 name: impl Into<String>,
288 clip: Clip,
289 ) -> Result<Handle<Clip>, ClipError> {
290 let name = name.into();
291 if self.names.contains_key(&name) {
292 return Err(ClipError::NameTaken(name));
293 }
294 let handle = Handle::new(self.clips.insert(Named {
295 clip,
296 name: Some(name.clone()),
297 }));
298 self.names.insert(name, handle);
299 Ok(handle)
300 }
301
302 pub fn add_atlas(
322 &mut self,
323 atlas: &Atlas,
324 pages: &[Handle<Texture>],
325 ) -> Result<Vec<Handle<Clip>>, ClipError> {
326 if pages.len() != atlas.pages().len() {
327 return Err(ClipError::WrongPages {
328 needed: atlas.pages().len(),
329 given: pages.len(),
330 });
331 }
332 if let Some(known) = self.atlases.iter_mut().find(|known| known.pages == pages) {
333 known.holds = known.holds.saturating_add(1);
334 return Ok(known.clips.clone());
335 }
336 let mut made = Vec::new();
337 for (name, clip) in atlas_clips(atlas, pages) {
338 if self.names.contains_key(&name) {
339 return Err(ClipError::NameTaken(name));
340 }
341 made.push((name, clip?));
342 }
343 let handles: Vec<Handle<Clip>> = made
344 .into_iter()
345 .map(|(name, clip)| {
346 self.add_named(name, clip)
347 .expect("each name was checked as free, and they differ")
348 })
349 .collect();
350 if !handles.is_empty() {
351 self.atlases.push(AtlasClips {
352 pages: pages.to_vec(),
353 clips: handles.clone(),
354 holds: 1,
355 });
356 }
357 Ok(handles)
358 }
359
360 #[cfg(feature = "dev")]
377 pub(crate) fn reload_atlas(
378 &mut self,
379 atlas: &Atlas,
380 pages: &[Handle<Texture>],
381 ) -> Option<AtlasReload> {
382 let index = self
383 .atlases
384 .iter()
385 .position(|known| known.pages == pages)
386 .or_else(|| {
387 self.atlases
388 .iter()
389 .position(|known| known.pages.iter().any(|page| pages.contains(page)))
390 })?;
391 let made = atlas_clips(atlas, pages);
392 let names: Vec<String> = made.iter().map(|(name, _)| name.clone()).collect();
393 let mut reload = AtlasReload {
394 old_pages: Vec::new(),
395 replaced: 0,
396 added: 0,
397 kept: Vec::new(),
398 refused: Vec::new(),
399 };
400 for (name, clip) in made {
401 let clip = match clip {
402 Ok(clip) => clip,
403 Err(error) => {
404 reload.refused.push((name, error));
405 continue;
406 }
407 };
408 match self.names.get(&name).copied() {
409 Some(handle) if self.atlases[index].clips.contains(&handle) => {
410 if let Some(named) = self.clips.get_mut(handle.id()) {
411 named.clip = clip;
412 reload.replaced += 1;
413 }
414 }
415 Some(_) => reload
416 .refused
417 .push((name.clone(), ClipError::NameTaken(name))),
418 None => {
419 let handle = self
420 .add_named(name, clip)
421 .expect("the name was checked as free");
422 self.atlases[index].clips.push(handle);
423 reload.added += 1;
424 }
425 }
426 }
427 let known = &mut self.atlases[index];
428 for &handle in &known.clips {
429 if let Some(name) = self.clips.get(handle.id()).and_then(|it| it.name.as_ref())
430 && !names.contains(name)
431 {
432 reload.kept.push(name.clone());
433 }
434 }
435 reload.old_pages = std::mem::replace(&mut known.pages, pages.to_vec());
436 Some(reload)
437 }
438
439 pub fn release_atlas(&mut self, pages: &[Handle<Texture>]) -> bool {
445 let Some(index) = self.atlases.iter().position(|known| known.pages == pages) else {
446 return false;
447 };
448 let known = &mut self.atlases[index];
449 known.holds -= 1;
450 if known.holds > 0 {
451 return false;
452 }
453 let atlas = self.atlases.remove(index);
454 for handle in atlas.clips {
455 if let Some(named) = self.clips.remove(handle.id())
456 && let Some(name) = &named.name
457 {
458 self.names.remove(name);
459 }
460 }
461 true
462 }
463
464 pub fn get(&self, handle: Handle<Clip>) -> Option<&Clip> {
466 self.clips.get(handle.id()).map(|named| &named.clip)
467 }
468
469 pub fn find(&self, name: &str) -> Option<Handle<Clip>> {
471 self.names.get(name).copied()
472 }
473
474 pub fn name(&self, handle: Handle<Clip>) -> Option<&str> {
476 self.clips.get(handle.id())?.name.as_deref()
477 }
478
479 pub fn remove(&mut self, handle: Handle<Clip>) -> Option<Clip> {
483 let named = self.clips.remove(handle.id())?;
484 if let Some(name) = &named.name {
485 self.names.remove(name);
486 for atlas in &mut self.atlases {
488 atlas.clips.retain(|&clip| clip != handle);
489 }
490 self.atlases.retain(|atlas| !atlas.clips.is_empty());
491 }
492 Some(named.clip)
493 }
494
495 pub fn len(&self) -> usize {
497 self.clips.len()
498 }
499
500 pub fn is_empty(&self) -> bool {
502 self.clips.is_empty()
503 }
504}
505
506impl Default for Clips {
507 fn default() -> Self {
508 Self::new()
509 }
510}
511
512impl fmt::Debug for Clips {
513 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
514 f.debug_struct("Clips").field("len", &self.len()).finish()
515 }
516}
517
518#[cfg(feature = "dev")]
520#[derive(Debug, PartialEq)]
521pub(crate) struct AtlasReload {
522 pub(crate) old_pages: Vec<Handle<Texture>>,
524 pub(crate) replaced: usize,
526 pub(crate) added: usize,
528 pub(crate) kept: Vec<String>,
530 pub(crate) refused: Vec<(String, ClipError)>,
533}
534
535fn atlas_clips(atlas: &Atlas, pages: &[Handle<Texture>]) -> Vec<(String, Result<Clip, ClipError>)> {
539 let mut made = Vec::new();
540 for sprite in atlas.sprites() {
541 for clip in sprite.clips() {
542 let name = format!("{}/{}", sprite.name(), clip.name());
543 let frames = clip
546 .frames()
547 .iter()
548 .filter_map(|step| {
549 let page = sprite.frame(step.frame())?.page();
550 ClipFrame::from_atlas(*pages.get(page)?, sprite, step.frame(), step.duration())
551 })
552 .collect();
553 let playback = if clip.is_looping() {
554 Playback::Loop
555 } else {
556 Playback::Once
557 };
558 made.push((name, Clip::try_new(frames, playback)));
559 }
560 }
561 made
562}
563
564#[derive(Clone, Copy, Debug, PartialEq, Eq)]
594pub struct Animator {
595 clip: Handle<Clip>,
596 elapsed: Duration,
599 finished: bool,
601}
602
603impl Animator {
604 pub const fn new(clip: Handle<Clip>) -> Self {
606 Self::starting_at(clip, Duration::ZERO)
607 }
608
609 pub const fn starting_at(clip: Handle<Clip>, elapsed: Duration) -> Self {
618 Self {
619 clip,
620 elapsed,
621 finished: false,
622 }
623 }
624
625 pub fn clip(&self) -> Handle<Clip> {
627 self.clip
628 }
629
630 pub fn elapsed(&self) -> Duration {
635 self.elapsed
636 }
637
638 pub fn is_finished(&self) -> bool {
641 self.finished
642 }
643
644 pub fn play(&mut self, clip: Handle<Clip>) {
649 if clip != self.clip {
650 *self = Self::new(clip);
651 }
652 }
653
654 pub fn restart(&mut self) {
656 *self = Self::new(self.clip);
657 }
658
659 pub(crate) fn advance(&mut self, clip: &Clip, by: Duration) -> (usize, bool) {
663 let duration = clip.duration();
664 let ended = match clip.playback() {
665 Playback::Loop => {
666 let nanos = self.elapsed.as_nanos() + by.as_nanos();
668 self.elapsed = from_nanos(nanos % duration.as_nanos());
669 false
670 }
671 Playback::Once => {
672 self.elapsed = if self.finished {
675 duration
676 } else {
677 self.elapsed.saturating_add(by).min(duration)
678 };
679 let ended = !self.finished && self.elapsed == duration;
680 self.finished |= ended;
681 ended
682 }
683 };
684 (clip.frame_at(self.elapsed), ended)
685 }
686}
687
688#[derive(Clone, Copy, Debug, PartialEq, Eq)]
698pub struct AnimationFinished {
699 pub entity: Entity,
701 pub clip: Handle<Clip>,
703}
704
705#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
708pub(crate) struct AnimationClock(pub(crate) Duration);
709
710impl Component for Animator {}
711
712#[cfg(test)]
713mod tests {
714 use std::num::NonZeroU32;
715
716 use nadir_core::{GenIndex, Vec2};
717
718 use super::*;
719
720 const MS: Duration = Duration::from_millis(1);
721 const NS: Duration = Duration::from_nanos(1);
722
723 fn texture(index: u32) -> Handle<Texture> {
724 Handle::new(GenIndex::new(index, NonZeroU32::MIN))
725 }
726
727 fn clip(ms: &[u64], playback: Playback) -> Clip {
729 let frames = (0..)
730 .zip(ms)
731 .map(|(i, &ms)| {
732 let uv = Rect::new(Vec2::new(i as f32, 0.0), Vec2::new(i as f32 + 1.0, 1.0));
733 ClipFrame::new(texture(0), uv, Duration::from_millis(ms))
734 })
735 .collect();
736 Clip::new(frames, playback)
737 }
738
739 fn handle() -> Handle<Clip> {
741 Handle::new(GenIndex::new(0, NonZeroU32::MIN))
742 }
743
744 #[test]
747 fn a_looping_clip_shows_each_frame_from_its_start_up_to_its_end() {
748 let clip = clip(&[30, 50, 20], Playback::Loop);
750 assert_eq!(clip.duration(), 100 * MS);
751 let cases = [
752 (Duration::ZERO, 0),
753 (30 * MS - NS, 0),
754 (30 * MS, 1),
755 (80 * MS - NS, 1),
756 (80 * MS, 2),
757 (100 * MS - NS, 2),
758 (100 * MS, 0),
759 (130 * MS, 1),
760 (1_000_080 * MS, 2),
761 (Duration::MAX, 2),
763 ];
764 for (elapsed, frame) in cases {
765 assert_eq!(clip.frame_at(elapsed), frame, "at {elapsed:?}");
766 }
767 }
768
769 #[test]
770 fn a_clip_that_plays_once_holds_its_last_frame_from_its_end() {
771 let clip = clip(&[30, 50, 20], Playback::Once);
772 let cases = [
773 (Duration::ZERO, 0),
774 (30 * MS, 1),
775 (100 * MS - NS, 2),
776 (100 * MS, 2),
777 (100 * MS + NS, 2),
778 (130 * MS, 2),
779 (Duration::MAX, 2),
780 ];
781 for (elapsed, frame) in cases {
782 assert_eq!(clip.frame_at(elapsed), frame, "at {elapsed:?}");
783 }
784 }
785
786 #[test]
787 fn a_clip_needs_frames_that_last() {
788 let empty = std::panic::catch_unwind(|| Clip::new(Vec::new(), Playback::Loop));
789 assert!(empty.is_err(), "no frames");
790 let zero = std::panic::catch_unwind(|| clip(&[30, 0], Playback::Loop));
791 assert!(zero.is_err(), "a frame of zero");
792 let frame =
793 |duration| ClipFrame::new(texture(0), Rect::new(Vec2::ZERO, Vec2::ONE), duration);
794 let long = std::panic::catch_unwind(|| {
795 Clip::new(vec![frame(Duration::MAX), frame(NS)], Playback::Loop)
796 });
797 assert!(long.is_err(), "longer than a Duration");
798 assert_eq!(
800 Clip::try_new(Vec::new(), Playback::Loop),
801 Err(ClipError::NoFrames)
802 );
803 assert_eq!(
804 Clip::try_new(vec![frame(MS), frame(Duration::ZERO)], Playback::Once),
805 Err(ClipError::FrameLastsZero { index: 1 })
806 );
807 assert_eq!(
808 Clip::try_new(vec![frame(Duration::MAX), frame(NS)], Playback::Loop),
809 Err(ClipError::TooLong)
810 );
811 assert_eq!(
812 ClipError::FrameLastsZero { index: 1 }.to_string(),
813 "frame 1 of a clip lasts zero"
814 );
815 let longest = Clip::new(vec![frame(Duration::MAX - NS), frame(NS)], Playback::Loop);
817 assert_eq!(longest.duration(), Duration::MAX);
818 assert_eq!(longest.frame_at(Duration::MAX - NS), 1);
819 }
820
821 #[test]
824 fn a_looping_clip_wraps_whole_cycles_and_never_ends() {
825 let clip = clip(&[30, 50, 20], Playback::Loop);
826 let mut animator = Animator::new(handle());
827 assert_eq!(animator.advance(&clip, Duration::ZERO), (0, false));
828 assert_eq!(animator.elapsed(), Duration::ZERO);
829 assert_eq!(animator.advance(&clip, 30 * MS), (1, false));
830 assert_eq!(animator.elapsed(), 30 * MS);
831 assert_eq!(animator.advance(&clip, 250 * MS), (2, false));
833 assert_eq!(animator.elapsed(), 80 * MS);
834 assert_eq!(animator.advance(&clip, 200 * MS), (2, false));
836 assert_eq!(animator.elapsed(), 80 * MS);
837 assert_eq!(animator.advance(&clip, 20 * MS), (0, false));
839 assert_eq!(animator.elapsed(), Duration::ZERO);
840 assert_eq!(animator.advance(&clip, Duration::MAX), (2, false));
842 assert_eq!(animator.elapsed(), 100 * MS - NS);
843 assert!(!animator.is_finished());
844 }
845
846 #[test]
847 fn a_clip_that_plays_once_ends_once_on_the_step_that_reaches_its_end() {
848 let clip = clip(&[30, 50, 20], Playback::Once);
849 let mut animator = Animator::new(handle());
850 assert_eq!(animator.advance(&clip, 100 * MS - NS), (2, false));
851 assert!(!animator.is_finished());
852 assert_eq!(animator.advance(&clip, NS), (2, true));
854 assert_eq!(animator.elapsed(), 100 * MS);
855 assert!(animator.is_finished());
856 assert_eq!(animator.advance(&clip, Duration::ZERO), (2, false));
858 assert_eq!(animator.advance(&clip, 250 * MS), (2, false));
859 assert_eq!(animator.elapsed(), 100 * MS);
860 assert_eq!(animator.advance(&clip, Duration::MAX), (2, false));
861 }
862
863 #[test]
864 fn a_step_past_the_end_of_a_clip_that_plays_once_ends_it_there() {
865 let clip = clip(&[80, 80, 80], Playback::Once);
868 let mut animator = Animator::new(handle());
869 assert_eq!(animator.advance(&clip, 250 * MS), (2, true));
870 assert_eq!(animator.elapsed(), 240 * MS);
871 let flash = clip_of_one(16);
873 let mut animator = Animator::new(handle());
874 assert_eq!(animator.advance(&flash, 16 * MS), (0, true));
875 }
876
877 fn clip_of_one(ms: u64) -> Clip {
878 clip(&[ms], Playback::Once)
879 }
880
881 #[test]
882 fn restart_plays_a_finished_clip_again_and_play_switches_only_to_another() {
883 let once = clip(&[30, 50, 20], Playback::Once);
884 let mut animator = Animator::new(handle());
885 assert_eq!(animator.advance(&once, 100 * MS), (2, true));
886 animator.play(handle());
888 assert!(animator.is_finished());
889 assert_eq!(animator.advance(&once, 16 * MS), (2, false));
890 animator.restart();
892 assert_eq!(
893 (animator.elapsed(), animator.is_finished()),
894 (Duration::ZERO, false)
895 );
896 assert_eq!(animator.advance(&once, 50 * MS), (1, false));
897 assert_eq!(animator.advance(&once, 50 * MS), (2, true));
898 let other = Handle::new(GenIndex::new(1, NonZeroU32::MIN));
900 animator.play(other);
901 assert_eq!(animator.clip(), other);
902 assert_eq!(
903 (animator.elapsed(), animator.is_finished()),
904 (Duration::ZERO, false)
905 );
906
907 let looping = clip(&[30, 50, 20], Playback::Loop);
909 let mut animator = Animator::new(handle());
910 animator.advance(&looping, 50 * MS);
911 animator.play(handle());
912 assert_eq!(animator.elapsed(), 50 * MS);
913 assert_eq!(animator.advance(&looping, 30 * MS), (2, false));
914 }
915
916 #[test]
917 fn an_animator_can_start_partway_through_its_clip() {
918 let looping = clip(&[100, 100, 100], Playback::Loop);
919 let mut animator = Animator::starting_at(handle(), 250 * MS);
920 assert_eq!(animator.advance(&looping, Duration::ZERO), (2, false));
921 let mut animator = Animator::starting_at(handle(), 37_310 * MS);
923 assert_eq!(animator.advance(&looping, Duration::ZERO), (1, false));
924 assert_eq!(animator.elapsed(), 110 * MS);
925 let once = clip(&[30, 50, 20], Playback::Once);
928 let mut animator = Animator::starting_at(handle(), 130 * MS);
929 assert_eq!(animator.advance(&once, Duration::ZERO), (2, true));
930 assert_eq!(animator.elapsed(), 100 * MS);
931 }
932
933 #[test]
936 fn clips_are_found_by_handle_until_removed() {
937 let mut clips = Clips::new();
938 assert!(clips.is_empty());
939 let walk = clips.add(clip(&[100, 100], Playback::Loop));
940 let jump = clips.add(clip(&[50], Playback::Once));
941 assert_eq!(clips.len(), 2);
942 assert_eq!(clips.get(walk).map(Clip::playback), Some(Playback::Loop));
943 assert_eq!(clips.get(jump).map(Clip::duration), Some(50 * MS));
944 assert_eq!(clips.remove(walk).map(|clip| clip.frames().len()), Some(2));
945 assert_eq!(clips.get(walk), None);
946 assert_eq!(clips.remove(walk), None);
947 let fall = clips.add(clip(&[10], Playback::Once));
949 assert_ne!(fall, walk);
950 assert_eq!(clips.get(walk), None);
951 assert_eq!(format!("{clips:?}"), "Clips { len: 2 }");
952 }
953
954 #[test]
955 fn a_named_clip_is_found_by_its_name_until_removed() {
956 let mut clips = Clips::new();
957 let walk = clips
958 .add_named("sprites/person/walk", clip(&[100], Playback::Loop))
959 .expect("a free name");
960 let unnamed = clips.add(clip(&[10], Playback::Once));
961 assert_eq!(clips.find("sprites/person/walk"), Some(walk));
962 assert_eq!(clips.name(walk), Some("sprites/person/walk"));
963 assert_eq!(clips.name(unnamed), None);
964 assert_eq!(clips.find("sprites/person"), None);
965 assert_eq!(
966 clips.add_named("sprites/person/walk", clip(&[5], Playback::Loop)),
967 Err(ClipError::NameTaken("sprites/person/walk".to_string()))
968 );
969 assert_eq!(clips.len(), 2);
970 clips.remove(walk);
971 assert_eq!(clips.find("sprites/person/walk"), None);
972 assert_eq!(clips.name(walk), None);
973 let again = clips
975 .add_named("sprites/person/walk", clip(&[5], Playback::Loop))
976 .expect("a free name");
977 assert_ne!(again, walk);
978 }
979
980 fn atlas() -> Atlas {
983 atlas_of(
984 r#"{ "version": 2,
985 "pages": [ { "path": "atlas/sprites_0.qoi", "w": 64, "h": 64 },
986 { "path": "atlas/sprites_1.qoi", "w": 64, "h": 64 } ],
987 "sprites": [
988 { "name": "sprites/person",
989 "frames": [ { "page": 0, "x": 1, "y": 1, "w": 10, "h": 20, "ox": 1, "oy": 0, "sw": 12, "sh": 20 },
990 { "page": 1, "x": 1, "y": 1, "w": 9, "h": 18, "ox": 2, "oy": 2, "sw": 12, "sh": 20 } ],
991 "pivot": [6.0, 20.0],
992 "clips": [ { "name": "stand", "loop": true, "frames": [[0, 100]] },
993 { "name": "wave", "loop": false, "frames": [[1, 40], [0, 60]] } ] },
994 { "name": "sprites/tree",
995 "frames": [ { "page": 0, "x": 20, "y": 1, "w": 24, "h": 44, "ox": 0, "oy": 4, "sw": 24, "sh": 48 } ],
996 "pivot": [12.0, 48.0] } ] }"#,
997 )
998 }
999
1000 fn atlas_of(text: &str) -> Atlas {
1002 use nadir_assets::{Asset, DecodeCtx};
1003 use nadir_codec::{Limits, json, kbj};
1004 let value = json::parse(text, Limits::default()).expect("the test's JSON");
1005 let bytes = kbj::encode(&value, Limits::default()).expect("encodable");
1006 Atlas::decode(
1007 &bytes,
1008 &DecodeCtx::new("atlas/sprites.kbj", Limits::default()),
1009 )
1010 .expect("an atlas")
1011 }
1012
1013 #[test]
1014 fn an_atlas_s_clips_are_added_by_name_each_frame_placed_on_its_page() {
1015 let atlas = atlas();
1016 let pages = [texture(7), texture(8)];
1017 let mut clips = Clips::new();
1018 let added = clips.add_atlas(&atlas, &pages).expect("the clips");
1019 let stand = clips.find("sprites/person/stand").expect("stand");
1020 let wave = clips.find("sprites/person/wave").expect("wave");
1021 assert_eq!(added, [stand, wave]);
1022 assert_eq!(clips.len(), 2);
1023
1024 let stand = clips.get(stand).expect("a clip");
1025 assert_eq!(stand.playback(), Playback::Loop);
1026 assert_eq!(stand.duration(), 100 * MS);
1027 let wave = clips.get(wave).expect("a clip");
1028 assert_eq!(wave.playback(), Playback::Once);
1029 let person = atlas.sprite("sprites/person").expect("the person");
1030 let shown: Vec<(Handle<Texture>, Rect, Duration)> = wave
1031 .frames()
1032 .iter()
1033 .map(|frame| (frame.texture, frame.uv, frame.duration))
1034 .collect();
1035 assert_eq!(
1036 shown,
1037 [
1038 (pages[1], person.frames()[1].uv(), 40 * MS),
1039 (pages[0], person.frames()[0].uv(), 60 * MS),
1040 ]
1041 );
1042 assert_eq!(
1046 wave.frames()[0].placement,
1047 Some(Placement {
1048 size: Vec2::new(9.0, 18.0),
1049 pivot: Vec2::new(4.0 / 9.0, 18.0 / 18.0),
1050 })
1051 );
1052 assert_eq!(
1053 wave.frames()[1].placement,
1054 Some(Placement {
1055 size: Vec2::new(10.0, 20.0),
1056 pivot: Vec2::new(0.5, 1.0),
1057 })
1058 );
1059 }
1060
1061 #[test]
1062 fn an_atlas_s_clips_are_added_all_or_none() {
1063 let atlas = atlas();
1064 let mut clips = Clips::new();
1065 assert_eq!(
1066 clips.add_atlas(&atlas, &[texture(7)]),
1067 Err(ClipError::WrongPages {
1068 needed: 2,
1069 given: 1
1070 })
1071 );
1072 assert!(clips.is_empty());
1073 clips
1075 .add_named("sprites/person/wave", clip(&[5], Playback::Loop))
1076 .expect("a free name");
1077 assert_eq!(
1078 clips.add_atlas(&atlas, &[texture(7), texture(8)]),
1079 Err(ClipError::NameTaken("sprites/person/wave".to_string()))
1080 );
1081 assert_eq!(clips.len(), 1);
1082 assert_eq!(clips.find("sprites/person/stand"), None);
1083 }
1084
1085 #[test]
1086 fn an_atlas_added_again_is_held_again_until_its_clips_are_removed() {
1087 let atlas = atlas();
1088 let pages = [texture(7), texture(8)];
1089 let mut clips = Clips::new();
1090 let added = clips.add_atlas(&atlas, &pages).expect("the clips");
1091 assert!(!added.is_empty());
1092 let count = clips.len();
1093 assert_eq!(clips.add_atlas(&atlas, &pages), Ok(added.clone()));
1095 assert_eq!(clips.len(), count);
1096 assert!(!clips.release_atlas(&pages));
1098 assert_eq!(clips.len(), count);
1099 assert!(clips.release_atlas(&pages));
1100 assert!(clips.is_empty());
1101 assert_eq!(clips.find("sprites/person/stand"), None);
1102 assert!(!clips.release_atlas(&pages));
1103 let added = clips.add_atlas(&atlas, &pages).expect("the clips");
1104 assert!(matches!(
1106 clips.add_atlas(&atlas, &[texture(9), texture(10)]),
1107 Err(ClipError::NameTaken(_))
1108 ));
1109 for handle in added {
1111 clips.remove(handle);
1112 }
1113 assert!(clips.is_empty());
1114 let again = clips.add_atlas(&atlas, &pages).expect("the clips");
1115 assert_eq!(again.len(), count);
1116 }
1117
1118 #[test]
1119 fn a_frame_of_an_atlas_is_placed_as_a_sprite_of_it_would_be() {
1120 let atlas = atlas();
1121 let person = atlas.sprite("sprites/person").expect("the person");
1122 let frame = ClipFrame::from_atlas(texture(8), person, 1, 40 * MS).expect("a frame");
1123 let sprite = crate::Sprite::from_atlas(texture(8), person, 1).expect("a sprite");
1124 let placement = frame.placement.expect("placed");
1125 assert_eq!(
1126 (frame.uv, placement.size, placement.pivot),
1127 (sprite.uv, sprite.size, sprite.pivot)
1128 );
1129 assert!(ClipFrame::from_atlas(texture(8), person, 2, MS).is_none());
1130 }
1131
1132 #[cfg(feature = "dev")]
1134 mod reloaded {
1135 use super::*;
1136
1137 const RELOADED: &str = r#"{ "version": 2,
1141 "pages": [ { "path": "atlas/sprites_0.qoi", "w": 64, "h": 64 },
1142 { "path": "atlas/sprites_1.qoi", "w": 64, "h": 64 } ],
1143 "sprites": [
1144 { "name": "sprites/person",
1145 "frames": [ { "page": 1, "x": 30, "y": 1, "w": 10, "h": 20, "ox": 1, "oy": 0, "sw": 12, "sh": 20 },
1146 { "page": 0, "x": 40, "y": 1, "w": 9, "h": 18, "ox": 2, "oy": 2, "sw": 12, "sh": 20 } ],
1147 "pivot": [6.0, 20.0],
1148 "clips": [ { "name": "sit", "loop": true, "frames": [[0, 50]] },
1149 { "name": "wave", "loop": false, "frames": [[1, 40], [0, 60], [1, 100]] } ] },
1150 { "name": "sprites/tree",
1151 "frames": [ { "page": 0, "x": 20, "y": 1, "w": 24, "h": 44, "ox": 0, "oy": 4, "sw": 24, "sh": 48 } ],
1152 "pivot": [12.0, 48.0],
1153 "clips": [ { "name": "sway", "loop": true, "frames": [[0, 80]] } ] } ] }"#;
1154
1155 #[test]
1156 fn a_reloaded_atlas_replaces_its_clips_by_name_under_their_handles() {
1157 let pages = [texture(7), texture(8)];
1158 let mut clips = Clips::new();
1159 clips.add_atlas(&atlas(), &pages).expect("the clips");
1160 let stand = clips.find("sprites/person/stand").expect("stand");
1161 let wave = clips.find("sprites/person/wave").expect("wave");
1162
1163 let reloaded = atlas_of(RELOADED);
1164 let reload = clips
1165 .reload_atlas(&reloaded, &pages)
1166 .expect("the atlas was added");
1167 assert_eq!(reload.old_pages, pages);
1168 assert_eq!((reload.replaced, reload.added), (1, 2));
1169 assert_eq!(reload.kept, ["sprites/person/stand"]);
1170 assert!(reload.refused.is_empty());
1171
1172 assert_eq!(clips.find("sprites/person/wave"), Some(wave));
1174 let person = reloaded.sprite("sprites/person").expect("the person");
1175 let shown: Vec<(Handle<Texture>, Rect, Duration)> = clips
1176 .get(wave)
1177 .expect("the wave")
1178 .frames()
1179 .iter()
1180 .map(|frame| (frame.texture, frame.uv, frame.duration))
1181 .collect();
1182 assert_eq!(
1183 shown,
1184 [
1185 (pages[0], person.frames()[1].uv(), 40 * MS),
1186 (pages[1], person.frames()[0].uv(), 60 * MS),
1187 (pages[0], person.frames()[1].uv(), 100 * MS),
1188 ]
1189 );
1190 assert_eq!(clips.find("sprites/person/stand"), Some(stand));
1192 assert_eq!(clips.get(stand).map(Clip::duration), Some(100 * MS));
1193 let sit = clips.find("sprites/person/sit").expect("the sit");
1194 assert_eq!(clips.get(sit).map(Clip::playback), Some(Playback::Loop));
1195 assert!(clips.find("sprites/tree/sway").is_some());
1196
1197 assert!(clips.release_atlas(&pages));
1199 assert!(clips.is_empty());
1200 }
1201
1202 #[test]
1203 fn a_reloaded_atlas_on_other_pages_is_known_by_them_from_then_on() {
1204 let mut clips = Clips::new();
1205 let pages = [texture(7), texture(8)];
1206 clips.add_atlas(&atlas(), &pages).expect("the clips");
1207 clips.add_atlas(&atlas(), &pages).expect("held twice");
1208 let wave = clips.find("sprites/person/wave").expect("wave");
1209
1210 let three = RELOADED.replace(
1212 r#"{ "path": "atlas/sprites_1.qoi", "w": 64, "h": 64 } ],"#,
1213 r#"{ "path": "atlas/sprites_1.qoi", "w": 64, "h": 64 },
1214 { "path": "atlas/sprites_2.qoi", "w": 64, "h": 64 } ],"#,
1215 );
1216 let more = [texture(7), texture(8), texture(9)];
1217 let reload = clips
1218 .reload_atlas(&atlas_of(&three), &more)
1219 .expect("found by name");
1220 assert_eq!(reload.old_pages, pages);
1221 assert_eq!(clips.find("sprites/person/wave"), Some(wave));
1222
1223 assert!(!clips.release_atlas(&pages));
1225 assert!(!clips.release_atlas(&more));
1226 assert!(!clips.is_empty());
1227 assert_eq!(
1228 clips.add_atlas(&atlas_of(&three), &more).map(|it| it.len()),
1229 Ok(4)
1230 );
1231 assert!(!clips.release_atlas(&more));
1232 assert!(clips.release_atlas(&more));
1233 assert!(clips.is_empty());
1234 }
1235
1236 #[test]
1237 fn an_atlas_whose_clips_were_never_added_is_not_reloaded() {
1238 let mut clips = Clips::new();
1239 let pages = [texture(7), texture(8)];
1240 assert_eq!(clips.reload_atlas(&atlas(), &pages), None);
1241 assert!(clips.is_empty());
1242
1243 clips.add_atlas(&atlas(), &pages).expect("the clips");
1246 let wave = clips.find("sprites/person/wave").expect("wave");
1247 let other = [texture(9), texture(10)];
1248 assert_eq!(clips.reload_atlas(&atlas_of(RELOADED), &other), None);
1249 assert_eq!(clips.get(wave).map(Clip::duration), Some(100 * MS));
1250 assert!(clips.release_atlas(&pages));
1251 assert!(clips.is_empty());
1252
1253 let theirs = clips
1255 .add_named("sprites/tree/sway", clip(&[5], Playback::Once))
1256 .expect("a free name");
1257 clips.add_atlas(&atlas(), &pages).expect("the clips");
1258 let reload = clips
1259 .reload_atlas(&atlas_of(RELOADED), &pages)
1260 .expect("the atlas was added");
1261 assert_eq!(
1262 reload.refused,
1263 [(
1264 "sprites/tree/sway".to_string(),
1265 ClipError::NameTaken("sprites/tree/sway".to_string())
1266 )]
1267 );
1268 assert_eq!(clips.find("sprites/tree/sway"), Some(theirs));
1269 assert_eq!(clips.get(theirs).map(Clip::duration), Some(5 * MS));
1270 assert!(clips.release_atlas(&pages));
1272 assert_eq!(clips.len(), 1);
1273 assert_eq!(clips.find("sprites/tree/sway"), Some(theirs));
1274 }
1275 }
1276
1277 #[test]
1278 fn an_animator_plays_on_through_a_clip_replaced_under_its_handle() {
1279 let mut looping = Animator::new(handle());
1282 looping.advance(&clip(&[100, 100, 100], Playback::Loop), 200 * MS);
1283 let (frame, ended) = looping.advance(&clip(&[50, 100], Playback::Loop), 10 * MS);
1284 assert_eq!((looping.elapsed(), frame, ended), (60 * MS, 1, false));
1285
1286 let mut once = Animator::new(handle());
1289 let (_, ended) = once.advance(&clip(&[100], Playback::Once), 150 * MS);
1290 assert!(ended && once.is_finished());
1291 let longer = clip(&[100, 100, 100], Playback::Once);
1292 let (frame, ended) = once.advance(&longer, 10 * MS);
1293 assert_eq!((once.elapsed(), frame, ended), (300 * MS, 2, false));
1294 assert!(once.is_finished());
1295 let (frame, ended) = once.advance(&clip(&[20, 20], Playback::Once), 10 * MS);
1297 assert_eq!((once.elapsed(), frame, ended), (40 * MS, 1, false));
1298
1299 let mut playing = Animator::new(handle());
1302 playing.advance(&clip(&[100], Playback::Once), 50 * MS);
1303 let (frame, ended) = playing.advance(&longer, 100 * MS);
1304 assert_eq!((playing.elapsed(), frame, ended), (150 * MS, 1, false));
1305 let (_, ended) = playing.advance(&longer, 200 * MS);
1306 assert!(ended && playing.is_finished());
1307 }
1308}