빠른 시작
엔진을 의존성으로 넣고, 흰 사각형 하나를 그리는 씬을 데스크탑 창으로 띄운 뒤, 같은 코드를 웹으로 빌드합니다. 끝에 저장소의 예제 목록이 있습니다.
의존성
Cargo.toml:
[dependencies]
vanilla-engine = { git = "https://github.com/ddukbaek2/vanilla-engine" }크레이트 이름은 vanilla-engine 이고, 코드에서는 짧게 vanilla 로 씁니다. (엔진 Cargo.toml 의 [lib] 이름이 vanilla 입니다. 고도가 godot, 베비가 bevy 로 쓰는 것과 같은 꼴입니다)
첫 씬
src/main.rs:
use vanilla::{Colors, Engine, EngineConfiguration, Graphic, Rect, Scene, SceneBase, Vector2};
struct MainScene {
scene_base: SceneBase,
}
impl Scene for MainScene {
fn get_scene_base(&self) -> &SceneBase {
&self.scene_base
}
fn get_scene_base_mut(&mut self) -> &mut SceneBase {
&mut self.scene_base
}
fn pre_draw(&mut self, graphic: &mut Graphic) {
self.scene_base.draw_scene_background(graphic);
}
fn draw(&mut self, graphic: &mut Graphic) {
graphic.set_fill_color(Colors::WHITE);
graphic.draw_rect(Rect::create(100.0, 100.0, 200.0, 120.0));
}
}
fn main() {
let mut engine_configuration = EngineConfiguration::new();
engine_configuration.title = String::from("My Game");
engine_configuration.auto_resize_on_window_resize = true;
engine_configuration.reference_resolution_size = Vector2::create(1280.0, 720.0);
let engine = Engine::new(engine_configuration);
let main_scene = MainScene {
scene_base: SceneBase::new(),
};
if let Err(error) = engine.run(Box::new(main_scene)) {
eprintln!("{}", error);
std::process::exit(1);
}
}cargo run
엔진 저장소 안에서는 같은 코드가 examples/quickstart.rs 에 있습니다. (cargo run --example quickstart, 창 제목만 다릅니다)
- 씬은
Scene트레이트를 구현합니다. 꼭 구현할 것은 씬 공통 상태(SceneBase)를 내주는get_scene_base,get_scene_base_mut둘이고, 나머지 훅(load,initialize,tick,pre_draw,draw같은 것)은 필요한 것만 덮어씁니다. 훅의 이름과 인자는 원본과 같습니다. (load(engine),tick(time_delta),draw(graphic), 엔진을 받지 않는 훅에서는Engine::get_engine()) pre_draw에서 부른SceneBase::draw_scene_background는 창 전체를 씬 배경색(처음 검정)으로 칠하고, 그다음 그리기를 뷰 좌표로 바꿉니다. 그래서draw의Rect::create(100.0, 100.0, 200.0, 120.0)은 기준 해상도 1280 x 720 안의 자리입니다.- 기본
draw는 씬의 노드 트리를 그립니다. 이 예제는 노드가 없어 덮어쓴draw에서 사각형만 그립니다. 노드를 쓰는 씬은 덮어쓴draw에서self.scene_base.draw(graphic)을 함께 부릅니다. reference_resolution_size는 게임이 그리는 기준 해상도입니다. 창 크기가 달라도 뷰 스케일 모드(처음ViewScaleMode::StretchShort)가 이 크기를 창에 맞춰 늘이고 줄입니다.auto_resize_on_window_resize를 켜면 창 크기가 바뀔 때 캔버스를 창에 맞춥니다.- 데스크탑 창은
EngineConfiguration::window_size가 0 이면(처음 값) 기준 해상도 크기로 열립니다. Engine::run은 데스크탑에서는 창을 닫거나Engine::exit_application을 부를 때까지 돌아오지 않고, 웹에서는 프레임 콜백을 걸어 둔 뒤 바로 돌아옵니다. 창이나 GL 컨텍스트를 만들지 못하면Err에 까닭을 담아 돌려줍니다.
웹으로 빌드
wasm32-unknown-unknown 타깃과 wasm-bindgen 명령줄 도구가 있으면 됩니다. 엔진 저장소에서 위 예제를 빌드하면 이렇습니다.
rustup target add wasm32-unknown-unknown
cargo build --profile wasm-release --example quickstart --target wasm32-unknown-unknown
wasm-bindgen --target web --no-typescript --remove-name-section --remove-producers-section --out-dir web target/wasm32-unknown-unknown/wasm-release/examples/quickstart.wasmweb/index.html:
<!doctype html>
<html>
<head><meta charset="utf-8"><style>html, body { margin: 0; overflow: hidden; background: #000; }</style></head>
<body>
<script type="module">
import init from "./quickstart.js";
init();
</script>
</body>
</html>wasm-release프로필은 엔진Cargo.toml에 있습니다. 자기 게임 크레이트에서는 같은 프로필을 게임의Cargo.toml에 둡니다. ("프로젝트 시작" 장)- 캔버스는
EngineConfiguration::canvas_id(처음mainCanvas)로 찾고, 페이지에 없으면 엔진이 그 아이디로 만들어body끝에 붙입니다. - 모듈 스크립트와 애셋 받기는
file://로 연 페이지에서 브라우저가 막습니다. 로컬 웹 서버로 엽니다. (예:python3 -m http.server --directory web 8000뒤http://localhost:8000)
예제
모두 엔진 저장소의 examples/ 에 소스가 있습니다.
cargo run --example uigallery
cargo run --release --example modelviewer| 예제 | 내용 |
|---|---|
quickstart |
이 장의 첫 씬과 같은 코드 |
nodebasics |
노드, Paint, Text, 직접 만든 컴포넌트 |
uigallery, uigallery2 |
UI 위젯 전부 |
inputgallery |
입력 필드, 한글 IME 조합, 선택 영역, 리치텍스트, 게임패드 진동 시험 |
effectgallery |
셰이더 스프라이트 49 종, 화면 효과, 트레일, 파티클 |
particleeffects |
파티클 이펙트 열여덟 |
spriteeffects |
스프라이트 셰이더, 화면 효과, 연출 |
uisample |
UIDocument 로 uiasset 읽기 |
uishowcase |
대시보드 앱 한 벌(uiasset 여섯, 테마, 팝업, 반응형) |
misctour |
카메라, 길찾기, 대화 시스템, 화면 흔들림, 플로팅 텍스트 |
cameratour |
Camera2D 회전 둘러보기: 천천히 도는 카메라, 끌어 팬, 커서 고정 휠 줌, 흔들림, 노드 배율 트윈, Indicator |
timelineshowcase |
타임라인 문서 재생 |
modelviewer |
스키닝 3D(glTF, FBX), 그림자, 블룸 |
ancientmountain |
3인칭 산 오르기: 절차 지형과 3중 텍스처, 마네킹 달리기, 점프, 등반, 뛰어내리기, 여우 여섯, 정상 깃발, 섀도우 맵, 블룸, 모션 블러, 옵션 패널 |
neonhorizon |
네온 그리드 지형 달리기: 별과 유성, 함대, 부스트 빛살, 먼지 파티클, 블룸, 색수차, 필름 그레인, 필믹 톤맵, 옵션 패널 |
oldface |
사람 피부 렌더러(피부, 눈, 머리카락), 그림자, AO, SSS, 블룸, 표정 모프와 주름 맵 |
engineextras |
테, 진행 고리, 부드러운 그늘, 마우스 커서, 카메라 손짓, 마우스 단추와 손가락 입력 |
devtoolsshowcase |
개발자 도구(F2): 하이어라키, 인스펙터, 통계, 로컬 스토리지, 설정 |
toonshowcase |
툰 3D: 기본 도형과 바깥선, GLB 모형의 뼈대 움직임, 셀 셰이딩, 인스턴싱과 화면 밖 거르기, 그림자, HDR 블룸 |
toonshading |
VRM 1.0 캐릭터 셀 셰이딩: 램프, 얼굴 구면 노멀, 앞머리 그림자와 비침, 림 라이트, 블룸, FXAA, 표정 단추, 동작 옮기기, 노드 제약, 궤도 카메라 |
toonview |
노드 사각형 안 툰(ToonView3D), Camera3D 로 3D 점 위에 얹은 2D |
toonfx |
툰 화면 공간 바깥선과 GPU 효과 |
toonpost |
툰 HDR 마무리 세 판 |
toonmaterial |
툰 머티리얼 셰이더 조각, 텍스처와 데칼, 점광, 평면 거울, 영구 인스턴스 버퍼 |
toonstyle |
툰 셰이딩과 바깥선 견주기 |
audiotone |
소리 재생, 효과음 풀, 비프 |
gamepadlist |
연결된 게임패드 목록 |
uiscenelayout |
UIScene 과 UINode 오토레이아웃 |
windowshowcase |
창 쌓기와 확인 창, 화면 페이드, UI 가 받지 않은 누름만 놀이 입력으로 |
loadingshowcase |
AssetLoader 로 함께 받기, 바꾼 로딩 화면, 빌드 판, FixedStepper |
asyncawait |
원본처럼 async/await: 불러오기 작업, wait::seconds, wait::next_frame, fade_screen_async, Promise |
textnodeextras |
글자 칸 맞춤, 배율이 움직이는 글, 반투명 고리와 호와 선분, 스프라이트 아틀라스, 그림자 글 |
panelayout |
화면 분할 패널(Pane) |
blendmodes |
블렌드 모드 26 가지 |
textshaping |
오른쪽에서 왼쪽 글, 가짜 기울임과 굵게, 한중일 낱말 줄바꿈, DynamicFont |
scenedocument |
vanilla.js 비주얼 에디터 꼴의 씬 파일(.scene.json)을 읽어 노드 트리를 짓고 다시 내보내 견주기 |
modelviewer,ancientmountain,oldface,toonshowcase,toonshading,timelineshowcase,loadingshowcase,scenedocument는 vanilla.js 의 예제 애셋을 씁니다. vanilla.js 저장소를 엔진 저장소 옆에 받아 둡니다. (vanilla.js와vanilla-engine폴더가 나란히)- 예제는 애셋 경로를 저장소 루트 기준으로 적어 두었으므로 저장소 루트에서 실행합니다.
- 무거운 3D 예제는
--release로 돌립니다. (Cargo 의 dev 빌드는 최적화를 하지 않습니다)
관련 타입
Engine, EngineConfiguration, Scene, SceneBase, Graphic, Rect, Colors, Vector2, ViewScaleMode
Getting Started
Add the engine as a dependency, open a scene that draws one white rectangle in a desktop window, then build the same code for the web. A list of the repository's examples follows at the end.
Dependency
Cargo.toml:
[dependencies]
vanilla-engine = { git = "https://github.com/ddukbaek2/vanilla-engine" }The crate name is vanilla-engine, and in code it is shortened to vanilla. (The [lib] name in the engine's Cargo.toml is vanilla, the same pattern as Godot using godot and Bevy using bevy)
First Scene
src/main.rs:
use vanilla::{Colors, Engine, EngineConfiguration, Graphic, Rect, Scene, SceneBase, Vector2};
struct MainScene {
scene_base: SceneBase,
}
impl Scene for MainScene {
fn get_scene_base(&self) -> &SceneBase {
&self.scene_base
}
fn get_scene_base_mut(&mut self) -> &mut SceneBase {
&mut self.scene_base
}
fn pre_draw(&mut self, graphic: &mut Graphic) {
self.scene_base.draw_scene_background(graphic);
}
fn draw(&mut self, graphic: &mut Graphic) {
graphic.set_fill_color(Colors::WHITE);
graphic.draw_rect(Rect::create(100.0, 100.0, 200.0, 120.0));
}
}
fn main() {
let mut engine_configuration = EngineConfiguration::new();
engine_configuration.title = String::from("My Game");
engine_configuration.auto_resize_on_window_resize = true;
engine_configuration.reference_resolution_size = Vector2::create(1280.0, 720.0);
let engine = Engine::new(engine_configuration);
let main_scene = MainScene {
scene_base: SceneBase::new(),
};
if let Err(error) = engine.run(Box::new(main_scene)) {
eprintln!("{}", error);
std::process::exit(1);
}
}cargo run
Inside the engine repository the same code is in examples/quickstart.rs. (cargo run --example quickstart, only the window title differs)
- A scene implements the
Scenetrait. The only required functions areget_scene_baseandget_scene_base_mut, which hand out the shared scene state (SceneBase); override only the other hooks you need (load,initialize,tick,pre_draw,drawand so on). Hook names and arguments are the same as the original (load(engine),tick(time_delta),draw(graphic); in hooks that do not receive the engine, useEngine::get_engine()). SceneBase::draw_scene_background, called inpre_draw, fills the whole window with the scene background color (black at first) and switches the following drawing to view coordinates. SoRect::create(100.0, 100.0, 200.0, 120.0)indrawis a position inside the 1280 x 720 reference resolution.- The default
drawdraws the scene's node tree. This example has no nodes, so the overriddendrawonly draws the rectangle. A scene that uses nodes also callsself.scene_base.draw(graphic)in its overriddendraw. reference_resolution_sizeis the reference resolution the game draws in. Whatever the window size, the view scale mode (ViewScaleMode::StretchShortat first) stretches and shrinks this size to fit the window.- With
auto_resize_on_window_resizeon, the canvas follows the window when the window is resized. - The desktop window opens at the reference resolution size when
EngineConfiguration::window_sizeis 0 (the default). - On desktop
Engine::rundoes not return until the window is closed orEngine::exit_applicationis called; on the web it registers the frame callback and returns right away. If it cannot create the window or GL context, it returnsErrwith the reason.
Building for the Web
You need the wasm32-unknown-unknown target and the wasm-bindgen command-line tool. Building the example above in the engine repository looks like this.
rustup target add wasm32-unknown-unknown
cargo build --profile wasm-release --example quickstart --target wasm32-unknown-unknown
wasm-bindgen --target web --no-typescript --remove-name-section --remove-producers-section --out-dir web target/wasm32-unknown-unknown/wasm-release/examples/quickstart.wasmweb/index.html:
<!doctype html>
<html>
<head><meta charset="utf-8"><style>html, body { margin: 0; overflow: hidden; background: #000; }</style></head>
<body>
<script type="module">
import init from "./quickstart.js";
init();
</script>
</body>
</html>- The
wasm-releaseprofile is defined in the engine'sCargo.toml. In your own game crate, put the same profile in the game'sCargo.toml. (See the "Project Setup" chapter) - The canvas is looked up by
EngineConfiguration::canvas_id(mainCanvasat first); if the page has none, the engine creates one with that id and appends it to the end ofbody. - Browsers block module scripts and asset fetches on a page opened from
file://. Open it through a local web server. (For examplepython3 -m http.server --directory web 8000, thenhttp://localhost:8000)
Examples
All sources are in examples/ of the engine repository.
cargo run --example uigallery
cargo run --release --example modelviewer| Example | Contents |
|---|---|
quickstart |
Same code as this chapter's first scene |
nodebasics |
Nodes, Paint, Text, a custom component |
uigallery, uigallery2 |
Every UI widget |
inputgallery |
Input fields, Korean IME composition, selection, rich text, gamepad vibration test |
effectgallery |
49 shader sprite effects, screen effects, trails, particles |
particleeffects |
Eighteen particle effects |
spriteeffects |
Sprite shaders, screen effects and staging |
uisample |
Load a uiasset with UIDocument |
uishowcase |
A dashboard app (six uiassets, themes, popups, responsive layout) |
misctour |
Camera, path finding, dialogue system, screen shake, floating text |
cameratour |
Camera2D rotation tour: a slowly turning camera, drag to pan, wheel zoom around the cursor, shake, a node scale tween, Indicator |
timelineshowcase |
Timeline document playback |
modelviewer |
Skinned 3D (glTF, FBX), shadows, bloom |
ancientmountain |
Third-person mountain climb: procedural terrain with three-way texture blending, mannequin run, jump, climb and drop, six foxes, summit flags, shadow map, bloom, motion blur, option panel |
neonhorizon |
Neon grid terrain run: stars and meteors, a fleet, boost streaks, dust particles, bloom, chromatic aberration, film grain, filmic tone map, option panel |
oldface |
Human skin renderer (skin, eyes, hair), shadows, AO, SSS, bloom, expression morphs and wrinkle maps |
engineextras |
Outlines, progress ring, soft shade, mouse cursor, camera gestures, mouse buttons and finger input |
devtoolsshowcase |
Developer tools (F2): hierarchy, inspector, statistics, local storage, settings |
toonshowcase |
Toon 3D: basic shapes and outlines, skeletal animation of a GLB model, cel shading, instancing and off-screen culling, shadows, HDR bloom |
toonshading |
Cel shading of a VRM 1.0 character: ramp, spherical face normals, bangs shadow and see-through, rim light, bloom, FXAA, expression buttons, animation retargeting, node constraints, orbit camera |
toonview |
Toon inside a node rectangle (ToonView3D), 2D placed on 3D points with Camera3D |
toonfx |
Toon screen-space outlines and GPU effects |
toonpost |
Three variants of toon HDR finishing |
toonmaterial |
Toon material shader snippets, textures and decals, point lights, planar mirror, persistent instance buffers |
toonstyle |
Comparing toon shading and outlines |
audiotone |
Sound playback, sound effect pool, beeps |
gamepadlist |
List of connected gamepads |
uiscenelayout |
UIScene and UINode auto layout |
windowshowcase |
Window stacking and confirm windows, screen fade, only presses the UI did not take go to play input |
loadingshowcase |
Loading together with AssetLoader, a customized loading screen, build version, FixedStepper |
asyncawait |
async/await like the original: a loading task, wait::seconds, wait::next_frame, fade_screen_async, Promise |
textnodeextras |
Fitting text to a box, text with animated scale, translucent rings, arcs and segments, sprite atlas, shadow text |
panelayout |
Split panes (Pane) |
blendmodes |
All 26 blend modes |
textshaping |
Right-to-left text, synthetic italic and bold, CJK word wrapping, DynamicFont |
scenedocument |
Reads a scene file in the vanilla.js visual editor format (.scene.json) into a node tree, exports it again and compares |
modelviewer,ancientmountain,oldface,toonshowcase,toonshading,timelineshowcase,loadingshowcaseandscenedocumentuse example assets from vanilla.js. Clone the vanilla.js repository next to the engine repository. (Thevanilla.jsandvanilla-enginefolders side by side)- The examples write asset paths relative to the repository root, so run them from the repository root.
- Run heavy 3D examples with
--release. (Cargo's dev build does not optimize)
Related Types
Engine, EngineConfiguration, Scene, SceneBase, Graphic, Rect, Colors, Vector2, ViewScaleMode