vanilladocs
vanillapunch.com

UI

버튼, 라벨, 슬라이더 같은 UI 를 화면에 올리는 방법을 다룹니다. UI 를 위한 씬 UIScene, 노드에 붙이는 위젯 컴포넌트, 붙으면 스스로 자식 노드를 짓는 완성 위젯, UI 문서를 읽는 UIDocument, 두 가지 배치 방법(NodeLayout, 제약 기반 LayoutSolver), 창 쌓기(UIWindowLayer), 단추 반응(ButtonMotion) 차례입니다. 노드와 컴포넌트 자체는 "노드와 컴포넌트" 장, 터치가 노드에 닿는 과정은 "입력" 장에서 다룹니다.

두 갈래 UI

엔진의 UI 는 노드의 자리를 정하는 방식에 따라 두 갈래입니다. 러스트 판은 노드 종류가 WorldNode 하나뿐이라, 원본에서 노드였던 위젯과 UINode 도 모두 노드에 붙이는 컴포넌트입니다.

  • 직접 놓기. 노드에 위젯 컴포넌트(UILabel, UIButton, UISlider 같은 UIView 계열)를 붙이고, 자리와 크기는 기준점(pivot), set_local_position, set_content_size 로 직접 정합니다. UIDropdown, UIDialog, UIToast, UIWindow 같은 완성 위젯은 create(node_tree, parent_id, ...) 로 노드를 만들어 붙입니다.
  • 제약으로 놓기. 노드에 UINode 컴포넌트를 붙이면 왼쪽, 오른쪽, 위, 아래, 너비, 높이, 가운데 X, 가운데 Y 여덟 변수가 생기고, 제약을 걸면 LayoutSolver 가 그 값을 풉니다. 푼 값은 노드의 로컬 자리와 내용 크기로 옮겨집니다. 화면 크기와 세이프 에어리어에 맞춰 늘고 주는 배치에 씁니다.

두 갈래 모두 UIScene 에서 씁니다. UINode 가 노드의 자리와 크기를 정해 주므로, 원본과 달리 같은 노드에 UIButton 을 붙이면 그대로 눌립니다.

UIScene

UIScene 은 UI 용 씬입니다. 러스트에는 상속이 없어서 씬 구조체가 UISceneBase 를 필드로 품고 UIScene 트레이트를 구현한 뒤, vanilla::ui_scene!(씬 타입); 한 줄로 Scene 구현을 얻습니다. UISceneBase 는 다음을 스스로 갖추고 있습니다.

  • 터치 전달. 품은 GameSceneBase 가 TouchRecognizer 를 들고 tick 마다 노드 트리에 터치를 넘깁니다. 스크롤 뷰 안의 단추를 끌어도 스크롤되는 손짓이 여기서 나옵니다.
  • 로딩 화면. 검은 바탕, 가운데 그림(set_loading_image_url), 아래 막대를 그립니다. 기본으로 최소 3000 밀리초 동안 보이고 화면을 누르면 바로 넘어갑니다. set_loading_min_duration_ms(milliseconds) 로 바꿉니다.
  • 애셋 읽기 자리 load_assets(&mut self). (원본 loadAssets()) 바탕의 load 바로 뒤에 불립니다. 읽기를 맡긴 애셋을 get_scene_base_mut().track_asset(...) 으로 씬에 맡기면 다 읽힌 뒤에 initialize 가 불립니다.
  • 바탕색 set_scene_background_color(color)(기본 검정), 뷰 배율 방식 set_view_scale_mode(mode, engine)(기본 ViewScaleMode::None, 엔진을 None 으로 주면 initialize 에서 적용합니다).
  • 제약 솔버(get_solver()), 화면 가이드(get_screen_node()), 세이프 에어리어 가이드(get_safe_area_layout_guide()). 아래 "제약 배치" 절에서 씁니다.
  • 개발자 도구. EngineConfiguration::use_dev_tools 가 꺼져 있으면 만들지 않습니다.
  • 러스트 판의 UISceneBase 는 GameSceneBase 를 품고 있어서 화면 페이드와 놀이 입력 같은 GameSceneBase 기능도 get_game_scene_base_mut() 로 씁니다. (원본 UIScene 에는 없습니다)

UIScene 트레이트의 load_assets, initialize, layout, tick, pre_draw, draw, post_draw, destroy, touch_press 같은 함수는 모두 기본 구현이 있어 필요한 것만 덮어씁니다. ui_scene! 이 만든 Scene 함수는 바탕을 먼저 부르고 트레이트의 같은 이름 함수를 부릅니다(원본에서 super 를 먼저 부르는 덮어쓰기). post_draw 만 씬의 것을 먼저 부르고 바탕(개발자 도구)을 위에 그립니다. layout 은 첫 tick 과 뷰 크기가 바뀔 때 불립니다.

아래는 제목 라벨과 단추 하나를 놓는 씬입니다. 단추 노드에 Paint(바탕), UILabel(글), UIButton(누름 처리)을 함께 붙입니다.

use vanilla::{Color, ComponentContext, Engine, EngineConfiguration, NodeId, NodeTree, Paint, Pivot, UIButton, UILabel, UIScene, UISceneBase, Vector2};

struct MenuScene {
	ui_scene_base: UISceneBase,
}

impl MenuScene {
	fn set_title(node_tree: &mut NodeTree, title_id: NodeId, text: &str) {
		if let Some(title_label) = node_tree[title_id].get_component_mut::<UILabel>() {
			title_label.set_text(text);
		}
	}
}

impl UIScene for MenuScene {
	fn get_ui_scene_base(&self) -> &UISceneBase {
		&self.ui_scene_base
	}

	fn get_ui_scene_base_mut(&mut self) -> &mut UISceneBase {
		&mut self.ui_scene_base
	}

	fn initialize(&mut self, _engine: &Engine) {
		let node_tree = self.ui_scene_base.get_scene_base_mut().get_node_tree_mut();
		let root_id = node_tree.get_root_id();

		let title_id = node_tree.create_child(root_id, "Title");
		node_tree[title_id].set_pivot(Pivot::TOP_LEFT);
		node_tree[title_id].set_local_position(Vector2::create(40.0, 40.0));
		node_tree[title_id].set_content_size(Vector2::create(400.0, 48.0));
		let title_label = node_tree.add_component(title_id, UILabel::create_with_text("Main Menu", 32.0)).expect("label");
		title_label.set_text_color(Color::create(0.95, 0.96, 1.0, 1.0));

		let button_id = node_tree.create_child(root_id, "StartButton");
		node_tree[button_id].set_pivot(Pivot::TOP_LEFT);
		node_tree[button_id].set_local_position(Vector2::create(40.0, 120.0));
		node_tree[button_id].set_content_size(Vector2::create(200.0, 56.0));
		let button_paint = node_tree[button_id].add_component(Paint::create_with_color(Color::create(0.23, 0.51, 0.96, 1.0)));
		button_paint.set_round_size(12.0);
		node_tree.add_component(button_id, UILabel::create_with_text("Start", 22.0));
		let button = node_tree.add_component(button_id, UIButton::new()).expect("button");
		button.set_clicked_event(Box::new(move |_button: &mut UIButton, context: &mut ComponentContext| {
			MenuScene::set_title(context.get_node_tree_mut(), title_id, "Started");
		}));
		button.set_long_press_seconds(0.8);
		button.set_long_pressed_event(Box::new(move |_button: &mut UIButton, context: &mut ComponentContext| {
			MenuScene::set_title(context.get_node_tree_mut(), title_id, "Long pressed");
		}));
	}
}

vanilla::ui_scene!(MenuScene);

fn main() {
	let mut engine_configuration = EngineConfiguration::new();
	engine_configuration.reference_resolution_size = Vector2::create(1280.0, 720.0);
	engine_configuration.auto_resize_on_window_resize = true;
	let engine = Engine::new(engine_configuration);
	let mut ui_scene_base = UISceneBase::new();
	ui_scene_base.set_loading_min_duration_ms(0.0);
	ui_scene_base.set_scene_background_color(Color::create(0.08, 0.09, 0.12, 1.0));
	let menu_scene = MenuScene {
		ui_scene_base,
	};
	if let Err(error) = engine.run(Box::new(menu_scene)) {
		eprintln!("{}", error);
	}
}
  • 위젯의 알림은 Box<dyn FnMut(&mut UIButton, &mut ComponentContext)> 처럼 위젯과 컴포넌트 문맥을 받습니다. 원본 콜백은 위젯만 받지만, 러스트 판은 문맥의 get_node_tree_mut() 로 다른 노드를 찾아 바꿀 수 있게 했습니다. 다른 노드는 NodeId 로 가리키고, NodeId 는 Copy 라서 move 클로저에 그대로 담깁니다.
  • 평범한 Scene 도 SceneBase::tick 이 가장 앞의 누를 수 있는 노드에 터치를 넘겨서 위젯이 눌립니다(원본 기본 씬도 같습니다). 다만 스크롤 뷰로 끌기를 넘기는 손짓은 없습니다. 그 손짓이 필요하면 UIScene 을 쓰거나, 씬이 TouchRecognizer 를 들고 SceneBase::tick 대신 노드 트리의 tick 과 touch_recognizer.tick_touch(node_tree, engine) 를 부릅니다(examples/uigallery.rs 가 그렇게 합니다).

위젯 컴포넌트

노드에 붙이는 위젯입니다. 노드의 내용 크기(set_content_size)를 영역으로 씁니다.

uigallery 예제: UIButton, UIToggleButton, UISlider, UIProgressView, UIImageView, UIScrollView 와 UIScrollBar

타입 하는 일
UIView 바탕색(set_background_color)과 내용 노드(get_content())를 가진 판. 아래 위젯들이 품는 바탕
UIControl 입력을 받는 위젯의 바탕. UIView 를 품습니다
UILabel 글. RichText 를 품고, RichText 가 Text 를 품습니다
UIImageView 그림. Sprite 를 품습니다
UIButton 누름 처리와 눌림 색
UIToggleButton 켜고 끄는 단추 (UIButton 을 품습니다)
UISlider 끌거나 눌러서 값을 고르는 막대
UIProgressView 진행 막대 (입력 없음)
UIScrollView 끌어서 넘기는 영역. 붙으면 자식을 잘라 그리도록 Mask 를 함께 붙입니다
  • 원본은 위젯이 UIView 를 상속하지만, 러스트 판은 위젯이 UIView(또는 UIControl)를 필드로 품고 내용 노드와 바탕색을 넘겨줍니다. 그래서 get_component::<UIView>() 로 하위 위젯까지 한 번에 찾는 쓰임은 없고, get_component::<UIButton>() 처럼 구체 타입으로 찾습니다.
  • 위젯은 node_tree.add_component(node_id, UIButton::new()) 처럼 트리에 붙입니다. 그래야 붙을 때 노드 밑에 내용 노드(content)를 만들고, 누르는 위젯이면 노드를 interactable 로 켭니다. node_tree[node_id].add_component(...) 로 붙이면 이 일이 일어나지 않아 눌리지 않습니다. 위젯 안에 넣을 자식은 get_content() 가 돌려준 노드에 붙입니다.
  • UILabel 과 UIImageView 는 글자 컴포넌트와 스프라이트를 품기 때문에, 라벨 노드의 get_component::<Text>() 와 이미지 뷰 노드의 get_component::<Sprite>() 는 None 입니다. 품은 것은 get_text_component(), get_rich_text_component(), get_sprite() 로 꺼냅니다.

UIButton

  • UIButton 은 스스로 아무것도 그리지 않습니다. 같은 노드와 그 아래 노드의 Sprite, UIImageView 에는 눌림 색을 덮고, Paint, Text, UILabel 에는 원래 색에서 눌림 색 쪽으로 섞습니다. 눌림 색 기본은 (0, 0, 0, 0.3), 마우스를 올렸을 때 (1, 1, 1, 0.12), 바뀌는 시간은 0.3 초이고 set_pressed_tint_color, set_hover_tint_color, set_transition_duration 으로 바꿉니다. 섞지 않을 것은 exclude_node_from_tint(node_id), exclude_component_from_tint::<UILabel>(node_id) 로 뺍니다. 원본은 컴포넌트 객체로 빼지만 러스트 판은 (노드, 컴포넌트 타입)으로 뺍니다.
  • 알림: set_clicked_event, set_click_event(클릭하면 이 둘이 차례로 불림), set_pressed_event, set_released_event, set_hover_event(마우스가 들어올 때 한 번), set_long_pressed_event. 클릭은 뗀 자리가 단추 안일 때만 납니다.
  • 길게 누름은 set_long_press_seconds(기본 0.5 초)를 넘기는 순간 한 번 알리고, 그 누름의 클릭은 삼킵니다.
  • set_interactable(false) 면 누를 수 없고 어둡게((0, 0, 0, 0.5)) 덮습니다. 색은 다음 tick 에 걸립니다.
  • set_minimum_pressed_seconds(seconds) 를 주면 짧게 눌러도 눌린 모습을 그만큼 보여 준 뒤 뗌을 처리합니다(기본 0).
  • 지금 상태는 get_button_state() 가 ButtonState::Normal, Hover, Pressed, Released, Disabled 로 알려 줍니다.

아래는 창 없이 노드 트리만으로 단추를 눌러 보는 예입니다. dispatch_touch 는 엔진이 터치를 넘길 때 쓰는 함수와 같습니다.

use std::cell::Cell;
use std::rc::Rc;
use vanilla::{ComponentContext, Engine, EngineConfiguration, NodeTree, Paint, Pivot, TouchKind, UIButton, UILabel, Vector2};

let engine = Engine::new(EngineConfiguration::new());
let mut node_tree = NodeTree::new();
let root_id = node_tree.get_root_id();

let status_id = node_tree.create_child(root_id, "Status");
node_tree.add_component(status_id, UILabel::create_with_text("Ready", 20.0));

let button_id = node_tree.create_child(root_id, "OkButton");
node_tree[button_id].set_pivot(Pivot::TOP_LEFT);
node_tree[button_id].set_local_position(Vector2::create(100.0, 100.0));
node_tree[button_id].set_content_size(Vector2::create(160.0, 48.0));
node_tree[button_id].add_component(Paint::create_with_color("#3b82f6"));
let long_press_count = Rc::new(Cell::new(0));
let long_press_count_for_event = long_press_count.clone();
let button = node_tree.add_component(button_id, UIButton::new()).expect("button");
button.set_clicked_event(Box::new(move |_button: &mut UIButton, context: &mut ComponentContext| {
	if let Some(status_label) = context.get_node_tree_mut()[status_id].get_component_mut::<UILabel>() {
		status_label.set_text("Clicked");
	}
}));
button.set_long_pressed_event(Box::new(move |_button: &mut UIButton, _context: &mut ComponentContext| {
	long_press_count_for_event.set(long_press_count_for_event.get() + 1);
}));
assert!(node_tree[button_id].is_interactable());

let inside = Vector2::create(180.0, 124.0);
let outside = Vector2::create(400.0, 124.0);
node_tree.dispatch_touch(button_id, &engine, TouchKind::Press, inside);
node_tree.dispatch_touch(button_id, &engine, TouchKind::Release, outside);
assert_eq!(node_tree[status_id].get_component::<UILabel>().expect("label").get_text(), "Ready");

node_tree.dispatch_touch(button_id, &engine, TouchKind::Press, inside);
node_tree.dispatch_touch(button_id, &engine, TouchKind::Release, inside);
assert_eq!(node_tree[status_id].get_component::<UILabel>().expect("label").get_text(), "Clicked");

node_tree[status_id].get_component_mut::<UILabel>().expect("label").set_text("Ready");
node_tree.dispatch_touch(button_id, &engine, TouchKind::Press, inside);
node_tree.tick(&engine, 0.6);
node_tree.dispatch_touch(button_id, &engine, TouchKind::Release, inside);
assert_eq!(long_press_count.get(), 1);
assert_eq!(node_tree[status_id].get_component::<UILabel>().expect("label").get_text(), "Ready");

그 밖의 위젯

  • UILabel: create_with_text(text, font_size), set_text, set_font_size, set_text_color, set_text_align(TextAlign), set_text_baseline(TextBaseline), set_bold, set_italic, set_underline, set_strikethrough, set_word_wrap_width(0 이면 줄바꿈 문자로만 나눔), set_wrap_mode, set_line_spacing, set_fit_width(width, minimum_ratio)(한 줄 글을 그 너비에 맞춰 글자 크기를 줄이되 비율 아래로는 줄이지 않음, 리치텍스트 모드는 맞추지 않음). 글꼴은 원본 setFont(FontFace) 대신 등록한 글꼴 이름을 set_font_family 로 줍니다. 새 라벨의 글자는 32 픽셀, 흰색, 가운데 정렬, 가운데 기준선입니다. use_rich_text(true) 면 <b>, <i>, <u>, <s>, <color=#RRGGBB[AA]>, <color=이름>, <size=N> 마크업을 읽습니다.
  • UIImageView: create_with_image(image), set_image(Option<Rc<Image>>), set_image_asset(&mut ImageAsset)(원본 setImage 는 둘을 함께 받습니다), set_image_rect, set_color(틴트), set_draw_mode(SpriteDrawMode::Simple, Sliced, Tiled), set_nine_slice, set_horizontal_flip, set_vertical_flip, set_blend_mode.
  • UIToggleButton: set_toggled_event, get_is_on, set_on_tint_color(기본 (0, 0, 0, 0.3)). set_is_on(is_on) 은 알림을 부르지 않고 상태만 바꾸며 색은 다음 tick 에 걸립니다. 길게 누름이나 누를 수 있음 같은 단추 설정은 get_uibutton_mut() 로 품은 UIButton 에 합니다. 알림 차례가 원본과 조금 다릅니다: 원본은 뗌, 뒤집기, 토글 알림, 클릭됨 알림, 클릭 알림 차례이고, 러스트 판은 뗌, 클릭 알림, 뒤집기, 토글 알림, 클릭됨 알림 차례입니다.
  • UISlider: set_range(min_value, max_value)(기본 0 ~ 1), set_value(범위로 자르고 알림은 부르지 않음), get_value, get_ratio, set_value_changed_event. 모양은 set_track_color, set_fill_color, set_thumb_color, set_thumb_radius(기본 16), set_track_thickness(0 이면 노드 영역 전체), set_corner_radius, set_direction(ProgressDirection::Horizontal 또는 Vertical). set_thumb_node(Some(node_id)) 로 손잡이 노드를 정하면 원을 그리지 않고 그 노드를 손잡이 자리로 옮깁니다(손잡이 노드는 슬라이더 노드의 자식으로 둡니다). 누를 수 없게 하려면 set_interactable(false) 입니다.
  • UIProgressView: set_range, set_value, set_track_color(바탕색과 같음), set_fill_color, set_corner_radius, set_direction. set_secondary_value(Some(value)) 를 주면 반대쪽 끝에서 차오르는 두 번째 채움(set_secondary_fill_color)을 그립니다. 값은 코드로만 바꿉니다.

아래는 슬라이더 값을 라벨과 진행 막대에 옮기고, 토글 단추로 슬라이더를 막는 예입니다.

use vanilla::{Color, ComponentContext, Engine, EngineConfiguration, NodeId, NodeTree, Paint, Pivot, TouchKind, UILabel, UIProgressView, UISlider, UIToggleButton, Vector2};

fn create_box_node(node_tree: &mut NodeTree, parent_id: NodeId, name: &str, position: Vector2, size: Vector2) -> NodeId {
	let node_id = node_tree.create_child(parent_id, name);
	node_tree[node_id].set_pivot(Pivot::TOP_LEFT);
	node_tree[node_id].set_local_position(position);
	node_tree[node_id].set_content_size(size);
	node_id
}

fn main() {
	let engine = Engine::new(EngineConfiguration::new());
	let mut node_tree = NodeTree::new();
	let root_id = node_tree.get_root_id();

	let value_id = create_box_node(&mut node_tree, root_id, "VolumeLabel", Vector2::create(240.0, 40.0), Vector2::create(320.0, 32.0));
	let value_label = node_tree.add_component(value_id, UILabel::create_with_text("Volume <b>50</b>", 20.0)).expect("label");
	value_label.use_rich_text(true);

	let progress_id = create_box_node(&mut node_tree, root_id, "VolumeBar", Vector2::create(240.0, 140.0), Vector2::create(320.0, 12.0));
	let progress_view = node_tree.add_component(progress_id, UIProgressView::new()).expect("progress");
	progress_view.set_track_color(Color::create(1.0, 1.0, 1.0, 0.15));
	progress_view.set_fill_color(Color::create(0.3, 0.8, 0.5, 1.0));
	progress_view.set_corner_radius(6.0);
	progress_view.set_value(0.5);

	let slider_id = create_box_node(&mut node_tree, root_id, "VolumeSlider", Vector2::create(240.0, 90.0), Vector2::create(320.0, 32.0));
	let slider = node_tree.add_component(slider_id, UISlider::new()).expect("slider");
	slider.set_range(0.0, 100.0);
	slider.set_value(50.0);
	slider.set_track_thickness(6.0);
	slider.set_corner_radius(3.0);
	slider.set_value_changed_event(Box::new(move |slider: &mut UISlider, context: &mut ComponentContext| {
		let value = slider.get_value().round();
		let node_tree = context.get_node_tree_mut();
		if let Some(value_label) = node_tree[value_id].get_component_mut::<UILabel>() {
			value_label.set_text(&format!("Volume <b>{}</b>", value));
		}
		if let Some(progress_view) = node_tree[progress_id].get_component_mut::<UIProgressView>() {
			progress_view.set_value(value / 100.0);
		}
	}));

	let toggle_id = create_box_node(&mut node_tree, root_id, "MuteToggle", Vector2::create(240.0, 180.0), Vector2::create(160.0, 48.0));
	let toggle_paint = node_tree[toggle_id].add_component(Paint::create_with_color(Color::create(0.25, 0.6, 0.35, 1.0)));
	toggle_paint.set_round_size(10.0);
	node_tree.add_component(toggle_id, UILabel::create_with_text("Mute", 18.0));
	let toggle_button = node_tree.add_component(toggle_id, UIToggleButton::new()).expect("toggle");
	toggle_button.set_on_tint_color(Color::create(0.0, 0.0, 0.0, 0.4));
	toggle_button.set_toggled_event(Box::new(move |toggle_button: &mut UIToggleButton, context: &mut ComponentContext| {
		let is_on = toggle_button.get_is_on();
		if let Some(slider) = context.get_node_tree_mut()[slider_id].get_component_mut::<UISlider>() {
			slider.set_interactable(!is_on);
		}
	}));

	let slider_position = Vector2::create(480.0, 106.0);
	node_tree.dispatch_touch(slider_id, &engine, TouchKind::Press, slider_position);
	node_tree.dispatch_touch(slider_id, &engine, TouchKind::Release, slider_position);
	assert_eq!(node_tree[value_id].get_component::<UILabel>().expect("label").get_text(), "Volume <b>75</b>");
	assert_eq!(node_tree[progress_id].get_component::<UIProgressView>().expect("progress").get_value(), 0.75);

	let toggle_position = Vector2::create(300.0, 200.0);
	node_tree.dispatch_touch(toggle_id, &engine, TouchKind::Press, toggle_position);
	node_tree.dispatch_touch(toggle_id, &engine, TouchKind::Release, toggle_position);
	assert!(node_tree[toggle_id].get_component::<UIToggleButton>().expect("toggle").get_is_on());
	assert!(!node_tree[slider_id].get_component::<UISlider>().expect("slider").get_interactable());
}

UIScrollView

스크롤 뷰를 붙인 노드의 내용 크기가 보이는 영역이고, 항목은 get_content() 가 돌려준 노드에 붙입니다. set_scroll_content_size(size) 로 끌 수 있는 전체 크기를 알려 줘야 하며 보이는 영역보다 커야 스크롤됩니다.

  • set_horizontal(false), set_vertical(false) 로 축을 끕니다.
  • set_scroll_mode(ScrollMode::Clamp) 는 경계를 넘지 않고(기본), ScrollMode::Elastic 은 넘으면 당기는 힘이 생기고 놓으면 튕겨 돌아옵니다.
  • set_shows_vertical_scroll_bar(true), set_shows_horizontal_scroll_bar(true) 로 스크롤바(UIScrollBar 가 붙은 노드)를 보입니다. 스크롤바 노드는 다음 tick 에 만들어지고, 그 자리에서 만들려면 UIScrollView::set_shows_vertical_scroll_bar_in_tree(node_tree, scroll_node_id, true) 를 부릅니다(만든 노드를 돌려줍니다).
  • set_scroll_offset(offset) 은 자리를 옮깁니다. 아래로 내린 만큼 y 가 음수이고, 값은 바로 범위로 잘리지만 내용 노드는 다음 tick 에 옮겨집니다. 같은 프레임에 옮기려면 UIScrollView::set_scroll_offset_in_tree(node_tree, scroll_node_id, offset) 를 씁니다.
  • set_drag_sensitivity(끌기 배율, 기본 1), set_wheel_scroll_scale(휠 배율, 기본 1), set_passes_cross_axis_drag(true)(스크롤하지 않는 축으로 더 많이 끈 손가락은 안쪽 위젯에 넘김, 세로 목록 안의 가로 슬라이더 같은 곳)도 있습니다.
  • TouchRecognizer 는 스크롤 뷰 안을 누르면 누름 전달을 150 밀리초 미루고, 10 픽셀 넘게 끌면 안쪽 위젯의 누름을 취소하고 스크롤로 넘깁니다.
use vanilla::{Color, Engine, EngineConfiguration, NodeTree, Paint, Pivot, ScrollMode, UILabel, UIScrollView, Vector2};

let engine = Engine::new(EngineConfiguration::new());
let mut node_tree = NodeTree::new();
let root_id = node_tree.get_root_id();
let viewport_id = node_tree.create_child(root_id, "List");
node_tree[viewport_id].set_pivot(Pivot::TOP_LEFT);
node_tree[viewport_id].set_local_position(Vector2::create(160.0, 60.0));
node_tree[viewport_id].set_content_size(Vector2::create(320.0, 240.0));

let row_count = 20;
let row_height = 40.0;
let content_id = {
	let scroll_view = node_tree.add_component(viewport_id, UIScrollView::new()).expect("scroll view");
	scroll_view.set_background_color(Color::create(0.1, 0.12, 0.16, 1.0));
	scroll_view.set_horizontal(false);
	scroll_view.set_scroll_mode(ScrollMode::Elastic);
	scroll_view.set_shows_vertical_scroll_bar(true);
	scroll_view.set_scroll_content_size(Vector2::create(320.0, row_count as f64 * row_height));
	scroll_view.get_content().expect("content")
};
for row_index in 0..row_count {
	let row_id = node_tree.create_child(content_id, "Row");
	node_tree[row_id].set_pivot(Pivot::TOP_LEFT);
	node_tree[row_id].set_local_position(Vector2::create(8.0, row_index as f64 * row_height + 2.0));
	node_tree[row_id].set_content_size(Vector2::create(296.0, row_height - 4.0));
	node_tree[row_id].add_component(Paint::create_with_color(Color::create(1.0, 1.0, 1.0, 0.06)));
	let row_text = format!("Row {}", row_index);
	node_tree.add_component(row_id, UILabel::create_with_text(&row_text, 18.0));
}

let scroll_view = node_tree[viewport_id].get_component_mut::<UIScrollView>().expect("scroll view");
scroll_view.set_scroll_offset(Vector2::create(0.0, -2000.0));
assert_eq!(scroll_view.get_scroll_offset(), Vector2::create(0.0, -560.0));
node_tree.tick(&engine, 0.016);
assert_eq!(node_tree[content_id].get_local_position(), Vector2::create(0.0, -560.0));
let scroll_view = node_tree[viewport_id].get_component::<UIScrollView>().expect("scroll view");
assert!(scroll_view.get_vertical_scroll_bar().is_some());

완성 위젯

붙으면 원본 생성자처럼 노드를 꾸미고 자식 노드와 컴포넌트를 스스로 짓는 위젯입니다. 원본에서는 WorldNode 를 이어받은 노드라 new 로 만들어 addChild 하지만, 러스트 판은 컴포넌트이고 UIDropdown::create(node_tree, parent_id, options) 처럼 노드를 만들어 붙이는 함수가 그 자리입니다. 원본의 options 객체는 ..Default::default() 로 채우는 옵션 구조체입니다. 트리를 바꾸는 함수는 트리를 받으므로 씬 코드에서는 node_tree.with_component_mut::<UIDropdown, _>(node_id, |dropdown, tree| ...) 로 부릅니다.

uigallery2 예제: UIListView, UISnapScrollView, UIDropdown, UIDraggable, UILineChart, UIBarChart, UISpinner, UIToast

  • UIInputField: 캔버스에 그리는 글 입력 칸. 다른 위젯처럼 node_tree.add_component(node_id, UIInputField::new()) 로 붙이며, 붙으면 노드의 기준점을 왼쪽 위로 맞춥니다. 입력을 받기 시작하려면 attach() 를, 그만 받을 때는 detach() 를 부릅니다. 기본은 필드가 키보드를 직접 받습니다. 한글 같은 IME 입력이 필요하면 set_use_dom_input(true) 를 켭니다(데스크탑은 그 필드가 포커스를 가질 때 winit IME 를 켜고, 웹은 원본처럼 숨긴 DOM <input> 을 씁니다). 원본의 setEngine 은 없습니다. set_placeholder, set_text(바뀜 알림 없음), get_text, set_max_length(UTF-16 단위, 0 이면 한없음), set_font_size(기본 28), set_font_family, set_on_change, set_on_submit(Enter), focus, blur, select_all, cut, copy, paste 가 있습니다. 알림은 필드와 문맥을 받고 값은 field.get_text() 로 읽습니다. 오른쪽 누름에는 잘라내기, 복사, 붙여넣기 메뉴가 뜹니다(데스크탑은 캔버스에 그리고, 웹은 DOM 메뉴). 노드를 끄거나 지우면 포커스와 IME 도 함께 사라집니다.
  • UIDropdown: 머리 단추에 지금 값을 보이고 누르면 목록을 펼칩니다. UIDropdown::create(node_tree, parent_id, UIDropdownOptions { width, height, option_height, font_size, base_color, popup_color, highlight_color, text_color })(기본 너비 180, 높이 30, 줄 높이 28, 글자 12). set_option_list(tree, &[...]), get_selected_index, get_selected_text, set_changed_event, set_open(tree, is_open) 이 있고, set_selected_index(tree, index) 는 알림 없이 고른 것만 바꿉니다. 펼친 목록은 루트의 마지막 자식으로 옮겨 다른 노드에 가리지 않게 합니다.
  • UIToast: show(message) 로 알약 모양 알림을 아래에서 띄워 잠시 보였다가 치웁니다. 여러 번 부르면 줄을 세웁니다. UIToast::create(node_tree, parent_id, UIToastOptions { width, height, rest_y, rest_x, hold_seconds, font_size, background_color, text_color })(기본 400 x 48, rest_y 560, rest_x 는 None 이면 부모 가로 가운데, 머무는 시간 1.8 초). show 는 줄에 넣기만 하고 보이는 것은 다음 tick 부터입니다.
  • UIDialog: 어둡게 가리는 막, 가운데 카드, 확인과 취소 단추를 show(tree, message, UIDialogShowOptions { on_confirm, on_cancel, confirm_text, cancel_text }) 한 번으로 띄웁니다. on_cancel 을 주지 않으면 확인만 있는 알림이 되고, 막을 누르면 취소로 칩니다. 처리기는 대화 상자와 문맥을 받는 한 번짜리 함수(FnOnce)입니다. 문맥이 없는 씬 코드에서 닫으려면 request_dismiss(is_confirmed) 를 부르면 다음 tick 에 닫습니다. UIDialogOptions 의 단추 글 기본값이 한국어("확인", "취소")이므로 다른 언어면 글을 넘깁니다. 부모의 내용 크기를 막 크기로 씁니다(없으면 960 x 640).

UIToast 와 UIDialog 는 다른 것 위에 그려지도록 루트의 마지막 자식으로 만듭니다. UIContextMenu, UISpinner, UIListView, UISnapScrollView, UIDraggable, UILineChart, UIBarChart, UIProgressRing, UIHitArea 같은 위젯도 있습니다(examples/uigallery2.rs 참고).

use vanilla::{ComponentContext, Engine, EngineConfiguration, NodeTree, TouchKind, UIDialog, UIDialogOptions, UIDialogShowOptions, UIDropdown, UIDropdownOptions, UIInputField, UILabel, UIToast, UIToastOptions, Vector2};

let engine = Engine::new(EngineConfiguration::new());
let mut node_tree = NodeTree::new();
let root_id = node_tree.get_root_id();
node_tree[root_id].set_content_size(Vector2::create(640.0, 360.0));

let field_id = node_tree.create_child(root_id, "NameField");
node_tree[field_id].set_local_position(Vector2::create(40.0, 40.0));
node_tree[field_id].set_content_size(Vector2::create(360.0, 56.0));
let input_field = node_tree.add_component(field_id, UIInputField::new()).expect("input field");
input_field.set_placeholder("Player name");
input_field.set_max_length(16);
input_field.attach();
input_field.set_text("Player");

let dropdown_options = UIDropdownOptions {
	width: 200.0,
	height: 36.0,
	font_size: 16.0,
	..UIDropdownOptions::default()
};
let dropdown_id = UIDropdown::create(&mut node_tree, root_id, dropdown_options);
node_tree[dropdown_id].set_local_position(Vector2::create(420.0, 50.0));
node_tree.with_component_mut::<UIDropdown, _>(dropdown_id, |dropdown, tree| {
	dropdown.set_option_list(tree, &["Low", "Medium", "High"]);
	dropdown.set_selected_index(tree, 1);
});

let toast_options = UIToastOptions {
	width: 320.0,
	height: 40.0,
	rest_y: 320.0,
	..UIToastOptions::default()
};
let toast_id = UIToast::create(&mut node_tree, root_id, toast_options);
let dialog_id = UIDialog::create(&mut node_tree, root_id, UIDialogOptions::default());

node_tree[dropdown_id].get_component_mut::<UIDropdown>().expect("dropdown").set_changed_event(Box::new(move |dropdown: &mut UIDropdown, context: &mut ComponentContext| {
	let message = format!("Quality: {}", dropdown.get_selected_text());
	if let Some(toast) = context.get_node_tree_mut()[toast_id].get_component_mut::<UIToast>() {
		toast.show(&message);
	}
}));

node_tree.with_component_mut::<UIDropdown, _>(dropdown_id, |dropdown, tree| {
	dropdown.set_open(tree, true);
});
let high_option_id = node_tree[dropdown_id].get_component::<UIDropdown>().expect("dropdown").get_option_nodes()[2];
let option_size = node_tree[high_option_id].get_content_size();
let option_center = node_tree.convert_node_position_to_view_position(high_option_id, option_size.multiply_scalar(0.5));
node_tree.dispatch_touch(high_option_id, &engine, TouchKind::Press, option_center);
node_tree.dispatch_touch(high_option_id, &engine, TouchKind::Release, option_center);
assert_eq!(node_tree[dropdown_id].get_component::<UIDropdown>().expect("dropdown").get_selected_text(), "High");
node_tree.tick(&engine, 0.016);
assert_eq!(node_tree[toast_id].get_component::<UILabel>().expect("label").get_text(), "Quality: High");

let player_name = node_tree[field_id].get_component::<UIInputField>().expect("input field").get_text().to_string();
let show_options = UIDialogShowOptions {
	on_confirm: Some(Box::new(move |_dialog: &mut UIDialog, context: &mut ComponentContext| {
		if let Some(toast) = context.get_node_tree_mut()[toast_id].get_component_mut::<UIToast>() {
			toast.show("Saved");
		}
	})),
	on_cancel: Some(Box::new(|_dialog: &mut UIDialog, _context: &mut ComponentContext| {})),
	confirm_text: Some(String::from("Save")),
	cancel_text: Some(String::from("Cancel")),
};
node_tree.with_component_mut::<UIDialog, _>(dialog_id, |dialog, tree| {
	dialog.show(tree, &format!("Save as {}?", player_name), show_options);
});
node_tree.tick(&engine, 0.4);
node_tree[dialog_id].get_component_mut::<UIDialog>().expect("dialog").request_dismiss(true);
node_tree.tick(&engine, 0.016);
node_tree.tick(&engine, 0.3);
assert!(!node_tree[dialog_id].is_active());

UIDocument 로 UI 문서 읽기

UI 문서는 노드 트리를 JSON 으로 적은 글입니다({ "version": 1, "root": 노드 }). vanilla.js 의 저작 도구가 이 꼴로 저장하고(저작 도구는 "저작 도구와 두 엔진이 같이 쓰는 파일" 장), 러스트 판에서 지은 트리도 같은 꼴로 내보냅니다.

  • 원본은 정적 클래스와 모듈 전역 표지만, 러스트 판은 표를 든 UIDocument 값을 UIDocument::new() 로 만들어 씁니다. new 가 엔진 컴포넌트 Paint, Sprite, Text, RichText, Mask, Outline, SoftShade, ShadowText, UIProgressRing, UILabel, UIImageView, UIButton, UIToggleButton, UIProgressView, UISlider, UIScrollView, ShadowImage 를 등록해 둡니다(get_component_type_names()). 저작 도구가 등록하는 종류 모두(컴포넌트 35, 노드 종류 12)는 register_editor_types() 한 줄로 더하고, 게임의 컴포넌트는 register_component_type(이름, 짓는 함수), 원본에서 노드 종류였던 것은 register_node_type 으로 더합니다. 등록하지 않은 종류는 읽을 때 건너뛰고 경고를 냅니다.
  • from_json_text(&mut node_tree, json_text) 는 문서를 노드 트리로 지어 뿌리 노드를 돌려줍니다. 뿌리는 어디에도 붙지 않았으므로 씬에 보이려면 add_child 로 붙입니다. JSON 이 아니거나 root 객체가 없으면 Err(까닭) 입니다(원본은 예외).
  • to_json_text(&mut node_tree, root_id, is_pretty) 는 반대로 노드 트리를 JSON 글로 적습니다. is_pretty 면 탭으로 들여 씁니다.
  • 문서는 그림 원본을 담지 않고 경로(imagePath)만 적습니다. set_image_resolver(|image_path| ...) 로 경로를 Option<Rc<Image>> 로 바꾸는 함수를 걸면 그것으로 찾습니다. 걸지 않으면 문서가 든 애셋 창고에서 찾는데, load_images(&engine, json_text) 가 문서의 그림을 ImageAsset 으로 요청하고(데스크탑은 EngineConfiguration::asset_directory_paths 에서), 웹처럼 나중에 읽히는 그림은 tick 에서 bind_pending_images(&mut node_tree) 가 남은 수가 0 이 될 때까지 붙입니다. 해석기와 load_images 는 from_json_text 전에 둡니다.
  • 문서에 있는 컴포넌트는 반사 매크로 #[reflect] 를 붙인 타입이어야 반사로 쓰고 읽습니다. 엔진 컴포넌트는 모두 붙어 있습니다("반사 매크로 #[reflect]" 장).

아래는 문서 글을 읽고 이름으로 단추를 찾아 동작을 붙이는 예입니다.

use std::cell::Cell;
use std::rc::Rc;
use vanilla::{ComponentContext, Engine, EngineConfiguration, NodeTree, TouchKind, UIButton, UIDocument, Vector2};

let json_text = r#"{
	"version": 1,
	"root": {
		"name": "Menu",
		"children": [
			{
				"name": "StartButton",
				"position": [120, 40],
				"contentSize": [200, 56],
				"interactable": true,
				"components": [
					{ "color": [0.23, 0.51, 0.96, 1], "roundSize": 12, "type": "Paint" },
					{ "type": "UIButton" }
				]
			}
		]
	}
}"#;

let engine = Engine::new(EngineConfiguration::new());
let mut node_tree = NodeTree::new();
let mut document = UIDocument::new();
let menu_id = document.from_json_text(&mut node_tree, json_text).expect("document");
let root_id = node_tree.get_root_id();
node_tree.add_child(root_id, menu_id);

let start_id = node_tree.find_descendant_by_name(menu_id, "StartButton").expect("start button");
let start_count = Rc::new(Cell::new(0));
let start_count_for_event = start_count.clone();
let start_button = node_tree[start_id].get_component_mut::<UIButton>().expect("button");
start_button.set_clicked_event(Box::new(move |_button: &mut UIButton, _context: &mut ComponentContext| {
	start_count_for_event.set(start_count_for_event.get() + 1);
}));
let center = Vector2::create(120.0, 40.0);
node_tree.dispatch_touch(start_id, &engine, TouchKind::Press, center);
node_tree.dispatch_touch(start_id, &engine, TouchKind::Release, center);
assert_eq!(start_count.get(), 1);

assert!(document.from_json_text(&mut node_tree, "{\"version\":1}").is_err());

씬에서는 문서 파일을 TextAsset 으로 읽고, 다 읽힌 뒤 initialize 에서 트리를 짓습니다. 아래는 저장소의 examples/assets/scenedocument.scene.json 을 읽어 진행 막대를 움직이는 씬입니다.

use std::path::PathBuf;
use vanilla::{Engine, EngineConfiguration, NodeId, TextAsset, UIDocument, UIProgressView, UIScene, UISceneBase, Vector2};

struct DocumentScene {
	ui_scene_base: UISceneBase,
	document: UIDocument,
	scene_asset: TextAsset,
	progress_id: Option<NodeId>,
	elapsed_seconds: f64,
}

impl UIScene for DocumentScene {
	fn get_ui_scene_base(&self) -> &UISceneBase {
		&self.ui_scene_base
	}

	fn get_ui_scene_base_mut(&mut self) -> &mut UISceneBase {
		&mut self.ui_scene_base
	}

	fn load_assets(&mut self) {
		let engine = Engine::get_engine().unwrap();
		self.scene_asset.load(engine, "scenedocument.scene.json");
		self.ui_scene_base.get_scene_base_mut().track_asset(&self.scene_asset);
	}

	fn initialize(&mut self, engine: &Engine) {
		let scene_text = match self.scene_asset.get_text() {
			Some(scene_text) => {
				scene_text.to_string()
			}
			None => {
				return;
			}
		};
		self.document.load_images(engine, &scene_text);
		let node_tree = self.ui_scene_base.get_scene_base_mut().get_node_tree_mut();
		let document_root_id = match self.document.from_json_text(node_tree, &scene_text) {
			Ok(document_root_id) => {
				document_root_id
			}
			Err(error) => {
				eprintln!("{}", error);
				return;
			}
		};
		let root_id = node_tree.get_root_id();
		node_tree.add_child(root_id, document_root_id);
		self.progress_id = node_tree.find_descendant_by_name(document_root_id, "progress");
	}

	fn tick(&mut self, time_delta: f64) {
		let node_tree = self.ui_scene_base.get_scene_base_mut().get_node_tree_mut();
		self.document.bind_pending_images(node_tree);
		self.elapsed_seconds += time_delta;
		let progress = (self.elapsed_seconds.sin() * 0.5 + 0.5) * 100.0;
		if let Some(progress_id) = self.progress_id {
			if let Some(progress_view) = node_tree[progress_id].get_component_mut::<UIProgressView>() {
				progress_view.set_value(progress);
			}
		}
	}
}

vanilla::ui_scene!(DocumentScene);

fn main() {
	let mut engine_configuration = EngineConfiguration::new();
	engine_configuration.reference_resolution_size = Vector2::create(1280.0, 720.0);
	engine_configuration.asset_directory_paths = vec![PathBuf::from("examples/assets")];
	let engine = Engine::new(engine_configuration);
	let mut ui_scene_base = UISceneBase::new();
	ui_scene_base.set_loading_min_duration_ms(0.0);
	let document_scene = DocumentScene {
		ui_scene_base,
		document: UIDocument::new(),
		scene_asset: TextAsset::new(),
		progress_id: None,
		elapsed_seconds: 0.0,
	};
	if let Err(error) = engine.run(Box::new(document_scene)) {
		eprintln!("{}", error);
	}
}

NodeLayout 으로 선언하듯 짓기

노드를 하나씩 만들고 지역 변수에 담는 대신, 노드 계층을 사슬로 이어 적는 빌더입니다. NodeLayout::create() 로 시작합니다(노드 종류가 하나라 원본의 create(nodeClass) 인자는 없습니다). name, active, pivot(pivot), anchor(x, y), anchored_position(x, y), local_position(x, y), content_size(x, y), local_scale(x, y), mask_enabled(is_enabled), component(component), component_with(component, callback), children([...]), apply(callback)(빌더에 없는 설정, &mut WorldNode 를 받음), parent(parent_id) 를 잇고, build(node_tree, Some(parent_id)) 가 노드를 만들어 부모에 붙이고 NodeId 를 돌려줍니다. 위치와 크기는 Vector2 없이 숫자 둘로 줍니다.

  • 빌더는 설정을 차례대로 모아 두었다가 build 때 노드를 만들고 그 차례대로 겁니다. 컴포넌트도 build 때 node_tree.add_component 로 붙어서, 붙을 때 자식 노드를 만드는 위젯도 됩니다.
  • 원본 component(type, callback) 은 component(값) 과 component_with(값, 콜백) 둘로 나눴고, children(...layouts) 의 가변 인자는 배열이나 Vec 하나로 받습니다.
  • anchored_position 은 build 때 부모 내용 크기를 기준으로 겁니다.
use vanilla::{Color, ComponentContext, Engine, EngineConfiguration, NodeLayout, NodeTree, Paint, Pivot, TouchKind, UIButton, UILabel, Vector2};

let engine = Engine::new(EngineConfiguration::new());
let mut node_tree = NodeTree::new();
let root_id = node_tree.get_root_id();
let panel_id = NodeLayout::create()
	.name("Panel")
	.pivot(Pivot::TOP_LEFT)
	.local_position(170.0, 60.0)
	.content_size(300.0, 240.0)
	.component_with(Paint::create_with_color(Color::create(0.13, 0.15, 0.2, 1.0)), |paint| {
		paint.set_round_size(16.0);
	})
	.children([
		NodeLayout::create()
			.name("Title")
			.pivot(Pivot::TOP_LEFT)
			.local_position(24.0, 20.0)
			.content_size(252.0, 40.0)
			.component(UILabel::create_with_text("Settings", 24.0)),
		NodeLayout::create()
			.name("CloseButton")
			.pivot(Pivot::TOP_LEFT)
			.local_position(24.0, 168.0)
			.content_size(252.0, 48.0)
			.component_with(Paint::create_with_color(Color::create(0.23, 0.51, 0.96, 1.0)), |paint| {
				paint.set_round_size(10.0);
			})
			.component(UILabel::create_with_text("Close", 18.0))
			.component_with(UIButton::new(), |button| {
				button.set_clicked_event(Box::new(|_button: &mut UIButton, context: &mut ComponentContext| {
					let button_id = context.get_node_id();
					let node_tree = context.get_node_tree_mut();
					if let Some(panel_id) = node_tree.get_parent_id(button_id) {
						node_tree[panel_id].set_visible(false);
					}
				}));
			}),
	])
	.build(&mut node_tree, Some(root_id));

let close_id = node_tree.find_descendant_by_name(panel_id, "CloseButton").expect("close button");
assert!(node_tree[close_id].is_interactable());
let center = Vector2::create(320.0, 252.0);
node_tree.dispatch_touch(close_id, &engine, TouchKind::Press, center);
node_tree.dispatch_touch(close_id, &engine, TouchKind::Release, center);
assert!(!node_tree[panel_id].is_visible());

NodeLayout::arrange_fan(node_tree, &node_ids, NodeLayoutFanOptions { center_x, center_y, radius, angle_step_radian, base_angle_radian, rotate_nodes }) 는 손패 카드처럼 노드 여러 개를 호 위에 펼칩니다(기본 간격 0.12 라디안, 위쪽, 회전함).

제약 배치: UINode 와 LayoutSolver

UINode 는 자리와 크기를 제약으로 정하는 컴포넌트입니다(UIKit 오토레이아웃과 같은 생각입니다). node_tree.add_component(node_id, UINode::new()) 로 붙이고, 제약은 node_tree.with_component_mut::<UINode, _>(node_id, |ui_node, _tree| ...) 안에서 겁니다.

uiscenelayout 예제: 세이프 에어리어에 붙은 머리 띠, 너비 제약을 받은 옆 판, 같은 너비로 놓인 단추 셋

  • 앵커 함수 left_anchor(), right_anchor(), top_anchor(), bottom_anchor(), width_anchor(), height_anchor(), center_x_anchor(), center_y_anchor()(그리고 leading_anchor(), trailing_anchor(), first_baseline_anchor(), last_baseline_anchor())는 부를 때마다 새 LayoutExpression 을 돌려줍니다. 원본은 게터 속성(leftAnchor)이지만 러스트 판은 함수입니다.
  • 식은 add, subtract, multiply, divide 로 새 식을 만들고, equal_to, less_than_or_equal_to, greater_than_or_equal_to 로 LayoutConstraint 를 만듭니다. 오른쪽에는 수(f64, i32), LayoutVariable, LayoutExpression 을 둘 수 있습니다.
  • 이렇게 만든 제약은 반드시 지켜야 하는(required) 제약입니다. 양보해도 되는 제약은 constraint.with_strength(LayoutStrength::STRONG) 처럼 세기를 바꾼 새 제약을 씁니다. 세기는 LayoutStrength::REQUIRED, STRONG, MEDIUM, WEAK 이고, 부딪히면 센 쪽이 이깁니다. 우선순위로 세기를 지으려면 LayoutStrength::from_priority(LayoutPriority::DEFAULT_LOW) 입니다.
  • ui_node.add_constraint(&constraint) 로 겁니다. 원본이 예외를 던지는 곳(겹친 제약, 지킬 수 없는 required 제약)은 Result<(), LayoutError> 의 Err 입니다.
  • UIScene 은 tick 마다 트리 안의 UINode 에 자기 솔버를 붙이고 값을 푼 뒤 노드에 옮깁니다. 푼 값은 get_left(), get_top(), get_width(), get_height(), get_center_x(), get_center_y()(f64)로 읽고, 노드의 기준점은 왼쪽 위, 로컬 자리와 내용 크기는 푼 값이 됩니다.
  • get_screen_node() 는 왼쪽 위 (0, 0) 에 고정되고 너비와 높이가 뷰 크기를 따르는 가이드입니다. get_safe_area_layout_guide() 는 그 안에서 세이프 에어리어만큼 들어간 가이드입니다. 데스크탑 앱과 데스크탑 브라우저에서는 세이프 에어리어가 0 이라 두 가이드가 같고, 시험할 때는 engine.get_view_manager_mut().set_safe_area_override(Some(SafeAreaInsets::create(top, right, bottom, left))) 로 흉내 냅니다.
  • UINode 의 왼쪽과 위 값은 UI 트리 뿌리 기준의 절대 좌표입니다. 부모도 UINode 면 자식 노드는 (자식 left - 부모 left, 자식 top - 부모 top) 의 로컬 자리에 놓이므로 화면에서는 값 그대로의 자리입니다.
  • 글처럼 제 크기가 있는 노드는 내재 크기(get_intrinsic_content_size)를 가지고, set_content_hugging_priority(priority, axis), set_content_compression_resistance_priority(priority, axis) 로 늘고 줄기를 얼마나 버틸지 정합니다(LayoutPriority::DEFAULT_LOW 250, DEFAULT_HIGH 750, REQUIRED 1000, FITTING_SIZE_LEVEL 50, 축은 LayoutConstraintAxis::Horizontal, Vertical). 원본 UILabel 은 글이 바뀌면 노드의 내재 크기를 다시 재게 하지만, 러스트 판은 UINode 가 tick 마다 같은 노드 컴포넌트의 값을 다시 읽어 바뀌었으면 스스로 다시 잽니다.
  • set_layout_margins(LayoutMargins::create(top, left, bottom, right))(기본 모두 8)와 get_layout_margins_guide() 로 안쪽 여백 가이드를 씁니다.

아래는 씬의 initialize 에서 하는 일을 창 없이 UISceneBase 로 돌려 본 예입니다. 머리 띠는 세이프 에어리어 안쪽에 붙고, 카드는 화면 너비의 반을 바라되 480 을 넘지 않으며 화면 가운데에 섭니다. 카드에 붙인 UIButton 도 푼 자리에서 눌립니다.

use vanilla::{Engine, EngineConfiguration, LayoutStrength, Paint, UIButton, UINode, UISceneBase, Vector2};

let engine = Engine::new(EngineConfiguration::new());
engine.get_view_manager_mut().calculate_view_rect(640, 360, 1.0);
let mut ui_scene_base = UISceneBase::new();
ui_scene_base.initialize(engine);

let safe_area_guide = ui_scene_base.get_safe_area_layout_guide();
let safe_left = safe_area_guide.left_anchor();
let safe_right = safe_area_guide.right_anchor();
let safe_top = safe_area_guide.top_anchor();
let screen_node = ui_scene_base.get_screen_node();
let screen_width = screen_node.width_anchor();
let screen_center_x = screen_node.center_x_anchor();
let screen_center_y = screen_node.center_y_anchor();

let node_tree = ui_scene_base.get_scene_base_mut().get_node_tree_mut();
let root_id = node_tree.get_root_id();

let header_id = node_tree.create_child(root_id, "Header");
node_tree[header_id].add_component(Paint::create_with_color("#3366cc"));
node_tree.add_component(header_id, UINode::new());
node_tree.with_component_mut::<UINode, _>(header_id, |header, _tree| {
	header.add_constraint(&header.left_anchor().equal_to(safe_left.add(16))).unwrap();
	header.add_constraint(&header.right_anchor().equal_to(safe_right.subtract(16))).unwrap();
	header.add_constraint(&header.top_anchor().equal_to(safe_top.add(16))).unwrap();
	header.add_constraint(&header.height_anchor().equal_to(56)).unwrap();
});

let card_id = node_tree.create_child(root_id, "Card");
node_tree[card_id].add_component(Paint::create_with_color("#222833"));
node_tree.add_component(card_id, UINode::new());
node_tree.add_component(card_id, UIButton::new());
node_tree.with_component_mut::<UINode, _>(card_id, |card, _tree| {
	let half_width = card.width_anchor().equal_to(screen_width.multiply(0.5));
	card.add_constraint(&half_width.with_strength(LayoutStrength::STRONG)).unwrap();
	card.add_constraint(&card.width_anchor().less_than_or_equal_to(480)).unwrap();
	card.add_constraint(&card.height_anchor().equal_to(160)).unwrap();
	card.add_constraint(&card.center_x_anchor().equal_to(screen_center_x.clone())).unwrap();
	card.add_constraint(&card.center_y_anchor().equal_to(screen_center_y.clone())).unwrap();
});

ui_scene_base.tick(0.016);
let node_tree = ui_scene_base.get_scene_base().get_node_tree();
assert_eq!(node_tree[header_id].get_local_position(), Vector2::create(16.0, 16.0));
assert_eq!(node_tree[header_id].get_content_size(), Vector2::create(608.0, 56.0));
assert_eq!(node_tree[card_id].get_local_position(), Vector2::create(160.0, 100.0));
assert_eq!(node_tree[card_id].get_content_size(), Vector2::create(320.0, 160.0));
assert_eq!(node_tree.find_topmost_interactable_node(Vector2::create(320.0, 180.0)), Some(card_id));

솔버는 엔진 없이 혼자도 씁니다. LayoutVariable::new(name) 으로 변수를 만들고 LayoutExpression::from_variable(&variable) 로 식을 만듭니다. 바깥에서 값을 밀어 넣을 변수는 add_edit_variable(&variable, strength) 로 등록하고 suggest_value(&variable, value) 로 값을 줍니다. update_variables() 를 부르면 변수에 푼 값이 들어가고 get_value() 로 읽습니다. LayoutSolver 는 값싸게 복제되는 핸들이라 함수가 모두 &self 입니다.

use vanilla::{LayoutExpression, LayoutSolver, LayoutStrength, LayoutVariable};

let solver = LayoutSolver::new();
let view_width = LayoutVariable::new("viewWidth");
let left = LayoutVariable::new("left");
let width = LayoutVariable::new("width");
let view_width_expression = LayoutExpression::from_variable(&view_width);
let left_expression = LayoutExpression::from_variable(&left);
let right_expression = left_expression.add(&width);
let right_margin_expression = view_width_expression.subtract(16);
solver.add_constraint(&left_expression.equal_to(16)).unwrap();
solver.add_constraint(&right_expression.equal_to(right_margin_expression)).unwrap();
solver.add_edit_variable(&view_width, LayoutStrength::STRONG).unwrap();

solver.suggest_value(&view_width, 640.0).unwrap();
solver.update_variables();
assert_eq!(width.get_value(), 608.0);

solver.suggest_value(&view_width, 360.0).unwrap();
solver.update_variables();
assert_eq!(width.get_value(), 328.0);

assert!(solver.add_constraint(&left_expression.equal_to(20)).is_err());

창 쌓기

UIWindowLayer 는 영역 위에 UIWindow 를 쌓는 층입니다. 맨 위 창만 보이고, 위 창이 닫히면 아래 창이 다시 보입니다. 원본에서는 둘 다 노드지만 러스트 판은 층 노드와 창 노드에 붙는 컴포넌트이고, 창 노드는 층 노드의 자식입니다.

windowshowcase 예제: 긴 글을 스크롤하는 확인 창이 맨 위에 뜨고 뒤를 어둡게 덮은 화면

  • UIWindowLayer::create(node_tree, parent_id) 가 층 노드를 만들어 돌려줍니다. 층은 영역 노드(보통 루트)의 마지막 자식으로 두고, 영역 크기가 바뀔 때마다 set_view_size(tree, width, height, css_pixel_scale) 로 알립니다. CSS 배율은 engine.get_view_manager().get_css_pixel_scale() 입니다. 세이프 에어리어까지 어둡게 덮으려면 set_view_bleed(tree, top, right, bottom, left) 도 알립니다.
  • open_window(tree, window_id)(씬 코드에서는 UIWindowLayer::open_window_in_tree(node_tree, layer_id, window_id))는 맨 위에 쌓고(이미 떠 있으면 맨 위로 올림), close_window(tree, window_id), close_top_window(tree)(기기의 뒤로 가기 자리, 닫았으면 true), close_all_windows(tree) 로 닫습니다. has_open_window(), get_window_count(), get_top_window(), find_window(tree, name) 으로 상태를 읽고, set_window_change_event(Some(Box::new(|window_count| ...))) 는 창이 뜨거나 닫힐 때 떠 있는 창 수를 넘겨 불립니다. 창이 떠 있는 동안 게임을 멈출 때 씁니다.
  • 닫힌 창 노드는 층에서 떼어 낼 뿐 지우지 않아 다시 띄울 수 있습니다. 다시 쓰지 않을 창은 destroy_node 로 지웁니다.
  • 층은 작은 화면에서도 글이 읽히게 UI 배율(UIScale::read)만큼 커집니다. set_ui_scale_options(tree, None) 이면 키우지 않습니다.

UIWindow 는 영역 전체를 어둡게 덮고(뒤로 누름이 가지 않음) 가운데에 판을 띄웁니다. UIWindow::create(node_tree, layer_id, name, Box::new(UIWindowDefaultBehavior)) 로 만들며, 만든 창 노드는 띄울 때까지 꺼져 있습니다. 내용은 get_panel_node() 가 돌려준 노드에 붙입니다. 판 가로는 영역에 맞춰 넓어지되 set_maximum_width(기본 480)를 넘지 않고, 영역 가장자리와 set_margin(기본 16)만큼 띄웁니다. 세로는 set_panel_height(기본 240)입니다. 원본에서 파생 클래스가 덮어쓰던 layoutContent 같은 자리는 UIWindowBehavior 트레이트이고(build, layout_content(tree, parts, panel_width) 가 판 세로를 돌려줌, layout_panel, apply_motion, set_covered, handle_wheel, handle_closed 등), 기본 구현이 UIWindowDefaultBehavior 입니다. 바깥(어둠)을 누르면 닫히며 set_outside_close_enabled(false) 로 끕니다. set_panel_color, set_dim_color, set_close_event(Some(Box::new(|| ...))) 도 있고, 씬과 알림 코드에서 닫을 때는 UIWindow::close_in_tree(node_tree, window_id) 를 부릅니다. 열고 닫을 때는 PopupMotion 으로 움직입니다.

UIConfirmWindow 는 제목, 묻는 글, 취소와 확인 단추를 가진 창입니다. UIConfirmWindow::create(node_tree, layer_id, name, UIConfirmWindowOptions { title, message, cancel_text, confirm_text }) 로 만들고(단추 글 기본값은 한국어 "취소", "확인"), 창 노드의 UIWindow 에서 get_behavior_mut::<UIConfirmWindow>() 로 꺼내 set_confirm_event, set_cancel_event 를 겁니다. 알림은 인자 없는 함수입니다. 확인을 누르면 확인 알림 뒤 닫히고, 취소 단추, 바깥 누르기, close_top_window, close_all_windows 로 닫히면 취소 알림입니다. 글이 길면 글 칸만 스크롤됩니다. set_right_to_left(true) 면 단추 차례를 뒤집습니다.

use vanilla::{Engine, EngineConfiguration, NodeId, Pivot, UIConfirmWindow, UIConfirmWindowOptions, UILabel, UIScene, UISceneBase, UIWindow, UIWindowDefaultBehavior, UIWindowLayer, Vector2};

struct WindowScene {
	ui_scene_base: UISceneBase,
	layer_id: Option<NodeId>,
}

impl UIScene for WindowScene {
	fn get_ui_scene_base(&self) -> &UISceneBase {
		&self.ui_scene_base
	}

	fn get_ui_scene_base_mut(&mut self) -> &mut UISceneBase {
		&mut self.ui_scene_base
	}

	fn initialize(&mut self, _engine: &Engine) {
		let node_tree = self.ui_scene_base.get_scene_base_mut().get_node_tree_mut();
		let root_id = node_tree.get_root_id();
		let layer_id = UIWindowLayer::create(node_tree, root_id);
		if let Some(window_layer) = node_tree[layer_id].get_component_mut::<UIWindowLayer>() {
			window_layer.set_window_change_event(Some(Box::new(|window_count: usize| {
				println!("open windows: {}", window_count);
			})));
		}

		let settings_id = UIWindow::create(node_tree, layer_id, "settings", Box::new(UIWindowDefaultBehavior));
		let panel_id = {
			let settings_window = node_tree[settings_id].get_component_mut::<UIWindow>().expect("window");
			settings_window.set_panel_height(200.0);
			settings_window.get_panel_node().expect("panel")
		};
		let label_id = node_tree.create_child(panel_id, "SettingsTitle");
		node_tree[label_id].set_pivot(Pivot::TOP_LEFT);
		node_tree[label_id].set_local_position(Vector2::create(24.0, 24.0));
		node_tree[label_id].set_content_size(Vector2::create(300.0, 40.0));
		node_tree.add_component(label_id, UILabel::create_with_text("Settings", 24.0));
		UIWindowLayer::open_window_in_tree(node_tree, layer_id, settings_id);

		let confirm_options = UIConfirmWindowOptions {
			title: String::from("Quit"),
			message: String::from("Do you really want to quit?"),
			cancel_text: String::from("Cancel"),
			confirm_text: String::from("Quit"),
		};
		let quit_id = UIConfirmWindow::create(node_tree, layer_id, "quit", confirm_options);
		if let Some(confirm_window) = node_tree[quit_id].get_component_mut::<UIWindow>().and_then(|window| window.get_behavior_mut::<UIConfirmWindow>()) {
			confirm_window.set_confirm_event(Some(Box::new(|| {
				println!("quit");
			})));
			confirm_window.set_cancel_event(Some(Box::new(|| {
				println!("stay");
			})));
		}
		UIWindowLayer::open_window_in_tree(node_tree, layer_id, quit_id);
		self.layer_id = Some(layer_id);
	}

	fn layout(&mut self) {
		let engine = Engine::get_engine().unwrap();
		let layer_id = match self.layer_id {
			Some(layer_id) => {
				layer_id
			}
			None => {
				return;
			}
		};
		let view_manager = engine.get_view_manager();
		let view_size = view_manager.get_view_size();
		let css_pixel_scale = view_manager.get_css_pixel_scale();
		let node_tree = self.ui_scene_base.get_scene_base_mut().get_node_tree_mut();
		node_tree.with_component_mut::<UIWindowLayer, _>(layer_id, |window_layer, tree| {
			window_layer.set_view_size(tree, view_size.x, view_size.y, css_pixel_scale);
		});
	}
}

vanilla::ui_scene!(WindowScene);

fn main() {
	let mut engine_configuration = EngineConfiguration::new();
	engine_configuration.reference_resolution_size = Vector2::create(640.0, 360.0);
	engine_configuration.auto_resize_on_window_resize = true;
	let engine = Engine::new(engine_configuration);
	let mut ui_scene_base = UISceneBase::new();
	ui_scene_base.set_loading_min_duration_ms(0.0);
	let window_scene = WindowScene {
		ui_scene_base,
		layer_id: None,
	};
	if let Err(error) = engine.run(Box::new(window_scene)) {
		eprintln!("{}", error);
	}
}

ButtonMotion

단추에 크기 반응을 붙입니다. UIButton 이 붙은 노드에 attach_button_motion(node_tree, node_id) 를 부르면 ButtonMotion 이 UIButton 다음 컴포넌트로 붙고, 매 프레임 단추 상태를 읽어 노드를 가운데를 두고 키우고 줄입니다. 색은 건드리지 않습니다. 반응이 없을 때는 노드의 자리와 크기를 건드리지 않습니다.

  • 꼴은 ButtonMotionStyle::Normal(올리면 1.06 배, 누르는 동안 0.92 배, 떼면 1.04 배로 통 튐)과 ButtonMotionStyle::Inset(창 안의 단추, 커지지 않고 올리면 바탕 Paint 가 밝아지고 안쪽에 흰 테, 누르면 0.96 배)입니다.
  • button_motion.set_style(Some(style)) 로 단추마다 정하거나, set_button_motion_area(node_tree, node_id, style) 로 그 노드 아래 단추 모두의 꼴을 정합니다. 둘 다 없으면 Normal 입니다.
  • shake_button(node_tree, node_id) 는 누를 수 없을 때 단추를 0.25 초 동안 좌우로 흔듭니다.
  • 터치가 주된 기기에서는 올림 반응을 쓰지 않습니다.
  • 원본은 왼쪽 위 기준점만 생각해 가운데를 셈하지만, 러스트 판은 노드의 기준점을 읽어 셈합니다. Inset 의 밝힌 바탕과 흰 테를 자식 노드로 두지 않고 직접 그리며, 꾸밈이 제 모양으로 밝히게 하려면 set_lit_handler 로 함수를 겁니다.
use std::cell::Cell;
use std::rc::Rc;
use vanilla::{attach_button_motion, shake_button, ButtonMotionStyle, Color, ComponentContext, Engine, EngineConfiguration, NodeTree, Paint, Pivot, TouchKind, UIButton, UILabel, Vector2};

let engine = Engine::new(EngineConfiguration::new());
let mut node_tree = NodeTree::new();
let root_id = node_tree.get_root_id();
let button_id = node_tree.create_child(root_id, "BuyButton");
node_tree[button_id].set_pivot(Pivot::TOP_LEFT);
node_tree[button_id].set_local_position(Vector2::create(240.0, 156.0));
node_tree[button_id].set_content_size(Vector2::create(160.0, 48.0));
let button_paint = node_tree[button_id].add_component(Paint::create_with_color(Color::create(0.36, 0.42, 1.0, 1.0)));
button_paint.set_round_size(10.0);
node_tree.add_component(button_id, UILabel::create_with_text("Buy", 18.0));

let coin_count = Rc::new(Cell::new(40));
let coin_count_for_event = coin_count.clone();
let button = node_tree.add_component(button_id, UIButton::new()).expect("button");
button.set_clicked_event(Box::new(move |_button: &mut UIButton, context: &mut ComponentContext| {
	if coin_count_for_event.get() < 100 {
		let button_id = context.get_node_id();
		shake_button(context.get_node_tree_mut(), button_id);
		return;
	}
	coin_count_for_event.set(coin_count_for_event.get() - 100);
}));
let button_motion = attach_button_motion(&mut node_tree, button_id).expect("button motion");
button_motion.set_style(Some(ButtonMotionStyle::Normal));

let center = Vector2::create(320.0, 180.0);
node_tree.dispatch_touch(button_id, &engine, TouchKind::Press, center);
node_tree.tick(&engine, 0.1);
assert!(node_tree[button_id].get_local_scale().x < 1.0);
node_tree.dispatch_touch(button_id, &engine, TouchKind::Release, center);
assert_eq!(coin_count.get(), 40);

주의할 점

  • UIScene 의 로딩 화면은 기본으로 3 초 동안 보입니다. 바로 넘기려면 set_loading_min_duration_ms(0.0) 을 줍니다.
  • 위젯은 node_tree.add_component(node_id, ...) 로 붙입니다. node_tree[node_id].add_component(...) 로 붙이면 내용 노드가 생기지 않고 노드가 interactable 로 켜지지 않아 눌리지 않습니다.
  • 평범한 Scene 도 위젯에 누름을 넘기지만 스크롤 뷰로 끌기를 넘기는 손짓은 없습니다. 스크롤 뷰 안에 단추를 두면 UIScene 을 쓰거나 TouchRecognizer 를 직접 돌립니다.
  • 씬 코드가 컴포넌트만 쥐고 바꾼 값 가운데 다른 노드에 닿아야 하는 것(스크롤 오프셋과 스크롤바, set_interactable 과 set_is_on 의 색, 토스트 띄우기)은 다음 tick 에 반영됩니다. 같은 프레임에 바로 옮기려면 set_scroll_offset_in_tree 같은 *_in_tree 함수를 씁니다.
  • UIButton 은 바탕을 그리지 않습니다. 같은 노드에 Paint 나 UIImageView 를 함께 붙여 모양을 만듭니다.
  • 위젯 알림은 Box 에 담은 클로저라 씬의 필드를 직접 빌릴 수 없습니다. 알림 밖과 나눌 값은 Rc<Cell<T>> 나 Rc<RefCell<T>> 에 담고, 다른 노드는 NodeId 와 문맥으로 바꿉니다.
  • UIInputField 는 attach() 를 불러야 키 입력을 받습니다. 한글 같은 IME 입력은 set_use_dom_input(true) 에서만 됩니다.
  • UIDialogOptions, UIConfirmWindowOptions 의 단추 글 기본값은 한국어입니다.
  • UIDocument::from_json_text 가 돌려준 뿌리는 어디에도 붙지 않았습니다. 그림 해석기와 load_images 는 from_json_text 전에 둡니다.

관련 타입

UIScene, UISceneBase, UINode, UIView, UIControl, UILabel, UIImageView, UIButton, ButtonState, UIToggleButton, UISlider, UIProgressView, ProgressDirection, UIScrollView, ScrollMode, UIScrollBar, TouchRecognizer, UIInputField, UIDropdown, UIDropdownOptions, UIToast, UIToastOptions, UIDialog, UIDialogOptions, UIDialogShowOptions, UIContextMenu, UISpinner, UIListView, UISnapScrollView, UIDraggable, UILineChart, UIBarChart, UIProgressRing, UIHitArea, UIDocument, NodeLayout, NodeLayoutFanOptions, LayoutSolver, LayoutVariable, LayoutExpression, LayoutConstraint, LayoutStrength, LayoutPriority, LayoutConstraintAxis, LayoutMargins, LayoutError, UIWindowLayer, UIWindow, UIWindowBehavior, UIWindowDefaultBehavior, UIConfirmWindow, UIConfirmWindowOptions, UIScale, UIScaleOptions, PopupMotion, ButtonMotion, ButtonMotionStyle, ButtonMotionArea

UI

This chapter covers putting UI such as buttons, labels, and sliders on screen. It goes through the UI scene UIScene, widget components you attach to nodes, complete widgets that build their own child nodes when attached, UIDocument for reading UI documents, two ways to lay things out (NodeLayout and the constraint-based LayoutSolver), window stacking (UIWindowLayer), and button feedback (ButtonMotion). Nodes and components themselves are covered in the "Nodes and Components" chapter, and how a touch reaches a node is covered in the "Input" chapter.

Two kinds of UI

The engine's UI comes in two kinds, depending on how a node's place is decided. The Rust version has only one node type, WorldNode, so the widgets that were nodes in the original and UINode are all components you attach to a node.

  • Placing directly. Attach widget components (the UIView family, such as UILabel, UIButton, and UISlider) to a node, and set its place and size yourself with the pivot, set_local_position, and set_content_size. Complete widgets such as UIDropdown, UIDialog, UIToast, and UIWindow are created and attached with create(node_tree, parent_id, ...).
  • Placing with constraints. Attaching a UINode component to a node gives it eight variables: left, right, top, bottom, width, height, center X, and center Y. When you add constraints, LayoutSolver solves those values. The solved values are copied into the node's local position and content size. Use this for layouts that grow and shrink with the screen size and the safe area.

Both kinds are used in a UIScene. Because UINode sets the node's place and size, a UIButton attached to the same node can be pressed as is, unlike in the original.

UIScene

UIScene is the scene for UI. Rust has no inheritance, so the scene struct holds a UISceneBase as a field, implements the UIScene trait, and gets a Scene implementation from the one line vanilla::ui_scene!(SceneType);. UISceneBase provides the following by itself.

  • Touch delivery. The GameSceneBase it holds owns a TouchRecognizer and passes touches to the node tree every tick. This is where the gesture that scrolls even when you drag a button inside a scroll view comes from.
  • Loading screen. It draws a black background, an image in the middle (set_loading_image_url), and a bar at the bottom. By default it stays up for at least 3000 milliseconds, and tapping the screen skips it right away. Change this with set_loading_min_duration_ms(milliseconds).
  • An asset loading hook, load_assets(&mut self) (the original loadAssets()). It is called right after the base's load. If you hand requested assets to the scene with get_scene_base_mut().track_asset(...), initialize is called after they have all loaded.
  • Background color set_scene_background_color(color) (black by default) and view scale mode set_view_scale_mode(mode, engine) (ViewScaleMode::None by default; passing None for the engine applies it in initialize).
  • The constraint solver (get_solver()), the screen guide (get_screen_node()), and the safe area guide (get_safe_area_layout_guide()). These are used in the "Constraint layout" section below.
  • Developer tools. They are not created when EngineConfiguration::use_dev_tools is off.
  • In the Rust version UISceneBase holds a GameSceneBase, so GameSceneBase features such as the screen fade and play input are also available through get_game_scene_base_mut(). (The original UIScene does not have them)

Functions of the UIScene trait such as load_assets, initialize, layout, tick, pre_draw, draw, post_draw, destroy, and touch_press all have default implementations, so you override only the ones you need. The Scene functions generated by ui_scene! call the base first and then the trait 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 (developer tools) on top. layout is called on the first tick and whenever the view size changes.

Below is a scene with a title label and one button. The button node gets Paint (background), UILabel (text), and UIButton (press handling) together.

use vanilla::{Color, ComponentContext, Engine, EngineConfiguration, NodeId, NodeTree, Paint, Pivot, UIButton, UILabel, UIScene, UISceneBase, Vector2};

struct MenuScene {
	ui_scene_base: UISceneBase,
}

impl MenuScene {
	fn set_title(node_tree: &mut NodeTree, title_id: NodeId, text: &str) {
		if let Some(title_label) = node_tree[title_id].get_component_mut::<UILabel>() {
			title_label.set_text(text);
		}
	}
}

impl UIScene for MenuScene {
	fn get_ui_scene_base(&self) -> &UISceneBase {
		&self.ui_scene_base
	}

	fn get_ui_scene_base_mut(&mut self) -> &mut UISceneBase {
		&mut self.ui_scene_base
	}

	fn initialize(&mut self, _engine: &Engine) {
		let node_tree = self.ui_scene_base.get_scene_base_mut().get_node_tree_mut();
		let root_id = node_tree.get_root_id();

		let title_id = node_tree.create_child(root_id, "Title");
		node_tree[title_id].set_pivot(Pivot::TOP_LEFT);
		node_tree[title_id].set_local_position(Vector2::create(40.0, 40.0));
		node_tree[title_id].set_content_size(Vector2::create(400.0, 48.0));
		let title_label = node_tree.add_component(title_id, UILabel::create_with_text("Main Menu", 32.0)).expect("label");
		title_label.set_text_color(Color::create(0.95, 0.96, 1.0, 1.0));

		let button_id = node_tree.create_child(root_id, "StartButton");
		node_tree[button_id].set_pivot(Pivot::TOP_LEFT);
		node_tree[button_id].set_local_position(Vector2::create(40.0, 120.0));
		node_tree[button_id].set_content_size(Vector2::create(200.0, 56.0));
		let button_paint = node_tree[button_id].add_component(Paint::create_with_color(Color::create(0.23, 0.51, 0.96, 1.0)));
		button_paint.set_round_size(12.0);
		node_tree.add_component(button_id, UILabel::create_with_text("Start", 22.0));
		let button = node_tree.add_component(button_id, UIButton::new()).expect("button");
		button.set_clicked_event(Box::new(move |_button: &mut UIButton, context: &mut ComponentContext| {
			MenuScene::set_title(context.get_node_tree_mut(), title_id, "Started");
		}));
		button.set_long_press_seconds(0.8);
		button.set_long_pressed_event(Box::new(move |_button: &mut UIButton, context: &mut ComponentContext| {
			MenuScene::set_title(context.get_node_tree_mut(), title_id, "Long pressed");
		}));
	}
}

vanilla::ui_scene!(MenuScene);

fn main() {
	let mut engine_configuration = EngineConfiguration::new();
	engine_configuration.reference_resolution_size = Vector2::create(1280.0, 720.0);
	engine_configuration.auto_resize_on_window_resize = true;
	let engine = Engine::new(engine_configuration);
	let mut ui_scene_base = UISceneBase::new();
	ui_scene_base.set_loading_min_duration_ms(0.0);
	ui_scene_base.set_scene_background_color(Color::create(0.08, 0.09, 0.12, 1.0));
	let menu_scene = MenuScene {
		ui_scene_base,
	};
	if let Err(error) = engine.run(Box::new(menu_scene)) {
		eprintln!("{}", error);
	}
}
  • Widget events receive the widget and the component context, as in Box<dyn FnMut(&mut UIButton, &mut ComponentContext)>. Callbacks in the original receive only the widget, but the Rust version lets you find and change other nodes through the context's get_node_tree_mut(). Other nodes are referred to by NodeId, and since NodeId is Copy it goes into a move closure as is.
  • A plain Scene also presses widgets, because SceneBase::tick passes touches to the frontmost pressable node (the original base scene does the same). It does not have the gesture that hands a drag over to a scroll view, though. If you need that gesture, use UIScene, or have the scene own a TouchRecognizer and call the node tree's tick and touch_recognizer.tick_touch(node_tree, engine) instead of SceneBase::tick (examples/uigallery.rs does this).

Widget components

These are widgets you attach to a node. They use the node's content size (set_content_size) as their area.

uigallery example: UIButton, UIToggleButton, UISlider, UIProgressView, UIImageView, UIScrollView and UIScrollBar

Type What it does
UIView A panel with a background color (set_background_color) and a content node (get_content()). The base held by the widgets below
UIControl The base of widgets that take input. It holds a UIView
UILabel Text. It holds a RichText, and the RichText holds a Text
UIImageView An image. It holds a Sprite
UIButton Press handling and pressed color
UIToggleButton A button that turns on and off (holds a UIButton)
UISlider A bar you drag or tap to pick a value
UIProgressView A progress bar (no input)
UIScrollView An area you drag to scroll. When attached it also attaches a Mask so its children are clipped
  • In the original, widgets inherit from UIView. In the Rust version, a widget holds a UIView (or UIControl) as a field and forwards the content node and background color. So there is no way to find derived widgets all at once with get_component::<UIView>(); find them by concrete type, as in get_component::<UIButton>().
  • Attach widgets to the tree, as in node_tree.add_component(node_id, UIButton::new()). That way, when attached, the widget creates a content node (content) under the node and, for widgets you press, turns the node interactable. Attaching with node_tree[node_id].add_component(...) skips this, so the widget cannot be pressed. Children that go inside a widget are attached to the node returned by get_content().
  • UILabel and UIImageView hold their text components and sprite, so get_component::<Text>() on a label node and get_component::<Sprite>() on an image view node return None. Get the held ones with get_text_component(), get_rich_text_component(), and get_sprite().

UIButton

  • UIButton draws nothing by itself. It covers Sprite and UIImageView on the same node and the nodes below it with the pressed color, and blends Paint, Text, and UILabel from their original color toward the pressed color. The pressed color defaults to (0, 0, 0, 0.3), the hover color to (1, 1, 1, 0.12), and the transition time to 0.3 seconds; change them with set_pressed_tint_color, set_hover_tint_color, and set_transition_duration. Exclude things from the tint with exclude_node_from_tint(node_id) and exclude_component_from_tint::<UILabel>(node_id). The original excludes component objects, while the Rust version excludes by (node, component type).
  • Events: set_clicked_event, set_click_event (a click calls these two in order), set_pressed_event, set_released_event, set_hover_event (once when the mouse enters), and set_long_pressed_event. A click happens only when the release position is inside the button.
  • A long press fires once the moment it passes set_long_press_seconds (0.5 seconds by default), and swallows the click of that press.
  • With set_interactable(false) the button cannot be pressed and is covered dark ((0, 0, 0, 0.5)). The color is applied on the next tick.
  • Giving set_minimum_pressed_seconds(seconds) shows the pressed look for that long even on a short tap before handling the release (0 by default).
  • get_button_state() reports the current state as ButtonState::Normal, Hover, Pressed, Released, or Disabled.

Below is an example that presses a button with just a node tree and no window. dispatch_touch is the same function the engine uses to pass touches.

use std::cell::Cell;
use std::rc::Rc;
use vanilla::{ComponentContext, Engine, EngineConfiguration, NodeTree, Paint, Pivot, TouchKind, UIButton, UILabel, Vector2};

let engine = Engine::new(EngineConfiguration::new());
let mut node_tree = NodeTree::new();
let root_id = node_tree.get_root_id();

let status_id = node_tree.create_child(root_id, "Status");
node_tree.add_component(status_id, UILabel::create_with_text("Ready", 20.0));

let button_id = node_tree.create_child(root_id, "OkButton");
node_tree[button_id].set_pivot(Pivot::TOP_LEFT);
node_tree[button_id].set_local_position(Vector2::create(100.0, 100.0));
node_tree[button_id].set_content_size(Vector2::create(160.0, 48.0));
node_tree[button_id].add_component(Paint::create_with_color("#3b82f6"));
let long_press_count = Rc::new(Cell::new(0));
let long_press_count_for_event = long_press_count.clone();
let button = node_tree.add_component(button_id, UIButton::new()).expect("button");
button.set_clicked_event(Box::new(move |_button: &mut UIButton, context: &mut ComponentContext| {
	if let Some(status_label) = context.get_node_tree_mut()[status_id].get_component_mut::<UILabel>() {
		status_label.set_text("Clicked");
	}
}));
button.set_long_pressed_event(Box::new(move |_button: &mut UIButton, _context: &mut ComponentContext| {
	long_press_count_for_event.set(long_press_count_for_event.get() + 1);
}));
assert!(node_tree[button_id].is_interactable());

let inside = Vector2::create(180.0, 124.0);
let outside = Vector2::create(400.0, 124.0);
node_tree.dispatch_touch(button_id, &engine, TouchKind::Press, inside);
node_tree.dispatch_touch(button_id, &engine, TouchKind::Release, outside);
assert_eq!(node_tree[status_id].get_component::<UILabel>().expect("label").get_text(), "Ready");

node_tree.dispatch_touch(button_id, &engine, TouchKind::Press, inside);
node_tree.dispatch_touch(button_id, &engine, TouchKind::Release, inside);
assert_eq!(node_tree[status_id].get_component::<UILabel>().expect("label").get_text(), "Clicked");

node_tree[status_id].get_component_mut::<UILabel>().expect("label").set_text("Ready");
node_tree.dispatch_touch(button_id, &engine, TouchKind::Press, inside);
node_tree.tick(&engine, 0.6);
node_tree.dispatch_touch(button_id, &engine, TouchKind::Release, inside);
assert_eq!(long_press_count.get(), 1);
assert_eq!(node_tree[status_id].get_component::<UILabel>().expect("label").get_text(), "Ready");

Other widgets

  • UILabel: create_with_text(text, font_size), set_text, set_font_size, set_text_color, set_text_align (TextAlign), set_text_baseline (TextBaseline), set_bold, set_italic, set_underline, set_strikethrough, set_word_wrap_width (0 splits only at newline characters), set_wrap_mode, set_line_spacing, and set_fit_width(width, minimum_ratio) (shrinks the font size so a single line fits that width, but not below the ratio; not applied in rich text mode). Instead of the original setFont(FontFace), give the name of a registered font with set_font_family. A new label's text is 32 pixels, white, center aligned, with a middle baseline. With use_rich_text(true) it reads the markup <b>, <i>, <u>, <s>, <color=#RRGGBB[AA]>, <color=name>, and <size=N>.
  • UIImageView: create_with_image(image), set_image(Option<Rc<Image>>), set_image_asset(&mut ImageAsset) (the original setImage takes both), set_image_rect, set_color (tint), set_draw_mode (SpriteDrawMode::Simple, Sliced, Tiled), set_nine_slice, set_horizontal_flip, set_vertical_flip, and set_blend_mode.
  • UIToggleButton: set_toggled_event, get_is_on, and set_on_tint_color ((0, 0, 0, 0.3) by default). set_is_on(is_on) changes only the state without calling the event, and the color is applied on the next tick. Button settings such as long press or interactable are made on the held UIButton through get_uibutton_mut(). The event order differs slightly from the original: the original goes release, flip, toggled event, clicked event, click event, while the Rust version goes release, click event, flip, toggled event, clicked event.
  • UISlider: set_range(min_value, max_value) (0 to 1 by default), set_value (clamped to the range, no event), get_value, get_ratio, and set_value_changed_event. For the look: set_track_color, set_fill_color, set_thumb_color, set_thumb_radius (16 by default), set_track_thickness (0 means the whole node area), set_corner_radius, and set_direction(ProgressDirection::Horizontal or Vertical). Setting a thumb node with set_thumb_node(Some(node_id)) stops drawing the circle and moves that node to the thumb position (keep the thumb node as a child of the slider node). To make it unpressable, use set_interactable(false).
  • UIProgressView: set_range, set_value, set_track_color (same as the background color), set_fill_color, set_corner_radius, and set_direction. Giving set_secondary_value(Some(value)) draws a second fill (set_secondary_fill_color) that fills from the opposite end. The value is changed only from code.

Below is an example that copies a slider's value to a label and a progress bar, and blocks the slider with a toggle button.

use vanilla::{Color, ComponentContext, Engine, EngineConfiguration, NodeId, NodeTree, Paint, Pivot, TouchKind, UILabel, UIProgressView, UISlider, UIToggleButton, Vector2};

fn create_box_node(node_tree: &mut NodeTree, parent_id: NodeId, name: &str, position: Vector2, size: Vector2) -> NodeId {
	let node_id = node_tree.create_child(parent_id, name);
	node_tree[node_id].set_pivot(Pivot::TOP_LEFT);
	node_tree[node_id].set_local_position(position);
	node_tree[node_id].set_content_size(size);
	node_id
}

fn main() {
	let engine = Engine::new(EngineConfiguration::new());
	let mut node_tree = NodeTree::new();
	let root_id = node_tree.get_root_id();

	let value_id = create_box_node(&mut node_tree, root_id, "VolumeLabel", Vector2::create(240.0, 40.0), Vector2::create(320.0, 32.0));
	let value_label = node_tree.add_component(value_id, UILabel::create_with_text("Volume <b>50</b>", 20.0)).expect("label");
	value_label.use_rich_text(true);

	let progress_id = create_box_node(&mut node_tree, root_id, "VolumeBar", Vector2::create(240.0, 140.0), Vector2::create(320.0, 12.0));
	let progress_view = node_tree.add_component(progress_id, UIProgressView::new()).expect("progress");
	progress_view.set_track_color(Color::create(1.0, 1.0, 1.0, 0.15));
	progress_view.set_fill_color(Color::create(0.3, 0.8, 0.5, 1.0));
	progress_view.set_corner_radius(6.0);
	progress_view.set_value(0.5);

	let slider_id = create_box_node(&mut node_tree, root_id, "VolumeSlider", Vector2::create(240.0, 90.0), Vector2::create(320.0, 32.0));
	let slider = node_tree.add_component(slider_id, UISlider::new()).expect("slider");
	slider.set_range(0.0, 100.0);
	slider.set_value(50.0);
	slider.set_track_thickness(6.0);
	slider.set_corner_radius(3.0);
	slider.set_value_changed_event(Box::new(move |slider: &mut UISlider, context: &mut ComponentContext| {
		let value = slider.get_value().round();
		let node_tree = context.get_node_tree_mut();
		if let Some(value_label) = node_tree[value_id].get_component_mut::<UILabel>() {
			value_label.set_text(&format!("Volume <b>{}</b>", value));
		}
		if let Some(progress_view) = node_tree[progress_id].get_component_mut::<UIProgressView>() {
			progress_view.set_value(value / 100.0);
		}
	}));

	let toggle_id = create_box_node(&mut node_tree, root_id, "MuteToggle", Vector2::create(240.0, 180.0), Vector2::create(160.0, 48.0));
	let toggle_paint = node_tree[toggle_id].add_component(Paint::create_with_color(Color::create(0.25, 0.6, 0.35, 1.0)));
	toggle_paint.set_round_size(10.0);
	node_tree.add_component(toggle_id, UILabel::create_with_text("Mute", 18.0));
	let toggle_button = node_tree.add_component(toggle_id, UIToggleButton::new()).expect("toggle");
	toggle_button.set_on_tint_color(Color::create(0.0, 0.0, 0.0, 0.4));
	toggle_button.set_toggled_event(Box::new(move |toggle_button: &mut UIToggleButton, context: &mut ComponentContext| {
		let is_on = toggle_button.get_is_on();
		if let Some(slider) = context.get_node_tree_mut()[slider_id].get_component_mut::<UISlider>() {
			slider.set_interactable(!is_on);
		}
	}));

	let slider_position = Vector2::create(480.0, 106.0);
	node_tree.dispatch_touch(slider_id, &engine, TouchKind::Press, slider_position);
	node_tree.dispatch_touch(slider_id, &engine, TouchKind::Release, slider_position);
	assert_eq!(node_tree[value_id].get_component::<UILabel>().expect("label").get_text(), "Volume <b>75</b>");
	assert_eq!(node_tree[progress_id].get_component::<UIProgressView>().expect("progress").get_value(), 0.75);

	let toggle_position = Vector2::create(300.0, 200.0);
	node_tree.dispatch_touch(toggle_id, &engine, TouchKind::Press, toggle_position);
	node_tree.dispatch_touch(toggle_id, &engine, TouchKind::Release, toggle_position);
	assert!(node_tree[toggle_id].get_component::<UIToggleButton>().expect("toggle").get_is_on());
	assert!(!node_tree[slider_id].get_component::<UISlider>().expect("slider").get_interactable());
}

UIScrollView

The content size of the node with the scroll view is the visible area, and items are attached to the node returned by get_content(). You must tell it the full draggable size with set_scroll_content_size(size), and it scrolls only when that is larger than the visible area.

  • Turn an axis off with set_horizontal(false) or set_vertical(false).
  • set_scroll_mode(ScrollMode::Clamp) never goes past the edges (default), and with ScrollMode::Elastic going past them creates a pulling force and it bounces back on release.
  • Show scroll bars (nodes with a UIScrollBar) with set_shows_vertical_scroll_bar(true) and set_shows_horizontal_scroll_bar(true). The scroll bar node is created on the next tick; to create it on the spot, call UIScrollView::set_shows_vertical_scroll_bar_in_tree(node_tree, scroll_node_id, true) (it returns the created node).
  • set_scroll_offset(offset) moves the position. y becomes negative as you scroll down. The value is clamped to the range right away, but the content node moves on the next tick. To move it in the same frame, use UIScrollView::set_scroll_offset_in_tree(node_tree, scroll_node_id, offset).
  • There are also set_drag_sensitivity (drag multiplier, 1 by default), set_wheel_scroll_scale (wheel multiplier, 1 by default), and set_passes_cross_axis_drag(true) (a finger dragged further along the non-scrolling axis is handed to the inner widget, for places like a horizontal slider inside a vertical list).
  • When you press inside a scroll view, TouchRecognizer delays delivering the press by 150 milliseconds, and once you drag more than 10 pixels it cancels the inner widget's press and hands the drag to scrolling.
use vanilla::{Color, Engine, EngineConfiguration, NodeTree, Paint, Pivot, ScrollMode, UILabel, UIScrollView, Vector2};

let engine = Engine::new(EngineConfiguration::new());
let mut node_tree = NodeTree::new();
let root_id = node_tree.get_root_id();
let viewport_id = node_tree.create_child(root_id, "List");
node_tree[viewport_id].set_pivot(Pivot::TOP_LEFT);
node_tree[viewport_id].set_local_position(Vector2::create(160.0, 60.0));
node_tree[viewport_id].set_content_size(Vector2::create(320.0, 240.0));

let row_count = 20;
let row_height = 40.0;
let content_id = {
	let scroll_view = node_tree.add_component(viewport_id, UIScrollView::new()).expect("scroll view");
	scroll_view.set_background_color(Color::create(0.1, 0.12, 0.16, 1.0));
	scroll_view.set_horizontal(false);
	scroll_view.set_scroll_mode(ScrollMode::Elastic);
	scroll_view.set_shows_vertical_scroll_bar(true);
	scroll_view.set_scroll_content_size(Vector2::create(320.0, row_count as f64 * row_height));
	scroll_view.get_content().expect("content")
};
for row_index in 0..row_count {
	let row_id = node_tree.create_child(content_id, "Row");
	node_tree[row_id].set_pivot(Pivot::TOP_LEFT);
	node_tree[row_id].set_local_position(Vector2::create(8.0, row_index as f64 * row_height + 2.0));
	node_tree[row_id].set_content_size(Vector2::create(296.0, row_height - 4.0));
	node_tree[row_id].add_component(Paint::create_with_color(Color::create(1.0, 1.0, 1.0, 0.06)));
	let row_text = format!("Row {}", row_index);
	node_tree.add_component(row_id, UILabel::create_with_text(&row_text, 18.0));
}

let scroll_view = node_tree[viewport_id].get_component_mut::<UIScrollView>().expect("scroll view");
scroll_view.set_scroll_offset(Vector2::create(0.0, -2000.0));
assert_eq!(scroll_view.get_scroll_offset(), Vector2::create(0.0, -560.0));
node_tree.tick(&engine, 0.016);
assert_eq!(node_tree[content_id].get_local_position(), Vector2::create(0.0, -560.0));
let scroll_view = node_tree[viewport_id].get_component::<UIScrollView>().expect("scroll view");
assert!(scroll_view.get_vertical_scroll_bar().is_some());

Complete widgets

These widgets decorate the node and build their own child nodes and components when attached, like the original constructors. In the original they are nodes that inherit from WorldNode, created with new and attached with addChild. In the Rust version they are components, and a function that creates and attaches a node, such as UIDropdown::create(node_tree, parent_id, options), takes that role. The original options object is an options struct you fill with ..Default::default(). Functions that change the tree take the tree, so scene code calls them with node_tree.with_component_mut::<UIDropdown, _>(node_id, |dropdown, tree| ...).

uigallery2 example: UIListView, UISnapScrollView, UIDropdown, UIDraggable, UILineChart, UIBarChart, UISpinner, UIToast

  • UIInputField: a text input box drawn on the canvas. Like other widgets it is attached with node_tree.add_component(node_id, UIInputField::new()), and when attached it sets the node's pivot to the top left. Call attach() to start receiving input and detach() to stop. By default the field takes the keyboard directly. If you need IME input such as Korean, turn on set_use_dom_input(true) (on desktop it turns on the winit IME while that field has focus, and on the web it uses a hidden DOM <input> like the original). There is no setEngine from the original. It has set_placeholder, set_text (no change event), get_text, set_max_length (in UTF-16 units, 0 means unlimited), set_font_size (28 by default), set_font_family, set_on_change, set_on_submit (Enter), focus, blur, select_all, cut, copy, and paste. Events receive the field and the context, and the value is read with field.get_text(). A right press opens a cut, copy, and paste menu (drawn on the canvas on desktop, a DOM menu on the web). Turning off or destroying the node also drops the focus and the IME.
  • UIDropdown: shows the current value on a header button and opens a list when pressed. UIDropdown::create(node_tree, parent_id, UIDropdownOptions { width, height, option_height, font_size, base_color, popup_color, highlight_color, text_color }) (default width 180, height 30, row height 28, font 12). It has set_option_list(tree, &[...]), get_selected_index, get_selected_text, set_changed_event, and set_open(tree, is_open), and set_selected_index(tree, index) changes only the selection without an event. The opened list is moved to the last child of the root so other nodes do not cover it.
  • UIToast: show(message) brings up a pill shaped notice from below, shows it briefly, and removes it. Calling it several times queues the messages. UIToast::create(node_tree, parent_id, UIToastOptions { width, height, rest_y, rest_x, hold_seconds, font_size, background_color, text_color }) (default 400 x 48, rest_y 560, rest_x of None centers it horizontally on the parent, hold time 1.8 seconds). show only queues the message; it becomes visible from the next tick.
  • UIDialog: brings up a darkening overlay, a card in the middle, and confirm and cancel buttons with a single show(tree, message, UIDialogShowOptions { on_confirm, on_cancel, confirm_text, cancel_text }). Without on_cancel it becomes a notice with only a confirm button, and pressing the overlay counts as cancel. The handlers are one-shot functions (FnOnce) that receive the dialog and the context. To close it from scene code that has no context, call request_dismiss(is_confirmed) and it closes on the next tick. The default button texts of UIDialogOptions are Korean (confirm and cancel), so pass your own texts for other languages. It uses the parent's content size as the overlay size (960 x 640 if there is none).

Create UIToast and UIDialog as the last children of the root so they draw on top of everything else. There are also widgets such as UIContextMenu, UISpinner, UIListView, UISnapScrollView, UIDraggable, UILineChart, UIBarChart, UIProgressRing, and UIHitArea (see examples/uigallery2.rs).

use vanilla::{ComponentContext, Engine, EngineConfiguration, NodeTree, TouchKind, UIDialog, UIDialogOptions, UIDialogShowOptions, UIDropdown, UIDropdownOptions, UIInputField, UILabel, UIToast, UIToastOptions, Vector2};

let engine = Engine::new(EngineConfiguration::new());
let mut node_tree = NodeTree::new();
let root_id = node_tree.get_root_id();
node_tree[root_id].set_content_size(Vector2::create(640.0, 360.0));

let field_id = node_tree.create_child(root_id, "NameField");
node_tree[field_id].set_local_position(Vector2::create(40.0, 40.0));
node_tree[field_id].set_content_size(Vector2::create(360.0, 56.0));
let input_field = node_tree.add_component(field_id, UIInputField::new()).expect("input field");
input_field.set_placeholder("Player name");
input_field.set_max_length(16);
input_field.attach();
input_field.set_text("Player");

let dropdown_options = UIDropdownOptions {
	width: 200.0,
	height: 36.0,
	font_size: 16.0,
	..UIDropdownOptions::default()
};
let dropdown_id = UIDropdown::create(&mut node_tree, root_id, dropdown_options);
node_tree[dropdown_id].set_local_position(Vector2::create(420.0, 50.0));
node_tree.with_component_mut::<UIDropdown, _>(dropdown_id, |dropdown, tree| {
	dropdown.set_option_list(tree, &["Low", "Medium", "High"]);
	dropdown.set_selected_index(tree, 1);
});

let toast_options = UIToastOptions {
	width: 320.0,
	height: 40.0,
	rest_y: 320.0,
	..UIToastOptions::default()
};
let toast_id = UIToast::create(&mut node_tree, root_id, toast_options);
let dialog_id = UIDialog::create(&mut node_tree, root_id, UIDialogOptions::default());

node_tree[dropdown_id].get_component_mut::<UIDropdown>().expect("dropdown").set_changed_event(Box::new(move |dropdown: &mut UIDropdown, context: &mut ComponentContext| {
	let message = format!("Quality: {}", dropdown.get_selected_text());
	if let Some(toast) = context.get_node_tree_mut()[toast_id].get_component_mut::<UIToast>() {
		toast.show(&message);
	}
}));

node_tree.with_component_mut::<UIDropdown, _>(dropdown_id, |dropdown, tree| {
	dropdown.set_open(tree, true);
});
let high_option_id = node_tree[dropdown_id].get_component::<UIDropdown>().expect("dropdown").get_option_nodes()[2];
let option_size = node_tree[high_option_id].get_content_size();
let option_center = node_tree.convert_node_position_to_view_position(high_option_id, option_size.multiply_scalar(0.5));
node_tree.dispatch_touch(high_option_id, &engine, TouchKind::Press, option_center);
node_tree.dispatch_touch(high_option_id, &engine, TouchKind::Release, option_center);
assert_eq!(node_tree[dropdown_id].get_component::<UIDropdown>().expect("dropdown").get_selected_text(), "High");
node_tree.tick(&engine, 0.016);
assert_eq!(node_tree[toast_id].get_component::<UILabel>().expect("label").get_text(), "Quality: High");

let player_name = node_tree[field_id].get_component::<UIInputField>().expect("input field").get_text().to_string();
let show_options = UIDialogShowOptions {
	on_confirm: Some(Box::new(move |_dialog: &mut UIDialog, context: &mut ComponentContext| {
		if let Some(toast) = context.get_node_tree_mut()[toast_id].get_component_mut::<UIToast>() {
			toast.show("Saved");
		}
	})),
	on_cancel: Some(Box::new(|_dialog: &mut UIDialog, _context: &mut ComponentContext| {})),
	confirm_text: Some(String::from("Save")),
	cancel_text: Some(String::from("Cancel")),
};
node_tree.with_component_mut::<UIDialog, _>(dialog_id, |dialog, tree| {
	dialog.show(tree, &format!("Save as {}?", player_name), show_options);
});
node_tree.tick(&engine, 0.4);
node_tree[dialog_id].get_component_mut::<UIDialog>().expect("dialog").request_dismiss(true);
node_tree.tick(&engine, 0.016);
node_tree.tick(&engine, 0.3);
assert!(!node_tree[dialog_id].is_active());

Reading UI documents with UIDocument

A UI document is text that describes a node tree in JSON ({ "version": 1, "root": node }). The vanilla.js authoring tools save in this format (authoring tools are covered in the "Authoring Tools and Files Shared by Both Engines" chapter), and trees built in the Rust version are exported in the same format.

  • The original is a static class with module global tables, while the Rust version uses a UIDocument value holding the tables, created with UIDocument::new(). new registers the engine components Paint, Sprite, Text, RichText, Mask, Outline, SoftShade, ShadowText, UIProgressRing, UILabel, UIImageView, UIButton, UIToggleButton, UIProgressView, UISlider, UIScrollView, and ShadowImage (get_component_type_names()). All the types the authoring tools register (35 components, 12 node types) are added with the single line register_editor_types(); your game's components are added with register_component_type(name, constructor), and what were node types in the original are added with register_node_type. Unregistered types are skipped with a warning when reading.
  • from_json_text(&mut node_tree, json_text) builds the document into the node tree and returns the root node. The root is not attached anywhere, so attach it with add_child to show it in the scene. If the text is not JSON or has no root object, it returns Err(reason) (the original throws).
  • to_json_text(&mut node_tree, root_id, is_pretty) does the reverse and writes the node tree as JSON text. With is_pretty it indents with tabs.
  • A document does not contain image data, only paths (imagePath). If you set a function that turns a path into Option<Rc<Image>> with set_image_resolver(|image_path| ...), images are looked up with it. Otherwise they are looked up in the document's own asset store: load_images(&engine, json_text) requests the document's images as ImageAssets (on desktop from EngineConfiguration::asset_directory_paths), and for images that load later, as on the web, bind_pending_images(&mut node_tree) attaches them in tick until the remaining count reaches 0. Set the resolver and call load_images before from_json_text.
  • Components in a document are written and read through reflection only if their type has the reflection macro #[reflect]. All engine components have it (see the "Reflection Macro #[reflect]" chapter).

Below is an example that reads document text, finds a button by name, and gives it behavior.

use std::cell::Cell;
use std::rc::Rc;
use vanilla::{ComponentContext, Engine, EngineConfiguration, NodeTree, TouchKind, UIButton, UIDocument, Vector2};

let json_text = r#"{
	"version": 1,
	"root": {
		"name": "Menu",
		"children": [
			{
				"name": "StartButton",
				"position": [120, 40],
				"contentSize": [200, 56],
				"interactable": true,
				"components": [
					{ "color": [0.23, 0.51, 0.96, 1], "roundSize": 12, "type": "Paint" },
					{ "type": "UIButton" }
				]
			}
		]
	}
}"#;

let engine = Engine::new(EngineConfiguration::new());
let mut node_tree = NodeTree::new();
let mut document = UIDocument::new();
let menu_id = document.from_json_text(&mut node_tree, json_text).expect("document");
let root_id = node_tree.get_root_id();
node_tree.add_child(root_id, menu_id);

let start_id = node_tree.find_descendant_by_name(menu_id, "StartButton").expect("start button");
let start_count = Rc::new(Cell::new(0));
let start_count_for_event = start_count.clone();
let start_button = node_tree[start_id].get_component_mut::<UIButton>().expect("button");
start_button.set_clicked_event(Box::new(move |_button: &mut UIButton, _context: &mut ComponentContext| {
	start_count_for_event.set(start_count_for_event.get() + 1);
}));
let center = Vector2::create(120.0, 40.0);
node_tree.dispatch_touch(start_id, &engine, TouchKind::Press, center);
node_tree.dispatch_touch(start_id, &engine, TouchKind::Release, center);
assert_eq!(start_count.get(), 1);

assert!(document.from_json_text(&mut node_tree, "{\"version\":1}").is_err());

In a scene, read the document file as a TextAsset and build the tree in initialize after it has loaded. Below is a scene that reads the repository's examples/assets/scenedocument.scene.json and moves its progress bar.

use std::path::PathBuf;
use vanilla::{Engine, EngineConfiguration, NodeId, TextAsset, UIDocument, UIProgressView, UIScene, UISceneBase, Vector2};

struct DocumentScene {
	ui_scene_base: UISceneBase,
	document: UIDocument,
	scene_asset: TextAsset,
	progress_id: Option<NodeId>,
	elapsed_seconds: f64,
}

impl UIScene for DocumentScene {
	fn get_ui_scene_base(&self) -> &UISceneBase {
		&self.ui_scene_base
	}

	fn get_ui_scene_base_mut(&mut self) -> &mut UISceneBase {
		&mut self.ui_scene_base
	}

	fn load_assets(&mut self) {
		let engine = Engine::get_engine().unwrap();
		self.scene_asset.load(engine, "scenedocument.scene.json");
		self.ui_scene_base.get_scene_base_mut().track_asset(&self.scene_asset);
	}

	fn initialize(&mut self, engine: &Engine) {
		let scene_text = match self.scene_asset.get_text() {
			Some(scene_text) => {
				scene_text.to_string()
			}
			None => {
				return;
			}
		};
		self.document.load_images(engine, &scene_text);
		let node_tree = self.ui_scene_base.get_scene_base_mut().get_node_tree_mut();
		let document_root_id = match self.document.from_json_text(node_tree, &scene_text) {
			Ok(document_root_id) => {
				document_root_id
			}
			Err(error) => {
				eprintln!("{}", error);
				return;
			}
		};
		let root_id = node_tree.get_root_id();
		node_tree.add_child(root_id, document_root_id);
		self.progress_id = node_tree.find_descendant_by_name(document_root_id, "progress");
	}

	fn tick(&mut self, time_delta: f64) {
		let node_tree = self.ui_scene_base.get_scene_base_mut().get_node_tree_mut();
		self.document.bind_pending_images(node_tree);
		self.elapsed_seconds += time_delta;
		let progress = (self.elapsed_seconds.sin() * 0.5 + 0.5) * 100.0;
		if let Some(progress_id) = self.progress_id {
			if let Some(progress_view) = node_tree[progress_id].get_component_mut::<UIProgressView>() {
				progress_view.set_value(progress);
			}
		}
	}
}

vanilla::ui_scene!(DocumentScene);

fn main() {
	let mut engine_configuration = EngineConfiguration::new();
	engine_configuration.reference_resolution_size = Vector2::create(1280.0, 720.0);
	engine_configuration.asset_directory_paths = vec![PathBuf::from("examples/assets")];
	let engine = Engine::new(engine_configuration);
	let mut ui_scene_base = UISceneBase::new();
	ui_scene_base.set_loading_min_duration_ms(0.0);
	let document_scene = DocumentScene {
		ui_scene_base,
		document: UIDocument::new(),
		scene_asset: TextAsset::new(),
		progress_id: None,
		elapsed_seconds: 0.0,
	};
	if let Err(error) = engine.run(Box::new(document_scene)) {
		eprintln!("{}", error);
	}
}

Building declaratively with NodeLayout

Instead of creating nodes one by one and keeping them in local variables, this builder lets you write a node hierarchy as a chain. Start with NodeLayout::create() (there is only one node type, so the original create(nodeClass) argument does not exist). Chain name, active, pivot(pivot), anchor(x, y), anchored_position(x, y), local_position(x, y), content_size(x, y), local_scale(x, y), mask_enabled(is_enabled), component(component), component_with(component, callback), children([...]), apply(callback) (settings the builder lacks; it receives &mut WorldNode), and parent(parent_id), and build(node_tree, Some(parent_id)) creates the node, attaches it to the parent, and returns its NodeId. Positions and sizes are given as two numbers without Vector2.

  • The builder collects settings in order and, at build, creates the node and applies them in that order. Components are also attached with node_tree.add_component at build, so widgets that create child nodes when attached work too.
  • The original component(type, callback) is split into component(value) and component_with(value, callback), and the variadic arguments of children(...layouts) are taken as a single array or Vec.
  • anchored_position is applied at build relative to the parent's content size.
use vanilla::{Color, ComponentContext, Engine, EngineConfiguration, NodeLayout, NodeTree, Paint, Pivot, TouchKind, UIButton, UILabel, Vector2};

let engine = Engine::new(EngineConfiguration::new());
let mut node_tree = NodeTree::new();
let root_id = node_tree.get_root_id();
let panel_id = NodeLayout::create()
	.name("Panel")
	.pivot(Pivot::TOP_LEFT)
	.local_position(170.0, 60.0)
	.content_size(300.0, 240.0)
	.component_with(Paint::create_with_color(Color::create(0.13, 0.15, 0.2, 1.0)), |paint| {
		paint.set_round_size(16.0);
	})
	.children([
		NodeLayout::create()
			.name("Title")
			.pivot(Pivot::TOP_LEFT)
			.local_position(24.0, 20.0)
			.content_size(252.0, 40.0)
			.component(UILabel::create_with_text("Settings", 24.0)),
		NodeLayout::create()
			.name("CloseButton")
			.pivot(Pivot::TOP_LEFT)
			.local_position(24.0, 168.0)
			.content_size(252.0, 48.0)
			.component_with(Paint::create_with_color(Color::create(0.23, 0.51, 0.96, 1.0)), |paint| {
				paint.set_round_size(10.0);
			})
			.component(UILabel::create_with_text("Close", 18.0))
			.component_with(UIButton::new(), |button| {
				button.set_clicked_event(Box::new(|_button: &mut UIButton, context: &mut ComponentContext| {
					let button_id = context.get_node_id();
					let node_tree = context.get_node_tree_mut();
					if let Some(panel_id) = node_tree.get_parent_id(button_id) {
						node_tree[panel_id].set_visible(false);
					}
				}));
			}),
	])
	.build(&mut node_tree, Some(root_id));

let close_id = node_tree.find_descendant_by_name(panel_id, "CloseButton").expect("close button");
assert!(node_tree[close_id].is_interactable());
let center = Vector2::create(320.0, 252.0);
node_tree.dispatch_touch(close_id, &engine, TouchKind::Press, center);
node_tree.dispatch_touch(close_id, &engine, TouchKind::Release, center);
assert!(!node_tree[panel_id].is_visible());

NodeLayout::arrange_fan(node_tree, &node_ids, NodeLayoutFanOptions { center_x, center_y, radius, angle_step_radian, base_angle_radian, rotate_nodes }) spreads several nodes along an arc like cards in a hand (default spacing 0.12 radians, facing up, with rotation).

Constraint layout: UINode and LayoutSolver

UINode is a component that decides place and size with constraints (the same idea as UIKit Auto Layout). Attach it with node_tree.add_component(node_id, UINode::new()) and add constraints inside node_tree.with_component_mut::<UINode, _>(node_id, |ui_node, _tree| ...).

uiscenelayout example: a header bar pinned to the safe area, a side panel with a width constraint and three buttons of equal width

  • The anchor functions left_anchor(), right_anchor(), top_anchor(), bottom_anchor(), width_anchor(), height_anchor(), center_x_anchor(), center_y_anchor() (and leading_anchor(), trailing_anchor(), first_baseline_anchor(), last_baseline_anchor()) return a new LayoutExpression on every call. The original has getter properties (leftAnchor), while the Rust version has functions.
  • Expressions make new expressions with add, subtract, multiply, and divide, and make a LayoutConstraint with equal_to, less_than_or_equal_to, and greater_than_or_equal_to. The right side can be a number (f64, i32), a LayoutVariable, or a LayoutExpression.
  • Constraints made this way are required constraints. For a constraint that may yield, use a new constraint with a different strength, as in constraint.with_strength(LayoutStrength::STRONG). The strengths are LayoutStrength::REQUIRED, STRONG, MEDIUM, and WEAK, and the stronger one wins in a conflict. To build a strength from a priority, use LayoutStrength::from_priority(LayoutPriority::DEFAULT_LOW).
  • Add a constraint with ui_node.add_constraint(&constraint). Where the original throws (duplicate constraints, required constraints that cannot be satisfied), you get the Err of Result<(), LayoutError>.
  • Every tick, UIScene attaches its solver to the UINodes in the tree, solves the values, and copies them to the nodes. Read the solved values with get_left(), get_top(), get_width(), get_height(), get_center_x(), and get_center_y() (f64); the node's pivot becomes the top left, and its local position and content size become the solved values.
  • get_screen_node() is a guide fixed at the top left (0, 0) whose width and height follow the view size. get_safe_area_layout_guide() is a guide inset from it by the safe area. In the desktop app and in desktop browsers the safe area is 0, so the two guides are the same; for testing, simulate one with engine.get_view_manager_mut().set_safe_area_override(Some(SafeAreaInsets::create(top, right, bottom, left))).
  • The left and top values of a UINode are absolute coordinates relative to the root of the UI tree. If the parent is also a UINode, the child node is placed at the local position (child left - parent left, child top - parent top), so on screen it ends up exactly at the values.
  • Nodes with a size of their own, such as text, have an intrinsic content size (get_intrinsic_content_size), and set_content_hugging_priority(priority, axis) and set_content_compression_resistance_priority(priority, axis) decide how much they resist growing and shrinking (LayoutPriority::DEFAULT_LOW 250, DEFAULT_HIGH 750, REQUIRED 1000, FITTING_SIZE_LEVEL 50; the axis is LayoutConstraintAxis::Horizontal or Vertical). In the original, UILabel asks the node to remeasure its intrinsic size when the text changes; in the Rust version, UINode rereads the values of the components on the same node every tick and remeasures by itself when they change.
  • Use the inner margin guide with set_layout_margins(LayoutMargins::create(top, left, bottom, right)) (all 8 by default) and get_layout_margins_guide().

Below is what a scene does in initialize, run with a UISceneBase and no window. The header bar sticks inside the safe area, and the card aims for half the screen width without exceeding 480 and stands in the middle of the screen. The UIButton attached to the card can also be pressed at its solved place.

use vanilla::{Engine, EngineConfiguration, LayoutStrength, Paint, UIButton, UINode, UISceneBase, Vector2};

let engine = Engine::new(EngineConfiguration::new());
engine.get_view_manager_mut().calculate_view_rect(640, 360, 1.0);
let mut ui_scene_base = UISceneBase::new();
ui_scene_base.initialize(engine);

let safe_area_guide = ui_scene_base.get_safe_area_layout_guide();
let safe_left = safe_area_guide.left_anchor();
let safe_right = safe_area_guide.right_anchor();
let safe_top = safe_area_guide.top_anchor();
let screen_node = ui_scene_base.get_screen_node();
let screen_width = screen_node.width_anchor();
let screen_center_x = screen_node.center_x_anchor();
let screen_center_y = screen_node.center_y_anchor();

let node_tree = ui_scene_base.get_scene_base_mut().get_node_tree_mut();
let root_id = node_tree.get_root_id();

let header_id = node_tree.create_child(root_id, "Header");
node_tree[header_id].add_component(Paint::create_with_color("#3366cc"));
node_tree.add_component(header_id, UINode::new());
node_tree.with_component_mut::<UINode, _>(header_id, |header, _tree| {
	header.add_constraint(&header.left_anchor().equal_to(safe_left.add(16))).unwrap();
	header.add_constraint(&header.right_anchor().equal_to(safe_right.subtract(16))).unwrap();
	header.add_constraint(&header.top_anchor().equal_to(safe_top.add(16))).unwrap();
	header.add_constraint(&header.height_anchor().equal_to(56)).unwrap();
});

let card_id = node_tree.create_child(root_id, "Card");
node_tree[card_id].add_component(Paint::create_with_color("#222833"));
node_tree.add_component(card_id, UINode::new());
node_tree.add_component(card_id, UIButton::new());
node_tree.with_component_mut::<UINode, _>(card_id, |card, _tree| {
	let half_width = card.width_anchor().equal_to(screen_width.multiply(0.5));
	card.add_constraint(&half_width.with_strength(LayoutStrength::STRONG)).unwrap();
	card.add_constraint(&card.width_anchor().less_than_or_equal_to(480)).unwrap();
	card.add_constraint(&card.height_anchor().equal_to(160)).unwrap();
	card.add_constraint(&card.center_x_anchor().equal_to(screen_center_x.clone())).unwrap();
	card.add_constraint(&card.center_y_anchor().equal_to(screen_center_y.clone())).unwrap();
});

ui_scene_base.tick(0.016);
let node_tree = ui_scene_base.get_scene_base().get_node_tree();
assert_eq!(node_tree[header_id].get_local_position(), Vector2::create(16.0, 16.0));
assert_eq!(node_tree[header_id].get_content_size(), Vector2::create(608.0, 56.0));
assert_eq!(node_tree[card_id].get_local_position(), Vector2::create(160.0, 100.0));
assert_eq!(node_tree[card_id].get_content_size(), Vector2::create(320.0, 160.0));
assert_eq!(node_tree.find_topmost_interactable_node(Vector2::create(320.0, 180.0)), Some(card_id));

The solver can also be used alone without the engine. Create variables with LayoutVariable::new(name) and expressions with LayoutExpression::from_variable(&variable). Register variables whose values are pushed in from outside with add_edit_variable(&variable, strength) and give them values with suggest_value(&variable, value). Calling update_variables() puts the solved values into the variables, which you read with get_value(). LayoutSolver is a cheaply cloned handle, so all its functions take &self.

use vanilla::{LayoutExpression, LayoutSolver, LayoutStrength, LayoutVariable};

let solver = LayoutSolver::new();
let view_width = LayoutVariable::new("viewWidth");
let left = LayoutVariable::new("left");
let width = LayoutVariable::new("width");
let view_width_expression = LayoutExpression::from_variable(&view_width);
let left_expression = LayoutExpression::from_variable(&left);
let right_expression = left_expression.add(&width);
let right_margin_expression = view_width_expression.subtract(16);
solver.add_constraint(&left_expression.equal_to(16)).unwrap();
solver.add_constraint(&right_expression.equal_to(right_margin_expression)).unwrap();
solver.add_edit_variable(&view_width, LayoutStrength::STRONG).unwrap();

solver.suggest_value(&view_width, 640.0).unwrap();
solver.update_variables();
assert_eq!(width.get_value(), 608.0);

solver.suggest_value(&view_width, 360.0).unwrap();
solver.update_variables();
assert_eq!(width.get_value(), 328.0);

assert!(solver.add_constraint(&left_expression.equal_to(20)).is_err());

Window stacking

UIWindowLayer is a layer that stacks UIWindows over an area. Only the top window is visible, and when the window above closes, the one below becomes visible again. In the original both are nodes, but in the Rust version they are components attached to a layer node and window nodes, and the window nodes are children of the layer node.

windowshowcase example: a confirm window with scrolling text on top, dimming everything behind it

  • UIWindowLayer::create(node_tree, parent_id) creates the layer node and returns it. Keep the layer as the last child of the area node (usually the root), and every time the area size changes, report it with set_view_size(tree, width, height, css_pixel_scale). The CSS scale is engine.get_view_manager().get_css_pixel_scale(). To darken all the way into the safe area, also report set_view_bleed(tree, top, right, bottom, left).
  • open_window(tree, window_id) (in scene code, UIWindowLayer::open_window_in_tree(node_tree, layer_id, window_id)) stacks a window on top (or raises it to the top if it is already open), and close_window(tree, window_id), close_top_window(tree) (the place for the device's back action; true if it closed one), and close_all_windows(tree) close windows. Read the state with has_open_window(), get_window_count(), get_top_window(), and find_window(tree, name); set_window_change_event(Some(Box::new(|window_count| ...))) is called with the number of open windows whenever a window opens or closes. Use it to pause the game while a window is open.
  • A closed window node is only detached from the layer, not destroyed, so it can be opened again. Destroy windows you will not use again with destroy_node.
  • The layer grows by the UI scale (UIScale::read) so text stays readable on small screens. With set_ui_scale_options(tree, None) it does not grow.

UIWindow darkens the whole area (presses do not reach what is behind it) and brings up a panel in the middle. Create it with UIWindow::create(node_tree, layer_id, name, Box::new(UIWindowDefaultBehavior)); the created window node stays off until it is opened. Attach content to the node returned by get_panel_node(). The panel's width grows with the area but does not exceed set_maximum_width (480 by default), and it keeps set_margin (16 by default) away from the area's edges. Its height is set_panel_height (240 by default). The places that derived classes overrode in the original, such as layoutContent, are the UIWindowBehavior trait (build, layout_content(tree, parts, panel_width) which returns the panel height, layout_panel, apply_motion, set_covered, handle_wheel, handle_closed, and so on), and its default implementation is UIWindowDefaultBehavior. Pressing outside (the dark area) closes the window; turn this off with set_outside_close_enabled(false). There are also set_panel_color, set_dim_color, and set_close_event(Some(Box::new(|| ...))), and to close from scene or event code call UIWindow::close_in_tree(node_tree, window_id). It moves with PopupMotion when it opens and closes.

UIConfirmWindow is a window with a title, a question, and cancel and confirm buttons. Create it with UIConfirmWindow::create(node_tree, layer_id, name, UIConfirmWindowOptions { title, message, cancel_text, confirm_text }) (the default button texts are Korean words for cancel and confirm), take it out of the window node's UIWindow with get_behavior_mut::<UIConfirmWindow>(), and set set_confirm_event and set_cancel_event. The events are functions with no arguments. Pressing confirm fires the confirm event and then closes the window; closing it with the cancel button, an outside press, close_top_window, or close_all_windows fires the cancel event. If the text is long, only the text area scrolls. With set_right_to_left(true) the button order is reversed.

use vanilla::{Engine, EngineConfiguration, NodeId, Pivot, UIConfirmWindow, UIConfirmWindowOptions, UILabel, UIScene, UISceneBase, UIWindow, UIWindowDefaultBehavior, UIWindowLayer, Vector2};

struct WindowScene {
	ui_scene_base: UISceneBase,
	layer_id: Option<NodeId>,
}

impl UIScene for WindowScene {
	fn get_ui_scene_base(&self) -> &UISceneBase {
		&self.ui_scene_base
	}

	fn get_ui_scene_base_mut(&mut self) -> &mut UISceneBase {
		&mut self.ui_scene_base
	}

	fn initialize(&mut self, _engine: &Engine) {
		let node_tree = self.ui_scene_base.get_scene_base_mut().get_node_tree_mut();
		let root_id = node_tree.get_root_id();
		let layer_id = UIWindowLayer::create(node_tree, root_id);
		if let Some(window_layer) = node_tree[layer_id].get_component_mut::<UIWindowLayer>() {
			window_layer.set_window_change_event(Some(Box::new(|window_count: usize| {
				println!("open windows: {}", window_count);
			})));
		}

		let settings_id = UIWindow::create(node_tree, layer_id, "settings", Box::new(UIWindowDefaultBehavior));
		let panel_id = {
			let settings_window = node_tree[settings_id].get_component_mut::<UIWindow>().expect("window");
			settings_window.set_panel_height(200.0);
			settings_window.get_panel_node().expect("panel")
		};
		let label_id = node_tree.create_child(panel_id, "SettingsTitle");
		node_tree[label_id].set_pivot(Pivot::TOP_LEFT);
		node_tree[label_id].set_local_position(Vector2::create(24.0, 24.0));
		node_tree[label_id].set_content_size(Vector2::create(300.0, 40.0));
		node_tree.add_component(label_id, UILabel::create_with_text("Settings", 24.0));
		UIWindowLayer::open_window_in_tree(node_tree, layer_id, settings_id);

		let confirm_options = UIConfirmWindowOptions {
			title: String::from("Quit"),
			message: String::from("Do you really want to quit?"),
			cancel_text: String::from("Cancel"),
			confirm_text: String::from("Quit"),
		};
		let quit_id = UIConfirmWindow::create(node_tree, layer_id, "quit", confirm_options);
		if let Some(confirm_window) = node_tree[quit_id].get_component_mut::<UIWindow>().and_then(|window| window.get_behavior_mut::<UIConfirmWindow>()) {
			confirm_window.set_confirm_event(Some(Box::new(|| {
				println!("quit");
			})));
			confirm_window.set_cancel_event(Some(Box::new(|| {
				println!("stay");
			})));
		}
		UIWindowLayer::open_window_in_tree(node_tree, layer_id, quit_id);
		self.layer_id = Some(layer_id);
	}

	fn layout(&mut self) {
		let engine = Engine::get_engine().unwrap();
		let layer_id = match self.layer_id {
			Some(layer_id) => {
				layer_id
			}
			None => {
				return;
			}
		};
		let view_manager = engine.get_view_manager();
		let view_size = view_manager.get_view_size();
		let css_pixel_scale = view_manager.get_css_pixel_scale();
		let node_tree = self.ui_scene_base.get_scene_base_mut().get_node_tree_mut();
		node_tree.with_component_mut::<UIWindowLayer, _>(layer_id, |window_layer, tree| {
			window_layer.set_view_size(tree, view_size.x, view_size.y, css_pixel_scale);
		});
	}
}

vanilla::ui_scene!(WindowScene);

fn main() {
	let mut engine_configuration = EngineConfiguration::new();
	engine_configuration.reference_resolution_size = Vector2::create(640.0, 360.0);
	engine_configuration.auto_resize_on_window_resize = true;
	let engine = Engine::new(engine_configuration);
	let mut ui_scene_base = UISceneBase::new();
	ui_scene_base.set_loading_min_duration_ms(0.0);
	let window_scene = WindowScene {
		ui_scene_base,
		layer_id: None,
	};
	if let Err(error) = engine.run(Box::new(window_scene)) {
		eprintln!("{}", error);
	}
}

ButtonMotion

This adds size feedback to a button. Calling attach_button_motion(node_tree, node_id) on a node with a UIButton attaches ButtonMotion as the component after the UIButton; every frame it reads the button state and grows and shrinks the node around its center. It does not touch colors. When there is no feedback to show, it leaves the node's place and size alone.

  • The styles are ButtonMotionStyle::Normal (1.06 times on hover, 0.92 times while pressed, a 1.04 times bounce on release) and ButtonMotionStyle::Inset (a button inside a window; it does not grow, the background Paint brightens with a white inner ring on hover, and it goes to 0.96 times when pressed).
  • Set it per button with button_motion.set_style(Some(style)), or set the style of every button under a node with set_button_motion_area(node_tree, node_id, style). If neither is set, it is Normal.
  • shake_button(node_tree, node_id) shakes the button left and right for 0.25 seconds when it cannot be pressed.
  • Hover feedback is not used on devices where touch is primary.
  • The original computes the center assuming only a top left pivot, while the Rust version reads the node's pivot. The brightened background and white ring of Inset are drawn directly rather than kept as child nodes; to let decorations brighten in their own way, set a function with set_lit_handler.
use std::cell::Cell;
use std::rc::Rc;
use vanilla::{attach_button_motion, shake_button, ButtonMotionStyle, Color, ComponentContext, Engine, EngineConfiguration, NodeTree, Paint, Pivot, TouchKind, UIButton, UILabel, Vector2};

let engine = Engine::new(EngineConfiguration::new());
let mut node_tree = NodeTree::new();
let root_id = node_tree.get_root_id();
let button_id = node_tree.create_child(root_id, "BuyButton");
node_tree[button_id].set_pivot(Pivot::TOP_LEFT);
node_tree[button_id].set_local_position(Vector2::create(240.0, 156.0));
node_tree[button_id].set_content_size(Vector2::create(160.0, 48.0));
let button_paint = node_tree[button_id].add_component(Paint::create_with_color(Color::create(0.36, 0.42, 1.0, 1.0)));
button_paint.set_round_size(10.0);
node_tree.add_component(button_id, UILabel::create_with_text("Buy", 18.0));

let coin_count = Rc::new(Cell::new(40));
let coin_count_for_event = coin_count.clone();
let button = node_tree.add_component(button_id, UIButton::new()).expect("button");
button.set_clicked_event(Box::new(move |_button: &mut UIButton, context: &mut ComponentContext| {
	if coin_count_for_event.get() < 100 {
		let button_id = context.get_node_id();
		shake_button(context.get_node_tree_mut(), button_id);
		return;
	}
	coin_count_for_event.set(coin_count_for_event.get() - 100);
}));
let button_motion = attach_button_motion(&mut node_tree, button_id).expect("button motion");
button_motion.set_style(Some(ButtonMotionStyle::Normal));

let center = Vector2::create(320.0, 180.0);
node_tree.dispatch_touch(button_id, &engine, TouchKind::Press, center);
node_tree.tick(&engine, 0.1);
assert!(node_tree[button_id].get_local_scale().x < 1.0);
node_tree.dispatch_touch(button_id, &engine, TouchKind::Release, center);
assert_eq!(coin_count.get(), 40);

Things to watch out for

  • The UIScene loading screen stays up for 3 seconds by default. To skip it, give set_loading_min_duration_ms(0.0).
  • Attach widgets with node_tree.add_component(node_id, ...). Attaching with node_tree[node_id].add_component(...) creates no content node and does not turn the node interactable, so it cannot be pressed.
  • A plain Scene also passes presses to widgets, but it lacks the gesture that hands a drag over to a scroll view. If you put buttons inside a scroll view, use UIScene or run a TouchRecognizer yourself.
  • Among values that scene code changes while holding only a component, those that must reach other nodes (scroll offset and scroll bars, the colors of set_interactable and set_is_on, showing a toast) take effect on the next tick. To apply them in the same frame, use the *_in_tree functions such as set_scroll_offset_in_tree.
  • UIButton does not draw a background. Attach a Paint or UIImageView to the same node to give it a shape.
  • Widget events are closures in a Box, so they cannot borrow the scene's fields directly. Put values shared with code outside the event in Rc<Cell<T>> or Rc<RefCell<T>>, and change other nodes through their NodeId and the context.
  • UIInputField receives key input only after you call attach(). IME input such as Korean works only with set_use_dom_input(true).
  • The default button texts of UIDialogOptions and UIConfirmWindowOptions are Korean.
  • The root returned by UIDocument::from_json_text is not attached anywhere. Set the image resolver and call load_images before from_json_text.

UIScene, UISceneBase, UINode, UIView, UIControl, UILabel, UIImageView, UIButton, ButtonState, UIToggleButton, UISlider, UIProgressView, ProgressDirection, UIScrollView, ScrollMode, UIScrollBar, TouchRecognizer, UIInputField, UIDropdown, UIDropdownOptions, UIToast, UIToastOptions, UIDialog, UIDialogOptions, UIDialogShowOptions, UIContextMenu, UISpinner, UIListView, UISnapScrollView, UIDraggable, UILineChart, UIBarChart, UIProgressRing, UIHitArea, UIDocument, NodeLayout, NodeLayoutFanOptions, LayoutSolver, LayoutVariable, LayoutExpression, LayoutConstraint, LayoutStrength, LayoutPriority, LayoutConstraintAxis, LayoutMargins, LayoutError, UIWindowLayer, UIWindow, UIWindowBehavior, UIWindowDefaultBehavior, UIConfirmWindow, UIConfirmWindowOptions, UIScale, UIScaleOptions, PopupMotion, ButtonMotion, ButtonMotionStyle, ButtonMotionArea