vanilladocs
vanillapunch.com
API / core/node/nodetree

core/node/nodetree

노드 트리.

  • 씬의 노드를 저장소 하나(slotmap)에 담고, 부모와 자식을 핸들(NodeId)로 잇는다.
  • 게임 코드는 NodeId 를 들고 다니다가 get_node / get_node_mut (또는 tree[node_id]) 로 노드를 꺼낸다. 지운 노드의 NodeId 는 get_node 가 None 을 돌려준다. (원본 isDestroyed 자리)
  • 원본은 부모가 children[] 으로 자식 객체를 들고 자식이 parent 로 거꾸로 가리킨다. 러스트에서 그 꼴(Rc<RefCell>)은 실행 중 빌림 검사 비용과 순환 참조가 생겨서 핸들로 바꿨다.
  • tick / 터치를 돌 때는 부르는 컴포넌트 하나만 노드에서 잠깐 꺼내(그 자리에는 빈 자리표를 둔다) ComponentContext(자기 노드 + 트리 전체 + 엔진)를 넘긴다. 그래서 컴포넌트가 다른 노드를 찾고 바꾸고 만들 수 있고, 같은 노드의 다른 컴포넌트(형제)도 get_node_mut().get_component_mut::<T>() 로 찾는다.
  • 도는 중에 지운 노드는 그 자리에서 비활성으로 두고, 다 돈 뒤에 실제로 지운다.
  • 형제 순서(원본 Node.setSiblingIndex, getSiblingIndex, getSiblings)와 계층 판정(isActiveInHierarchy, TransformNode.isVisibleInHierarchy)은 부모를 봐야 해서 NodeTree 가 노드 핸들을 받아 한다. 원본의 -1 과 null 은 None 이다. 원본 isVisible 은 활성이고 불투명도가 0 보다 큰 것이다. 러스트 판은 그리기를 끄는 보이기 플래그(set_visible)가 따로 있어 그것까지 본다.
  • 원본 Node 의 계층 함수는 같은 이름으로 둔다. 노드 객체를 주고받는 자리는 NodeId 이고, 이름 끝에 _id(_ids)가 붙은 것은 핸들을 돌려주는 짝이다. (getParent → get_parent_id, getChildren → get_child_ids, getSiblings → get_sibling_ids) 부모에서 떼는 것(remove_child)은 노드를 지우지 않는다.
  • 원본 WorldNode.getPosition, setPosition, getWorldCorners, getWorldBounds 도 노드 핸들을 받아 한다. 전역 위치는 원본처럼 부모 피벗 기준으로 셈한 피벗 점의 자리이고, 네 모서리는 그 전역 위치와 전역 크기, 전역 회전으로 셈한다.

Node tree.

  • Holds the scene's nodes in one storage (slotmap) and links parents and children by handle (NodeId).
  • Game code carries NodeIds around and takes nodes out with get_node / get_node_mut (or tree[node_id]). For the NodeId of a deleted node, get_node returns None. (in place of the original isDestroyed)
  • In the original, a parent holds child objects in children[] and a child points back with parent. In Rust that form (Rc<RefCell>) brings runtime borrow checking costs and reference cycles, so it was changed to handles.
  • When running tick / touch, only the one component being called is briefly taken out of its node (an empty placeholder is left in its place) and a ComponentContext (own node + whole tree + engine) is passed. So a component can find, change and create other nodes, and also find other components of the same node (siblings) with get_node_mut().get_component_mut::<T>().
  • Nodes deleted while running are left inactive in place and actually deleted after the run finishes.
  • Sibling order (the original Node.setSiblingIndex, getSiblingIndex, getSiblings) and hierarchy checks (isActiveInHierarchy, TransformNode.isVisibleInHierarchy) need to look at the parent, so NodeTree does them taking a node handle. The original -1 and null are None. The original isVisible means active with opacity greater than 0. The Rust version also has a separate visibility flag (set_visible) that turns off drawing, and checks that too.
  • The hierarchy functions of the original Node keep the same names. Where node objects are passed it is NodeId, and names ending in _id (_ids) are the counterparts that return handles. (getParent → get_parent_id, getChildren → get_child_ids, getSiblings → get_sibling_ids) Detaching from the parent (remove_child) does not delete the node.
  • The original WorldNode.getPosition, setPosition, getWorldCorners, getWorldBounds are also done taking a node handle. The global position is, like the original, the position of the pivot point computed relative to the parent pivot, and the four corners are computed from that global position, global size and global rotation.

NodeTreestruct traits Default, Index<NodeId>, IndexMut<NodeId>

소스source

노드 트리.

  • 씬마다 하나 든다. (SceneBase::get_node_tree_mut) 노드는 NodeId 로 꺼내고, node_tree[node_id] 는 지운 노드면 멈춘다.

Node tree.

  • Each scene holds one. (SceneBase::get_node_tree_mut) Nodes are fetched by NodeId, and node_tree[node_id] panics if the node was removed.
예제Example층 노드 밑에 노드를 만들고 찾고 지우기Create, find and remove nodes under a layer node
use vanilla::NodeTree;

let mut node_tree = NodeTree::new();
let root_id = node_tree.get_root_id();
let layer_id = node_tree.create_child(root_id, "layer");
let player_id = node_tree.create_child(layer_id, "player");
assert_eq!(node_tree.find_descendant_by_name(root_id, "player"), Some(player_id));
assert_eq!(node_tree[player_id].get_parent_id(), Some(layer_id));
node_tree.destroy_node(layer_id);
assert!(node_tree.get_node(player_id).is_none());
assert_eq!(node_tree.get_node_count(), 1);
생성자constructorpub fn new() -> NodeTree#0.3.2 부터since 0.3.2소스source

생성. (루트 노드 "root" 를 함께 만든다. 루트의 피봇은 왼쪽 위)

Creates. (also creates the root node "root". The root's pivot is top-left)

반환ReturnsNodeTree 루트 노드 하나만 든 트리.A tree holding only the root node.

짝Counterpart: vanilla.js WorldNode.constructor

메서드methodpub fn get_root_id(&self) -> NodeId#0.3.2 부터since 0.3.2소스source

루트 노드 핸들.

Root node handle.

반환ReturnsNodeId 루트 노드 핸들. (루트는 지울 수 없다)Root node handle. (the root cannot be removed)

메서드methodpub fn get_node_count(&self) -> usize#0.3.2 부터since 0.3.2소스source

노드 수. (루트와 아직 트리에 붙지 않은 노드까지)

Node count. (including the root and nodes not yet attached to the tree)

반환Returnsusize 든 노드 수. (루트와 아직 붙지 않은 노드까지)Number of nodes held. (including the root and nodes not yet attached)

메서드methodpub fn contains(&self, node_id: NodeId) -> bool#0.3.2 부터since 0.3.2소스source

노드가 살아 있는지.

Whether the node is alive.

node_idNodeId
볼 노드.Node to look at.

반환Returnsbool 지우지 않은 노드면 true.True if the node has not been removed.

짝Counterpart: vanilla.js WorldNode.contains

메서드methodpub fn get_node(&self, node_id: NodeId) -> Option<&WorldNode>#0.3.2 부터since 0.3.2소스source

노드 반환.

Returns the node.

node_idNodeId
꺼낼 노드.Node to fetch.

반환ReturnsOption<&WorldNode> 노드. 지웠거나 모르는 핸들이면 None.The node. None if removed or an unknown handle.

메서드methodpub fn get_node_mut(&mut self, node_id: NodeId) -> Option<&mut WorldNode>#0.3.2 부터since 0.3.2소스source

노드 반환. (변경용)

Returns the node. (mutable)

node_idNodeId
꺼낼 노드.Node to fetch.

반환ReturnsOption<&mut WorldNode> 노드. (변경용) 지웠거나 모르는 핸들이면 None.The node. (mutable) None if removed or an unknown handle.

메서드methodpub fn create_node(&mut self, name: &str) -> NodeId#0.3.2 부터since 0.3.2소스source

노드 만들기. (아직 어느 부모에도 붙지 않는다. add_child 로 붙여야 그려진다)

Creates a node. (not attached to any parent yet. It is drawn only after attaching with add_child)

name&str
노드 이름.Node name.

반환ReturnsNodeId 새 노드 핸들.New node handle.

메서드methodpub fn create_child(&mut self, parent_id: NodeId, name: &str) -> NodeId#0.3.2 부터since 0.3.2소스source

자식 노드 만들기. (만들어서 parent_id 의 맨 뒤 자식으로 붙인다)

Creates a child node. (creates it and attaches it as the last child of parent_id)

parent_idNodeId
붙일 부모.Parent to attach to.
name&str
노드 이름.Node name.

반환ReturnsNodeId 새 노드 핸들. (parent_id 가 없는 노드면 붙지 않은 채로 남는다)New node handle. (left unattached if parent_id is a missing node)

메서드methodpub fn add_child(&mut self, parent_id: NodeId, child_id: NodeId) -> bool#0.3.2 부터since 0.3.2소스source

자식 붙이기. (맨 뒤. 다른 부모에 붙어 있으면 떼어서 옮긴다)

  • 자기 자신이나 자기 조상 밑으로는 붙이지 않는다. (false)

Adds a child. (at the end. If attached to another parent, detaches and moves it)

  • Does not attach under itself or its own ancestors. (false)
parent_idNodeId
부모가 될 노드.Node that becomes the parent.
child_idNodeId
붙일 노드.Node to attach.

반환Returnsbool 붙였으면 true. 둘 가운데 하나가 없거나, child_id 가 루트거나, child_id 가 parent_id 자신이나 조상이면 false.True if attached. False if either is missing, child_id is the root, or child_id is parent_id itself or its ancestor.

짝Counterpart: vanilla.js Node.addChild

메서드methodpub fn insert_child(&mut self, parent_id: NodeId, child_id: NodeId, child_index: usize) -> bool#0.3.2 부터since 0.3.2소스source

자식 끼워 넣기. (child_index 자리, 자식 수보다 크면 맨 뒤)

Inserts a child. (at child_index, at the end if greater than the child count)

parent_idNodeId
부모가 될 노드.Node that becomes the parent.
child_idNodeId
끼울 노드.Node to insert.
child_indexusize
끼울 자리. (0 부터, 앞일수록 먼저 그려진다)Position to insert at. (from 0, earlier is drawn first)

반환Returnsbool 끼웠으면 true. 막히는 경우는 add_child 와 같다.True if inserted. Blocked in the same cases as add_child.

예제Example맨 앞에 끼워 가장 먼저(뒤에 깔리게) 그리기Insert at the front to draw first (underneath)
use vanilla::NodeTree;

let mut node_tree = NodeTree::new();
let root_id = node_tree.get_root_id();
let player_id = node_tree.create_child(root_id, "player");
let background_id = node_tree.create_node("background");
assert!(node_tree.insert_child(root_id, background_id, 0));
assert_eq!(node_tree.get_child_ids(root_id), &[background_id, player_id]);
assert!(!node_tree.insert_child(player_id, root_id, 0));
메서드methodpub fn remove_from_parent(&mut self, child_id: NodeId)#0.3.2 부터since 0.3.2소스source

부모에서 떼기. (노드는 지우지 않는다. 다시 add_child 할 수 있다)

Detaches from the parent. (does not remove the node. It can be add_child'ed again)

child_idNodeId
뗄 노드. (부모가 없거나 없는 노드면 아무것도 하지 않는다)Node to detach. (does nothing if it has no parent or is a missing node)
메서드methodpub fn set_parent(&mut self, child_id: NodeId, parent_id: Option<NodeId>) -> bool#0.4.0 부터since 0.4.0소스source

부모 설정. (None 이면 부모에서 뗀다, 자기 자신이나 자손 밑으로는 붙이지 않는다, 원본 setParent)

Sets the parent. (detaches from the parent if None, does not attach under itself or its descendants, the original setParent)

child_idNodeId
옮길 노드.Node to move.
parent_idOption<NodeId>
새 부모. None 이면 부모에서 뗀다.New parent. Detaches from the parent if None.

반환Returnsbool 붙였거나, 이미 그 부모의 자식이거나(자리는 그대로), 뗐으면 true. add_child 가 막는 경우는 false.True if attached, already a child of that parent (position unchanged), or detached. False in the cases add_child blocks.

짝Counterpart: vanilla.js TransformNode.setParent

메서드methodpub fn remove_child(&mut self, parent_id: NodeId, child_id: NodeId)#0.4.0 부터since 0.4.0소스source

자식 떼기. (그 부모의 자식일 때만, 노드는 지우지 않는다, 원본 removeChild)

Removes a child. (only if it is a child of that parent, does not destroy the node, the original removeChild)

parent_idNodeId
부모.Parent.
child_idNodeId
뗄 자식. (parent_id 의 자식이 아니면 아무것도 하지 않는다)Child to detach. (does nothing if not a child of parent_id)

짝Counterpart: vanilla.js Node.removeChild

메서드methodpub fn remove_child_at(&mut self, parent_id: NodeId, child_index: usize)#0.4.0 부터since 0.4.0소스source

그 자리의 자식 떼기. (원본 removeChildAt)

Removes the child at that position. (the original removeChildAt)

parent_idNodeId
부모.Parent.
child_indexusize
뗄 자식의 자리. (0 부터, 범위 밖이면 아무것도 하지 않는다)Position of the child to detach. (from 0, does nothing if out of range)

짝Counterpart: vanilla.js Node.removeChildAt

메서드methodpub fn remove_children(&mut self, parent_id: NodeId)#0.4.0 부터since 0.4.0소스source

모든 자식 떼기. (바로 아래만 떼고 자식들의 계층은 그대로, 원본 removeChildren)

Removes all children. (detaches only the direct children and keeps their hierarchies, the original removeChildren)

parent_idNodeId
자식을 뗄 부모.Parent to detach children from.

짝Counterpart: vanilla.js Node.removeChildren

메서드methodpub fn remove_child_by_name(&mut self, parent_id: NodeId, name: &str)#0.4.0 부터since 0.4.0소스source

이름으로 자식 떼기. (바로 아래 처음 하나, 원본 removeChildByName)

Removes a child by name. (the first direct child, the original removeChildByName)

parent_idNodeId
부모.Parent.
name&str
뗄 자식 이름.Name of the child to detach.

짝Counterpart: vanilla.js Node.removeChildByName

메서드methodpub fn destroy_node(&mut self, node_id: NodeId)#0.3.2 부터since 0.3.2소스source

노드 지우기. (자손까지. 루트는 지우지 않는다)

  • tick / 터치를 도는 중이면 비활성으로 두고 다 돈 뒤에 지운다.

Destroys a node. (including descendants. Does not destroy the root)

  • While tick / touch is iterating, deactivates it and destroys it after the iteration.
node_idNodeId
지울 노드. (루트이거나 없는 노드면 아무것도 하지 않는다)Node to destroy. (does nothing if it is the root or a missing node)
메서드methodpub fn destroy_children(&mut self, parent_id: NodeId)#0.3.2 부터since 0.3.2소스source

자식 모두 지우기.

  • 바로 아래 자식마다 destroy_node 를 부른다. (자손까지 지운다)

Destroys all children.

  • Calls destroy_node for each direct child. (destroys descendants too)
parent_idNodeId
자식을 지울 부모.Parent whose children to destroy.
메서드methodpub fn destroy_children_where(&mut self, parent_id: NodeId, predicate: impl Fn(&WorldNode) -> bool) -> usize#0.3.2 부터since 0.3.2소스source

조건에 맞는 자식 지우기. (지운 수)

Destroys children matching a condition. (count destroyed)

parent_idNodeId
자식을 지울 부모.Parent whose children to destroy.
predicateimpl Fn(&WorldNode) -> bool
바로 아래 자식마다 불러 지울 것이면 true 를 돌려주는 조건.Condition called for each direct child that returns true for ones to destroy.

반환Returnsusize 지운 자식 수.Number of children destroyed.

짝Counterpart: vanilla.js Node.destroyChildrenWhere

예제Example이름이 enemy 인 자식만 지우기Destroy only children named enemy
use vanilla::NodeTree;

let mut node_tree = NodeTree::new();
let root_id = node_tree.get_root_id();
for name in ["enemy", "item", "enemy"] {
	node_tree.create_child(root_id, name);
}
let destroyed_count = node_tree.destroy_children_where(root_id, |node| node.get_name() == "enemy");
assert_eq!(destroyed_count, 2);
assert_eq!(node_tree.get_child_count(root_id), 1);
메서드methodpub fn get_parent_id(&self, node_id: NodeId) -> Option<NodeId>#0.3.2 부터since 0.3.2소스source

부모 핸들.

Parent handle.

node_idNodeId
볼 노드.Node to look at.

반환ReturnsOption<NodeId> 부모 핸들. 루트, 붙지 않은 노드, 없는 노드면 None.Parent handle. None for the root, unattached nodes and missing nodes.

메서드methodpub fn get_child_ids(&self, node_id: NodeId) -> &[NodeId]#0.3.2 부터since 0.3.2소스source

자식 핸들 목록. (그리는 순서)

Child handle list. (draw order)

node_idNodeId
볼 노드.Node to look at.

반환Returns&[NodeId] 자식 핸들 목록. (앞이 먼저 그려진다) 없는 노드면 빈 목록.Child handle list. (earlier is drawn first) An empty list if the node is missing.

메서드methodpub fn get_child_count(&self, node_id: NodeId) -> usize#0.3.2 부터since 0.3.2소스source

자식 수.

Child count.

node_idNodeId
볼 노드.Node to look at.

반환Returnsusize 바로 아래 자식 수. 없는 노드면 0.Number of direct children. 0 if the node is missing.

짝Counterpart: vanilla.js Node.getChildCount

메서드methodpub fn get_child_index(&self, parent_id: NodeId, child_id: NodeId) -> Option<usize>#0.4.0 부터since 0.4.0소스source

자식의 자리. (그리는 순서의 번호, parent_id 의 자식이 아니면 None)

Position of the child. (index in draw order, None if not a child of parent_id)

parent_idNodeId
부모.Parent.
child_idNodeId
찾을 자식.Child to find.

반환ReturnsOption<usize> 그리는 순서의 번호. (0 부터) parent_id 의 자식이 아니면 None.Index in draw order. (from 0) None if not a child of parent_id.

짝Counterpart: vanilla.js Node.getChildIndex

메서드methodpub fn get_sibling_ids(&self, node_id: NodeId) -> Option<&[NodeId]>#0.4.0 부터since 0.4.0소스source

형제 목록. (자기 자신을 포함한 부모의 자식 핸들, 부모가 없으면 None)

Sibling list. (the parent's child handles including itself, None if there is no parent)

node_idNodeId
볼 노드.Node to look at.

반환ReturnsOption<&[NodeId]> 자기를 포함한 형제 핸들 목록. (그리는 순서) 부모가 없으면 None.Sibling handle list including itself. (draw order) None if there is no parent.

메서드methodpub fn get_sibling_index(&self, node_id: NodeId) -> Option<usize>#0.4.0 부터since 0.4.0소스source

형제 사이의 자리. (부모가 없으면 None)

Position among siblings. (None if there is no parent)

node_idNodeId
볼 노드.Node to look at.

반환ReturnsOption<usize> 형제 사이의 번호. (0 부터) 부모가 없으면 None.Index among siblings. (from 0) None if there is no parent.

짝Counterpart: vanilla.js Node.getSiblingIndex

메서드methodpub fn set_sibling_index(&mut self, node_id: NodeId, child_index: usize)#0.4.0 부터since 0.4.0소스source

형제 사이의 자리 설정. (자식 수 - 1 까지로 자르고, 그 자리로 옮긴다. 부모가 없으면 아무것도 하지 않는다)

  • 앞일수록 먼저 그려져 뒤에 깔린다.

Sets the position among siblings. (clamps to child count - 1 and moves it there. Does nothing if there is no parent)

  • Earlier is drawn first and lies underneath.
node_idNodeId
옮길 노드.Node to move.
child_indexusize
새 자리. (0 부터, 자식 수 - 1 을 넘으면 맨 뒤)New position. (from 0, at the end if over child count - 1)

짝Counterpart: vanilla.js Node.setSiblingIndex

예제Example앞으로 옮겼다가 맨 뒤(맨 위에 그려지게)로 보내기Move to the front, then send to the back (drawn on top)
use vanilla::NodeTree;

let mut node_tree = NodeTree::new();
let root_id = node_tree.get_root_id();
let back_id = node_tree.create_child(root_id, "back");
let front_id = node_tree.create_child(root_id, "front");
node_tree.set_sibling_index(front_id, 0);
assert_eq!(node_tree.get_child_ids(root_id), &[front_id, back_id]);
node_tree.set_sibling_index(front_id, 100);
assert_eq!(node_tree.get_sibling_index(front_id), Some(1));
메서드methodpub fn is_active_in_hierarchy(&self, node_id: NodeId) -> bool#0.4.0 부터since 0.4.0소스source

자기부터 루트까지 모두 활성인지. (하나라도 꺼져 있으면 false, 없는 노드도 false)

Whether it and everything up to the root are active. (false if any is off, false for a missing node too)

node_idNodeId
볼 노드.Node to look at.

반환Returnsbool 자기와 조상이 모두 활성이면 true.True if it and all its ancestors are active.

짝Counterpart: vanilla.js Node.isActiveInHierarchy

메서드methodpub fn is_visible_in_hierarchy(&self, node_id: NodeId) -> bool#0.4.0 부터since 0.4.0소스source

자기부터 루트까지 모두 보이는지. (활성, 보이기 플래그, 불투명도 > 0 가운데 하나라도 아니면 false, 없는 노드도 false)

Whether it and everything up to the root are visible. (false if any of active, the visible flag, opacity > 0 fails, false for a missing node too)

node_idNodeId
볼 노드.Node to look at.

반환Returnsbool 자기와 조상이 모두 활성이고 보이기가 켜져 있고 불투명도가 0 보다 크면 true.True if it and all its ancestors are active, visible is on and opacity is greater than 0.

짝Counterpart: vanilla.js TransformNode.isVisibleInHierarchy

메서드methodpub fn is_ancestor_or_self(&self, ancestor_id: NodeId, node_id: NodeId) -> bool#0.3.2 부터since 0.3.2소스source

ancestor_id 가 node_id 자신이거나 조상인지.

Whether ancestor_id is node_id itself or its ancestor.

ancestor_idNodeId
조상인지 볼 노드.Node to test as an ancestor.
node_idNodeId
기준 노드.Reference node.

반환Returnsbool ancestor_id 가 node_id 자신이거나 그 조상이면 true.True if ancestor_id is node_id itself or its ancestor.

메서드methodpub fn find_child(&self, parent_id: NodeId, predicate: impl Fn(&WorldNode) -> bool) -> Option<NodeId>#0.4.0 부터since 0.4.0소스source

조건으로 자식 찾기. (바로 아래만, 처음 하나, 원본 findChild)

Finds a child by condition. (direct children only, the first one, the original findChild)

parent_idNodeId
찾을 부모.Parent to search.
predicateimpl Fn(&WorldNode) -> bool
찾는 노드면 true 를 돌려주는 조건.Condition that returns true for the node being searched for.

반환ReturnsOption<NodeId> 처음 맞는 바로 아래 자식. 없으면 None.The first matching direct child. None if none.

짝Counterpart: vanilla.js Node.findChild

메서드methodpub fn find_child_recursive(&self, parent_id: NodeId, predicate: &dyn Fn(&WorldNode) -> bool) -> Option<NodeId>#0.4.0 부터since 0.4.0소스source

조건으로 자손 찾기. (깊이 우선, 그리는 순서로 처음 하나, 원본 findChildRecursive)

Finds a descendant by condition. (depth first, the first one in draw order, the original findChildRecursive)

parent_idNodeId
찾을 조상. (자신은 보지 않는다)Ancestor to search. (itself is not checked)
predicate&dyn Fn(&WorldNode) -> bool
찾는 노드면 true 를 돌려주는 조건. (&|node| ... 꼴로 넘긴다)Condition that returns true for the node being searched for. (pass it in &|node| ... form)

반환ReturnsOption<NodeId> 처음 맞는 자손. 없으면 None.The first matching descendant. None if none.

짝Counterpart: vanilla.js Node.findChildRecursive

예제Example터치를 받는 자손 찾기Find a descendant that receives touches
use vanilla::NodeTree;

let mut node_tree = NodeTree::new();
let root_id = node_tree.get_root_id();
let panel_id = node_tree.create_child(root_id, "panel");
let button_id = node_tree.create_child(panel_id, "button");
node_tree[button_id].set_interactable(true);
assert_eq!(node_tree.find_child_recursive(root_id, &|node| node.is_interactable()), Some(button_id));
assert_eq!(node_tree.find_child(root_id, |node| node.is_interactable()), None);
메서드methodpub fn find_child_recursive_by_name(&self, parent_id: NodeId, name: &str) -> Option<NodeId>#0.4.0 부터since 0.4.0소스source

이름으로 자손 찾기. (원본 findChildRecursiveByName, find_descendant_by_name 과 같다)

Finds a descendant by name. (the original findChildRecursiveByName, same as find_descendant_by_name)

parent_idNodeId
찾을 조상. (자신은 보지 않는다)Ancestor to search. (itself is not checked)
name&str
찾을 이름.Name to find.

반환ReturnsOption<NodeId> 처음 맞는 자손. (깊이 우선, 그리는 순서) 없으면 None.The first matching descendant. (depth first, draw order) None if none.

짝Counterpart: vanilla.js Node.findChildRecursiveByName

메서드methodpub fn find_child_by_name(&self, parent_id: NodeId, name: &str) -> Option<NodeId>#0.3.2 부터since 0.3.2소스source

이름으로 자식 찾기. (바로 아래만, 처음 하나)

Finds a child by name. (direct children only, the first one)

parent_idNodeId
찾을 부모.Parent to search.
name&str
찾을 이름.Name to find.

반환ReturnsOption<NodeId> 처음 맞는 바로 아래 자식. 없으면 None.The first matching direct child. None if none.

짝Counterpart: vanilla.js Node.findChildByName

메서드methodpub fn find_descendant_by_name(&self, parent_id: NodeId, name: &str) -> Option<NodeId>#0.3.2 부터since 0.3.2소스source

이름으로 자손 찾기. (깊이 우선, 그리는 순서로 처음 하나)

Finds a descendant by name. (depth first, the first one in draw order)

parent_idNodeId
찾을 조상. (자신은 보지 않는다)Ancestor to search. (itself is not checked)
name&str
찾을 이름.Name to find.

반환ReturnsOption<NodeId> 처음 맞는 자손. (깊이 우선, 그리는 순서) 없으면 None.The first matching descendant. (depth first, draw order) None if none.

짝Counterpart: vanilla.js Node.findDescendantByName

메서드methodpub fn get_position(&self, node_id: NodeId) -> Vector2#0.4.0 부터since 0.4.0소스source

전역 위치. (피벗 점의 전역 위치, 원본 WorldNode.getPosition)

  • 로컬 위치는 부모 내용 영역의 왼쪽 위에서 본 자리라, 부모 피벗 점(부모 내용 크기 x 부모 피벗) 기준으로 옮긴 뒤 부모의 전역 회전과 크기를 걸고 부모 피벗 점의 전역 위치에 더한다. (앵커는 넣지 않는다) 그리는 변환(calculate_world_matrix)이 피벗 점을 놓는 자리와 같다.

Global position. (global position of the pivot point, the original WorldNode.getPosition)

  • The local position is measured from the top-left of the parent's content area, so it is shifted to be relative to the parent pivot point (parent content size x parent pivot), then the parent's global rotation and scale are applied and it is added to the global position of the parent pivot point. (anchors are not included) Same place where the draw transform (calculate_world_matrix) puts the pivot point.
node_idNodeId
볼 노드. (없는 노드면 멈춘다)Node to read. (panics if the node is missing)

반환ReturnsVector2 피벗 점의 전역 위치. (루트 아래 노드면 뷰 좌표)Global position of the pivot point. (view coordinates for nodes under the root)

짝Counterpart: vanilla.js WorldNode.getPosition

예제Example전역 위치를 읽고 전역 위치로 옮기기Read the global position and move to a global position
use vanilla::{NodeTree, Vector2};

let mut node_tree = NodeTree::new();
let root_id = node_tree.get_root_id();
let parent_id = node_tree.create_child(root_id, "parent");
let child_id = node_tree.create_child(parent_id, "child");
node_tree[parent_id].set_local_position(Vector2::create(100.0, 50.0));
node_tree[child_id].set_local_position(Vector2::create(10.0, 20.0));
assert_eq!(node_tree.get_position(child_id), Vector2::create(110.0, 70.0));
node_tree.set_position(child_id, Vector2::create(200.0, 100.0));
assert_eq!(node_tree[child_id].get_local_position(), Vector2::create(100.0, 50.0));
메서드methodpub fn set_position(&mut self, node_id: NodeId, position: Vector2)#0.4.0 부터since 0.4.0소스source

전역 위치 설정. (부모가 없으면 로컬 위치, get_position 의 거꾸로. 원본 WorldNode.setPosition)

  • 부모 피벗 점의 전역 위치에서 본 차이를 부모의 전역 회전과 크기를 풀어 부모 피벗 점 기준으로 되돌리고, 부모 내용 영역의 왼쪽 위 기준(로컬 위치)으로 옮긴다.
  • 부모의 전역 크기가 0 인 축은 부모 피벗 점에 놓는다.

Sets the global position. (the local position if there is no parent, the inverse of get_position. The original WorldNode.setPosition)

  • Takes the offset from the global position of the parent pivot point, undoes the parent's global rotation and scale to bring it back relative to the parent pivot point, and shifts it to be relative to the top-left of the parent's content area (local position).
  • On axes where the parent's global scale is 0, it is placed at the parent pivot point.
node_idNodeId
옮길 노드. (없는 노드면 멈춘다)Node to move. (panics if the node is missing)
positionVector2
피벗 점이 갈 전역 위치.Global position the pivot point goes to.

짝Counterpart: vanilla.js WorldNode.setPosition

메서드methodpub fn get_scale(&self, node_id: NodeId) -> Vector2#0.4.0 부터since 0.4.0소스source

전역 크기. (부모들의 크기를 곱한다, 원본 TransformNode.getScale)

Global scale. (multiplies the parents' scales, the original TransformNode.getScale)

node_idNodeId
볼 노드. (없는 노드면 멈춘다)Node to read. (panics if the node is missing)

반환ReturnsVector2 전역 배율. (자기와 조상의 로컬 배율을 곱한 것)Global scale. (product of its own and its ancestors' local scales)

짝Counterpart: vanilla.js TransformNode.getScale

메서드methodpub fn read_position(&self, node_id: NodeId, out: &mut Vector2)#0.4.0 부터since 0.4.0소스source

전역 위치를 out 에 적는다. (원본 WorldNode.readPosition, TransformNode.readPosition, get_position 과 같은 값)

Writes the global position into out. (original WorldNode.readPosition, TransformNode.readPosition, the same value as get_position)

node_idNodeId
볼 노드. (없는 노드면 멈춘다)Node to read. (panics if the node is missing)
out&mut Vector2
적을 자리.The place to write into.

짝Counterpart: vanilla.js WorldNode.readPosition

메서드methodpub fn read_scale(&self, node_id: NodeId, out: &mut Vector2)#0.4.0 부터since 0.4.0소스source

전역 배율을 out 에 적는다. (원본 TransformNode.readScale, get_scale 과 같은 값)

Writes the global scale into out. (original TransformNode.readScale, the same value as get_scale)

node_idNodeId
볼 노드. (없는 노드면 멈춘다)Node to read. (panics if the node is missing)
out&mut Vector2
적을 자리.The place to write into.

짝Counterpart: vanilla.js TransformNode.readScale

메서드methodpub fn set_scale(&mut self, node_id: NodeId, scale: Vector2)#0.4.0 부터since 0.4.0소스source

전역 크기 설정. (부모의 전역 크기로 나눈다, 0 이면 0, 원본 TransformNode.setScale)

Sets the global scale. (divides by the parent's global scale, 0 if it is 0, the original TransformNode.setScale)

node_idNodeId
바꿀 노드. (없는 노드면 멈춘다)Node to change. (panics if the node is missing)
scaleVector2
전역 배율.Global scale.

짝Counterpart: vanilla.js TransformNode.setScale

메서드methodpub fn get_rotation(&self, node_id: NodeId) -> f64#0.4.0 부터since 0.4.0소스source

전역 회전. (도, 부모들의 회전을 더한다, 원본 TransformNode.getRotation)

Global rotation. (degrees, adds the parents' rotations, the original TransformNode.getRotation)

node_idNodeId
볼 노드. (없는 노드면 멈춘다)Node to read. (panics if the node is missing)

반환Returnsf64 전역 회전. (도, 자기와 조상의 로컬 회전을 더한 것)Global rotation. (degrees, sum of its own and its ancestors' local rotations)

짝Counterpart: vanilla.js TransformNode.getRotation

메서드methodpub fn set_rotation(&mut self, node_id: NodeId, rotation: f64)#0.4.0 부터since 0.4.0소스source

전역 회전 설정. (도, 원본 TransformNode.setRotation)

Sets the global rotation. (degrees, the original TransformNode.setRotation)

node_idNodeId
바꿀 노드. (없는 노드면 멈춘다)Node to change. (panics if the node is missing)
rotationf64
전역 회전. (도)Global rotation. (degrees)

짝Counterpart: vanilla.js TransformNode.setRotation

메서드methodpub fn get_opacity(&self, node_id: NodeId) -> f64#0.4.0 부터since 0.4.0소스source

전역 투명도. (부모들의 투명도를 곱한다, 원본 TransformNode.getOpacity)

Global opacity. (multiplies the parents' opacities, the original TransformNode.getOpacity)

node_idNodeId
볼 노드. (없는 노드면 멈춘다)Node to read. (panics if the node is missing)

반환Returnsf64 전역 불투명도. (0 ~ 1, 자기와 조상의 로컬 불투명도를 곱한 것)Global opacity. (0 ~ 1, product of its own and its ancestors' local opacities)

짝Counterpart: vanilla.js TransformNode.getOpacity

메서드methodpub fn get_world_corners(&self, node_id: NodeId) -> [Vector2; 4]#0.4.0 부터since 0.4.0소스source

실제 화면에 그려지는 영역의 네 모서리. (원본 WorldNode.getWorldCorners, OBB. 왼쪽 위, 오른쪽 위, 오른쪽 아래, 왼쪽 아래)

  • 크기는 전역 크기의 절댓값을 곱하고, 피벗 점의 전역 위치를 중심으로 전역 회전만큼 돌린다.

The four corners of the area actually drawn on screen. (the original WorldNode.getWorldCorners, OBB. top-left, top-right, bottom-right, bottom-left)

  • The size is multiplied by the absolute value of the global scale and rotated by the global rotation around the global position of the pivot point.
node_idNodeId
볼 노드. (없는 노드면 멈춘다)Node to read. (panics if the node is missing)

반환Returns[Vector2; 4] 네 모서리. (뷰 좌표, 왼쪽 위, 오른쪽 위, 오른쪽 아래, 왼쪽 아래 차례)The four corners. (view coordinates, in top-left, top-right, bottom-right, bottom-left order)

짝Counterpart: vanilla.js WorldNode.getWorldCorners

예제Example가운데 피봇 노드의 모서리와 감싸는 사각형Corners and bounding rectangle of a center-pivot node
use vanilla::{NodeTree, Rect, Vector2};

let mut node_tree = NodeTree::new();
let root_id = node_tree.get_root_id();
let node_id = node_tree.create_child(root_id, "box");
node_tree[node_id].set_local_position(Vector2::create(100.0, 100.0));
node_tree[node_id].set_content_size(Vector2::create(40.0, 20.0));
let world_corners = node_tree.get_world_corners(node_id);
assert_eq!(world_corners[0], Vector2::create(80.0, 90.0));
assert_eq!(world_corners[2], Vector2::create(120.0, 110.0));
assert_eq!(node_tree.get_world_bounds(node_id), Rect::create(80.0, 90.0, 40.0, 20.0));
메서드methodpub fn get_world_bounds(&self, node_id: NodeId) -> Rect#0.4.0 부터since 0.4.0소스source

네 모서리를 감싸는 사각형. (원본 WorldNode.getWorldBounds)

Rectangle enclosing the four corners. (the original WorldNode.getWorldBounds)

node_idNodeId
볼 노드. (없는 노드면 멈춘다)Node to read. (panics if the node is missing)

반환ReturnsRect 네 모서리를 감싸는 축 정렬 사각형. (뷰 좌표)Axis-aligned rectangle enclosing the four corners. (view coordinates)

짝Counterpart: vanilla.js WorldNode.getWorldBounds

메서드methodpub fn calculate_world_matrix(&self, node_id: NodeId) -> TransformMatrix#0.3.2 부터since 0.3.2소스source

월드 행렬. (루트부터 이 노드까지 로컬 행렬을 곱한 것. 루트의 부모 좌표계 = 뷰 좌표계)

World matrix. (product of the local matrices from the root to this node. The root's parent coordinate system = the view coordinate system)

node_idNodeId
볼 노드.Node to look at.

반환ReturnsTransformMatrix 이 노드 내용 좌표의 점을 뷰 좌표로 옮기는 행렬. 없는 노드면 단위 행렬.Matrix that maps a point in this node's content coordinates to view coordinates. The identity matrix if the node is missing.

메서드methodpub fn convert_node_position_to_view_position(&self, node_id: NodeId, node_position: Vector2) -> Vector2#0.3.2 부터since 0.3.2소스source

노드 영역 안의 점 → 뷰 좌표.

Point in the node area → view coordinates.

node_idNodeId
기준 노드.Reference node.
node_positionVector2
노드 내용 좌표의 점. (내용 영역의 왼쪽 위가 원점)Point in node content coordinates. (origin at the top-left of the content area)

반환ReturnsVector2 뷰 좌표의 점.Point in view coordinates.

짝Counterpart: vanilla.js WorldNode.convertNodePositionToViewPosition

메서드methodpub fn convert_view_position_to_node_position(&self, node_id: NodeId, view_position: Vector2) -> Option<Vector2>#0.3.2 부터since 0.3.2소스source

뷰 좌표 → 노드 영역 안의 점. (행렬이 뒤집히지 않으면 None)

View coordinates → point in the node area. (None if the matrix is not invertible)

node_idNodeId
기준 노드.Reference node.
view_positionVector2
뷰 좌표의 점.Point in view coordinates.

반환ReturnsOption<Vector2> 노드 내용 좌표의 점. 행렬을 뒤집을 수 없으면(배율 0) None.Point in node content coordinates. None if the matrix cannot be inverted (scale 0).

짝Counterpart: vanilla.js WorldNode.convertViewPositionToNodePosition

메서드methodpub fn convert_view_to_local(&self, node_id: NodeId, view_position: Vector2) -> Option<Vector2>#0.4.0 부터since 0.4.0소스source

뷰 좌표 → 노드의 로컬 좌표. (내용 영역의 왼쪽 위가 원점, 부모들의 변환을 모두 거친다, 원본 WorldNode.convertViewToLocal)

  • convert_view_position_to_node_position 과 같다. 행렬이 뒤집히지 않으면(배율 0) None.

View coordinates → node local coordinates. (origin at the top-left of the content area, goes through all parent transforms, the original WorldNode.convertViewToLocal)

  • Same as convert_view_position_to_node_position. None if the matrix is not invertible (scale 0).
node_idNodeId
기준 노드.Reference node.
view_positionVector2
뷰 좌표의 점.Point in view coordinates.

반환ReturnsOption<Vector2> 노드 내용 좌표의 점. 행렬을 뒤집을 수 없으면(배율 0) None.Point in node content coordinates. None if the matrix cannot be inverted (scale 0).

짝Counterpart: vanilla.js WorldNode.convertViewToLocal

예제Example터치 자리를 패널 안의 자리로 바꾸기Convert a touch position to a position inside the panel
use vanilla::{NodeTree, Pivot, Vector2};

let mut node_tree = NodeTree::new();
let root_id = node_tree.get_root_id();
let panel_id = node_tree.create_child(root_id, "panel");
node_tree[panel_id].set_pivot(Pivot::TOP_LEFT);
node_tree[panel_id].set_rect(100.0, 50.0, 200.0, 100.0);
assert_eq!(node_tree.convert_view_to_local(panel_id, Vector2::create(110.0, 60.0)), Some(Vector2::create(10.0, 10.0)));
node_tree[panel_id].set_local_scale(Vector2::zero());
assert_eq!(node_tree.convert_view_to_local(panel_id, Vector2::create(110.0, 60.0)), None);
메서드methodpub fn tick(&mut self, engine: &Engine, time_delta: f64)#0.3.2 부터since 0.3.2소스source

주기적 갱신. (루트부터 깊이 우선: 컴포넌트 → 자식 순, 원본 ComponentNode.tick)

  • 도는 중에 지운 노드는 다 돈 뒤에 지운다.

Periodic update. (depth first from the root: components → children, the original ComponentNode.tick)

  • Nodes destroyed during the iteration are destroyed after it finishes.
engine&Engine
컴포넌트 문맥에 넘길 엔진.Engine to pass to the component context.
time_deltaf64
지난 tick 뒤로 흐른 시간. (초)Time elapsed since the last tick. (seconds)

짝Counterpart: vanilla.js ComponentNode.tick

메서드methodpub fn add_component<T: Component + 'static>(&mut self, node_id: NodeId, component: T) -> Option<&mut T>#0.3.2 부터since 0.3.2소스source

컴포넌트 붙이기. (attach 다음 attach_to_tree 를 불러, 컴포넌트가 자식 노드를 만들 수 있게 한다)

  • UIView 처럼 자식 노드를 만드는 컴포넌트는 이것으로 붙인다. 붙인 컴포넌트를 돌려준다.
  • 원본 addComponent 처럼 자기 자리를 먼저 잡고, 의존 컴포넌트(require)가 노드에 없으면 같은 길로 붙인 다음 붙는다.
  • 의존 컴포넌트와 붙는 동안 함께 붙인 컴포넌트(UIScrollView 의 Mask 같은 것)는 그 뒤에 온다.

Adds a component. (calls attach then attach_to_tree so the component can create child nodes)

  • Components that create child nodes, like UIView, are added with this. Returns the added component.
  • Like the original addComponent, it takes its own slot first, and if a required component (require) is not on the node, attaches it the same way before attaching itself.
  • Required components and components attached together while attaching (like UIScrollView's Mask) come after it.
node_idNodeId
붙일 노드.Node to attach.
componentT
붙일 컴포넌트.Component to add.

반환ReturnsOption<&mut T> 붙인 컴포넌트. (변경용) 노드가 없으면 None.The added component. (mutable) None if the node is missing.

짝Counterpart: vanilla.js ComponentNode.addComponent

예제Example붙인 컴포넌트를 돌려받고, 지운 노드에는 붙지 않는다Get the added component back, and nothing is attached to a destroyed node
use vanilla::{NodeTree, Paint};

let mut node_tree = NodeTree::new();
let root_id = node_tree.get_root_id();
let node_id = node_tree.create_child(root_id, "panel");
let paint = node_tree.add_component(node_id, Paint::new()).expect("node");
paint.set_round_size(12.0);
assert_eq!(node_tree[node_id].get_component::<Paint>().expect("paint").get_round_size(), 12.0);
node_tree.destroy_node(node_id);
assert!(node_tree.add_component(node_id, Paint::new()).is_none());
메서드methodpub fn with_component_mut<T: Component + 'static, R>(&mut self, node_id: NodeId, action: impl FnOnce(&mut T, &mut NodeTree) -> R) -> Option<R>#0.3.2 부터since 0.3.2소스source

컴포넌트 하나를 트리와 함께 쥐고 부르기. (씬 코드에서 위젯처럼 다른 노드도 만지는 컴포넌트를 바로 바꿀 때)

  • node_id 노드의 첫 번째 T 컴포넌트만 잠깐 빼고, 그 컴포넌트와 트리를 action 에 넘긴다. 없으면 None.
  • 예: node_tree.with_component_mut::<UIScrollView, _>(scroll_id, |scroll_view, tree| scroll_view.set_scroll_offset_in_tree(tree, scroll_id, offset))
  • action 안에서 지운 노드는 action 이 끝난 뒤에 지운다.

Calls with one component held together with the tree. (when scene code directly changes a component that also touches other nodes, like a widget)

  • Briefly takes out only the first T component of node node_id and passes that component and the tree to action. None if there is none.
  • Example: node_tree.with_component_mut::<UIScrollView, _>(scroll_id, |scroll_view, tree| scroll_view.set_scroll_offset_in_tree(tree, scroll_id, offset))
  • Nodes destroyed inside action are destroyed after action finishes.
node_idNodeId
컴포넌트가 붙은 노드.Node the component is attached to.
actionimpl FnOnce(&mut T, &mut NodeTree) -> R
꺼낸 컴포넌트와 트리를 받아 부를 함수. (그동안 그 컴포넌트는 노드에서 빠져 있다)Function called with the taken-out component and the tree. (the component is out of the node meanwhile)

반환ReturnsOption<R> action 이 돌려준 값. 노드가 없거나 T 컴포넌트가 없으면 None.The value action returned. None if the node is missing or has no T component.

예제Example컴포넌트를 바꾸면서 트리에 노드 만들기Create nodes in the tree while changing a component
use vanilla::{NodeTree, Paint};

let mut node_tree = NodeTree::new();
let root_id = node_tree.get_root_id();
let node_id = node_tree.create_child(root_id, "panel");
node_tree[node_id].add_component(Paint::new());
let shadow_id = node_tree.with_component_mut::<Paint, _>(node_id, |paint, tree| {
	paint.set_round_size(4.0);
	tree.create_child(node_id, "shadow")
}).expect("paint");
assert_eq!(node_tree.get_parent_id(shadow_id), Some(node_id));
assert_eq!(node_tree[node_id].get_component::<Paint>().expect("paint").get_round_size(), 4.0);
메서드methodpub fn with_component_at_mut<R>(&mut self, node_id: NodeId, component_index: usize, action: impl FnOnce(&mut dyn Component, &mut NodeTree) -> R) -> Option<R>#0.4.0 부터since 0.4.0소스source

차례 번호로 컴포넌트 하나를 트리와 함께 쥐고 부르기. (종류를 모르는 자리, UIDocument 가 트리를 받는 반사 세터를 부를 때)

  • node_id 노드의 component_index 번째 컴포넌트를 잠깐 빼고, 그 컴포넌트와 트리를 action 에 넘긴다. 없으면 None.

Calls with one component, by index, held together with the tree. (where the type is unknown, when UIDocument calls a reflection setter that takes the tree)

  • Briefly takes out the component_index-th component of node node_id and passes that component and the tree to action. None if there is none.
node_idNodeId
컴포넌트가 붙은 노드.Node the component is attached to.
component_indexusize
컴포넌트 자리. (붙인 차례, 0 부터)Component position. (order added, from 0)
actionimpl FnOnce(&mut dyn Component, &mut NodeTree) -> R
꺼낸 컴포넌트와 트리를 받아 부를 함수.Function called with the taken-out component and the tree.

반환ReturnsOption<R> action 이 돌려준 값. 노드가 없거나 자리가 범위 밖이면 None.The value action returned. None if the node is missing or the position is out of range.

예제Example종류를 모르는 첫 컴포넌트의 이름 읽기Read the name of the first component whose type is unknown
use vanilla::{NodeTree, Paint};

let mut node_tree = NodeTree::new();
let root_id = node_tree.get_root_id();
let node_id = node_tree.create_child(root_id, "panel");
node_tree[node_id].add_component(Paint::new());
let component_type = node_tree.with_component_at_mut(node_id, 0, |component, _tree| component.get_component_type());
assert_eq!(component_type, Some("Paint"));
assert!(node_tree.with_component_at_mut(node_id, 1, |_component, _tree| ()).is_none());
메서드methodpub fn draw(&mut self, graphic: &mut Graphic)#0.3.2 부터since 0.3.2소스source

출력. (루트부터 재귀, 원본 Graphic.drawNode)

Draws. (recursively from the root, the original Graphic.drawNode)

graphic&mut Graphic
그릴 Graphic. (화면 밖이라 건너뛴 노드 수를 더해 둔다)Graphic to draw with. (adds the number of nodes skipped for being off screen)

짝Counterpart: vanilla.js WorldNode.draw

메서드methodpub fn draw_node(&mut self, node_id: NodeId, graphic: &mut Graphic)#0.3.2 부터since 0.3.2소스source

노드 하나와 그 자손 출력.

  • push_transform → 컴포넌트의 push_transform → (투명도 층 시작) → 컴포넌트 → (Mask 면 클립 시작) → 자식 → (클립 끝) → (투명도 층 끝) → 기즈모 → 컴포넌트의 pop_transform → pop_transform

Draws one node and its descendants.

  • push_transform → the component's push_transform → (opacity layer begin) → components → (clip begin if Mask) → children → (clip end) → (opacity layer end) → gizmo → the component's pop_transform → pop_transform
node_idNodeId
그릴 노드. (없거나 비활성이면 그리지 않는다)Node to draw. (not drawn if missing or inactive)
graphic&mut Graphic
그릴 Graphic. (부모의 트랜스폼이 걸린 상태)Graphic to draw with. (with the parent's transform applied)
메서드methodpub fn draw_children(&mut self, node_id: NodeId, graphic: &mut Graphic)#0.4.0 부터since 0.4.0소스source

자식 목록 출력. (자식 차례대로 draw_node, draw_node 가 부른다, 원본 TransformNode.drawChildren)

  • 하위 트리 거르기가 켜졌으면 부모 좌표의 보이는 사각형(Graphic::read_local_visible_bounds)으로 보이는 자식 범위를 이분 찾기로 좁혀 그 앞뒤 자식은 부르지 않는다. 범위 밖 자식 가운데 하나씩 거를 때 셀 것은 Graphic::add_culled_subtree_count 로 더한다. (건너뛴 하위 트리 수가 하나씩 거를 때와 같다)
  • 지금 변환은 이 노드의 내용 좌표여야 한다. (push_transform 을 건 뒤)

Draws the child list. (draw_node for each child in order, called by draw_node, original TransformNode.drawChildren)

  • With subtree culling on, narrows the visible child range by binary search with the visible rect in parent coordinates (Graphic::read_local_visible_bounds) and does not call the children before and after it. Children outside the range that would be counted when culled one by one are added with Graphic::add_culled_subtree_count. (the skipped subtree count is the same as culling one by one)
  • The current transform must be this node's content coordinates. (after push_transform)
node_idNodeId
자식을 그릴 노드.Node whose children are drawn.
graphic&mut Graphic
그릴 Graphic.Graphic to draw to.

짝Counterpart: vanilla.js TransformNode.drawChildren

예제Example화면 밖 자식은 부르지 않는다Off-screen children are not called
use vanilla::{NodeTree, Paint, Pivot};

let mut node_tree = NodeTree::new();
let root_id = node_tree.get_root_id();
let list_id = node_tree.create_child(root_id, "list");
node_tree[list_id].set_pivot(Pivot::TOP_LEFT);
for row_index in 0..100 {
	let row_id = node_tree.create_child(list_id, "row");
	node_tree[row_id].set_pivot(Pivot::TOP_LEFT);
	node_tree[row_id].set_rect(0.0, row_index as f64 * 40.0, 200.0, 36.0);
	node_tree.add_component(row_id, Paint::new());
}
assert_eq!(node_tree.get_child_count(list_id), 100);
메서드methodpub fn read_subtree_draw_bounds(&mut self, node_id: NodeId, graphic: &mut Graphic) -> Option<Rect>#0.4.0 부터since 0.4.0소스source

하위 트리 그리기 경계 읽기. (이 노드의 내용 좌표, push_transform 을 건 뒤의 좌표, 원본 TransformNode.readSubtreeDrawBounds)

  • 이 노드와 켜지고 보이는 자손이 그리는 곳을 모두 품는 사각형이다. 크기가 0 이면 아무것도 그리지 않는다.
  • 바뀐 때만 다시 셈하고 그 밖에는 셈해 둔 것을 준다. 그리기 순회가 이 사각형이 화면과 자르기 밖이면 하위 트리를 통째로 건너뛴다.
  • 자기 그림: 켜지고 그리는 컴포넌트(Component::is_draw_overridden)의 calculate_drawn_rect. 내용 영역 안에서만 그리는 컴포넌트는 내용 영역을 한 단위씩 넓혀 본다.
  • 자식: 자식의 경계를 자식의 변환(위치, 회전, 배율, 피봇)으로 옮긴 이 노드의 내용 좌표 경계 상자. 마스크로 잘라도 줄이지 않는다. (넉넉하게 본다)

Reads the subtree draw bounds. (this node's content coordinates, the coordinates after push_transform, original TransformNode.readSubtreeDrawBounds)

  • The rect that holds everything this node and its enabled, visible descendants draw. Size 0 means nothing is drawn.
  • Recomputed only when something changed, otherwise the stored value is returned. The draw traversal skips the whole subtree when this rect is outside the screen and the clip.
  • Own drawing: calculate_drawn_rect of enabled drawing components (Component::is_draw_overridden). Components that draw only inside the content area count as the content area widened by one unit.
  • Children: bounding box in this node's content coordinates of each child's bounds moved by the child's transform (position, rotation, scale, pivot). Not reduced by a mask clip. (generous)
node_idNodeId
읽을 노드.Node to read.
graphic&mut Graphic
컴포넌트가 그리는 사각형을 셀 때 쓰는 Graphic. (글 크기 재기)Graphic used to compute the components' drawn rects. (text measuring)

반환ReturnsOption<Rect> 경계. 어디에 그리는지 모르는 것(경계를 알리지 않는 컴포넌트, 기즈모를 그리는 노드)이 들거나 없는 노드면 None.Bounds. None if it holds something that draws somewhere unknown (a component that does not report its bounds, a node that draws gizmos) or the node does not exist.

짝Counterpart: vanilla.js TransformNode.readSubtreeDrawBounds

예제Example자식 경계가 부모 좌표로 모인다Child bounds gather in parent coordinates
use vanilla::{Graphic, NodeTree, Paint, Pivot, Rect};

fn read_bounds(graphic: &mut Graphic) {
	let mut node_tree = NodeTree::new();
	let root_id = node_tree.get_root_id();
	let list_id = node_tree.create_child(root_id, "list");
	node_tree[list_id].set_pivot(Pivot::TOP_LEFT);
	let row_id = node_tree.create_child(list_id, "row");
	node_tree[row_id].set_pivot(Pivot::TOP_LEFT);
	node_tree[row_id].set_rect(10.0, 20.0, 100.0, 30.0);
	node_tree.add_component(row_id, Paint::new());
	let bounds = node_tree.read_subtree_draw_bounds(list_id, graphic).expect("known");
	assert_eq!(bounds, Rect::create(9.0, 19.0, 102.0, 32.0));
	assert_eq!(node_tree.read_parent_draw_bounds(row_id), Some(Rect::create(9.0, 19.0, 102.0, 32.0)));
}
메서드methodpub fn read_parent_draw_bounds(&self, node_id: NodeId) -> Option<Rect>#0.4.0 부터since 0.4.0소스source

부모가 셈해 둔 이 노드의 하위 트리 그리기 경계 읽기. (부모의 내용 좌표, 이 노드의 변환을 건 경계 상자, 원본 TransformNode.readParentDrawBounds)

  • 부모가 하위 트리 경계를 셈할 때 자식마다 옮겨 적어 둔 것이다. 이 노드의 변환이나 경계가 바뀌면 부모가 다시 셈하므로 그때까지 그대로 쓴다.
  • 그리기 순회가 부모의 변환 아래에서 이 사각형을 먼저 보아, 부모 좌표의 보이는 사각형 밖이면 이 노드에 변환을 걸지 않고 건너뛴다.

Reads this node's subtree draw bounds stored by the parent. (parent's content coordinates, bounding box with this node's transform applied, original TransformNode.readParentDrawBounds)

  • The parent writes it for each child while computing its subtree bounds. When this node's transform or bounds change the parent recomputes, so it is used as is until then.
  • The draw traversal checks this rect first under the parent's transform and skips this node without applying its transform when it is outside the visible rect in parent coordinates.
node_idNodeId
읽을 노드.Node to read.

반환ReturnsOption<Rect> 부모 좌표 경계. 부모가 아직 셈하지 않았거나 셈한 뒤 바뀌었거나, 이 노드가 어디에 그리는지 모르면 None. (아무것도 그리지 않으면 크기 0)Bounds in parent coordinates. None if the parent has not computed them yet, something changed since, or this node draws somewhere unknown. (size 0 if nothing is drawn)

짝Counterpart: vanilla.js TransformNode.readParentDrawBounds

메서드methodpub fn find_topmost_interactable_node(&self, view_position: Vector2) -> Option<NodeId>#0.3.2 부터since 0.3.2소스source

그리는 순서로 돌며 점 아래 맨 위의 interactable 노드 찾기. (원본 TouchRecognizer 의 대상 고르기)

  • 비활성이거나 안 보이는 노드와 그 자손, 자르는(Mask) 노드 밖의 자손은 맞지 않는다.

Iterates in draw order to find the topmost interactable node under a point. (the original TouchRecognizer's target selection)

  • Inactive or invisible nodes and their descendants, and descendants outside a clipping (Mask) node, do not hit.
view_positionVector2
볼 점. (뷰 좌표)Point to check. (view coordinates)

반환ReturnsOption<NodeId> 점 아래에서 가장 나중에 그리는 터치 받는 노드. 없으면 None.The touch-receiving node drawn last under the point. None if none.

예제Example겹친 두 노드 가운데 뒤에 그리는 것이 맞는다Of two overlapping nodes, the one drawn later is hit
use vanilla::{NodeTree, Pivot, Vector2};

let mut node_tree = NodeTree::new();
let root_id = node_tree.get_root_id();
for name in ["back", "front"] {
	let node_id = node_tree.create_child(root_id, name);
	node_tree[node_id].set_pivot(Pivot::TOP_LEFT);
	node_tree[node_id].set_rect(0.0, 0.0, 100.0, 100.0);
	node_tree[node_id].set_interactable(true);
}
let found_id = node_tree.find_topmost_interactable_node(Vector2::create(50.0, 50.0)).expect("node");
assert_eq!(node_tree[found_id].get_name(), "front");
assert_eq!(node_tree.find_topmost_interactable_node(Vector2::create(150.0, 50.0)), None);
메서드methodpub fn dispatch_touch(&mut self, node_id: NodeId, engine: &Engine, touch_kind: TouchKind, view_input_position: Vector2)#0.3.2 부터since 0.3.2소스source

터치 전달. (노드의 컴포넌트들에게)

  • 켜진 컴포넌트에게 붙인 차례로 부르고, 도는 중에 지운 노드는 다 돈 뒤에 지운다.

Dispatches a touch. (to the node's components)

  • Calls the enabled components in the order added, and nodes destroyed during the iteration are destroyed after it finishes.
node_idNodeId
터치를 받을 노드.Node to receive the touch.
engine&Engine
컴포넌트 문맥에 넘길 엔진.Engine to pass to the component context.
touch_kindTouchKind
부를 터치 함수의 종류.Kind of touch function to call.
view_input_positionVector2
터치 자리. (뷰 좌표)Touch position. (view coordinates)
메서드methodpub fn find_wheel_target_node(&self, view_position: Vector2) -> Option<NodeId>#0.4.0 부터since 0.4.0소스source

그 자리에서 휠을 받을 노드 찾기. (find_topmost_interactable_node 와 같은 그리는 순서, 없으면 None)

  • 그 자리를 품은 노드 가운데 누를 수 있는 노드와 휠을 받는 칸(Component::is_wheel_receiver)의 노드를 보고 가장 앞(나중에 그리는 것)을 고른다. 스크롤 칸이 가장 앞이면 그 칸의 노드다. (칸 안의 글이나 그림처럼 누를 수 없는 것 위에서 굴려도 칸이 받는다)
  • 누를 수 있는 노드가 가장 앞이면 그 노드다. (dispatch_wheel 이 부모 쪽으로 올라가며 묻는다, 스크롤 칸을 덮은 막이나 창이 휠을 가린다)

Finds the node that receives the wheel at that position. (same draw order as find_topmost_interactable_node, None if none)

  • Among nodes containing that position, looks at pressable nodes and nodes of wheel-receiving panes (Component::is_wheel_receiver) and picks the frontmost (drawn last). If a scroll pane is frontmost, it is that pane's node. (the pane receives it even when scrolling over unpressable things in it like text or images)
  • If a pressable node is frontmost, it is that node. (dispatch_wheel asks upward toward the parents, a blocker or window covering a scroll pane blocks the wheel)
view_positionVector2
볼 점. (뷰 좌표)Point to check. (view coordinates)

반환ReturnsOption<NodeId> 휠을 받을 노드. 없으면 None.Node to receive the wheel. None if none.

메서드methodpub fn dispatch_wheel_at(&mut self, view_position: Vector2, engine: &Engine, wheel_delta: Vector2) -> bool#0.4.0 부터since 0.4.0소스source

그 자리에 휠 전달. (find_wheel_target_node 로 찾은 노드부터 부모 쪽으로, 받아 쓴 컴포넌트가 있으면 true)

Dispatches the wheel at that position. (from the node found by find_wheel_target_node toward the parents, true if a component consumed it)

view_positionVector2
휠을 굴린 자리. (뷰 좌표)Position where the wheel was rolled. (view coordinates)
engine&Engine
컴포넌트 문맥에 넘길 엔진.Engine to pass to the component context.
wheel_deltaVector2
휠 이동량. (픽셀, 내용을 아래로 넘기면 y 가 양수)Wheel delta. (pixels, y is positive when scrolling the content down)

반환Returnsbool 받아 쓴 컴포넌트가 있으면 true. 받을 노드가 없으면 false.True if a component consumed it. False if there is no node to receive it.

메서드methodpub fn dispatch_wheel(&mut self, node_id: NodeId, engine: &Engine, wheel_delta: Vector2) -> bool#0.3.2 부터since 0.3.2소스source

휠 전달. (node_id 자신부터 부모 쪽으로 올라가며 처음 받아 쓴 컴포넌트에서 멈춘다. 원본 touchWheel)

Dispatches the wheel. (goes up from node_id itself toward the parents and stops at the first component that consumes it. The original touchWheel)

node_idNodeId
처음 물을 노드.First node to ask.
engine&Engine
컴포넌트 문맥에 넘길 엔진.Engine to pass to the component context.
wheel_deltaVector2
휠 이동량. (픽셀, 내용을 아래로 넘기면 y 가 양수)Wheel delta. (pixels, y is positive when scrolling the content down)

반환Returnsbool 받아 쓴 컴포넌트가 있으면 true.True if a component consumed it.

예제Example항목 위에서 굴린 휠을 목록 노드의 컴포넌트가 받는다A list node's component receives the wheel scrolled over an item
use vanilla::{Component, ComponentBase, ComponentContext, Engine, EngineConfiguration, NodeTree, Vector2};

struct Scroller {
	component_base: ComponentBase,
	scroll_offset: f64,
}

#[vanilla::reflect]
impl Scroller {}

#[vanilla::reflect]
impl Component for Scroller {
	fn wheel(&mut self, _context: &mut ComponentContext, wheel_delta: Vector2) -> bool {
		self.scroll_offset += wheel_delta.y;
		true
	}
}

let engine = Engine::new(EngineConfiguration::new());
let mut node_tree = NodeTree::new();
let root_id = node_tree.get_root_id();
let list_id = node_tree.create_child(root_id, "list");
node_tree[list_id].add_component(Scroller {
	component_base: ComponentBase::new(),
	scroll_offset: 0.0,
});
let item_id = node_tree.create_child(list_id, "item");
assert!(node_tree.dispatch_wheel(item_id, &engine, Vector2::create(0.0, 40.0)));
assert_eq!(node_tree[list_id].get_component::<Scroller>().expect("scroller").scroll_offset, 40.0);
assert!(!node_tree.dispatch_wheel(root_id, &engine, Vector2::create(0.0, 40.0)));
메서드methodpub fn get_local_bounds(&self, node_id: NodeId) -> Option<Rect>#0.3.2 부터since 0.3.2소스source

노드 경계 사각형을 부모 영역 기준으로. (회전 없을 때 정확, 충돌 검사 등)

Node bounding rectangle relative to the parent area. (exact without rotation, for collision tests and such)

node_idNodeId
볼 노드.Node to look at.

반환ReturnsOption<Rect> 부모 내용 좌표의 경계 사각형. (NodeTransform::get_local_bounds) 없는 노드면 None.Bounding rectangle in the parent's content coordinates. (NodeTransform::get_local_bounds) None if the node is missing.

ComponentContextstruct

소스source

컴포넌트 문맥. (tick / 터치 때 컴포넌트가 받는 것: 자기 노드, 트리 전체, 엔진)

  • 원본 컴포넌트의 get_node(), get_node().getParent(), Engine.get_engine() 자리.

Component context. (what a component receives on tick / touch: its own node, the whole tree, the engine)

  • In place of the original component's get_node(), get_node().getParent(), Engine.get_engine().
예제Exampletick 에서 트리의 다른 노드를 찾아 그 자리로 따라가기Find another node in the tree on tick and follow its position
use vanilla::{Component, ComponentBase, ComponentContext, Engine, EngineConfiguration, NodeTree, Vector2};

struct Follower {
	component_base: ComponentBase,
}

#[vanilla::reflect]
impl Follower {}

#[vanilla::reflect]
impl Component for Follower {
	fn tick(&mut self, context: &mut ComponentContext, _time_delta: f64) {
		let node_tree = context.get_node_tree();
		let root_id = node_tree.get_root_id();
		if let Some(target_id) = node_tree.find_descendant_by_name(root_id, "target") {
			let target_position = node_tree[target_id].get_local_position();
			context.get_transform_mut().set_local_position(target_position);
		}
	}
}

let engine = Engine::new(EngineConfiguration::new());
let mut node_tree = NodeTree::new();
let root_id = node_tree.get_root_id();
let target_id = node_tree.create_child(root_id, "target");
node_tree[target_id].set_local_position(Vector2::create(30.0, 40.0));
let follower_id = node_tree.create_child(root_id, "follower");
node_tree[follower_id].add_component(Follower {
	component_base: ComponentBase::new(),
});
node_tree.tick(&engine, 0.016);
assert_eq!(node_tree[follower_id].get_local_position(), Vector2::create(30.0, 40.0));
메서드methodpub fn get_node_id(&self) -> NodeId#0.3.2 부터since 0.3.2소스source

자기 노드 핸들.

Own node handle.

반환ReturnsNodeId 자기 노드 핸들.Own node handle.

메서드methodpub fn get_node(&self) -> &WorldNode#0.3.2 부터since 0.3.2소스source

자기 노드. (지금 불리는 컴포넌트만 빠져 있고, 같은 노드의 다른 컴포넌트는 get_component 로 찾는다)

Own node. (only the component being called is out of it, other components on the same node are found with get_component)

반환Returns&WorldNode 자기 노드. (지금 불리는 컴포넌트는 빠져 있다)Own node. (the component being called is out of it)

메서드methodpub fn get_node_mut(&mut self) -> &mut WorldNode#0.3.2 부터since 0.3.2소스source

자기 노드. (변경용)

Own node. (mutable)

반환Returns&mut WorldNode 자기 노드. (변경용, 지금 불리는 컴포넌트는 빠져 있다)Own node. (mutable, the component being called is out of it)

메서드methodpub fn get_transform(&self) -> &NodeTransform#0.3.2 부터since 0.3.2소스source

자기 노드 트랜스폼.

Own node transform.

반환Returns&NodeTransform 자기 노드의 트랜스폼.The own node's transform.

메서드methodpub fn get_transform_mut(&mut self) -> &mut NodeTransform#0.3.2 부터since 0.3.2소스source

자기 노드 트랜스폼. (변경용)

Own node transform. (mutable)

반환Returns&mut NodeTransform 자기 노드의 트랜스폼. (변경용)The own node's transform. (mutable)

메서드methodpub fn get_node_tree(&self) -> &NodeTree#0.3.2 부터since 0.3.2소스source

트리 전체.

The whole tree.

반환Returns&NodeTree 트리 전체.The whole tree.

메서드methodpub fn get_node_tree_mut(&mut self) -> &mut NodeTree#0.3.2 부터since 0.3.2소스source

트리 전체. (변경용. 다른 노드를 바꾸거나 만들고 지울 때)

The whole tree. (mutable. For changing, creating or destroying other nodes)

반환Returns&mut NodeTree 트리 전체. (변경용, 도는 중에 지운 노드는 다 돈 뒤에 지워진다)The whole tree. (mutable, nodes destroyed during the iteration are destroyed after it finishes)

메서드methodpub fn get_engine(&self) -> &'a Engine#0.3.2 부터since 0.3.2소스source

엔진. (입력, 시간, 뷰)

Engine. (input, time, view)

반환Returns&'a Engine 엔진.Engine.

메서드methodpub fn with_component_mut<T: Component + 'static, R>(&mut self, node_id: NodeId, action: impl FnOnce(&mut T, &mut ComponentContext) -> R) -> Option<R>#0.3.2 부터since 0.3.2소스source

다른 노드(또는 자기 노드)의 T 컴포넌트를 그 노드의 문맥과 함께 부르기. (없거나 지금 꺼내져 있으면 None)

  • 위젯 안의 행 버튼이 위젯 본체를 부를 때 쓴다: context.with_component_mut::<UIDropdown, _>(dropdown_id, |dropdown, dropdown_context| ...)

Calls another node's (or its own node's) T component together with that node's context. (None if missing or currently taken out)

  • Used when a row button inside a widget calls the widget body: context.with_component_mut::<UIDropdown, _>(dropdown_id, |dropdown, dropdown_context| ...)
node_idNodeId
T 컴포넌트가 붙은 노드.Node the T component is attached to.
actionimpl FnOnce(&mut T, &mut ComponentContext) -> R
꺼낸 컴포넌트와 그 노드의 문맥을 받아 부를 함수.Function called with the taken-out component and that node's context.

반환ReturnsOption<R> action 이 돌려준 값. 노드가 없거나, T 컴포넌트가 없거나, 지금 꺼내져 있으면 None.The value action returned. None if the node is missing, has no T component, or it is currently taken out.

예제Example버튼 노드의 컴포넌트가 다른 노드의 셈 컴포넌트를 부르기A button node's component calls a counter component on another node
use vanilla::{Component, ComponentBase, ComponentContext, Engine, EngineConfiguration, NodeId, NodeTree};

struct Counter {
	component_base: ComponentBase,
	count: u32,
}

#[vanilla::reflect]
impl Counter {}

#[vanilla::reflect]
impl Component for Counter {
}

struct Clicker {
	component_base: ComponentBase,
	counter_id: NodeId,
}

#[vanilla::reflect]
impl Clicker {}

#[vanilla::reflect]
impl Component for Clicker {
	fn tick(&mut self, context: &mut ComponentContext, _time_delta: f64) {
		context.with_component_mut::<Counter, _>(self.counter_id, |counter, _counter_context| {
			counter.count += 1;
		});
	}
}

let engine = Engine::new(EngineConfiguration::new());
let mut node_tree = NodeTree::new();
let root_id = node_tree.get_root_id();
let counter_id = node_tree.create_child(root_id, "counter");
node_tree[counter_id].add_component(Counter {
	component_base: ComponentBase::new(),
	count: 0,
});
let clicker_id = node_tree.create_child(root_id, "clicker");
node_tree[clicker_id].add_component(Clicker {
	component_base: ComponentBase::new(),
	counter_id,
});
node_tree.tick(&engine, 0.016);
assert_eq!(node_tree[counter_id].get_component::<Counter>().expect("counter").count, 1);

TouchKindenum traits Clone, Copy, Debug, PartialEq, Eq

소스source

터치 종류. (NodeTree::dispatch_touch 가 컴포넌트의 어느 함수를 부를지)

Touch kind. (which component function NodeTree::dispatch_touch calls)

이름Name설명Description
Press눌림. (Component::touch_press)Press. (Component::touch_press)
Moved이동. (Component::touch_move)Move. (Component::touch_move)
Release뗌. (Component::touch_release)Release. (Component::touch_release)
Cancel취소. (Component::touch_cancel)Cancel. (Component::touch_cancel)