game/gamescene
게임 공통 베이스 씬. (원본 game/gamescene.js 의 GameScene)
- 로딩 화면 (가운데 이미지 + 아래 게이지 + 터치로 건너뛰기, 최소 노출 시간).
- 터치 입력은 TouchRecognizer 로 돌린다. (스크롤 뷰 안의 버튼을 끌어도 스크롤되는 손짓)
- 세이프 에어리어 노드 "safeArea" + 세이프 에어리어 영역 계산.
- 뷰 크기가 바뀌면 다음 tick 에서 layout 을 다시 부른다.
- 캔버스 전체를 배경색으로 칠한다. (pre_draw)
- 러스트 판은 상속 대신 씬이 GameSceneBase 를 품고 GameScene 트레이트(원본에서 덮어쓰는 자리)를 구현한 뒤 game_scene! 한 줄로 Scene 을 얻는다:
struct TitleScene { game_scene_base: GameSceneBase, logo_asset: ImageAsset }
impl GameScene for TitleScene {
fn get_game_scene_base(&self) -> &GameSceneBase { &self.game_scene_base }
fn get_game_scene_base_mut(&mut self) -> &mut GameSceneBase { &mut self.game_scene_base }
fn load_assets(&mut self) { // 원본 loadAssets 재정의 자리 (바탕의 로딩 이미지 요청 뒤)
self.logo_asset.load(engine, "logo.png");
self.game_scene_base.get_scene_base_mut().track_asset(&self.logo_asset);
}
fn initialize(&mut self, engine: &Engine) { // 바탕 initialize 뒤
let safe_area_id = self.game_scene_base.get_safe_area_node_id().unwrap(); // 콘텐츠는 여기 아래에 붙인다
}
fn layout(&mut self) { /* game_scene_base.get_safe_area_rect() 를 읽어 콘텐츠를 놓는다 */ }
}
vanilla::game_scene!(TitleScene);Scene 함수마다 바탕을 먼저 부르고 GameScene 의 같은 이름 함수를 부른다. (원본에서 super 를 먼저 부르는 덮어쓰기) post_draw 만 씬의 것을 먼저 부르고 바탕(페이드 막, 개발자 도구)을 위에 그린다. layout 은 바탕이 세이프 에어리어를 다시 계산한 뒤 부른다. (크기 바뀜, 그리고 tick 이 뷰 크기 변화를 볼 때. 첫 tick 에도 한 번) GameSceneBase 함수를 Scene 함수에서 직접 부르는 길도 그대로 된다. 그때는 tick 이 돌려준 bool 을 보고 씬이 자기 layout 을 부르고, post_draw 도 직접 부른다.
- 원본과 다른 점:
- 원본 load(비동기)의 "load_assets 를 기다린 뒤 최소 시간 / 터치까지 기다림"은 러스트 애셋 흐름으로 옮겼다. load 에서 "로딩 문" 읽기 손잡이 하나를 맡겨 두고(SceneBase 가 든다), 엔진이 로딩 중 프레임마다 최소 시간이 지나거나 화면을 누르면 문을 연다. (원본 load 가 거는 엔진 프레임 함수와 같은 자리, 덮어쓸 수 있는 draw_on_load 에 기대지 않아 씬이 바탕 draw_on_load 를 부르지 않아도 멈추지 않는다) 엔진은 맡긴 애셋이 모두(문 포함) 끝나야 initialize 를 부르므로 결과는 원본과 같다. (애셋 다 읽힘 + (최소 시간 또는 터치))
- 두 엔진이 같게 하는 것:
- 로딩 시간은 엔진 시계(get_realtime_since_startup)로 잰다. 엔진 시계가 아직 돌지 않았으면(첫 프레임 전, 0) 첫 로딩 화면 프레임의 시각부터 잰다.
- 로딩 화면 누름은 엔진 입력(is_touch_pressed)으로 엔진이 로딩 중 프레임마다 본다.
- TouchRecognizer 는 원본처럼 initialize 에서 만든다. (그 전에는 get_touch_recognizer 가 None, 원본 undefined) 터치는 원본 touchPress 같은 함수 대신 tick 이 넘긴다. (SceneBase 의 터치 레이캐스터와 첫 터치 콜백은 쓰지 않는다)
- 그 밖에 원본과 다른 점:
- 세이프 에어리어: 웹은 원본처럼 CSS env(safe-area-inset-*) 를 읽는다. 데스크탑은 크롬 데스크탑처럼 0 이고, set_safe_area_insets 로 정해 줄 수 있다. (정하면 웹에서도 그 값을 쓴다)
- set_view_scale_mode 는 엔진을 같이 받는다. (뷰 매니저를 &mut 로 고쳐서 전역 엔진(&Engine)으로는 안 된다) 엔진을 주면 원본처럼 바로 뷰 영역을 다시 계산한다.
- 개발자 도구(DevTools)는 EngineConfiguration::use_dev_tools 가 켜져 있으면 initialize 에서 만든다. (원본과 같음) tick 이 F2 와 터치를 넘기고 post_draw 가 그린다.
- 로딩 화면 바꾸기: set_loading_colors 로 색만, set_loading_drawer 로 바탕 위 그림 전체를 바꾼다. (원본 setLoadingColors, setLoadingDrawer) 건 함수는
Rc<RefCell>에 담는다. get_loading_drawer 는 그 Rc 를 돌려주고, 부르는 쪽은 borrow_mut 로 빌려 부른다. 게이지는 기본으로 최소 노출 시간의 경과(get_loading_progress)를 보이고, set_loading_progress 나 track_asset_loader 로 진행률을 알리면 그 진행률을 부드럽게 따라간다. (LoadingProgress, get_loading_progress_state) - 원본 getLoadingProgress(LoadingProgress 를 돌려줌)는 러스트 판에 이미 같은 이름(경과 시간 비율)이 있어 get_loading_progress_state 다.
- 원본은 load_assets 가 끝나면(알린 적이 있을 때) 진행률을 1 로 채운다. 러스트 판은 씬에 맡긴 애셋 가운데 로딩 문을 뺀 것이 다 끝나면 draw_on_load 가 1 로 채운다. (complete_loading_progress_if_assets_finished, 프레임에 걸쳐 일하는 씬은 읽기 손잡이를 맡겨 두고 끝나면 연다)
- track_asset_loader 로 맡긴 AssetLoader 는 draw_on_load 가 프레임마다 update 를 불러 준다.
- 원본 setLoadingColors 의 넷째 값(바깥 색)은 러스트에 기본값 인자가 없어 set_loading_outside_color 로 따로 정한다.
- 화면 틀 (vanilla.js GameScene 의 fadeScreen, isUserInterfaceAt, setPlayInputHandler, setPlayAreaReference 와 같은 기능):
- 화면 페이드: 원본은 onDark 가 Promise 를 돌려주면 끝날 때까지 어둡게 둔다. 러스트 판의 같은 꼴은 fade_screen_async(on_dark) 다. 다 어두워진 그 tick 에서 on_dark 의 퓨처를 씬 작업으로 맡겨 원본처럼 그 자리에서 첫 await 까지 돌리고(SceneContext 로 씬과 엔진에 닿는다), 퓨처가 끝나면 밝아진다. GameScene 을 구현한 씬은 GameScene::fade_screen_async 로 부르고 game_scene! 이 시작을 맡는다. Scene 을 직접 구현한 씬은
GameSceneBase::fade_screen_async::<씬 타입>으로 부르고, 바탕 tick 뒤에 take_screen_fade_dark_starter 로 꺼내 start 한다. (꺼내지 않으면 바탕이 post_draw 나 다음 tick 에서 다음 폴링 차례로 맡긴다) 동기 꼴 fade_screen(on_dark) 은 다 어두워지면 on_dark(트리, 엔진)를 부르고, on_dark 가 ScreenFadeHold 를 돌려주면 그 손잡이의 release 가 불릴 때까지 어둡게 둔다. (None 이면 바로 밝힌다) 콜백 꼴 fade_screen_with_hold(on_dark) 는 on_dark 가 손잡이를 받아 두었다가 일이 끝나면 release 한다. (Promise 의 resolve 자리) 막은 post_draw 가 그린다. 막이 걸린 동안은 누름과 휠을 받지 않는다. - UI 가 받지 않은 입력: 원본처럼 처리기(set_play_input_handler)를 부른다. 원본 처리기 객체의 press, move, release, wheel 은 PlayInput 의 갈래다. 처리기는 씬을 빌릴 수 없어서 씬 상태는
Rc<RefCell>로 나눠 쥔다. 씬이 tick 에서 직접 꺼내 쓰려면 set_play_input_enabled(true) 로 모아 take_play_inputs 로 꺼낸다. (좌표는 세이프 에어리어 왼쪽 위 기준) - 휠: 원본처럼 창 층(UIWindowLayer) 안을 가리키면 맨 위의 창이 먼저 받고(UIWindowLayer::scroll_window_at), 아니면 그 자리의 스크롤 칸이 받는다.
- 세이프 에어리어는 set_safe_area_insets 로 정하지 않았으면 ViewManager::get_safe_area_insets 를 읽는다. (강제값, 주소, env, 무시할 쪽을 따른다)
Common base scene for games. (GameScene in the original game/gamescene.js)
- Loading screen (center image + gauge at the bottom + touch to skip, minimum display time).
- Touch input goes through TouchRecognizer. (gestures that scroll even when dragging a button inside a scroll view)
- Safe area node "safeArea" + safe area rectangle computation.
- When the view size changes, layout is called again at the next tick.
- Fills the whole canvas with the background color. (pre_draw)
- In the Rust version, instead of inheritance the scene contains a GameSceneBase, implements the GameScene trait (where the original overrides), and gets a Scene with one game_scene! line:
struct TitleScene { game_scene_base: GameSceneBase, logo_asset: ImageAsset }
impl GameScene for TitleScene {
fn get_game_scene_base(&self) -> &GameSceneBase { &self.game_scene_base }
fn get_game_scene_base_mut(&mut self) -> &mut GameSceneBase { &mut self.game_scene_base }
fn load_assets(&mut self) { // where the original overrides loadAssets (after the base requests the loading image)
self.logo_asset.load(engine, "logo.png");
self.game_scene_base.get_scene_base_mut().track_asset(&self.logo_asset);
}
fn initialize(&mut self, engine: &Engine) { // after the base initialize
let safe_area_id = self.game_scene_base.get_safe_area_node_id().unwrap(); // attach content under here
}
fn layout(&mut self) { /* read game_scene_base.get_safe_area_rect() and place content */ }
}
vanilla::game_scene!(TitleScene);For each Scene function, the base is called first and then the GameScene function of the same name. (an override that calls super first in the original) Only post_draw calls the scene's first and draws the base (fade curtain, developer tools) on top. layout is called after the base recomputes the safe area. (on resize, and when tick sees a view size change. Also once on the first tick) Calling GameSceneBase functions directly from Scene functions still works. In that case the scene looks at the bool returned by tick and calls its own layout, and also calls post_draw directly.
- Differences from the original:
- The original load (async) "waits for load_assets, then waits for the minimum time / a touch", which has been moved to the Rust asset flow. In load it hands over one "loading gate" read handle (held by SceneBase), and the engine opens the gate during each loading frame when the minimum time has passed or the screen is pressed. (the same place as the engine frame function the original load registers; it does not rely on draw_on_load, which can be overridden, so the scene does not hang even if it does not call the base draw_on_load) The engine calls initialize only after all handed over assets (including the gate) finish, so the result is the same as the original. (all assets read + (minimum time or touch))
- What both engines do the same way:
- Loading time is measured with the engine clock (get_realtime_since_startup). If the engine clock has not started yet (before the first frame, 0), it is measured from the time of the first loading screen frame.
- A press on the loading screen is read from engine input (is_touch_pressed) by the engine during each loading frame.
- The TouchRecognizer is created in initialize like the original. (Before that get_touch_recognizer is None, undefined in the original) Touches are passed by tick instead of functions like the original touchPress. (SceneBase's touch raycaster and first-touch callback are not used)
- Other differences from the original:
- Safe area: the web reads CSS env(safe-area-inset-*) as in the original. Desktop is 0 like Chrome desktop, and it can be set with set_safe_area_insets. (once set, that value is used on the web too)
- set_view_scale_mode also takes the engine. (it changes the view manager through &mut, so the global engine (&Engine) cannot do it) Given the engine, it recomputes the view area right away as in the original.
- Developer tools (DevTools) are made in initialize if EngineConfiguration::use_dev_tools is on. (same as the original) tick passes F2 and touches, and post_draw draws them.
- Changing the loading screen: set_loading_colors changes only the colors, set_loading_drawer changes the whole drawing on top of the background. (the original setLoadingColors, setLoadingDrawer) The set function is kept in an
Rc<RefCell>. get_loading_drawer returns that Rc, and the caller borrows it with borrow_mut to call it. By default the gauge shows the elapsed minimum display time (get_loading_progress), and if progress is reported with set_loading_progress or track_asset_loader, it smoothly follows that progress. (LoadingProgress, get_loading_progress_state) - The original getLoadingProgress (returns LoadingProgress) is get_loading_progress_state, because the Rust version already has the same name (elapsed time ratio).
- The original fills the progress to 1 when load_assets finishes (if it was ever reported). The Rust version fills it to 1 in draw_on_load when all assets handed to the scene except the loading gate finish. (complete_loading_progress_if_assets_finished, a scene that works across frames hands over a read handle and opens it when done)
- For an AssetLoader handed over with track_asset_loader, draw_on_load calls update every frame.
- The fourth value (outside color) of the original setLoadingColors is set separately with set_loading_outside_color, because Rust has no default arguments.
- Screen frame (the same features as fadeScreen, isUserInterfaceAt, setPlayInputHandler and setPlayAreaReference of vanilla.js GameScene):
- Screen fade: in the original, if onDark returns a Promise, it stays dark until it finishes. The same form in the Rust version is fade_screen_async(on_dark). At the tick it becomes fully dark, it hands on_dark's future over as a scene task and runs it right there up to the first await as in the original (reaching the scene and engine through SceneContext), and when the future finishes it brightens. A scene implementing GameScene calls it with GameScene::fade_screen_async, and game_scene! takes care of starting it. A scene implementing Scene directly calls it with
GameSceneBase::fade_screen_async::<scene type>, and after the base tick takes it out with take_screen_fade_dark_starter and starts it. (if not taken out, the base hands it over at the next polling turn in post_draw or the next tick) The synchronous form fade_screen(on_dark) calls on_dark(tree, engine) when fully dark, and if on_dark returns a ScreenFadeHold, it stays dark until that handle's release is called. (brightens right away if None) The callback form fade_screen_with_hold(on_dark) has on_dark keep the handle and release it when the work is done. (in place of the Promise's resolve) The curtain is drawn by post_draw. While the curtain is up, presses and the wheel are not accepted. - Input the UI did not take: calls the handler (set_play_input_handler) as in the original. press, move, release and wheel of the original handler object are variants of PlayInput. The handler cannot borrow the scene, so scene state is shared through
Rc<RefCell>. For the scene to take them directly in tick, collect them with set_play_input_enabled(true) and take them with take_play_inputs. (coordinates relative to the top left of the safe area) - Wheel: as in the original, if it points inside the window layer (UIWindowLayer), the topmost window takes it first (UIWindowLayer::scroll_window_at), otherwise the scroll box at that position takes it.
- If the safe area is not set with set_safe_area_insets, it reads ViewManager::get_safe_area_insets. (follows the forced value, URL, env and sides to ignore)
LoadingDrawertype
로딩 화면 그리기 함수. (graphic, 뷰 크기, 보이는 진행률 0 ~ 1, 로딩을 시작한 뒤의 초. 뷰 좌표계가 걸려 있다)
Loading screen drawing function. (graphic, view size, visible progress 0 ~ 1, seconds since loading started. The view coordinate system is applied)
pub type LoadingDrawer = Box<dyn FnMut(&mut Graphic, Vector2, f64, f64)>ScreenFadeHoldstruct traits Clone, Debug, Default
화면 페이드를 어둡게 붙잡는 손잡이. (원본 onDark 가 돌려주는 Promise 자리, 복제한 손잡이 어느 것이든 release 하면 밝아진다)
Handle that holds the screen fade dark. (in place of the Promise returned by the original onDark, releasing any clone of the handle brightens it)
use vanilla::{Engine, EngineConfiguration, GameSceneBase, NodeTree, ScreenFadeHold};
let engine = Engine::new(EngineConfiguration::new());
engine.get_view_manager_mut().calculate_view_rect(800, 600, 1.0);
let mut game_scene_base = GameSceneBase::new();
game_scene_base.set_screen_fade_seconds(0.0);
let screen_fade_hold = ScreenFadeHold::new();
let returned_hold = screen_fade_hold.clone();
assert!(game_scene_base.fade_screen(Some(Box::new(move |_node_tree: &mut NodeTree, _engine: &Engine| {
Some(returned_hold)
}))));
game_scene_base.tick(0.016);
game_scene_base.tick(0.016);
assert_eq!(game_scene_base.get_screen_fade_alpha(), 1.0);
screen_fade_hold.release();
assert!(screen_fade_hold.is_released());
game_scene_base.tick(0.016);
game_scene_base.tick(0.016);
assert_eq!(game_scene_base.get_screen_fade_alpha(), 0.0);
assert!(!game_scene_base.is_screen_fading());생성. (아직 놓지 않음)
Creates. (not released yet)
반환ReturnsScreenFadeHold 놓지 않은 손잡이.An unreleased handle.
짝Counterpart: vanilla.js ScreenFadeHold.constructor
놓기. (막이 밝아진다)
Releases. (the curtain brightens)
짝Counterpart: vanilla.js ScreenFadeHold.release
놓았는지.
Whether it has been released.
반환Returnsbool 이 손잡이나 복제한 손잡이 가운데 하나라도 release 했으면 true.true if release was called on this handle or any of its clones.
짝Counterpart: vanilla.js ScreenFadeHold.isReleased
ScreenFadeDarkStarterstruct
화면 페이드의 async on_dark 를 시작하는 것. (fade_screen_async 가 만들고, 다 어두워지면 씬이 take_screen_fade_dark_starter 로 꺼내 start 한다)
- Scene 을 직접 구현한 씬이 바탕 tick 뒤에 꺼내 start 한다. (game_scene!, ui_scene! 은 저절로 한다)
Starter for the async on_dark of a screen fade. (made by fade_screen_async, and when fully dark the scene takes it out with take_screen_fade_dark_starter and starts it)
- A scene that implements Scene directly takes it out and starts it after the base tick. (game_scene!, ui_scene! do this automatically)
use vanilla::{Engine, EngineConfiguration, GameSceneBase, Scene, SceneBase, SceneContext};
struct PuzzleScene {
game_scene_base: GameSceneBase,
stage_number: u32,
}
impl Scene for PuzzleScene {
fn get_scene_base(&self) -> &SceneBase {
self.game_scene_base.get_scene_base()
}
fn get_scene_base_mut(&mut self) -> &mut SceneBase {
self.game_scene_base.get_scene_base_mut()
}
fn tick(&mut self, time_delta: f64) {
self.game_scene_base.tick(time_delta);
if let Some(screen_fade_dark_starter) = self.game_scene_base.take_screen_fade_dark_starter() {
screen_fade_dark_starter.start(self);
}
}
}
let engine = Engine::new(EngineConfiguration::new());
engine.get_view_manager_mut().calculate_view_rect(800, 600, 1.0);
let mut puzzle_scene = PuzzleScene {
game_scene_base: GameSceneBase::new(),
stage_number: 1,
};
puzzle_scene.game_scene_base.set_screen_fade_seconds(0.0);
assert!(puzzle_scene.game_scene_base.fade_screen_async::<PuzzleScene, _, _>(|mut scene_context: SceneContext<PuzzleScene>| async move {
scene_context.with(|scene, _engine| {
scene.stage_number += 1;
});
}));
puzzle_scene.tick(0.016);
assert_eq!(puzzle_scene.stage_number, 2);
puzzle_scene.tick(0.016);
puzzle_scene.tick(0.016);
assert!(!puzzle_scene.game_scene_base.is_screen_fading());시작. (on_dark 의 퓨처를 이 씬의 작업으로 맡겨 그 자리에서 첫 await 까지 돌린다. 씬이 fade_screen_async 의 타입이 아니면 바로 밝아진다)
Starts. (hands on_dark's future over as this scene's task and runs it right there up to the first await. Brightens right away if the scene is not the type of fade_screen_async)
- scene&mut dyn Scene
- 이 바탕을 든 씬. (보통 tick 안의 self, fade_screen_async 의 S 타입이어야 한다. 작업은 전역 엔진에 맡긴다)Scene that holds this base. (usually self inside tick, must be the S type of fade_screen_async. The task is handed to the global engine)
ScreenFadeEventtype
다 어두워졌을 때 부르는 함수. (트리와 엔진을 받는다. 손잡이를 돌려주면 놓을 때까지 어둡게 둔다)
Function called when fully dark. (takes the tree and engine. If it returns a handle, it stays dark until released)
pub type ScreenFadeEvent = Box<dyn FnOnce(&mut NodeTree, &Engine) -> Option<ScreenFadeHold>>ScreenFadeHoldEventtype
다 어두워졌을 때 부르는 함수의 콜백 꼴. (트리, 엔진, 손잡이를 받는다. 손잡이를 놓을 때까지 어둡게 둔다, fade_screen_with_hold)
Callback form of the function called when fully dark. (takes the tree, engine and handle. Stays dark until the handle is released, fade_screen_with_hold)
pub type ScreenFadeHoldEvent = Box<dyn FnOnce(&mut NodeTree, &Engine, ScreenFadeHold)>PlayInputHandlertype
UI 가 받지 않은 입력의 처리기. (원본 setPlayInputHandler 의 처리기 객체, 좌표는 게임 영역 좌표)
Handler for input the UI did not take. (the handler object of the original setPlayInputHandler, coordinates in play area coordinates)
pub type PlayInputHandler = Box<dyn FnMut(PlayInput)>GameSceneBasestruct traits Default
게임 공통 베이스 씬.
- 로딩 화면, 터치 인식, 세이프 에어리어, 화면 페이드, 놀이 입력을 맡는다. 씬이 품고 GameScene 트레이트와 game_scene! 으로 쓰거나, Scene 함수에서 직접 부른다.
Common base scene for games.
- Handles the loading screen, touch recognition, safe area, screen fade, and play input. A scene contains it and uses it through the GameScene trait and game_scene!, or calls it directly from Scene functions.
use vanilla::{Engine, EngineConfiguration, GameSceneBase, Graphic, Scene, SceneBase, Vector2};
struct PuzzleScene {
game_scene_base: GameSceneBase,
layout_count: u32,
}
impl PuzzleScene {
fn layout(&mut self) {
self.layout_count += 1;
}
}
impl Scene for PuzzleScene {
fn get_scene_base(&self) -> &SceneBase {
self.game_scene_base.get_scene_base()
}
fn get_scene_base_mut(&mut self) -> &mut SceneBase {
self.game_scene_base.get_scene_base_mut()
}
fn load(&mut self, engine: &Engine) {
self.game_scene_base.load(engine);
}
fn draw_on_load(&mut self, graphic: &mut Graphic) {
self.game_scene_base.draw_on_load(graphic);
}
fn initialize(&mut self, engine: &Engine) {
self.game_scene_base.initialize(engine);
}
fn resize(&mut self, canvas_native_size: Vector2) {
self.game_scene_base.resize(canvas_native_size);
self.layout();
}
fn tick(&mut self, time_delta: f64) {
if self.game_scene_base.tick(time_delta) {
self.layout();
}
if let Some(screen_fade_dark_starter) = self.game_scene_base.take_screen_fade_dark_starter() {
screen_fade_dark_starter.start(self);
}
}
fn pre_draw(&mut self, graphic: &mut Graphic) {
self.game_scene_base.pre_draw(graphic);
}
fn draw(&mut self, graphic: &mut Graphic) {
self.game_scene_base.get_scene_base_mut().draw(graphic);
}
fn post_draw(&mut self, graphic: &mut Graphic) {
self.game_scene_base.post_draw(graphic);
}
}
let engine = Engine::new(EngineConfiguration::new());
engine.get_view_manager_mut().calculate_view_rect(800, 600, 1.0);
let mut puzzle_scene = PuzzleScene {
game_scene_base: GameSceneBase::new(),
layout_count: 0,
};
puzzle_scene.initialize(engine);
puzzle_scene.tick(0.016);
assert_eq!(puzzle_scene.layout_count, 1);
assert!(puzzle_scene.game_scene_base.get_safe_area_node_id().is_some());
assert_eq!(puzzle_scene.game_scene_base.get_safe_area_rect().size, Vector2::create(800.0, 600.0));생성. (최소 노출 3 초, 검은 배경, ViewScaleMode::None)
- 로딩 색은 검정, #333333, #ffffff, 페이드는 검정 0.35 초다. 세이프 에어리어 노드는 initialize 에서 만든다.
Creates. (minimum display 3 seconds, black background, ViewScaleMode::None)
- Loading colors are black, #333333, #ffffff, and the fade is black for 0.35 seconds. The safe area node is created in initialize.
반환ReturnsGameSceneBase initialize 전의 바탕.Base before initialize.
짝Counterpart: vanilla.js GameScene.constructor
pub fn calculate_safe_area_rect(view_size: Vector2, target_resolution_scale: f64, insets: SafeAreaInsets) -> Rect#세이프 에어리어 계산. (정적. CSS 픽셀 인셋을 뷰 배율로 나눠 뷰 영역에서 뺀다)
Computes the safe area. (static. Divides the CSS pixel insets by the view scale and subtracts them from the view area)
- view_sizeVector2
- 뷰 크기. (뷰 좌표)View size. (view coordinates)
- target_resolution_scalef64
- 뷰 배율. (뷰 좌표 1 이 CSS 픽셀 몇인지, 0 이하이면 1)View scale. (how many CSS pixels one view coordinate unit is, 1 if 0 or less)
- insetsSafeAreaInsets
- 위, 오른쪽, 아래, 왼쪽 인셋. (CSS 픽셀)Top, right, bottom, left insets. (CSS pixels)
반환ReturnsRect 세이프 에어리어 영역. (뷰 좌표, 크기는 0 아래로 내려가지 않는다)Safe area rectangle. (view coordinates, the size does not go below 0)
짝Counterpart: vanilla.js GameScene.calculateSafeAreaRect
use vanilla::{GameSceneBase, Rect, SafeAreaInsets, Vector2};
let safe_area_rect = GameSceneBase::calculate_safe_area_rect(Vector2::create(400.0, 300.0), 2.0, SafeAreaInsets::create(40.0, 10.0, 20.0, 30.0));
assert_eq!(safe_area_rect, Rect::create(15.0, 20.0, 380.0, 270.0));
let collapsed_rect = GameSceneBase::calculate_safe_area_rect(Vector2::create(10.0, 10.0), 0.0, SafeAreaInsets::create(20.0, 20.0, 20.0, 20.0));
assert_eq!(collapsed_rect, Rect::create(20.0, 20.0, 0.0, 0.0));pub fn calculate_play_area_reference_length(fixed_length: f64, is_landscape: bool, canvas_native_size: Vector2, safe_area_insets: SafeAreaInsets, inset_scale: f64) -> f64#게임 영역 기준의 기준 해상도 길이 셈. (정적, 인셋은 뷰 좌표, inset_scale 은 뷰 좌표 → 캔버스 단위 배율, 못 셈하면 0)
- fixed_length × 캔버스 길이 / (캔버스 길이 - 인셋 합 × inset_scale) 이다.
Computes the reference resolution length for the play area reference. (static, insets in view coordinates, inset_scale is the view coordinates → canvas units scale, 0 if it cannot be computed)
- It is fixed_length × canvas length / (canvas length - inset sum × inset_scale).
- fixed_lengthf64
- 게임 영역의 고정 쪽 길이.Fixed side length of the play area.
- is_landscapebool
- true 면 가로(왼쪽, 오른쪽 인셋), false 면 세로(위, 아래 인셋)로 셈한다.true computes horizontally (left, right insets), false vertically (top, bottom insets).
- canvas_native_sizeVector2
- 캔버스 논리 크기.Logical canvas size.
- safe_area_insetsSafeAreaInsets
- 세이프 에어리어 인셋. (뷰 좌표)Safe area insets. (view coordinates)
- inset_scalef64
- 인셋을 캔버스 단위로 바꾸는 배율.Scale that converts insets to canvas units.
반환Returnsf64 고정 쪽의 기준 해상도 길이. 캔버스 길이나 인셋을 뺀 길이가 0 이하이면 0.Reference resolution length of the fixed side. 0 if the canvas length or the length minus the insets is 0 or less.
짝Counterpart: vanilla.js GameScene.calculatePlayAreaReferenceLength
use vanilla::{GameSceneBase, SafeAreaInsets, Vector2};
let reference_length = GameSceneBase::calculate_play_area_reference_length(720.0, false, Vector2::create(800.0, 600.0), SafeAreaInsets::create(40.0, 0.0, 30.0, 0.0), 1.0);
assert!((reference_length - 720.0 * 600.0 / 530.0).abs() < 0.01);
let landscape_length = GameSceneBase::calculate_play_area_reference_length(1920.0, true, Vector2::create(1000.0, 500.0), SafeAreaInsets::create(0.0, 25.0, 0.0, 25.0), 2.0);
assert!((landscape_length - 1920.0 * 1000.0 / 900.0).abs() < 0.01);
assert_eq!(GameSceneBase::calculate_play_area_reference_length(720.0, false, Vector2::create(800.0, 0.0), SafeAreaInsets::create(0.0, 0.0, 0.0, 0.0), 1.0), 0.0);개발자 도구 반환. (initialize 전이거나 EngineConfiguration::use_dev_tools 가 꺼져 있으면 None)
Returns the developer tools. (None before initialize or if EngineConfiguration::use_dev_tools is off)
반환ReturnsOption<&DevTools> 개발자 도구. initialize 전이거나 꺼져 있으면 None.Developer tools. None before initialize or when turned off.
짝Counterpart: vanilla.js GameScene.getDevTools
개발자 도구 반환. (변경용)
Returns the developer tools. (mutable)
반환ReturnsOption<&mut DevTools> 개발자 도구. (변경용) initialize 전이거나 꺼져 있으면 None.Developer tools. (mutable) None before initialize or when turned off.
짝Counterpart: vanilla.js GameScene.getDevTools
씬 공통 상태 반환. (Scene::get_scene_base 에서 돌려준다)
Returns the common scene state. (returned from Scene::get_scene_base)
반환Returns&SceneBase 바탕이 품은 씬 공통 상태.Common scene state held by the base.
씬 공통 상태 반환. (변경용)
Returns the common scene state. (mutable)
반환Returns&mut SceneBase 바탕이 품은 씬 공통 상태. (변경용)Common scene state held by the base. (mutable)
터치 인식기 반환. (원본 getTouchRaycaster, initialize 에서 만든다)
Returns the touch recognizer. (Original getTouchRaycaster, created in initialize)
반환ReturnsOption<&TouchRecognizer> tick 이 터치를 넘기는 인식기. initialize 전에는 None. (원본 undefined)The recognizer tick passes touches to. None before initialize. (undefined in the original)
터치 인식기 반환. (변경용)
Returns the touch recognizer. (mutable)
반환ReturnsOption<&mut TouchRecognizer> tick 이 터치를 넘기는 인식기. (변경용) initialize 전에는 None.The recognizer tick passes touches to. (mutable) None before initialize.
pub fn set_view_scale_mode(&mut self, view_scale_mode: ViewScaleMode, engine: Option<&Engine>)#ViewScaleMode 설정. (기본 none. 엔진을 주면 바로 뷰 영역에 반영하고, 아니면 initialize 에서 적용한다)
Sets the ViewScaleMode. (default none. Given the engine, it applies to the view area right away, otherwise it is applied in initialize)
- view_scale_modeViewScaleMode
- 뷰 배율 방식.View scale mode.
- engineOption<&Engine>
- 바로 반영할 엔진. None 이면 initialize 에서 적용한다.Engine to apply it to right away. If None, it is applied in initialize.
짝Counterpart: vanilla.js GameScene.setViewScaleMode
use vanilla::{Engine, EngineConfiguration, GameSceneBase, Vector2, ViewScaleMode};
let engine = Engine::new(EngineConfiguration::new());
engine.get_view_manager_mut().calculate_view_rect(800, 600, 1.0);
let mut game_scene_base = GameSceneBase::new();
game_scene_base.set_view_scale_mode(ViewScaleMode::ReferenceResolution, Some(engine));
assert_eq!(game_scene_base.get_view_scale_mode(), ViewScaleMode::ReferenceResolution);
assert_eq!(engine.get_view_manager().get_view_size(), Vector2::create(1280.0, 720.0));지금 ViewScaleMode 반환.
Returns the current ViewScaleMode.
반환ReturnsViewScaleMode 이 바탕에 정한 뷰 배율 방식. (기본 ViewScaleMode::None)View scale mode set on this base. (default ViewScaleMode::None)
짝Counterpart: vanilla.js GameScene.getViewScaleMode
로딩 화면 가운데 이미지 경로 설정. (빈 글이면 이미지 없이 게이지만. create 전에 정한다)
Sets the path of the loading screen center image. (only the gauge without an image for empty text. Set before create)
- url&str
- 로딩 이미지의 애셋 경로. (create 의 load_assets 가 읽어 씬에 맡긴다)Asset path of the loading image. (load_assets in create loads it and hands it to the scene)
짝Counterpart: vanilla.js GameScene.setLoadingImageUrl
로딩 화면 최소 노출 시간 설정. (밀리초. create 전에 정한다)
Sets the minimum display time of the loading screen. (milliseconds. Set before create)
- millisecondsf64
- 최소 노출 시간. (밀리초, 기본 3000, 0 이하이면 기다리지 않는다)Minimum display time. (milliseconds, default 3000, does not wait if 0 or less)
짝Counterpart: vanilla.js GameScene.setLoadingMinDurationMs
로딩 화면 그리기 함수 설정. (None 이면 기본 그림: 가운데 로딩 이미지 + 아래 게이지)
- 캔버스를 바깥 색으로, 뷰를 바탕색으로 칠하고 뷰 좌표계를 건 뒤 drawer(graphic, 뷰 크기, 보이는 진행률, 경과 초) 를 부른다.
- 그림과 글꼴을 받기 전에도 그려지므로 도형과 기본 글꼴로 그린다. 그릴 것은 함수가 스스로 들고 있는다.
Sets the loading screen drawing function. (None for the default drawing: loading image in the center + gauge at the bottom)
- Fills the canvas with the outside color and the view with the background color, applies the view coordinate system, then calls drawer(graphic, view size, visible progress, elapsed seconds).
- It is drawn even before images and fonts are received, so draw with shapes and the default font. The function itself holds what it draws.
- loading_drawerOption<LoadingDrawer>
- 로딩 화면 그리기 함수. (graphic, 뷰 크기, 보이는 진행률 0 ~ 1, 경과 초) None 이면 기본 그림.Loading screen drawing function. (graphic, view size, displayed progress 0 ~ 1, elapsed seconds) None uses the default drawing.
짝Counterpart: vanilla.js GameScene.setLoadingDrawer
use vanilla::{Colors, GameSceneBase, Graphic, Rect, Vector2};
let mut game_scene_base = GameSceneBase::new();
game_scene_base.set_loading_drawer(Some(Box::new(|graphic: &mut Graphic, view_size: Vector2, progress: f64, _elapsed_seconds: f64| {
graphic.set_fill_color(Colors::WHITE);
graphic.draw_rect(Rect::create(0.0, view_size.y - 8.0, view_size.x * progress, 8.0));
})));
assert!(game_scene_base.has_loading_drawer());로딩 화면 그리기 함수가 있는지.
Whether there is a loading screen drawing function.
반환Returnsbool 그리기 함수를 걸었으면 true.true if a drawing function is set.
짝Counterpart: vanilla.js GameScene.hasLoadingDrawer
로딩 화면 그리기 함수 반환. (없으면 None, 부를 때는 borrow_mut 로 빌린다)
Returns the loading screen drawing function. (None if absent, borrow it with borrow_mut to call it)
반환ReturnsOption<Rc<RefCell<LoadingDrawer>>> 그리기 함수를 담은 Rc<RefCell>. 없으면 None.Rc<RefCell> holding the drawing function. None if there is none.
짝Counterpart: vanilla.js GameScene.getLoadingDrawer
pub fn set_loading_colors(&mut self, background_color: impl Into<Color>, bar_back_color: impl Into<Color>, bar_fill_color: impl Into<Color>)#로딩 화면 색 설정. (바탕, 게이지 바탕, 게이지. 뷰 바깥도 바탕색이 된다. 기본은 검정, #333333, #ffffff)
Sets the loading screen colors. (background, gauge background, gauge. Outside the view also becomes the background color. Defaults are black, #333333, #ffffff)
- background_colorimpl Into<Color>
- 뷰 바탕색이자 뷰 바깥 색. (Color 나 "#rrggbb" 같은 글)View background color, also the color outside the view. (a Color or a string like "#rrggbb")
- bar_back_colorimpl Into<Color>
- 게이지 바탕색.Gauge background color.
- bar_fill_colorimpl Into<Color>
- 게이지 채움색.Gauge fill color.
짝Counterpart: vanilla.js GameScene.setLoadingColors
로딩 화면 뷰 바깥(캔버스 나머지)의 색 설정. (원본 setLoadingColors 의 넷째 값, set_loading_colors 뒤에 부른다)
Sets the color outside the loading screen view (the rest of the canvas). (the fourth value of the original setLoadingColors, call after set_loading_colors)
- outside_colorimpl Into<Color>
- 뷰 바깥 색. (Color 나 "#rrggbb" 같은 글)Color outside the view. (a Color or a string like "#rrggbb")
짝Counterpart: vanilla.js GameScene.setLoadingOutsideColor
로딩 진행률 알리기. (0 ~ 1, 줄어들지 않는다. 알린 뒤로 게이지가 경과 시간 대신 이 값을 따라간다)
Reports loading progress. (0 ~ 1, never decreases. After reporting, the gauge follows this value instead of the elapsed time)
- progressf64
- 알릴 진행률. (0 ~ 1)Progress to report. (0 ~ 1)
짝Counterpart: vanilla.js GameScene.setLoadingProgress
로딩 진행률 상태. (알린 정도와 부드럽게 따라가는 보이는 정도, 원본 getLoadingProgress)
Loading progress state. (the reported amount and the visible amount that smoothly follows it, the original getLoadingProgress)
반환Returns&LoadingProgress 로딩 진행률 상태.Loading progress state.
로딩 진행률 상태. (변경용, 따라가는 빠르기를 바꿀 때)
Loading progress state. (mutable, for changing the follow speed)
반환Returns&mut LoadingProgress 로딩 진행률 상태. (변경용)Loading progress state. (mutable)
애셋 함께 받기 맡기기. (다 받을 때까지 initialize 를 미루고, draw_on_load 가 update 를 부르고 진행률을 알린다)
- 맡긴 뒤로 게이지는 경과 시간 대신 받은 진행률을 따라간다.
Hands over a batch asset load. (delays initialize until everything is received, draw_on_load calls update and reports progress)
- After handing over, the gauge follows the load progress instead of the elapsed time.
- asset_loader&AssetLoader
- 맡길 받기. (나눠 든다, load 는 부르는 쪽이 한다)Load to hand over. (shared, the caller calls load)
짝Counterpart: vanilla.js GameScene.trackAssetLoader
use vanilla::{AssetLoadHandle, AssetLoader, Engine, EngineConfiguration, GameSceneBase};
let engine = Engine::new(EngineConfiguration::new());
let mut game_scene_base = GameSceneBase::new();
game_scene_base.set_loading_min_duration_ms(0.0);
game_scene_base.begin_loading(0.0);
let asset_loader = AssetLoader::new();
asset_loader.add_image("examples/assets/atlas/icons.png");
let generate_handle = AssetLoadHandle::create_pending("level.generate");
asset_loader.add_load_handle(&generate_handle);
game_scene_base.track_asset_loader(&asset_loader);
asset_loader.load(&engine);
game_scene_base.update_tracked_asset_loaders(&engine);
assert_eq!(game_scene_base.get_loading_progress_state().get_progress(), 0.5);
assert!(!game_scene_base.get_scene_base().are_tracked_assets_finished());
generate_handle.finish(Ok(Vec::new()));
game_scene_base.update_tracked_asset_loaders(&engine);
assert_eq!(game_scene_base.get_loading_progress_state().get_progress(), 1.0);
assert!(game_scene_base.get_scene_base().are_tracked_assets_finished());맡긴 애셋 함께 받기를 갱신하고 진행률을 알린다. (맡긴 것들의 끝난 수 / 전체 수)
- 맡긴 것이 없으면 아무것도 하지 않는다. draw_on_load 가 프레임마다 부른다.
Updates the handed over batch asset loads and reports progress. (finished count / total count of those handed over)
- Does nothing if nothing was handed over. draw_on_load calls it every frame.
- engine&Engine
- 받기의 update 에 넘길 엔진.Engine to pass to the loads' update.
로딩 문을 뺀 맡긴 애셋이 다 끝났으면 진행률을 1 로 채운다. (원본 load 가 load_assets 를 기다린 뒤 1 을 알리는 자리, 알린 적이 없으면 하지 않는다)
Fills progress to 1 when all handed over assets except the loading gate finish. (where the original load reports 1 after waiting for load_assets, does nothing if never reported)
캔버스 배경색 설정. (pre_draw 에서 캔버스 전체에 칠한다)
Sets the canvas background color. (fills the whole canvas in pre_draw)
- colorimpl Into<Color>
- 배경색. (Color 나 "#rrggbb" 같은 글, 기본 검정)Background color. (a Color or a string like "#rrggbb", default black)
짝Counterpart: vanilla.js Scene.setSceneBackgroundColor
세이프 에어리어 노드 반환. (씬이 콘텐츠를 여기에 붙인다. initialize 전이면 None)
Returns the safe area node. (the scene attaches content here. None before initialize)
반환ReturnsOption<NodeId> 루트 아래 "safeArea" 노드. initialize 전이거나 노드를 만들지 않는 바탕(UISceneBase)이면 None.The "safeArea" node under the root. None before initialize or for a base that does not create the node (UISceneBase).
마지막으로 계산한 세이프 에어리어 영역 반환. (뷰 좌표)
Returns the last computed safe area rectangle. (view coordinates)
반환ReturnsRect 마지막 layout 이 계산한 영역. (뷰 좌표, 계산 전이면 0)Area computed by the last layout. (view coordinates, 0 before it is computed)
짝Counterpart: vanilla.js GameScene.getSafeAreaRect
세이프 에어리어 인셋 직접 설정. (CSS 픽셀, None 이면 뷰 매니저의 get_safe_area_insets 를 읽는다)
Sets the safe area insets directly. (CSS pixels, None reads the view manager's get_safe_area_insets)
- insetsOption<SafeAreaInsets>
- 위, 오른쪽, 아래, 왼쪽 인셋. (CSS 픽셀, 다음 layout 부터 쓴다) None 이면 뷰 매니저에서 읽는다.Top, right, bottom, left insets. (CSS pixels, used from the next layout) None reads them from the view manager.
짝Counterpart: vanilla.js GameScene.setSafeAreaInsets
생성. (씬 load 에서 맨 먼저 부른다. 원본 load 의 앞부분 + load_assets)
- 엔진 시작 뒤 실제 경과 시간으로 begin_loading 을 부르고 load_assets 를 부른다.
Creates. (called first in the scene's load. The front part of the original load + load_assets)
- Calls begin_loading with the real time elapsed since the engine started, then calls load_assets.
- engine&Engine
- 시각을 읽고 로딩 이미지를 부탁할 엔진.Engine to read the time from and request the loading image from.
짝Counterpart: vanilla.js GameScene.load
로딩 시작. (시작 시각을 적고, 최소 시간 / 터치를 기다리는 로딩 문을 씬에 맡긴다)
- 최소 노출 시간이 0 이하이면 로딩 문을 처음부터 열어 둔다.
- 문은 엔진이 로딩 중 프레임마다(엔진 시계와 엔진 입력으로) 갱신해 연다. 덮어쓸 수 있는 draw_on_load 에 기대지 않아, 씬이 바탕 draw_on_load 를 부르지 않아도 initialize 가 불린다. (원본 load 가 거는 엔진 프레임 함수)
Starts loading. (records the start time and hands the scene a loading gate that waits for the minimum time / a touch)
- If the minimum display time is 0 or less, the loading gate is left open from the start.
- The engine updates and opens the gate during each loading frame (with the engine clock and engine input). It does not rely on draw_on_load, which can be overridden, so initialize is called even if the scene does not call the base draw_on_load. (the engine frame function the original load registers)
- current_timef64
- 지금 시각. (초, 엔진 시작 뒤 실제 경과 시간)Current time. (seconds, real time elapsed since the engine started)
자산 읽기. (원본 loadAssets 의 기본 부분: 로딩 이미지. 씬의 자체 애셋은 씬 load 에서 요청하고 track_asset 으로 맡긴다)
- 로딩 이미지 경로가 비었으면 아무것도 하지 않는다.
Loads assets. (the default part of the original loadAssets: the loading image. The scene's own assets are requested in the scene's load and handed over with track_asset)
- Does nothing if the loading image path is empty.
짝Counterpart: vanilla.js GameScene.loadAssets
로딩 갱신. (누르면 건너뛰기로 적고, 최소 시간이 지났거나 건너뛰었으면 로딩 문을 연다)
- begin_loading 전이거나 문이 이미 열렸으면 문은 그대로다.
- 엔진이 로딩 중 프레임마다 같은 갱신을 부른다. 게임이 따로 부르지 않아도 된다. (시각을 손으로 주는 시험과 도구 자리)
Updates loading. (records a skip when pressed, and opens the loading gate when the minimum time has passed or it was skipped)
- The gate is left as is before begin_loading or if it is already open.
- The engine calls the same update during each loading frame, so the game does not need to call it. (for tests and tools that pass the time by hand)
- current_timef64
- 지금 시각. (초, begin_loading 에 준 것과 같은 시계)Current time. (seconds, the same clock as given to begin_loading)
- is_touch_pressedbool
- 이번 프레임에 화면을 눌렀는지.Whether the screen was pressed this frame.
use vanilla::GameSceneBase;
let mut game_scene_base = GameSceneBase::new();
game_scene_base.set_loading_min_duration_ms(3000.0);
game_scene_base.begin_loading(10.0);
assert_eq!(game_scene_base.get_loading_progress(11.5), 0.5);
game_scene_base.update_loading(12.9, false);
assert!(!game_scene_base.get_scene_base().are_tracked_assets_finished());
game_scene_base.update_loading(13.0, false);
assert!(game_scene_base.get_scene_base().are_tracked_assets_finished());use vanilla::GameSceneBase;
let mut game_scene_base = GameSceneBase::new();
game_scene_base.begin_loading(0.0);
game_scene_base.update_loading(0.2, true);
assert!(game_scene_base.is_load_touched_to_skip());
assert!(game_scene_base.get_scene_base().are_tracked_assets_finished());로딩 게이지 진행률. (경과 시간 / 최소 노출 시간, 0 ~ 1)
Loading gauge progress. (elapsed time / minimum display time, 0 ~ 1)
- current_timef64
- 지금 시각. (초, begin_loading 에 준 것과 같은 시계)Current time. (seconds, the same clock as given to begin_loading)
반환Returnsf64 경과 시간 비율. (0 ~ 1, 최소 노출 시간이 0 이하이면 1)Elapsed time ratio. (0 ~ 1, 1 if the minimum display time is 0 or less)
짝Counterpart: vanilla.js GameScene.getLoadingProgress
건너뛰기 눌렸는지.
Whether skip was pressed.
반환Returnsbool begin_loading 뒤 update_loading 에 누름이 왔으면 true.true if a press came to update_loading after begin_loading.
짝Counterpart: vanilla.js GameScene.isLoadTouchedToSkip
로딩 화면 출력. (엔진이 initialize 전까지 매 프레임 부른다. 바깥 색 캔버스 + 바탕색 뷰 + (그리기 함수, 없으면 가운데 로딩 이미지 + 아래 게이지))
- 그리기 전에 맡긴 받기를 갱신하고, 보이는 진행률을 따라가게 한다. (로딩 시각과 건너뛰기는 엔진이 로딩 중 프레임마다 잡는다)
Draws the loading screen. (the engine calls it every frame until initialize. Outside color canvas + background color view + (the drawing function, or if none, loading image in the center + gauge at the bottom))
- Before drawing, updates the handed over loads and makes the displayed progress catch up. (the engine takes the loading time and skip during each loading frame)
- graphic&mut Graphic
- 로딩 화면을 그릴 그래픽.Graphic to draw the loading screen with.
짝Counterpart: vanilla.js GameScene.drawOnLoad
초기화. (씬 initialize 에서 맨 먼저 부른다. ViewScaleMode 적용, 세이프 에어리어 노드 생성)
- 게임 영역 기준을 걸고, EngineConfiguration::use_dev_tools 가 켜져 있으면 개발자 도구를 만든다.
Initializes. (called first in the scene's initialize. Applies the ViewScaleMode, creates the safe area node)
- Applies the play area reference, and creates the developer tools if EngineConfiguration::use_dev_tools is on.
- engine&Engine
- 뷰 매니저와 설정을 가진 엔진.Engine that has the view manager and configuration.
짝Counterpart: vanilla.js GameScene.initialize
화면 크기 변경됨. (게임 영역 기준을 다시 걸고 기본 레이아웃을 다시 한다. 씬의 layout 은 game_scene! 이 이 뒤에 부른다)
Screen size changed. (resets the play area reference and redoes the default layout. game_scene! calls the scene's layout after this)
- _canvas_native_sizeVector2
- 창 안쪽 논리 크기. (쓰지 않는다, 뷰 매니저에서 읽는다)Logical size of the window interior. (unused, read from the view manager)
짝Counterpart: vanilla.js GameScene.resize
레이아웃. (세이프 에어리어 영역을 다시 계산해 노드에 건다)
Layout. (recomputes the safe area rectangle and applies it to the node)
짝Counterpart: vanilla.js GameScene.layout
세이프 에어리어 계산. (뷰 좌표)
- 직접 정한 인셋은 뷰 배율로 나눠 빼고, 아니면 뷰 매니저의 인셋(이미 뷰 좌표)을 뺀다. 게임 영역 기준을 쓰면 캔버스를 배율로 나눈 크기로 셈한다.
Computes the safe area. (view coordinates)
- Insets set directly are divided by the view scale and subtracted, otherwise the view manager's insets (already in view coordinates) are subtracted. When the play area reference is used, computes with the canvas size divided by the scale.
반환ReturnsRect 세이프 에어리어 영역. (뷰 좌표, 크기는 0 아래로 내려가지 않는다)Safe area rectangle. (view coordinates, the size does not go below 0)
짝Counterpart: vanilla.js GameScene.computeSafeAreaRect
뷰 크기가 바뀌었으면 기본 레이아웃을 다시 한다. (바뀌었으면 true)
Redoes the default layout if the view size changed. (true if it changed)
- engine&Engine
- 뷰 크기를 읽을 엔진.Engine to read the view size from.
반환Returnsbool 뷰 크기가 마지막으로 본 것과 달라 레이아웃을 다시 했으면 true. (initialize 가 본 크기를 0 으로 되돌려, 뷰 크기가 0 이 아니면 그 뒤 처음 부를 때도 true)true if the view size differed from the last one seen and the layout was redone. (initialize resets the seen size to 0, so it is also true on the first call after that if the view size is not 0)
갱신. (노드 → TouchRecognizer 터치 → 트윈, 그다음 뷰 크기 변화를 보고 레이아웃. 레이아웃을 다시 했으면 true)
- 모바일 주소창이 나타나고 사라질 때처럼 resize 만으로는 놓칠 수 있어 매 tick 확인한다. (원본과 같음)
- 뒤이어 화면 페이드와 개발자 도구를 갱신한다. 씬이 꺼내 가지 않은 페이드 시작은 다음 폴링 차례로 맡긴다.
Updates. (node → TouchRecognizer touches → tweens, then layout after checking for a view size change. true if layout was redone)
- Checked every tick because resize alone can miss cases like a mobile address bar appearing and disappearing. (same as the original)
- Then updates the screen fade and the developer tools. A fade starter the scene did not take out is handed to the next polling turn.
- time_deltaf64
- 배율을 곱한 프레임 간격. (초, 노드와 트윈에 쓴다. 페이드는 배율을 곱하지 않은 시간으로 돈다)Frame interval multiplied by the time scale. (seconds, used for nodes and tweens. The fade runs on unscaled time)
반환Returnsbool 뷰 크기가 바뀌어 레이아웃을 다시 했으면 true. (씬은 이때 자기 layout 을 부른다)true if the view size changed and the layout was redone. (the scene calls its own layout then)
짝Counterpart: vanilla.js GameScene.tick
use vanilla::{Engine, EngineConfiguration, GameSceneBase, Rect, SafeAreaInsets};
let engine = Engine::new(EngineConfiguration::new());
engine.get_view_manager_mut().calculate_view_rect(800, 600, 1.0);
let mut game_scene_base = GameSceneBase::new();
game_scene_base.set_safe_area_insets(Some(SafeAreaInsets::create(10.0, 0.0, 20.0, 5.0)));
game_scene_base.initialize(engine);
assert!(game_scene_base.tick(0.016));
assert_eq!(game_scene_base.get_safe_area_rect(), Rect::create(5.0, 10.0, 795.0, 570.0));
assert!(!game_scene_base.tick(0.016));
engine.get_view_manager_mut().calculate_view_rect(1024, 768, 1.0);
assert!(game_scene_base.tick(0.016));
assert_eq!(game_scene_base.get_safe_area_rect(), Rect::create(5.0, 10.0, 1019.0, 738.0));이번 프레임의 휠을 스크롤 칸 등이 받아 썼는지. (tick 뒤에 읽는다, false 일 때만 게임의 지도 확대 등에 쓰면 창의 스크롤과 겹치지 않는다)
Whether a scroll box or the like took this frame's wheel. (read after tick. Using it for the game's map zoom and the like only when false keeps it from overlapping window scrolling)
반환Returnsbool 이번 프레임의 휠을 스크롤 칸이나 창이 받아 썼으면 true.true if a scroll box or window consumed this frame's wheel.
개발자 도구가 입력을 가져가는 중인지. (보이고, 누른 자리가 판 안)
Whether the developer tools are taking input. (visible, and the pressed point is inside the panel)
반환Returnsbool 개발자 도구가 보이고 입력 자리가 판 안이면 true. 개발자 도구가 없으면 false.true if the developer tools are visible and the input position is inside the panel. false if there are no developer tools.
짝Counterpart: vanilla.js GameScene.isDevToolsCapturingInput
이전 출력. (캔버스 전체를 배경색으로 칠하고 뷰 좌표계를 건다. 세이프 에어리어 바깥 포함)
Pre-draw. (fills the whole canvas with the background color and applies the view coordinate system. Including outside the safe area)
- graphic&mut Graphic
- 칠할 그래픽.Graphic to fill.
짝Counterpart: vanilla.js GameScene.preDraw
이후 출력. (어두워지는 막을 세이프 에어리어까지 캔버스 전체에 그리고, 개발자 도구를 맨 위에 그린다)
- 씬이 꺼내 가지 않은 페이드 시작은 여기서 다음 폴링 차례로 맡긴다.
Post-draw. (draws the darkening curtain over the whole canvas including the safe area, and draws the developer tools on top)
- A fade starter the scene did not take out is handed to the next polling turn here.
- graphic&mut Graphic
- 그릴 그래픽.Graphic to draw with.
짝Counterpart: vanilla.js GameScene.postDraw
어두워지는 막 그리기. (세이프 에어리어까지 캔버스 전체, 원본 drawScreenFade)
- 막의 진하기가 0 이면 그리지 않는다. 그린 뒤 뷰 좌표계를 다시 건다.
Draws the darkening curtain. (over the whole canvas including the safe area, the original drawScreenFade)
- Does not draw if the curtain's opacity is 0. Sets the view coordinate system again after drawing.
- graphic&mut Graphic
- 그릴 그래픽.Graphic to draw with.
짝Counterpart: vanilla.js GameScene.drawScreenFade
어두워졌다 밝아지기. (다 어두워지면 on_dark 를 부르고, 그것이 손잡이를 돌려주면 놓을 때까지 어둡게 둔다, 이미 페이드 중이면 false)
- 막은 tick 이 움직이고 post_draw 가 그린다. 막이 걸린 동안은 누름과 휠을 받지 않는다.
Darkens then brightens. (calls on_dark when fully dark, and if it returns a handle, stays dark until it is released. false if already fading)
- tick moves the curtain and post_draw draws it. Presses and the wheel are not accepted while the curtain is up.
- on_darkOption<ScreenFadeEvent>
- 다 어두워졌을 때 부를 함수. (트리와 엔진을 받고, 손잡이를 돌려주면 놓을 때까지 어둡다) None 이면 어두워졌다 바로 밝아진다.Function to call when fully dark. (takes the tree and engine, and if it returns a handle, stays dark until it is released) None darkens and then brightens right away.
반환Returnsbool 페이드를 시작했으면 true. 이미 페이드 중이면 false.true if the fade started. false if already fading.
짝Counterpart: vanilla.js GameScene.fadeScreen
use vanilla::{Engine, EngineConfiguration, GameSceneBase, NodeTree};
let engine = Engine::new(EngineConfiguration::new());
engine.get_view_manager_mut().calculate_view_rect(800, 600, 1.0);
let mut game_scene_base = GameSceneBase::new();
game_scene_base.set_screen_fade_seconds(0.0);
assert!(game_scene_base.fade_screen(Some(Box::new(|node_tree: &mut NodeTree, _engine: &Engine| {
let root_id = node_tree.get_root_id();
node_tree.create_child(root_id, "nextStage");
None
}))));
assert!(!game_scene_base.fade_screen(None));
game_scene_base.tick(0.016);
assert_eq!(game_scene_base.get_screen_fade_alpha(), 1.0);
game_scene_base.tick(0.016);
assert!(!game_scene_base.is_screen_fading());어두워졌다 밝아지기의 콜백 꼴. (다 어두워지면 on_dark 에 손잡이를 넘기고, 그 손잡이를 놓을 때까지 어둡게 둔다, 이미 페이드 중이면 false)
- 원본 onDark 가 돌려주는 Promise 의 resolve 자리가 손잡이의 release 다. 다 어두워진 자리에서 바로 놓으면 바로 밝아진다.
Callback form of darken then brighten. (passes a handle to on_dark when fully dark, and stays dark until that handle is released. false if already fading)
- The handle's release is in place of the resolve of the Promise returned by the original onDark. Releasing it right when fully dark brightens it right away.
- on_darkScreenFadeHoldEvent
- 다 어두워졌을 때 트리, 엔진, 손잡이를 받을 함수. (손잡이를 들고 있다가 일이 끝나면 release 한다)Function that receives the tree, engine, and handle when fully dark. (hold the handle and release it when the work is done)
반환Returnsbool 페이드를 시작했으면 true. 이미 페이드 중이면 false.true if the fade started. false if already fading.
짝Counterpart: vanilla.js GameScene.fadeScreenWithHold
use std::cell::RefCell;
use std::rc::Rc;
use vanilla::{Engine, EngineConfiguration, GameSceneBase, NodeTree, ScreenFadeHold};
let engine = Engine::new(EngineConfiguration::new());
engine.get_view_manager_mut().calculate_view_rect(800, 600, 1.0);
let mut game_scene_base = GameSceneBase::new();
game_scene_base.set_screen_fade_seconds(0.0);
let held_hold: Rc<RefCell<Option<ScreenFadeHold>>> = Rc::new(RefCell::new(None));
let held_hold_for_event = held_hold.clone();
assert!(game_scene_base.fade_screen_with_hold(Box::new(move |_node_tree: &mut NodeTree, _engine: &Engine, screen_fade_hold: ScreenFadeHold| {
*held_hold_for_event.borrow_mut() = Some(screen_fade_hold);
})));
game_scene_base.tick(0.016);
game_scene_base.tick(0.016);
assert_eq!(game_scene_base.get_screen_fade_alpha(), 1.0);
if let Some(screen_fade_hold) = held_hold.borrow().as_ref() {
screen_fade_hold.release();
}
game_scene_base.tick(0.016);
game_scene_base.tick(0.016);
assert!(!game_scene_base.is_screen_fading());pub fn fade_screen_async<S, F, OnDarkFuture>(&mut self, on_dark: F) -> bool where S: Scene + 'static, F: FnOnce(SceneContext<S>) -> OnDarkFuture + 'static, OnDarkFuture: Future<Output = ()> + 'static,#어두워졌다 밝아지기의 async 꼴. (원본 fadeScreen(async () => { ... }), 이미 페이드 중이면 false)
- 다 어두워진 tick 에서 on_dark 가 돌려준 퓨처를 이 씬의 작업으로 맡겨 그 자리에서 첫 await 까지 돌리고, 퓨처가 끝나면 밝아진다. 퓨처 안에서는 SceneContext::with 로 씬(S 타입)과 엔진을 빌린다.
- S 는 이 바탕을 든 씬의 타입이다. (GameScene 을 구현한 씬은 GameScene::fade_screen_async 가 S 를 채운다) 다른 타입이면 바로 밝아진다.
- 시작은 바탕 tick 뒤에 씬이 take_screen_fade_dark_starter 로 꺼내 start 한다. (game_scene!, ui_scene! 은 저절로 한다) 꺼내지 않으면 바탕이 post_draw 나 다음 tick 에서 다음 폴링 차례로 맡긴다.
Async form of darken then brighten. (the original fadeScreen(async () => { ... }), false if already fading)
- At the tick it becomes fully dark, hands the future returned by on_dark over as this scene's task and runs it right there up to the first await, and brightens when the future finishes. Inside the future, SceneContext::with borrows the scene (type S) and the engine.
- S is the type of the scene holding this base. (for a scene implementing GameScene, GameScene::fade_screen_async fills in S) For another type it brightens right away.
- To start, the scene takes it out with take_screen_fade_dark_starter after the base tick and starts it. (game_scene! and ui_scene! do this automatically) If not taken out, the base hands it over at the next polling turn in post_draw or the next tick.
- on_darkF
- 다 어두워졌을 때
SceneContext<S>를 받아 퓨처를 돌려주는 함수. (퓨처가 끝나거나 버려지면 밝아진다)Function that takes aSceneContext<S>when fully dark and returns a future. (brightens when the future finishes or is dropped)
반환Returnsbool 페이드를 시작했으면 true. 이미 페이드 중이면 false.true if the fade started. false if already fading.
짝Counterpart: vanilla.js GameScene.fadeScreen
use vanilla::{Engine, GameSceneBase, Scene, SceneBase, SceneContext, Vector2};
struct PuzzleScene {
game_scene_base: GameSceneBase,
stage_number: u32,
}
impl Scene for PuzzleScene {
fn get_scene_base(&self) -> &SceneBase {
self.game_scene_base.get_scene_base()
}
fn get_scene_base_mut(&mut self) -> &mut SceneBase {
self.game_scene_base.get_scene_base_mut()
}
fn touch_press(&mut self, _view_input_position: Vector2) {
self.game_scene_base.fade_screen_async::<PuzzleScene, _, _>(|mut scene_context: SceneContext<PuzzleScene>| async move {
scene_context.with(|scene, _engine| {
scene.stage_number += 1;
});
});
}
fn tick(&mut self, time_delta: f64) {
self.game_scene_base.tick(time_delta);
if let Some(screen_fade_dark_starter) = self.game_scene_base.take_screen_fade_dark_starter() {
screen_fade_dark_starter.start(self);
}
}
}다 어두워진 fade_screen_async 의 시작 꺼내기. (바탕 tick 뒤에 씬이 꺼내 start(씬, 엔진) 한다, 아직이면 None)
Takes out the starter of a fully dark fade_screen_async. (the scene takes it out after the base tick and calls start(scene, engine), None if not yet)
반환ReturnsOption<ScreenFadeDarkStarter> 다 어두워진 뒤 처음 부를 때 시작. 아직 어두워지지 않았거나 이미 꺼냈으면 None.The starter, on the first call after it goes fully dark. None if not dark yet or already taken out.
페이드 중인지. (어두워지거나, 손잡이를 기다리거나, 밝아지는 중)
Whether it is fading. (darkening, waiting for the handle, or brightening)
반환Returnsbool 어두워지거나 손잡이를 기다리거나 밝아지는 중이면 true.true while darkening, waiting on a handle, or brightening.
짝Counterpart: vanilla.js GameScene.isScreenFading
어두워지는 막의 색 설정. (기본 검정)
Sets the color of the darkening curtain. (default black)
- colorimpl Into<Color>
- 막의 색. (Color 나 "#rrggbb" 같은 글)Curtain color. (a Color or a string like "#rrggbb")
짝Counterpart: vanilla.js GameScene.setScreenFadeColor
어두워지는 시간과 밝아지는 시간 설정. (초, 기본 0.35, 0 이면 바로)
Sets the darkening time and the brightening time. (seconds, default 0.35, immediate if 0)
- secondsf64
- 어두워지는 시간이자 밝아지는 시간. (초, 음수는 0)Time to darken, also the time to brighten. (seconds, negative is treated as 0)
짝Counterpart: vanilla.js GameScene.setScreenFadeSeconds
어두워지는 막의 진하기. (0 ~ 1)
Opacity of the darkening curtain. (0 ~ 1)
반환Returnsf64 막의 진하기. (0 이면 막 없음, 1 이면 다 어두움)Curtain opacity. (0 means no curtain, 1 means fully dark)
짝Counterpart: vanilla.js GameScene.getScreenFadeAlpha
그 자리에 UI(누를 수 있는 노드: 단추, 창의 어둠과 판, 스크롤 칸)가 있는지. (뷰 좌표)
Whether there is UI (a pressable node: a button, a window's dimmer and panel, a scroll box) at that point. (view coordinates)
- view_positionVector2
- 볼 자리. (뷰 좌표)Position to check. (view coordinates)
반환Returnsbool 그 자리에 누를 수 있는 노드가 있으면 true.true if there is a pressable node at that position.
짝Counterpart: vanilla.js GameScene.isUserInterfaceAt
놀이 입력 모으기 켜기. (끄면 모은 것을 버린다)
- 켜면 tick 이 UI 가 받지 않은 입력을 모으고, 씬이 take_play_inputs 로 꺼낸다. 놀이로 간 누름은 잊는다.
Turns on play input collection. (turning it off discards what was collected)
- When on, tick collects the input the UI did not take, and the scene takes it out with take_play_inputs. Presses that went to play are forgotten.
- is_play_input_enabledbool
- true 면 모으고, false 면 끄고 모은 것을 버린다.true collects, false turns it off and discards what was collected.
짝Counterpart: vanilla.js GameScene.setPlayInputEnabled
use vanilla::{Engine, EngineConfiguration, GameSceneBase, PlayInput, SafeAreaInsets, Vector2};
let engine = Engine::new(EngineConfiguration::new());
engine.get_view_manager_mut().calculate_view_rect(800, 600, 1.0);
let mut game_scene_base = GameSceneBase::new();
game_scene_base.set_safe_area_insets(Some(SafeAreaInsets::create(10.0, 0.0, 0.0, 20.0)));
game_scene_base.initialize(engine);
game_scene_base.tick(0.016);
game_scene_base.set_play_input_enabled(true);
engine.get_input_manager_mut().set_view_input_position(Vector2::create(120.0, 110.0));
engine.get_input_manager_mut().set_touch_pressed(true);
game_scene_base.tick(0.016);
engine.get_input_manager_mut().set_touch_pressed(false);
engine.get_input_manager_mut().set_touch_released(true);
game_scene_base.tick(0.016);
let play_inputs = game_scene_base.take_play_inputs();
assert_eq!(play_inputs.first(), Some(&PlayInput::Press(Vector2::create(100.0, 100.0))));
assert_eq!(play_inputs.last(), Some(&PlayInput::Release(Vector2::create(100.0, 100.0))));
assert!(game_scene_base.take_play_inputs().is_empty());UI 가 받지 않은 입력의 처리기 설정. (원본 setPlayInputHandler, None 이면 끈다, 놀이로 간 누름은 잊는다)
- 처리기는 씬을 빌릴 수 없어서 씬 상태는
Rc<RefCell>로 나눠 쥔다.
Sets the handler for input the UI did not take. (the original setPlayInputHandler, None turns it off, presses that went to play are forgotten)
- The handler cannot borrow the scene, so the scene state is shared through
Rc<RefCell>.
- play_input_handlerOption<PlayInputHandler>
- UI 가 받지 않은 입력을 받을 함수. (게임 영역 좌표) None 이면 끈다.Function that receives the input the UI did not take. (play area coordinates) None turns it off.
짝Counterpart: vanilla.js GameScene.setPlayInputHandler
use std::cell::RefCell;
use std::rc::Rc;
use vanilla::{Engine, EngineConfiguration, GameSceneBase, PlayInput, SafeAreaInsets, Vector2};
let engine = Engine::new(EngineConfiguration::new());
engine.get_view_manager_mut().calculate_view_rect(800, 600, 1.0);
let mut game_scene_base = GameSceneBase::new();
game_scene_base.set_safe_area_insets(Some(SafeAreaInsets::create(0.0, 0.0, 0.0, 0.0)));
game_scene_base.initialize(engine);
let play_input_list: Rc<RefCell<Vec<PlayInput>>> = Rc::new(RefCell::new(Vec::new()));
let play_input_list_for_handler = play_input_list.clone();
game_scene_base.set_play_input_handler(Some(Box::new(move |play_input: PlayInput| {
play_input_list_for_handler.borrow_mut().push(play_input);
})));
engine.get_input_manager_mut().set_view_input_position(Vector2::create(50.0, 60.0));
engine.get_input_manager_mut().set_touch_pressed(true);
game_scene_base.tick(0.016);
engine.get_input_manager_mut().set_touch_pressed(false);
engine.get_input_manager_mut().set_touch_released(true);
game_scene_base.tick(0.016);
assert_eq!(*play_input_list.borrow(), vec![PlayInput::Press(Vector2::create(50.0, 60.0)), PlayInput::Release(Vector2::create(50.0, 60.0))]);모은 놀이 입력 꺼내기. (온 차례대로, 꺼내면 비운다)
Takes out the collected play inputs. (in arrival order, empties them when taken)
반환ReturnsVec<PlayInput> 모은 놀이 입력 목록. (모으기가 꺼져 있으면 빈 목록)List of collected play inputs. (an empty list if collection is off)
짝Counterpart: vanilla.js GameScene.takePlayInputs
뷰 좌표 → 게임 영역 좌표. (세이프 에어리어 왼쪽 위가 0, 0)
View coordinates → play area coordinates. (the top left of the safe area is 0, 0)
- view_positionVector2
- 바꿀 자리. (뷰 좌표)Position to convert. (view coordinates)
반환ReturnsVector2 마지막으로 계산한 세이프 에어리어 왼쪽 위를 뺀 자리.The position minus the top left of the last computed safe area.
짝Counterpart: vanilla.js GameScene.convertViewToPlayArea
pub fn set_play_area_reference(&mut self, fixed_length: f64, is_landscape: bool, engine: Option<&Engine>)#게임 영역 기준 설정. (세이프 에어리어를 뺀 게임 영역의 고정 쪽 길이가 늘 fixed_length 가 되게 기준 해상도를 늘린다)
- 캔버스 길이 : 세이프 에어리어를 뺀 길이 = 기준 해상도 길이 : fixed_length.
- is_landscape 면 가로, 아니면 세로가 고정 쪽이다. 뷰 배율 방식도 그에 맞춰 둔다. (가로 고정 StretchWidthExpandHeight, 세로 고정 StretchHeightExpandWidth)
- 무시할 세이프 에어리어 쪽은 ViewManager::set_ignored_safe_area_sides 로 넘긴다. fixed_length 가 0 이면 끈다.
- 엔진을 주면 바로 건다. 씬은 resize 첫머리에 apply_play_area_reference 를 부른다.
Sets the play area reference. (stretches the reference resolution so the fixed side length of the play area without the safe area is always fixed_length)
- Canvas length : length without the safe area = reference resolution length : fixed_length.
- If is_landscape, the width is the fixed side, otherwise the height. The view scale mode is set to match. (width fixed StretchWidthExpandHeight, height fixed StretchHeightExpandWidth)
- Safe area sides to ignore are passed with ViewManager::set_ignored_safe_area_sides. A fixed_length of 0 turns it off.
- Given the engine, it applies right away. The scene calls apply_play_area_reference at the start of resize.
- fixed_lengthf64
- 세이프 에어리어를 뺀 게임 영역의 고정 쪽 길이. (뷰 좌표, 0 이하이면 끈다)Fixed side length of the play area without the safe area. (view coordinates, 0 or less turns it off)
- is_landscapebool
- true 면 가로, false 면 세로가 고정 쪽이다.true fixes the horizontal side, false the vertical side.
- engineOption<&Engine>
- 바로 걸 엔진. None 이면 뷰 배율 방식만 정해 두고 initialize 에서 건다.Engine to apply it to right away. None only sets the view scale mode and applies it in initialize.
짝Counterpart: vanilla.js GameScene.setPlayAreaReference
use vanilla::{Engine, EngineConfiguration, GameSceneBase, SafeAreaInsets, ViewScaleMode};
let engine = Engine::new(EngineConfiguration::new());
engine.get_view_manager_mut().calculate_view_rect(800, 600, 1.0);
engine.get_view_manager_mut().set_safe_area_override(Some(SafeAreaInsets::create(40.0, 0.0, 30.0, 0.0)));
let mut game_scene_base = GameSceneBase::new();
game_scene_base.set_play_area_reference(720.0, false, Some(engine));
assert_eq!(engine.get_view_manager().get_view_scale_mode(), ViewScaleMode::StretchHeightExpandWidth);
assert_eq!(game_scene_base.get_play_area_fixed_length(), 720.0);
game_scene_base.initialize(engine);
game_scene_base.layout();
assert!((game_scene_base.get_safe_area_rect().size.y - 720.0).abs() < 0.01);게임 영역의 고정 쪽 길이. (0 이면 쓰지 않음)
Fixed side length of the play area. (not used if 0)
반환Returnsf64 고정 쪽 길이. (뷰 좌표, 0 이면 게임 영역 기준을 쓰지 않는다)Fixed side length. (view coordinates, 0 means the play area reference is not used)
짝Counterpart: vanilla.js GameScene.getPlayAreaFixedLength
게임 영역 기준을 기준 해상도에 걸기. (캔버스와 인셋 크기에서만 셈해 몇 번을 불러도 같다, 바꿨으면 뷰 영역을 다시 셈하고 true)
Applies the play area reference to the reference resolution. (computed only from the canvas and inset sizes, so calling it any number of times gives the same result. If changed, recomputes the view area and returns true)
반환Returnsbool 기준 해상도를 바꿨으면 true. 게임 영역 기준을 쓰지 않거나, 캔버스 크기가 0 이거나, 셈할 수 없거나, 이미 같으면 false.true if the reference resolution was changed. false if the play area reference is not used, the canvas size is 0, it cannot be computed, or it is already the same.
짝Counterpart: vanilla.js GameScene.applyPlayAreaReference
GameScenetrait traits 'static
게임 씬. (원본 GameScene 을 상속한 씬이 덮어쓰는 자리)
- 씬은 GameSceneBase 를 품고 이 트레이트를 구현한 뒤 game_scene!(씬 타입) 으로 Scene 을 얻는다.
- game_scene! 이 만든 Scene 함수는 바탕(GameSceneBase)을 먼저 부르고 이 트레이트의 같은 이름 함수를 부른다. (원본에서 super 를 먼저 부르는 덮어쓰기) post_draw 만 씬의 것을 먼저 부르고 바탕(페이드 막, 개발자 도구)을 위에 그린다.
- layout 은 바탕이 세이프 에어리어를 다시 계산한 뒤 부른다. (resize, 그리고 tick 이 뷰 크기 변화를 본 때. 첫 tick 에도 한 번)
- load_assets 는 load 에서 바탕의 로딩 이미지 요청 뒤에 부른다. 씬의 애셋을 요청하고 get_scene_base_mut().track_asset 으로 맡긴다.
Game scene. (where a scene inheriting the original GameScene overrides)
- The scene contains a GameSceneBase, implements this trait, and gets a Scene with game_scene!(scene type).
- The Scene functions made by game_scene! call the base (GameSceneBase) first and then the function of the same name in this trait. (an override that calls super first in the original) Only post_draw calls the scene's first and draws the base (fade curtain, developer tools) on top.
- layout is called after the base recomputes the safe area. (on resize, and when tick sees a view size change. Also once on the first tick)
- load_assets is called in load after the base requests the loading image. Request the scene's assets and hand them over with get_scene_base_mut().track_asset.
use vanilla::{Engine, EngineConfiguration, GameScene, GameSceneBase, ImageAsset, Scene};
struct TitleScene {
game_scene_base: GameSceneBase,
logo_asset: ImageAsset,
layout_count: u32,
}
impl GameScene for TitleScene {
fn get_game_scene_base(&self) -> &GameSceneBase {
&self.game_scene_base
}
fn get_game_scene_base_mut(&mut self) -> &mut GameSceneBase {
&mut self.game_scene_base
}
fn load_assets(&mut self) {
let engine = Engine::get_engine().unwrap();
self.logo_asset.load(engine, "examples/assets/atlas/icons.png");
self.game_scene_base.get_scene_base_mut().track_asset(&self.logo_asset);
}
fn initialize(&mut self, _engine: &Engine) {
let safe_area_id = self.game_scene_base.get_safe_area_node_id().expect("safe area node");
self.game_scene_base.get_scene_base_mut().get_node_tree_mut().create_child(safe_area_id, "logo");
}
fn layout(&mut self) {
self.layout_count += 1;
}
}
vanilla::game_scene!(TitleScene);
let engine = Engine::new(EngineConfiguration::new());
engine.get_view_manager_mut().calculate_view_rect(800, 600, 1.0);
let mut title_scene = TitleScene {
game_scene_base: GameSceneBase::new(),
logo_asset: ImageAsset::new(),
layout_count: 0,
};
title_scene.game_scene_base.set_loading_min_duration_ms(0.0);
Scene::create(&mut title_scene);
Scene::load(&mut title_scene, engine);
assert!(title_scene.get_scene_base().are_tracked_assets_finished());
Scene::initialize(&mut title_scene, engine);
Scene::tick(&mut title_scene, 0.016);
assert_eq!(title_scene.layout_count, 1);use vanilla::{Engine, EngineConfiguration, GameScene, GameSceneBase, Vector2};
struct MainScene {
game_scene_base: GameSceneBase,
}
impl GameScene for MainScene {
fn get_game_scene_base(&self) -> &GameSceneBase {
&self.game_scene_base
}
fn get_game_scene_base_mut(&mut self) -> &mut GameSceneBase {
&mut self.game_scene_base
}
}
vanilla::game_scene!(MainScene);
let mut engine_configuration = EngineConfiguration::new();
engine_configuration.reference_resolution_size = Vector2::create(1280.0, 720.0);
let engine = Engine::new(engine_configuration);
let mut game_scene_base = GameSceneBase::new();
game_scene_base.set_loading_image_url("examples/assets/atlas/icons.png");
let main_scene = MainScene {
game_scene_base,
};
if let Err(error) = engine.run(Box::new(main_scene)) {
eprintln!("{}", error);
}바탕 반환.
Returns the base.
반환Returns&GameSceneBase 씬이 품은 바탕.Base contained in the scene.
바탕 반환. (변경용)
Returns the base. (mutable)
반환Returns&mut GameSceneBase 씬이 품은 바탕. (변경용)Base contained in the scene. (mutable)
씬의 애셋 읽기. (원본 async loadAssets() 덮어쓰기, 바탕의 로딩 이미지 요청 뒤)
- 엔진은 Engine::get_engine() 으로 꺼낸다. await 로 읽으려면 engine.spawn_scene_task(self, ...) 로 불러오기 작업을 맡기고 get_game_scene_base_mut().get_scene_base_mut().track_task 로 맡긴다.
Loads the scene's assets. (overrides the original async loadAssets(), after the base requests the loading image)
- Take the engine with Engine::get_engine(). To load with await, hand over a loading task with engine.spawn_scene_task(self, ...) and register it with get_game_scene_base_mut().get_scene_base_mut().track_task.
짝Counterpart: vanilla.js GameScene.loadAssets
fn fade_screen_async<F, OnDarkFuture>(&mut self, on_dark: F) -> bool where Self: Scene + Sized, F: FnOnce(SceneContext<Self>) -> OnDarkFuture + 'static, OnDarkFuture: Future<Output = ()> + 'static,#어두워졌다 밝아지기의 async 꼴. (원본 fadeScreen(async () => { ... }), 이미 페이드 중이면 false)
- 다 어두워진 tick 에서 on_dark 가 돌려준 퓨처를 이 씬의 작업으로 맡겨 그 자리에서 첫 await 까지 돌리고, 끝나면 밝아진다. 퓨처 안에서는 SceneContext::with 로 이 씬과 엔진을 빌린다.
Async form of darken then brighten. (the original fadeScreen(async () => { ... }), false if already fading)
- At the tick it becomes fully dark, hands the future returned by on_dark over as this scene's task and runs it right there up to the first await, and brightens when it finishes. Inside the future, SceneContext::with borrows this scene and the engine.
- on_darkF
- 다 어두워졌을 때
SceneContext<Self>를 받아 퓨처를 돌려주는 함수. (퓨처가 끝나거나 버려지면 밝아진다)Function that takes aSceneContext<Self>when fully dark and returns a future. (brightens when the future finishes or is dropped)
반환Returnsbool 페이드를 시작했으면 true. 이미 페이드 중이면 false.true if the fade started. false if already fading.
짝Counterpart: vanilla.js GameScene.fadeScreen
use vanilla::{Engine, GameScene, GameSceneBase, SceneContext, Vector2};
struct StageScene {
game_scene_base: GameSceneBase,
stage_number: u32,
}
impl GameScene for StageScene {
fn get_game_scene_base(&self) -> &GameSceneBase {
&self.game_scene_base
}
fn get_game_scene_base_mut(&mut self) -> &mut GameSceneBase {
&mut self.game_scene_base
}
fn touch_press(&mut self, _view_input_position: Vector2) {
self.fade_screen_async(|mut scene_context: SceneContext<StageScene>| async move {
scene_context.with(|scene, _engine| {
scene.stage_number += 1;
});
});
}
}
vanilla::game_scene!(StageScene);로딩 화면 위에 더 그리기. (바탕의 로딩 화면 뒤)
Draws more on top of the loading screen. (after the base's loading screen)
- _graphic&mut Graphic
- 그릴 그래픽. (뷰 좌표계가 걸려 있다)Graphic to draw with. (the view coordinate system is set)
짝Counterpart: vanilla.js GameScene.drawOnLoad
초기화. (바탕 initialize 뒤, 세이프 에어리어 노드가 생긴 다음)
Initializes. (after the base initialize, once the safe area node exists)
- _engine&Engine
- 엔진.Engine.
짝Counterpart: vanilla.js GameScene.initialize
레이아웃. (원본 layout 덮어쓰기, 바탕이 세이프 에어리어를 다시 계산한 뒤)
Layout. (overrides the original layout, after the base recomputes the safe area)
짝Counterpart: vanilla.js GameScene.layout
갱신. (바탕 tick 뒤: 노드, 터치, 트윈, 레이아웃, 페이드, 개발자 도구)
Updates. (after the base tick: nodes, touches, tweens, layout, fade, developer tools)
- _time_deltaf64
- 배율을 곱한 프레임 간격. (초)Frame interval multiplied by the time scale. (seconds)
짝Counterpart: vanilla.js GameScene.tick
이전 출력. (바탕의 배경 칠하기 뒤)
Pre-draw. (after the base fills the background)
- _graphic&mut Graphic
- 그릴 그래픽.Graphic to draw with.
짝Counterpart: vanilla.js GameScene.preDraw
출력. (노드 트리를 그린 뒤)
Draw. (after drawing the node tree)
- _graphic&mut Graphic
- 그릴 그래픽.Graphic to draw with.
짝Counterpart: vanilla.js Scene.draw
이후 출력. (바탕의 페이드 막과 개발자 도구보다 먼저)
Post-draw. (before the base's fade curtain and developer tools)
- _graphic&mut Graphic
- 그릴 그래픽.Graphic to draw with.
짝Counterpart: vanilla.js GameScene.postDraw
종료처리. (내릴 때 unload 앞, 원본 Scene.finalize 덮어쓰기)
Finalizes. (before unload when taking down, overrides the original Scene.finalize)
- _engine&Engine
- 엔진.Engine.
짝Counterpart: vanilla.js Scene.finalize
로딩 해제. (내릴 때 finalize 뒤, 원본 Scene.unload 덮어쓰기)
Unloads. (after finalize when taking down, overrides the original Scene.unload)
- _engine&Engine
- 엔진.Engine.
짝Counterpart: vanilla.js Scene.unload
페이지 프로세스 복원과 가시성 복원. (원본 onPageProcessRestored, onPageVisibilityRestored 덮어쓰기)
- 이 함수는 페이지 프로세스 복원 자리다. 가시성 복원은 on_page_visibility_restored.
Page process restore and visibility restore. (overrides the original onPageProcessRestored, onPageVisibilityRestored)
- This function is the page process restore one. Visibility restore is on_page_visibility_restored.
짝Counterpart: vanilla.js Scene.onPageProcessRestored
페이지 가시성 복원. (원본 onPageVisibilityRestored 덮어쓰기)
Page visibility restored. (overrides the original onPageVisibilityRestored)
짝Counterpart: vanilla.js Scene.onPageVisibilityRestored
씬의 터치 훅. (원본 touchPress, touchMove, touchRelease, touchCancel, touchWheel 덮어쓰기, 바탕이 UI 와 놀이 입력에 넘긴 뒤 엔진이 부른다)
- 이 함수는 누름 자리다. 이동, 뗌, 취소, 휠은 touch_move, touch_release, touch_cancel, touch_wheel.
Touch hooks of the scene. (overrides the original touchPress, touchMove, touchRelease, touchCancel, touchWheel, called by the engine after the base passes them to the UI and play input)
- This function is the press one. Move, release, cancel, and wheel are touch_move, touch_release, touch_cancel, touch_wheel.
- _view_input_positionVector2
- 누른 자리. (뷰 좌표)Press position. (view coordinates)
짝Counterpart: vanilla.js GameScene.touchPress
터치 이동. (원본 touchMove 덮어쓰기)
Touch move. (overrides the original touchMove)
- _view_input_positionVector2
- 지금 자리. (뷰 좌표)Current position. (view coordinates)
짝Counterpart: vanilla.js GameScene.touchMove
터치 뗌. (원본 touchRelease 덮어쓰기)
Touch release. (overrides the original touchRelease)
- _view_input_positionVector2
- 뗀 자리. (뷰 좌표)Release position. (view coordinates)
짝Counterpart: vanilla.js GameScene.touchRelease
터치 취소. (원본 touchCancel 덮어쓰기)
Touch cancel. (overrides the original touchCancel)
- _view_input_positionVector2
- 취소된 자리. (뷰 좌표)Canceled position. (view coordinates)
짝Counterpart: vanilla.js GameScene.touchCancel
휠. (원본 touchWheel 덮어쓰기)
Wheel. (overrides the original touchWheel)
- _view_input_positionVector2
- 휠을 굴린 자리. (뷰 좌표)Position where the wheel was rolled. (view coordinates)
- _wheel_deltaVector2
- 휠 값. (가로, 세로)Wheel value. (horizontal, vertical)
짝Counterpart: vanilla.js GameScene.touchWheel
함수Functions
GameScene 을 구현한 씬에 Scene 을 만들어 준다. (vanilla::game_scene!(TitleScene);)
Makes a Scene for a scene implementing GameScene. (vanilla::game_scene!(TitleScene);)
PlayInputenum traits Clone, Copy, Debug, PartialEq
UI 가 받지 않은 입력. (게임 영역 좌표: 세이프 에어리어 왼쪽 위 기준, 원본 처리기의 press, move, release, wheel)
Input the UI did not take. (play area coordinates: relative to the top left of the safe area, press, move, release, wheel of the original handler)
| 이름Name | 값Value | 설명Description |
|---|---|---|
Press | Press(Vector2) | UI 가 받지 않은 누름.A press the UI did not take. |
Move | Move(Vector2) | 놀이로 간 누름의 이동.Move of a press that went to play. |
Release | Release(Vector2) | 놀이로 간 누름의 뗌. (취소 포함)Release of a press that went to play. (including cancel) |
Wheel | Wheel(Vector2, Vector2) | UI 밖의 휠. (자리, 휠 값)Wheel outside the UI. (position, wheel value) |