# resource/spriteatlas (vanilla-engine 0.4.0)

> https://vanillapunch.com/docs/vanilla-engine/0.4.0/api/resource/spriteatlas/

스프라이트 아틀라스. (vanilla.js resource/spriteatlas.js 의 SpriteAtlas)
- 쪽 그림 몇 장에 모은 그림을 이름으로 꺼낸다. 같은 쪽 그림을 쓰는 스프라이트는 엔진이 묶어 한 번에 그린다.
- 읽는 JSON 꼴은 원본과 같은 둘이다.
  1. tools/atlas.cjs 가 만든 것. { images: { "이름.png": { x, y, width, height, page } }, meta: { imageFileName, pages: [{ imageFileName }] } }
     page 가 없으면 0 쪽, meta.pages 가 없으면 meta.imageFileName 한 장이다.
  2. 쪽 경로와 [쪽, x, y, 가로, 세로] 표. { pagePaths: `["경로"]`, frames: { "이름": [쪽, x, y, 가로, 세로] } }
- 그림 이름은 확장자를 뗀 이름으로도 찾는다. ("icon-close.png" 는 "icon-close" 로도 "icon-close.png" 로도 찾는다)
- 쪽 경로에 빗금(/)이 없으면 JSON 이 있는 폴더를 기준으로, 있으면 적힌 그대로 읽는다. ("./" 로 시작하면 그 "./" 를 떼고 애셋 폴더 기준이다)
- 원본과 다른 것:
  원본은 load 가 JSON 을 기다린 뒤 쪽 그림을 받는 async 다. 러스트 판은 애셋처럼 요청만 하고, update 가 JSON 이 온 것을 보고 쪽 그림을 청한다.
  load, load_data 는 원본처럼 await 할 수 있는 SpriteAtlasLoadHandle 을 돌려준다. 손잡이는 불러오기 상태를 나눠 들어 아틀라스를 빌리지 않으므로
  씬이 든 아틀라스도 scene_context.with(|씬, 엔진| 씬.아틀라스.load(엔진, 경로)).await 로 기다린다. (기다리는 동안 프레임마다 update 를 불러 준다)
  데스크탑은 그 자리에서 읽혀 load 가 끝나면 다 읽혔다. 웹은 JSON 과 쪽 그림이 차례로 오므로 is_loaded 가 true 가 될 때까지 tick 에서 update 를 부르고,
  그 뒤에 조각을 건다. (씬이 맡아 기다리게 하려면 JSON 은 track_json_asset, 쪽 그림은 온 뒤 update 가 청한다)
  원본의 찾을 아틀라스 목록(add_search_atlas, find_frame, apply_search_frame)은 스레드 하나에 하나인 목록이고, 아틀라스를 나눠 들게 `Rc<RefCell<SpriteAtlas>>` 로 넣는다.
  find_frame 은 빌린 조각 대신 조각의 복사(Frame 은 그림 Rc 와 영역이라 값싸다)를 돌려준다. 넘긴 목록에서 찾는 find_frame_in_order 도 있다.
  get_page_images 는 원본 HTMLImageElement 목록 대신 읽힌 쪽 그림(Image) 목록이다.

## SpriteAtlasLoadHandle (struct) (Clone, IntoFuture)

아틀라스 받기 손잡이. (SpriteAtlas::load, load_data 가 돌려준다. 원본 load 의 Promise 자리, 아틀라스를 빌리지 않는다)
- await 하면 JSON 과 쪽 그림을 다 받아 조각을 지을 때까지 기다린다. (기다리는 동안 프레임마다 update 를 불러 준다)

예제: 엔진 작업 안에서 아틀라스 받기를 기다리기 (데스크탑은 load 에서 이미 끝나 바로 넘어간다)

```rust
use vanilla::{Engine, EngineConfiguration, SpriteAtlas};

let engine = Engine::new(EngineConfiguration::new());
let mut sprite_atlas = SpriteAtlas::new();
let atlas_load_handle = sprite_atlas.load(&engine, "examples/assets/atlas/icons.json");
assert!(atlas_load_handle.is_finished());
let task_handle = engine.spawn_task(|_engine_context| async move {
	atlas_load_handle.await;
});
assert!(task_handle.is_finished());
assert!(sprite_atlas.has_frame("star"));
```

- `pub fn is_finished(&self) -> bool` (method, since 0.4.0): 끝났는지. (조각을 지었거나 자료를 읽지 못해 끝났거나)
  - returns bool: 조각을 지었거나 자료를 읽지 못해 끝났으면 true.

## SpriteAtlasLoadFuture (struct) (Clone, Future)

아틀라스 받기를 기다리는 퓨처. (손잡이를 await 하거나 wait_for_load 가 돌려준다)
- 폴링할 때마다 update 를 부른다. 원본처럼 자료를 읽지 못해도 끝난다.

예제: load 를 부른 뒤 wait_for_load 로 기다리기

```rust
use vanilla::{Engine, EngineConfiguration, SpriteAtlas};

let engine = Engine::new(EngineConfiguration::new());
let mut sprite_atlas = SpriteAtlas::new();
sprite_atlas.load(&engine, "examples/assets/atlas/icons.json");
let atlas_load_future = sprite_atlas.wait_for_load();
let task_handle = engine.spawn_task(|_engine_context| async move {
	atlas_load_future.await;
});
assert!(task_handle.is_finished());
assert!(sprite_atlas.is_loaded());
```

## SpriteAtlas (struct) (Default)

스프라이트 아틀라스.
- 쪽 그림 몇 장에 모은 그림을 이름으로 꺼내 스프라이트에 건다. 이름은 확장자를 뗀 것으로도 찾는다.

예제: 저장소의 아틀라스를 읽어 조각을 스프라이트에 걸기

```rust
use vanilla::{Engine, EngineConfiguration, Rect, Sprite, SpriteAtlas};

let engine = Engine::new(EngineConfiguration::new());
let mut sprite_atlas = SpriteAtlas::new();
sprite_atlas.load(&engine, "examples/assets/atlas/icons.json");
assert!(sprite_atlas.is_loaded());
assert_eq!(sprite_atlas.get_page_count(), 1);
let coin_frame = sprite_atlas.read_frame("coin").expect("coin");
assert_eq!(coin_frame.get_image_rect(), Rect::create(84.0, 55.0, 30.0, 30.0));
assert!(sprite_atlas.has_frame("coin.png"));
let mut sprite = Sprite::new();
assert!(sprite_atlas.apply_frame(&mut sprite, "star"));
assert_eq!(sprite.get_image_rect(), Rect::create(63.0, 2.0, 48.0, 48.0));
assert!(!sprite_atlas.apply_frame(&mut sprite, "nothing"));
assert!(sprite.get_image().is_none());
```

- `pub fn new() -> SpriteAtlas` (constructor, since 0.4.0): 생성.
  - returns SpriteAtlas: 조각이 없는 빈 아틀라스.
- `pub fn load(&mut self, engine: &Engine, json_path: &str) -> SpriteAtlasLoadHandle` (method, since 0.4.0): 아틀라스 JSON 과 쪽 그림 불러오기. (JSON 이 오면 쪽 그림을 청한다, 데스크탑은 이 자리에서 다 읽힌다)
  - 원본처럼 await 할 수 있는 손잡이를 돌려준다. (조각을 지을 때까지)
  - 앞서 다 읽힌 조각은 새 것이 조각을 지을 때까지 그대로 쓴다.
  - `engine` &Engine: 바이트를 부탁할 엔진.
  - `json_path` &str: 아틀라스 JSON 경로. (빗금 없는 쪽 경로는 이 JSON 이 있는 폴더 기준)
  - returns SpriteAtlasLoadHandle: 조각을 짓거나 자료를 읽지 못해 끝나면 끝나는 손잡이. (아틀라스를 빌리지 않는다)
- `pub fn load_data(&mut self, engine: &Engine, atlas_data: &serde_json::Value, base_directory: &str) -> SpriteAtlasLoadHandle` (method, since 0.4.0): 아틀라스 자료로 불러오기. (JSON 을 읽은 값이나 코드에 둔 같은 꼴의 값, 쪽 경로에 빗금이 없으면 base_directory 를 앞에 붙인다)
  - 원본 loadData 처럼 await 할 수 있는 손잡이를 돌려준다. (쪽 그림을 다 받아 조각을 지을 때까지)
  - 꼴을 모르는 자료면 알리고 조각 없이 끝난다.
  - `engine` &Engine: 쪽 그림을 부탁할 엔진.
  - `atlas_data` &serde_json::Value: 아틀라스 자료. (images 와 meta 꼴이나 pagePaths 와 frames 꼴)
  - `base_directory` &str: 빗금 없는 쪽 경로 앞에 그대로 이어 붙일 폴더. (빗금으로 끝나게 준다, 비우면 애셋 폴더 기준)
  - returns SpriteAtlasLoadHandle: 조각을 짓거나 자료를 읽지 못해 끝나면 끝나는 손잡이. (아틀라스를 빌리지 않는다)

  예제: 코드에 둔 쪽 경로와 표 꼴로 불러오기

  ```rust
  use vanilla::{Engine, EngineConfiguration, Rect, SpriteAtlas};
  
  let engine = Engine::new(EngineConfiguration::new());
  let atlas_data = serde_json::json!({ "pagePaths": ["icons.png"], "frames": { "gem": [0, 2, 2, 56, 40] } });
  let mut sprite_atlas = SpriteAtlas::new();
  let atlas_load_handle = sprite_atlas.load_data(&engine, &atlas_data, "examples/assets/atlas/");
  assert!(atlas_load_handle.is_finished());
  assert_eq!(sprite_atlas.read_frame("gem").expect("gem").get_image_rect(), Rect::create(2.0, 2.0, 56.0, 40.0));
  ```

- `pub fn update(&mut self, engine: &Engine) -> bool` (method, since 0.4.0): 진행. (JSON 이 왔으면 쪽 그림을 청하고, 쪽 그림이 다 왔으면 조각을 짓는다. 끝났으면 true, 원본처럼 자료를 읽지 못해도 끝난다)
  - 웹은 is_loaded 가 true 가 될 때까지 tick 에서 부른다. 데스크탑은 load 에서 이미 끝나 있다.
  - `engine` &Engine: 쪽 그림을 부탁할 엔진.
  - returns bool: 끝났으면 true. 불러오기를 건 적이 없으면 false.
- `pub fn track_json_asset(&self, scene_base: &mut SceneBase)` (method, since 0.4.0): 씬이 아틀라스 JSON 을 기다리게 맡기기. (쪽 그림은 JSON 이 온 뒤 update 가 청한다)
  - load 로 건 불러오기만 맡긴다. (load_data 는 JSON 이 없어 아무것도 하지 않는다)
  - `scene_base` &mut SceneBase: JSON 애셋을 맡을 씬 공통 상태.
- `pub fn is_loaded(&self) -> bool` (method, since 0.4.0): 다 읽혔는지. (조각을 지었는지, 다시 불러오는 동안은 원본처럼 앞의 것으로 본다)
  - returns bool: 지금 보이는 불러오기가 조각을 지었으면 true.
- `pub fn wait_for_load(&self) -> SpriteAtlasLoadFuture` (method, since 0.4.0): 다 읽히기를 기다리는 퓨처. (load 나 load_data 가 돌려준 손잡이를 await 하는 것과 같다. 아틀라스를 빌리지 않는다)
  - returns SpriteAtlasLoadFuture: 마지막으로 건 불러오기가 끝나면 끝나는 퓨처. (불러오기를 건 적이 없으면 끝나지 않는다)
- `pub fn read_frame(&self, frame_name: &str) -> Option<&Frame>` (method, since 0.4.0): 조각 읽기. (없거나 아직 읽히지 않았으면 None)
  - `frame_name` &str: 그림 이름. (확장자를 뗀 이름도 된다)
  - returns Option<&Frame>: 그 이름의 조각. 없거나 아직 읽히지 않았으면 None.
- `pub fn has_frame(&self, frame_name: &str) -> bool` (method, since 0.4.0): 조각이 있는지.
  - `frame_name` &str: 그림 이름. (확장자를 뗀 이름도 된다)
  - returns bool: 그 이름의 조각이 있으면 true. 아직 읽히지 않았으면 false.
- `pub fn apply_frame(&self, sprite: &mut Sprite, frame_name: &str) -> bool` (method, since 0.4.0): 스프라이트에 조각 걸기. (없는 이름이면 그림을 비우고 false)
  - `sprite` &mut Sprite: 조각을 걸 스프라이트.
  - `frame_name` &str: 그림 이름. (확장자를 뗀 이름도 된다)
  - returns bool: 조각을 걸었으면 true. 없는 이름이거나 아직 읽히지 않았으면 그림을 비우고 false.
- `pub fn get_page_images(&mut self) -> Vec<Rc<Image>>` (method, since 0.4.0): 쪽 그림 목록. (읽힌 쪽만, 쪽 차례, 다시 불러오는 동안은 원본처럼 앞의 것)
  - returns Vec<Rc<Image>>: 읽혀 풀린 쪽 그림 목록. (읽히지 않았거나 풀지 못한 쪽은 빠진다)
- `pub fn get_page_count(&self) -> usize` (method, since 0.4.0): 쪽 수.
  - returns usize: 자료에 적힌 쪽 그림 수. (자료를 읽기 전이면 0)
- `pub fn get_frame_names(&self) -> Vec<String>` (method, since 0.4.0): 조각 이름 목록.
  - returns Vec<String>: 조각 이름 목록. (확장자가 있는 이름과 뗀 이름 모두, 차례는 정해지지 않는다. 읽히지 않았으면 빈 목록)

  예제: 이름 목록은 정렬해서 본다

  ```rust
  use vanilla::{Engine, EngineConfiguration, SpriteAtlas};
  
  let engine = Engine::new(EngineConfiguration::new());
  let atlas_data = serde_json::json!({ "pagePaths": ["icons.png"], "frames": { "star": [0, 63, 2, 48, 48], "gem.png": [0, 2, 2, 56, 40] } });
  let mut sprite_atlas = SpriteAtlas::new();
  sprite_atlas.load_data(&engine, &atlas_data, "examples/assets/atlas/");
  let mut frame_names = sprite_atlas.get_frame_names();
  frame_names.sort();
  assert_eq!(frame_names, vec!["gem", "gem.png", "star"]);
  ```

- `pub fn find_frame_in_order<'a>(atlas_list: &[&'a SpriteAtlas], frame_name: &str) -> Option<&'a Frame>` (static, since 0.4.0): 여러 아틀라스에서 차례로 조각 찾기. (앞의 것이 이긴다, 원본 SpriteAtlas.findFrame 의 찾을 목록 자리)
  - `atlas_list` &[&'a SpriteAtlas]: 찾을 아틀라스 목록. (앞의 것부터 찾는다)
  - `frame_name` &str: 그림 이름. (확장자를 뗀 이름도 된다)
  - returns Option<&'a Frame>: 처음 찾은 조각. 어느 아틀라스에도 없으면 None.

  예제: 같은 이름이면 앞의 아틀라스가 이긴다

  ```rust
  use vanilla::{Engine, EngineConfiguration, SpriteAtlas};
  
  let engine = Engine::new(EngineConfiguration::new());
  let mut first_atlas = SpriteAtlas::new();
  first_atlas.load_data(&engine, &serde_json::json!({ "pagePaths": ["icons.png"], "frames": { "star": [0, 0, 0, 8, 8] } }), "examples/assets/atlas/");
  let mut second_atlas = SpriteAtlas::new();
  second_atlas.load(&engine, "examples/assets/atlas/icons.json");
  let atlas_list = [&first_atlas, &second_atlas];
  assert_eq!(SpriteAtlas::find_frame_in_order(&atlas_list, "star").expect("star").get_image_rect().size.x, 8.0);
  assert_eq!(SpriteAtlas::find_frame_in_order(&atlas_list, "gem").expect("gem").get_image_rect().size.x, 56.0);
  assert!(SpriteAtlas::find_frame_in_order(&atlas_list, "nothing").is_none());
  ```

- `pub fn apply_frame_in_order(atlas_list: &[&SpriteAtlas], sprite: &mut Sprite, frame_name: &str) -> bool` (static, since 0.4.0): 여러 아틀라스에서 차례로 찾은 조각을 스프라이트에 걸기. (없으면 그림을 비우고 false, 원본 applySearchFrame)
  - `atlas_list` &[&SpriteAtlas]: 찾을 아틀라스 목록. (앞의 것부터 찾는다)
  - `sprite` &mut Sprite: 조각을 걸 스프라이트.
  - `frame_name` &str: 그림 이름. (확장자를 뗀 이름도 된다)
  - returns bool: 조각을 걸었으면 true. 어느 아틀라스에도 없으면 그림을 비우고 false.
- `pub fn add_search_atlas(sprite_atlas: &Rc<RefCell<SpriteAtlas>>)` (static, since 0.4.0): 찾을 아틀라스 넣기. (맨 뒤에 넣는다, 이미 들었으면 그대로)
  - 목록은 스레드 하나에 하나다. 같은 아틀라스인지는 Rc 가 같은 것을 가리키는지로 본다.
  - `sprite_atlas` &Rc<RefCell<SpriteAtlas>>: 넣을 아틀라스. (나눠 든다)

  예제: 찾을 목록에 넣고 이름으로 찾아 걸기

  ```rust
  use std::cell::RefCell;
  use std::rc::Rc;
  use vanilla::{Engine, EngineConfiguration, Sprite, SpriteAtlas};
  
  let engine = Engine::new(EngineConfiguration::new());
  let mut sprite_atlas = SpriteAtlas::new();
  sprite_atlas.load(&engine, "examples/assets/atlas/icons.json");
  let sprite_atlas = Rc::new(RefCell::new(sprite_atlas));
  SpriteAtlas::add_search_atlas(&sprite_atlas);
  assert_eq!(SpriteAtlas::find_frame("heart").expect("heart").get_image_rect().size.x, 40.0);
  let mut sprite = Sprite::new();
  assert!(SpriteAtlas::apply_search_frame(&mut sprite, "leaf"));
  assert!(!SpriteAtlas::apply_search_frame(&mut sprite, "nothing"));
  SpriteAtlas::remove_search_atlas(&sprite_atlas);
  assert!(SpriteAtlas::find_frame("heart").is_none());
  SpriteAtlas::clear_search_atlases();
  ```

- `pub fn remove_search_atlas(sprite_atlas: &Rc<RefCell<SpriteAtlas>>)` (static, since 0.4.0): 찾을 아틀라스 빼기.
  - `sprite_atlas` &Rc<RefCell<SpriteAtlas>>: 뺄 아틀라스. (Rc 가 같은 것을 가리키는 것을 뺀다, 없으면 아무것도 하지 않는다)
- `pub fn clear_search_atlases()` (static, since 0.4.0): 찾을 아틀라스 모두 빼기.
- `pub fn find_frame(frame_name: &str) -> Option<Frame>` (static, since 0.4.0): 찾을 아틀라스들에서 조각 찾기. (넣은 차례로, 없으면 None, 다른 곳에서 고치는 중인 아틀라스는 건너뛴다)
  - `frame_name` &str: 그림 이름. (확장자를 뗀 이름도 된다)
  - returns Option<Frame>: 처음 찾은 조각의 복사. (그림 Rc 와 영역이라 값싸다) 어디에도 없으면 None.
- `pub fn apply_search_frame(sprite: &mut Sprite, frame_name: &str) -> bool` (static, since 0.4.0): 찾을 아틀라스들에서 찾은 조각을 스프라이트에 걸기. (없으면 그림을 비우고 false)
  - `sprite` &mut Sprite: 조각을 걸 스프라이트.
  - `frame_name` &str: 그림 이름. (확장자를 뗀 이름도 된다)
  - returns bool: 조각을 걸었으면 true. 어디에도 없으면 그림을 비우고 false.
