# core/scene (vanilla.js 0.4.0)

> https://vanillapunch.com/docs/vanilla.js/0.4.0/api/core/scene/

씬.

## Scene extends Object

씬.
- new() ==> create() ==> async load(engine) ==> initialize(engine)
- finalize(engine) ==> async unload(engine) ==> destroy()
- resize(canvasNativeSize)
- tick(timeDelta)
- preDraw(graphic) ==> draw(graphic) ==> postDraw(graphic)
- touchPress(viewInputPosition) ==> touchMove(viewInputPosition) ==> touchRelease(viewInputPosition)
- reset()
- 터치는 씬 꼴과 상관없이 노드의 위젯이 받는다. tickTouch 가 씬의 터치 레이캐스터(처음은 TouchRaycaster, setTouchRaycaster 로 바꾼다)로
  가장 앞의 누를 수 있는 노드에 먼저 넘기고, 그 뒤에 씬의 터치 훅을 부른다. (유니티 EventSystem 처럼, 러스트 판 SceneBase.tick 과 같다)

예제: 불러오고, 갱신하고, 그리고, 누름 받기

```js
import { Engine, EngineConfiguration, Scene, Vector2, Rect, Colors } from "./build/vanilla.js";

class MainScene extends Scene {
	async load(engine) {
		await super.load(engine);
		this.boxPosition = Vector2.create(100, 100);
	}

	initialize(engine) {
		console.log("initialized");
	}

	tick(timeDelta) {
		super.tick(timeDelta);
		this.boxPosition.x += 60 * timeDelta;
	}

	draw(graphic) {
		super.draw(graphic);
		graphic.setFillColor(Colors.white);
		graphic.drawRect(Rect.create(this.boxPosition.x, this.boxPosition.y, 80, 80));
	}

	touchPress(viewInputPosition) {
		this.boxPosition = viewInputPosition.clone();
	}
}

const engineConfiguration = new EngineConfiguration();
const engine = new Engine(engineConfiguration);
engine.run(new MainScene());
```

- `constructor()` (constructor, since 0.0.8): 생성.
- `create()` (method, since 0.0.8): 생성.
- `setEngine(engine)` (method, since 0.2.0): 엔진 설정. (SceneManager가 load() 이전에 호출하여 drawOnLoad에서 접근 가능하게 함)
  - `engine` Engine: 이 씬을 불러온 엔진.
- `setLoaded(isLoaded)` (method, since 0.2.0): 로딩 완료 여부 설정. (SceneManager가 load+initialize 이후 true로 전환)
  - `isLoaded` boolean: 불러오기를 마쳤는지.
- `isLoaded()` (method, since 0.2.0): 로딩 완료 여부 반환.
  - returns boolean: 불러오기를 마쳤으면 참. (initialize 바로 앞에 참이 된다)
- `drawOnLoad(graphic)` (method, since 0.2.0): 로딩 중 출력. (비동기 load() 진행 중에만 호출되며, 씬의 일반 tick/draw는 호출되지 않음)
  - `graphic` Graphic: 그릴 그래픽.

  예제: 불러오는 동안 글 띄우기

  ```js
  import { Engine, EngineConfiguration, Scene, Colors } from "./build/vanilla.js";
  
  class MainScene extends Scene {
  	async load(engine) {
  		await super.load(engine);
  		await new Promise((resolve) => {
  			setTimeout(resolve, 500);
  		});
  	}
  
  	drawOnLoad(graphic) {
  		graphic.setFillColor(Colors.white);
  		graphic.setFontString("24px sans-serif");
  		graphic.drawFillText("Loading", 40, 40);
  	}
  }
  
  const engineConfiguration = new EngineConfiguration();
  const engine = new Engine(engineConfiguration);
  engine.run(new MainScene());
  ```

- `destroy()` (method, since 0.0.8): 파괴.
- `async load(engine)` (method, since 0.0.8): 비동기 로딩.
  - `engine` Engine: 씬을 불러오는 엔진.
- `initialize(engine)` (method, since 0.0.8): 초기화.
  - `engine` Engine: 씬을 불러온 엔진.
- `finalize(engine)` (method, since 0.0.8): 종료처리.
  - `engine` Engine: 씬을 내리는 엔진.
- `onPageProcessRestored()` (method, since 0.2.0): 페이지 프로세스 파기 후 복원 감지 (freeze/resume, bfcache 복원 등).
  엔진이 브라우저 이벤트를 감지하여 로드된 모든 씬에 호출한다.
- `onPageVisibilityRestored()` (method, since 0.2.0): 페이지 가시성 복원 감지 (백그라운드 → 포어그라운드).
  엔진이 visibilitychange 이벤트를 감지하여 로드된 모든 씬에 호출한다.
- `async unload(engine)` (method, since 0.0.8): 비동기 로딩 해제.
  - `engine` Engine: 씬을 내리는 엔진.
- `resize(canvasNativeSize)` (method, since 0.0.8): 화면 크기 변경됨.
  - `canvasNativeSize` Vector2: 바뀐 캔버스 요소의 크기. (CSS 픽셀)
- `tick(timeDelta)` (method, since 0.0.8): 주기적 갱신.
  - `timeDelta` number: 지난 프레임부터의 시간. (초)
- `preDraw(graphic)` (method, since 0.0.8): 이전 출력.
  - `graphic` Graphic: 그릴 그래픽.
- `draw(graphic)` (method, since 0.0.8): 출력.
  - `graphic` Graphic: 그릴 그래픽.
- `postDraw(graphic)` (method, since 0.0.8): 이후 출력.
  - `graphic` Graphic: 그릴 그래픽.
- `drawGizmos(graphic)` (method, since 0.0.11): 기즈모 출력.
  - `graphic` Graphic: 그릴 그래픽.
- `tickTouch(timeDelta)` (method, since 0.0.8): 터치 갱신.
  - `timeDelta` number: 지난 프레임부터의 시간. (초)
- `touchPress(viewInputPosition)` (method, since 0.0.8): 터치 누름.
  - `viewInputPosition` Vector2: 뷰 좌표의 입력 위치.
- `touchMove(viewInputPosition)` (method, since 0.0.8): 터치 이동.
  - `viewInputPosition` Vector2: 뷰 좌표의 입력 위치.
- `touchRelease(viewInputPosition)` (method, since 0.0.8): 터치 뗌.
  - `viewInputPosition` Vector2: 뷰 좌표의 입력 위치.
- `touchCancel(viewInputPosition)` (method, since 0.1.0): 터치 취소됨.
  - `viewInputPosition` Vector2: 뷰 좌표의 입력 위치.
- `touchWheel(viewInputPosition, wheelDelta)` (method, since 0.2.1): 마우스 휠.
  - `viewInputPosition` Vector2: 뷰 좌표의 입력 위치.
  - `wheelDelta` Vector2: 이번 프레임에 쌓인 휠 값. (WheelEvent 의 deltaX, deltaY 를 더한 것)
- `startTween(tween)` (method, since 0.0.8): 트윈 시작.
  - `tween` Tween: 시작할 트윈. (이미 도는 트윈이면 아무것도 하지 않는다)

  예제: 노드를 0.5 초 동안 나타나게 하기

  ```js
  import { Engine, EngineConfiguration, Scene, WorldNode, Tween, TweenProperty, Vector2 } from "./build/vanilla.js";
  
  class MainScene extends Scene {
  	initialize(engine) {
  		const root = this.getRoot();
  		const node = new WorldNode();
  		node.setContentSize(Vector2.create(100, 100));
  		root.addChild(node);
  		const tween = Tween.createNodeTween(node, TweenProperty.localOpacity, 0, 1, 0.5);
  		this.startTween(tween);
  		const tweenCount = this.getTweenCount();
  		console.log(tweenCount);
  	}
  }
  
  const engineConfiguration = new EngineConfiguration();
  const engine = new Engine(engineConfiguration);
  engine.run(new MainScene());
  ```

- `stopTween(tween)` (method, since 0.0.8): 트윈 중단.
  - `tween` Tween: 멈출 트윈. (이 씬에서 돌지 않으면 아무것도 하지 않는다)
- `getTweenCount()` (method, since 0.4.0): 도는 트윈 수 반환.
  - returns number: 도는 트윈 수.
- `stopAllTweens()` (method, since 0.0.8): 모든 트윈 중단.
- `getEngine()` (method, since 0.0.8): 엔진 반환.
  - returns Engine: 이 씬을 불러온 엔진. (불러오기 전에는 undefined)
- `getRoot()` (method, since 0.0.8): 루트 노드 반환.
  - returns WorldNode: 루트 노드. (create 에서 만들고, 크기는 뷰 크기)
- `setTouchRaycaster(touchRaycaster)` (method, since 0.4.0): 터치 레이캐스터 설정.
  - tickTouch 가 이 레이캐스터로 가장 앞의 누를 수 있는 노드에 터치를 넘긴다. 루트는 씬 루트로 건다.
  - TouchRecognizer 를 주면 스크롤 칸 안의 끌기 손짓(누름 늦추기, 끌면 스크롤 칸으로)도 넘긴다.
  - null 이면 노드에 넘기지 않는다. (씬이 터치 훅에서 직접 넘길 때, UIScene 과 GameScene 이 그렇게 한다)
  - `touchRaycaster` TouchRaycaster | null: 노드에 터치를 넘길 레이캐스터. (null 이면 넘기지 않는다)

  예제: 스크롤 칸 끌기 손짓까지 넘기기

  ```js
  import { Engine, EngineConfiguration, Scene, TouchRecognizer } from "./build/vanilla.js";
  
  class MainScene extends Scene {
  	initialize(engine) {
  		this.setTouchRaycaster(new TouchRecognizer());
  	}
  }
  
  const engineConfiguration = new EngineConfiguration();
  const engine = new Engine(engineConfiguration);
  engine.run(new MainScene());
  ```

- `setTouchDispatchEnabled(isEnabled)` (method, since 0.4.0): 노드에 터치 넘기기 켜고 끄기. (러스트 판 SceneBase.set_touch_dispatch_enabled 와 같다)
  - 끄면 tickTouch 가 레이캐스터로 노드에 넘기지 않고 씬의 터치 훅만 부른다. (훅에서 가로채 직접 넘길 때)
  - 레이캐스터는 그대로 두어 다시 켜면 이어서 넘긴다. setTouchRaycaster(null) 과 같은 효과다.
  - `isEnabled` boolean: 노드에 넘기면 참. (기본 참)

  예제: 씬 기본 넘기기를 끄고 훅에서 직접 받기

  ```js
  import { Scene } from "./build/vanilla.js";
  const scene = new Scene();
  scene.setTouchDispatchEnabled(false);
  console.log(scene.isTouchDispatchEnabled()); // false
  ```

- `isTouchDispatchEnabled()` (method, since 0.4.0): 노드에 터치를 넘기는지 반환.
  - returns boolean: 넘기면 참.
- `getTouchRaycaster()` (method, since 0.4.0): 터치 레이캐스터 반환.
  - returns TouchRaycaster | null: 노드에 터치를 넘기는 레이캐스터. (create 에서 TouchRaycaster 를 만든다, 넘기지 않으면 null)
- `setGizmoVisible(isVisible)` (method, since 0.0.9): 기즈모 그리기 설정.
  - `isVisible` boolean: 참이면 기즈모를 그린다.
- `isGizmoVisible()` (method, since 0.0.9): 기즈모 그리기 여부 반환.
  - returns boolean: 기즈모를 그리면 참.
- `setSceneBackgroundColor(color)` (method, since 0.4.0): 배경색 설정. (drawSceneBackground 가 칠한다, Color 나 "#202020" 같은 색 글)
  - `color` Color | string: 배경색. (색 글은 Color.from 으로 읽는다, 기본 검정)
- `getSceneBackgroundColor()` (method, since 0.4.0): 배경색 반환.
  - returns Color: 배경색. (기본 검정)
- `drawSceneBackground(graphic)` (method, since 0.4.0): 배경 그리기. (캔버스 전체를 배경색으로 칠하고 뷰 좌표계를 건다, 세이프 에어리어 바깥까지)
  - GameScene 과 UIScene 은 preDraw 에서 부른다. Scene 을 바로 잇는 씬은 preDraw 에서 불러 쓴다.
  - `graphic` Graphic: 그릴 그래픽.

  예제: Scene 을 바로 이은 씬의 배경을 칠하기

  ```js
  import { Engine, EngineConfiguration, Scene, Vector2 } from "./build/vanilla.js";
  
  class MainScene extends Scene {
  	create() {
  		super.create();
  		this.setSceneBackgroundColor("#203040");
  	}
  
  	preDraw(graphic) {
  		super.preDraw(graphic);
  		this.drawSceneBackground(graphic);
  	}
  }
  const engineConfiguration = new EngineConfiguration();
  engineConfiguration.referenceResolutionSize = Vector2.create(1280, 720);
  const engine = new Engine(engineConfiguration);
  engine.run(new MainScene());
  ```

