vanilladocs
vanillapunch.com
API / graphics3d/fbxloader

graphics3d/fbxloader

FBX 로더. (원본 graphics3d/fbxloader.js)

  • 바이너리 FBX → GL 무관 중간 표현(FbxSceneData). 저수준 노드/프로퍼티 파싱 후 오브젝트/커넥션 그래프를 해석해 노드 계층 / 스키닝 메시 / 머티리얼 / 임베디드 텍스처 / 골격 애니메이션을 뽑는다. 결과는 SkinnedModel 이 GL 리소스로 소비한다.
  • 원본처럼 순수 파서다. GL 이나 셰이딩을 모르고, wasm32 에서도 돈다. 압축 배열(deflate, zlib 머리)은 flate2(순수 러스트)로 푼다.
  • 원본과 다른 것:
  • 원본은 async 다. (압축 배열을 브라우저 DecompressionStream 으로 풀어서다) 러스트 판은 flate2 로 그 자리에서 끝난다. 원본 loadFromUrl(url) 의 Promise 는 ImageAsset 처럼 받기 손잡이(FbxLoadHandle)다. load_from_url(엔진, 애셋 경로)이 엔진의 애셋 받기 (데스크탑은 애셋 폴더 후보에서 읽고, 웹은 asset_base_url 에서 fetch)로 바이트를 부탁하고, 다 받으면 get_scene_data 가 파싱한 결과를 돌려준다. 손잡이는 그대로 await 할 수 있다. (엔진 작업 안에서 FbxLoader::load_from_url(engine, 경로).await 가 원본 await FbxLoader.loadFromUrl(url) 처럼 파싱 결과를 낸다)
  • 64비트 정수: 원본은 오브젝트 id 처럼 하나로 든 값이 2^53 을 넘으면 BigInt 로 든다. 러스트 판은 i64 다. 배열(키 시간)은 원본이 Number 다.
  • 원본은 순서 있는 Map 을 쓴다. 러스트 판은 넣은 순서를 지키는 FbxObjectMap 으로 같은 순회 순서를 낸다.
  • 원본에서 만들고 쓰지 않는 objectById 와 getDataView / getFileBytes / getTextDecoder 는 옮기지 않았다.
  • 노드와 애니메이션 스택의 name 은 원본처럼 FBX 이름에서 종류 꼬리("\u{0}\u{1}Model", "\u{0}\u{1}AnimStack")를 뗀 것이다. (본 이름 맞추기도 이 이름으로 한다)

FBX loader. (the original graphics3d/fbxloader.js)

  • Binary FBX → GL independent intermediate representation (FbxSceneData). After low level node/property parsing, it interprets the object/connection graph and extracts the node hierarchy / skinned meshes / materials / embedded textures / skeletal animation. The result is consumed as GL resources by SkinnedModel.
  • Like the original, it is a pure parser. It knows nothing of GL or shading and also runs on wasm32. Compressed arrays (deflate, zlib header) are decompressed with flate2 (pure Rust).
  • Differences from the original:
  • The original is async. (because it decompresses compressed arrays with the browser's DecompressionStream) The Rust version finishes on the spot with flate2. The Promise of the original loadFromUrl(url) is a load handle (FbxLoadHandle) like ImageAsset. load_from_url(engine, asset path) asks for the bytes through the engine's asset loading (desktop reads from the asset folder candidates, the web fetches from asset_base_url), and once received, get_scene_data returns the parsed result. The handle can be awaited as is. (inside an engine task, FbxLoader::load_from_url(engine, path).await yields the parsed result like the original await FbxLoader.loadFromUrl(url))
  • 64 bit integers: the original holds single values like object ids as BigInt when they exceed 2^53. The Rust version uses i64. Arrays (key times) are Number in the original.
  • The original uses ordered Maps. The Rust version gives the same iteration order with FbxObjectMap, which keeps insertion order.
  • objectById, which the original builds but does not use, and getDataView / getFileBytes / getTextDecoder were not carried over.
  • The name of nodes and animation stacks is the FBX name with the kind tail ("\u{0}\u{1}Model", "\u{0}\u{1}AnimStack") removed, as in the original. (bone name matching also uses this name)
예제Example노드 레코드로 짠 장면을 중간 표현으로 해석Interpret a scene built from node records into the intermediate representation
use vanilla::graphics3d::fbxloader::{FbxLoader, FbxNodeRecord, FbxPropertyValue};

fn record(name: &str, properties: Vec<FbxPropertyValue>, children: Vec<FbxNodeRecord>) -> FbxNodeRecord {
	FbxNodeRecord {
		name: String::from(name),
		properties,
		children,
	}
}

let hips = record("Model", vec![FbxPropertyValue::Int64(200), FbxPropertyValue::String(String::from("Hips")), FbxPropertyValue::String(String::from("LimbNode"))], Vec::new());
let root_connection = record("C", vec![FbxPropertyValue::String(String::from("OO")), FbxPropertyValue::Int64(200), FbxPropertyValue::Int64(0)], Vec::new());
let objects = record("Objects", Vec::new(), vec![hips]);
let connections = record("Connections", Vec::new(), vec![root_connection]);
let scene_data = FbxLoader::new().interpret(&[objects, connections]).unwrap();
assert_eq!(scene_data.node_list.len(), 1);
assert!(scene_data.node_list[0].is_bone);
assert_eq!(scene_data.root_node_indices, vec![0]);
assert!(FbxLoader::new().parse(b"; FBX 7.4.0 project file").is_err());

FbxNodeRecordstruct traits Clone, Debug, PartialEq

소스source

노드 레코드. (원본 { name, properties, children })

Node record. (the original { name, properties, children })

예제Example자식과 프로퍼티 읽기Read children and properties
use vanilla::graphics3d::fbxloader::{FbxNodeRecord, FbxPropertyValue};

let vertices = FbxNodeRecord {
	name: String::from("Vertices"),
	properties: vec![FbxPropertyValue::Float64array(vec![0.0, 0.0, 0.0, 1.0, 0.0, 0.0])],
	children: Vec::new(),
};
let geometry = FbxNodeRecord {
	name: String::from("Geometry"),
	properties: vec![FbxPropertyValue::Int64(100), FbxPropertyValue::String(String::from("Plane")), FbxPropertyValue::String(String::from("Mesh"))],
	children: vec![vertices],
};
assert_eq!(geometry.get_object_id(), Some(100));
assert_eq!(geometry.get_string_property(2), "Mesh");
assert_eq!(geometry.get_string_property(0), "");
let positions = geometry.find_child("Vertices").and_then(|child| child.get_property(0)).unwrap();
assert_eq!(positions.get_array_length(), 6);
assert_eq!(positions.get_number_at(3), Some(1.0));
assert!(geometry.find_child("Normals").is_none());
필드fieldpub name: String#0.3.2 부터since 0.3.2소스source

노드 이름. (Objects, Model, Vertices 같은 것)

Node name. (like Objects, Model, Vertices)

반환ReturnsString

필드fieldpub properties: Vec<FbxPropertyValue>#0.3.2 부터since 0.3.2소스source

프로퍼티 값 목록. (파일에 적힌 차례)

List of property values. (in the order written in the file)

반환ReturnsVec<FbxPropertyValue>

필드fieldpub children: Vec<FbxNodeRecord>#0.3.2 부터since 0.3.2소스source

자식 노드 레코드 목록.

List of child node records.

반환ReturnsVec<FbxNodeRecord>

메서드methodpub fn find_child(&self, child_name: &str) -> Option<&FbxNodeRecord>#0.3.2 부터since 0.3.2소스source

이름이 같은 첫 자식 반환. (원본 children.find)

Returns the first child with the same name. (the original children.find)

child_name&str
찾을 자식 이름. (대소문자까지 같아야 한다)Name of the child to find. (must match including case)

반환ReturnsOption<&FbxNodeRecord> 이름이 같은 첫 자식. 없으면 None.The first child with the same name. None if absent.

메서드methodpub fn get_property(&self, property_index: usize) -> Option<&FbxPropertyValue>#0.3.2 부터since 0.3.2소스source

프로퍼티 반환. (없으면 None)

Returns a property. (None if missing)

property_indexusize
프로퍼티 자리. (0 부터)Property position. (from 0)

반환ReturnsOption<&FbxPropertyValue> 그 자리의 프로퍼티. 자리가 밖이면 None.The property at that position. None if the position is out of range.

메서드methodpub fn get_object_id(&self) -> Option<i64>#0.3.2 부터since 0.3.2소스source

첫 프로퍼티를 정수로 반환. (오브젝트 id)

Returns the first property as an integer. (object id)

반환ReturnsOption<i64> 첫 프로퍼티를 정수로 읽은 값. (as_integer) 프로퍼티가 없거나 정수로 읽을 수 없으면 None.The first property read as an integer. (as_integer) None if there is no property or it cannot be read as an integer.

메서드methodpub fn get_string_property(&self, property_index: usize) -> String#0.3.2 부터since 0.3.2소스source

프로퍼티를 문자열로 반환. (없거나 문자열이 아니면 빈 문자열)

Returns a property as a string. (an empty string if absent or not a string)

property_indexusize
프로퍼티 자리. (0 부터)Property position. (from 0)

반환ReturnsString 그 자리의 문자열 복사본. 자리가 밖이거나 문자열이 아니면 빈 문자열.Copy of the string at that position. An empty string if the position is out of range or it is not a string.

FbxObjectMapstruct traits Clone, Debug, Default

소스source

넣은 순서를 지키는 id 맵. (원본 Map<number, object> 자리, 순회 순서가 결과 순서를 정한다)

Id map that keeps insertion order. (in place of the original Map<number, object>, the iteration order decides the result order)

예제Example넣은 차례 그대로 순회 (같은 id 를 다시 넣으면 자리는 그대로, 값만 바뀐다)Iterate in insertion order (inserting the same id again keeps its position and changes only the value)
use vanilla::graphics3d::fbxloader::FbxObjectMap;

let mut object_map = FbxObjectMap::new();
object_map.insert(30, "skin");
object_map.insert(10, "cluster");
object_map.insert(30, "replaced");
assert_eq!(object_map.keys(), &[30, 10]);
assert_eq!(object_map.values(), &["replaced", "cluster"]);
assert_eq!(object_map.get(30), Some(&"replaced"));
assert_eq!(object_map.index_of(10), Some(1));
assert!(!object_map.contains(20));
assert_eq!(object_map.len(), 2);
생성자constructorpub fn new() -> FbxObjectMap<T>#0.3.2 부터since 0.3.2소스source

생성. (비어 있음)

Constructor. (empty)

반환ReturnsFbxObjectMap<T> 빈 맵.Empty map.

메서드methodpub fn insert(&mut self, id: i64, value: T)#0.3.2 부터since 0.3.2소스source

넣기. (원본 Map.set, 이미 있는 id 면 자리를 지키고 값만 바꾼다)

Inserts. (the original Map.set, for an existing id keeps the position and changes only the value)

idi64
오브젝트 id.Object id.
valueT
넣을 값. (이미 있는 id 면 그 자리의 값을 바꾼다)Value to insert. (for an existing id, replaces the value at that position)
메서드methodpub fn get(&self, id: i64) -> Option<&T>#0.3.2 부터since 0.3.2소스source

값 반환. (원본 Map.get)

Returns a value. (the original Map.get)

idi64
찾을 오브젝트 id.Object id to find.

반환ReturnsOption<&T> 그 id 의 값. 없으면 None.The value for that id. None if absent.

메서드methodpub fn get_mut(&mut self, id: i64) -> Option<&mut T>#0.3.2 부터since 0.3.2소스source

값 반환. (변경용)

Returns a value. (mutable)

idi64
찾을 오브젝트 id.Object id to find.

반환ReturnsOption<&mut T> 그 id 의 바꿀 수 있는 값. 없으면 None.Mutable value for that id. None if absent.

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

있는지. (원본 Map.has)

Whether it exists. (the original Map.has)

idi64
찾을 오브젝트 id.Object id to find.

반환Returnsbool 있으면 true.true if it exists.

메서드methodpub fn index_of(&self, id: i64) -> Option<usize>#0.3.2 부터since 0.3.2소스source

넣은 순서의 자리 반환. (원본 Array.from(map.keys()).index_of)

Returns the position in insertion order. (the original Array.from(map.keys()).index_of)

idi64
찾을 오브젝트 id.Object id to find.

반환ReturnsOption<usize> 처음 넣은 차례의 자리. (0 부터, keys 와 values 의 자리) 없으면 None.Position in the order it was first inserted. (from 0, the position in keys and values) None if absent.

메서드methodpub fn keys(&self) -> &[i64]#0.3.2 부터since 0.3.2소스source

id 목록 반환. (넣은 순서)

Returns the id list. (insertion order)

반환Returns&[i64] id 목록. (넣은 차례)Id list. (in insertion order)

메서드methodpub fn values(&self) -> &[T]#0.3.2 부터since 0.3.2소스source

값 목록 반환. (넣은 순서)

Returns the value list. (insertion order)

반환Returns&[T] 값 목록. (넣은 차례, keys 와 같은 자리)Value list. (in insertion order, same positions as keys)

메서드methodpub fn values_mut(&mut self) -> &mut [T]#0.3.2 부터since 0.3.2소스source

값 목록 반환. (변경용)

Returns the value list. (mutable)

반환Returns&mut [T] 바꿀 수 있는 값 목록. (넣은 차례)Mutable value list. (in insertion order)

메서드methodpub fn iter(&self) -> impl Iterator<Item = (i64, &T)>#0.3.2 부터since 0.3.2소스source

(id, 값) 순회. (넣은 순서)

Iterates (id, value). (insertion order)

반환Returnsimpl Iterator<Item = (i64, &T)> (id, 값 참조) 반복자. (넣은 차례)Iterator of (id, value reference). (in insertion order)

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

개수 반환.

Returns the count.

반환Returnsusize 넣은 id 개수.Number of inserted ids.

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

비었는지.

Whether it is empty.

반환Returnsbool 하나도 없으면 true.true if there are none.

FbxGeometrystruct traits Clone, Debug, Default

소스source

지오메트리. (삼각화 + 노멀/UV 레이어를 코너 단위로 펼친 것 + 원본 정점 매핑)

Geometry. (triangulation + normal/UV layers expanded per corner + mapping to the original vertices)

예제Example사각형 폴리곤 하나가 삼각형 두 개(코너 6개)로 펼쳐진다One quad polygon expands into two triangles (6 corners)
use vanilla::graphics3d::fbxloader::{FbxLoader, FbxNodeRecord, FbxPropertyValue};

fn record(name: &str, properties: Vec<FbxPropertyValue>, children: Vec<FbxNodeRecord>) -> FbxNodeRecord {
	FbxNodeRecord {
		name: String::from(name),
		properties,
		children,
	}
}

let geometry = record("Geometry", vec![FbxPropertyValue::Int64(100)], vec![
	record("Vertices", vec![FbxPropertyValue::Float64array(vec![0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 1.0, 1.0, 0.0, 0.0, 1.0, 0.0])], Vec::new()),
	record("PolygonVertexIndex", vec![FbxPropertyValue::Int32array(vec![0, 1, 2, -4])], Vec::new()),
]);
let objects = record("Objects", Vec::new(), vec![geometry]);
let connections = record("Connections", Vec::new(), Vec::new());
let scene_data = FbxLoader::new().interpret(&[objects, connections]).unwrap();
let geometry = scene_data.geometry_by_id.get(100).unwrap();
assert_eq!(geometry.corner_count, 6);
assert_eq!(geometry.original_vertex_count, 4);
assert_eq!(geometry.original_vertex_indices, vec![0, 1, 2, 0, 2, 3]);
assert_eq!(&geometry.positions[3..6], &[1.0, 0.0, 0.0]);
assert_eq!(geometry.normals, vec![0.0; 18]);
필드fieldpub positions: Vec<f64>#0.3.2 부터since 0.3.2소스source

코너별 위치. (코너마다 x, y, z, 삼각형 코너 차례)

Per corner positions. (x, y, z per corner, in triangle corner order)

반환ReturnsVec<f64>

필드fieldpub normals: Vec<f64>#0.3.2 부터since 0.3.2소스source

코너별 노멀. (코너마다 3개, 노멀 레이어가 없으면 0)

Per corner normals. (3 per corner, 0 if there is no normal layer)

반환ReturnsVec<f64>

필드fieldpub texture_coordinates: Vec<f64>#0.3.2 부터since 0.3.2소스source

코너별 UV. (코너마다 2개, UV 레이어가 없으면 0)

Per corner UVs. (2 per corner, 0 if there is no UV layer)

반환ReturnsVec<f64>

필드fieldpub original_vertex_indices: Vec<i32>#0.3.2 부터since 0.3.2소스source

코너마다 원본 정점 인덱스. (스킨 가중치를 코너로 펼칠 때 쓴다)

Original vertex index per corner. (used when expanding skin weights to corners)

반환ReturnsVec<i32>

필드fieldpub material_index_per_triangle: Vec<i32>#0.3.2 부터since 0.3.2소스source

삼각형마다 머티리얼 인덱스. (노드 material_ids 안의 자리, 머티리얼 레이어가 없으면 0)

Material index per triangle. (position within the node's material_ids, 0 if there is no material layer)

반환ReturnsVec<i32>

필드fieldpub corner_count: usize#0.3.2 부터since 0.3.2소스source

코너 개수. (삼각형 수 x 3)

Number of corners. (triangle count x 3)

반환Returnsusize

필드fieldpub original_vertex_count: usize#0.3.2 부터since 0.3.2소스source

원본 정점 개수. (Vertices 배열 길이 / 3)

Number of original vertices. (Vertices array length / 3)

반환Returnsusize

FbxSkinDeformerstruct traits Clone, Debug, Default

소스source

스킨 디포머. (클러스터 목록 + 붙은 지오메트리)

Skin deformer. (list of clusters + the attached geometry)

예제Example스킨이 클러스터와 지오메트리에 이어진다A skin connects to clusters and a geometry
use vanilla::graphics3d::fbxloader::{FbxLoader, FbxNodeRecord, FbxPropertyValue};

fn record(name: &str, properties: Vec<FbxPropertyValue>, children: Vec<FbxNodeRecord>) -> FbxNodeRecord {
	FbxNodeRecord {
		name: String::from(name),
		properties,
		children,
	}
}

fn connect(source_id: i64, destination_id: i64) -> FbxNodeRecord {
	record("C", vec![FbxPropertyValue::String(String::from("OO")), FbxPropertyValue::Int64(source_id), FbxPropertyValue::Int64(destination_id)], Vec::new())
}

let geometry = record("Geometry", vec![FbxPropertyValue::Int64(100)], vec![
	record("Vertices", vec![FbxPropertyValue::Float64array(vec![0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0, 0.0])], Vec::new()),
	record("PolygonVertexIndex", vec![FbxPropertyValue::Int32array(vec![0, 1, -3])], Vec::new()),
]);
let skin = record("Deformer", vec![FbxPropertyValue::Int64(300), FbxPropertyValue::String(String::from("Skin")), FbxPropertyValue::String(String::from("Skin"))], Vec::new());
let cluster = record("Deformer", vec![FbxPropertyValue::Int64(301), FbxPropertyValue::String(String::from("Cluster")), FbxPropertyValue::String(String::from("Cluster"))], Vec::new());
let objects = record("Objects", Vec::new(), vec![geometry, skin, cluster]);
let connections = record("Connections", Vec::new(), vec![connect(301, 300), connect(300, 100)]);
let scene_data = FbxLoader::new().interpret(&[objects, connections]).unwrap();
let skin_deformer = scene_data.skin_deformer_by_id.get(300).unwrap();
assert_eq!(skin_deformer.cluster_ids, vec![301]);
assert_eq!(skin_deformer.geometry_id, Some(100));
필드fieldpub cluster_ids: Vec<i64>#0.3.2 부터since 0.3.2소스source

이 스킨의 클러스터 id 목록. (커넥션 차례, 클러스터 하나가 본 하나)

List of cluster ids of this skin. (in connection order, one cluster is one bone)

반환ReturnsVec<i64>

필드fieldpub geometry_id: Option<i64>#0.3.2 부터since 0.3.2소스source

스킨이 붙은 지오메트리 id. (커넥션이 없으면 None)

Id of the geometry the skin is attached to. (None if there is no connection)

반환ReturnsOption<i64>

FbxClusterstruct traits Clone, Debug, Default

소스source

클러스터. (본별 정점 가중치 + 바인드 역행렬용 링크 변환, 행렬은 열 우선 16개)

Cluster. (per bone vertex weights + link transform for the inverse bind matrix, matrices are 16 values in column major)

예제Example클러스터의 정점 가중치와 움직이는 본Vertex weights of a cluster and the bone that moves it
use vanilla::graphics3d::fbxloader::{FbxLoader, FbxNodeRecord, FbxPropertyValue};

fn record(name: &str, properties: Vec<FbxPropertyValue>, children: Vec<FbxNodeRecord>) -> FbxNodeRecord {
	FbxNodeRecord {
		name: String::from(name),
		properties,
		children,
	}
}

let cluster = record("Deformer", vec![FbxPropertyValue::Int64(301), FbxPropertyValue::String(String::from("Cluster")), FbxPropertyValue::String(String::from("Cluster"))], vec![
	record("Indexes", vec![FbxPropertyValue::Int32array(vec![0, 2])], Vec::new()),
	record("Weights", vec![FbxPropertyValue::Float64array(vec![1.0, 0.5])], Vec::new()),
]);
let bone_connection = record("C", vec![FbxPropertyValue::String(String::from("OO")), FbxPropertyValue::Int64(200), FbxPropertyValue::Int64(301)], Vec::new());
let objects = record("Objects", Vec::new(), vec![cluster]);
let connections = record("Connections", Vec::new(), vec![bone_connection]);
let scene_data = FbxLoader::new().interpret(&[objects, connections]).unwrap();
let cluster = scene_data.cluster_by_id.get(301).unwrap();
assert_eq!(cluster.vertex_indices, vec![0, 2]);
assert_eq!(cluster.weights, vec![1.0, 0.5]);
assert_eq!(cluster.bone_node_id, Some(200));
assert!(cluster.transform_link.is_none());
필드fieldpub vertex_indices: Vec<i64>#0.3.2 부터since 0.3.2소스source

영향을 받는 원본 정점 인덱스 목록. (Indexes)

List of affected original vertex indices. (Indexes)

반환ReturnsVec<i64>

필드fieldpub weights: Vec<f64>#0.3.2 부터since 0.3.2소스source

정점마다 가중치. (Weights, vertex_indices 와 같은 자리)

Weight per vertex. (Weights, same positions as vertex_indices)

반환ReturnsVec<f64>

필드fieldpub transform: Option<Vec<f64>>#0.3.2 부터since 0.3.2소스source

클러스터 Transform 행렬. (열 우선 16개, 그대로 역바인드 행렬로 쓴다. 없으면 None)

Cluster Transform matrix. (16 values in column major, used as is as the inverse bind matrix. None if absent)

반환ReturnsOption<Vec<f64>>

필드fieldpub bone_node_id: Option<i64>#0.3.2 부터since 0.3.2소스source

이 클러스터를 움직이는 본 노드 id. (커넥션이 없으면 None)

Id of the bone node that moves this cluster. (None if there is no connection)

반환ReturnsOption<i64>

FbxVideostruct traits Clone, Debug, Default

소스source

비디오. (임베디드 이미지 바이트)

Video. (embedded image bytes)

예제Example같은 파일을 두 번 참조해 비어 있는 Content 는 먼저 나온 바이트를 나눠 든다An empty Content that references the same file twice shares the bytes that came first
use std::rc::Rc;
use vanilla::graphics3d::fbxloader::{FbxLoader, FbxNodeRecord, FbxPropertyValue};

fn record(name: &str, properties: Vec<FbxPropertyValue>, children: Vec<FbxNodeRecord>) -> FbxNodeRecord {
	FbxNodeRecord {
		name: String::from(name),
		properties,
		children,
	}
}

fn video(id: i64, file_name: &str, content_bytes: Vec<u8>) -> FbxNodeRecord {
	record("Video", vec![FbxPropertyValue::Int64(id)], vec![
		record("RelativeFilename", vec![FbxPropertyValue::String(String::from(file_name))], Vec::new()),
		record("Content", vec![FbxPropertyValue::Raw(Rc::new(content_bytes))], Vec::new()),
	])
}

let objects = record("Objects", Vec::new(), vec![video(500, "textures\\skin.png", vec![1, 2, 3]), video(501, "other/skin.png", Vec::new())]);
let connections = record("Connections", Vec::new(), Vec::new());
let scene_data = FbxLoader::new().interpret(&[objects, connections]).unwrap();
let shared_video = scene_data.video_by_id.get(501).unwrap();
assert_eq!(shared_video.filename, "other/skin.png");
assert_eq!(shared_video.content_bytes.as_deref(), Some(&vec![1, 2, 3]));
필드fieldpub content_bytes: Option<Rc<Vec<u8>>>#0.3.2 부터since 0.3.2소스source

임베디드 이미지 바이트. (Content 의 R 값, 비어 있으면 파일 이름이 같은 다른 비디오의 바이트를 나눠 든다. Content 가 없으면 None)

Embedded image bytes. (the R value of Content, if empty it shares the bytes of another video with the same file name. None if there is no Content)

반환ReturnsOption<Rc<Vec<u8>>>

필드fieldpub filename: String#0.3.2 부터since 0.3.2소스source

파일 경로. (RelativeFilename 이나 Filename, 없으면 빈 문자열)

File path. (RelativeFilename or Filename, an empty string if absent)

반환ReturnsString

FbxTexturestruct traits Clone, Debug, Default

소스source

텍스처. (비디오 연결)

Texture. (video connection)

예제Example텍스처로 이어진 비디오 찾기Find the video connected to a texture
use vanilla::graphics3d::fbxloader::{FbxLoader, FbxNodeRecord, FbxPropertyValue};

fn record(name: &str, properties: Vec<FbxPropertyValue>, children: Vec<FbxNodeRecord>) -> FbxNodeRecord {
	FbxNodeRecord {
		name: String::from(name),
		properties,
		children,
	}
}

let texture = record("Texture", vec![FbxPropertyValue::Int64(501)], vec![
	record("RelativeFilename", vec![FbxPropertyValue::String(String::from("skin.png"))], Vec::new()),
]);
let video_connection = record("C", vec![FbxPropertyValue::String(String::from("OO")), FbxPropertyValue::Int64(500), FbxPropertyValue::Int64(501)], Vec::new());
let objects = record("Objects", Vec::new(), vec![texture]);
let connections = record("Connections", Vec::new(), vec![video_connection]);
let scene_data = FbxLoader::new().interpret(&[objects, connections]).unwrap();
let texture = scene_data.texture_by_id.get(501).unwrap();
assert_eq!(texture.filename, "skin.png");
assert_eq!(texture.video_id, Some(500));
필드fieldpub video_id: Option<i64>#0.3.2 부터since 0.3.2소스source

이 텍스처로 이어진 비디오 id. (커넥션이 없으면 None)

Id of the video connected to this texture. (None if there is no connection)

반환ReturnsOption<i64>

필드fieldpub filename: String#0.3.2 부터since 0.3.2소스source

파일 경로. (RelativeFilename 이나 FileName, 없으면 빈 문자열)

File path. (RelativeFilename or FileName, an empty string if absent)

반환ReturnsString

FbxMaterialstruct traits Clone, Debug

소스source

머티리얼. (phong 색상/광택 + 슬롯별 텍스처 id)

Material. (phong color/shininess + texture ids per slot)

예제ExampleProperties70 의 색과 OP 커넥션의 텍스처 슬롯Colors from Properties70 and texture slots from OP connections
use vanilla::graphics3d::fbxloader::{FbxLoader, FbxNodeRecord, FbxPropertyValue};

fn record(name: &str, properties: Vec<FbxPropertyValue>, children: Vec<FbxNodeRecord>) -> FbxNodeRecord {
	FbxNodeRecord {
		name: String::from(name),
		properties,
		children,
	}
}

fn text(value: &str) -> FbxPropertyValue {
	FbxPropertyValue::String(String::from(value))
}

let diffuse_record = record("P", vec![text("DiffuseColor"), text("Color"), text(""), text("A"), FbxPropertyValue::Float64(0.8), FbxPropertyValue::Float64(0.2), FbxPropertyValue::Float64(0.1)], Vec::new());
let material = record("Material", vec![FbxPropertyValue::Int64(600)], vec![record("Properties70", Vec::new(), vec![diffuse_record])]);
let texture = record("Texture", vec![FbxPropertyValue::Int64(501)], Vec::new());
let slot_connection = record("C", vec![text("OP"), FbxPropertyValue::Int64(501), FbxPropertyValue::Int64(600), text("DiffuseColor")], Vec::new());
let objects = record("Objects", Vec::new(), vec![material, texture]);
let connections = record("Connections", Vec::new(), vec![slot_connection]);
let scene_data = FbxLoader::new().interpret(&[objects, connections]).unwrap();
let material = scene_data.material_by_id.get(600).unwrap();
assert_eq!(material.diffuse_color, [0.8, 0.2, 0.1]);
assert_eq!(material.shininess, 20.0);
assert_eq!(material.diffuse_texture_id, Some(501));
assert_eq!(material.normal_texture_id, None);
필드fieldpub name: String#0.4.0 부터since 0.4.0소스source

머티리얼 이름. (FBX 이름에서 종류 꼬리를 뗀 것, 없으면 빈 문자열)

Material name. (The FBX name with the type suffix removed, an empty string if none)

반환ReturnsString

필드fieldpub diffuse_color: [f64; 3]#0.3.2 부터since 0.3.2소스source

난반사 색. (RGB, DiffuseColor 나 Diffuse, 없으면 1, 1, 1)

Diffuse color. (RGB, DiffuseColor or Diffuse, 1, 1, 1 if absent)

반환Returns[f64; 3]

필드fieldpub specular_color: [f64; 3]#0.3.2 부터since 0.3.2소스source

정반사 색. (RGB, SpecularColor 나 Specular, 없으면 0.5, 0.5, 0.5)

Specular color. (RGB, SpecularColor or Specular, 0.5, 0.5, 0.5 if absent)

반환Returns[f64; 3]

필드fieldpub shininess: f64#0.3.2 부터since 0.3.2소스source

광택 지수. (Shininess 나 ShininessExponent, 없으면 20)

Shininess exponent. (Shininess or ShininessExponent, 20 if absent)

반환Returnsf64

필드fieldpub diffuse_texture_id: Option<i64>#0.3.2 부터since 0.3.2소스source

난반사 텍스처 id. (OP 커넥션 DiffuseColor, 없으면 None)

Diffuse texture id. (OP connection DiffuseColor, None if absent)

반환ReturnsOption<i64>

필드fieldpub normal_texture_id: Option<i64>#0.3.2 부터since 0.3.2소스source

노멀 맵 텍스처 id. (OP 커넥션 NormalMap 이나 Bump, 없으면 None)

Normal map texture id. (OP connection NormalMap or Bump, None if absent)

반환ReturnsOption<i64>

필드fieldpub specular_texture_id: Option<i64>#0.3.2 부터since 0.3.2소스source

정반사 텍스처 id. (OP 커넥션 SpecularColor 나 SpecularFactor, 없으면 None)

Specular texture id. (OP connection SpecularColor or SpecularFactor, None if absent)

반환ReturnsOption<i64>

필드fieldpub gloss_texture_id: Option<i64>#0.3.2 부터since 0.3.2소스source

광택 텍스처 id. (OP 커넥션 Shininess 나 ShininessExponent, 없으면 None)

Shininess texture id. (OP connection Shininess or ShininessExponent, None if absent)

반환ReturnsOption<i64>

필드fieldpub opacity_texture_id: Option<i64>#0.3.2 부터since 0.3.2소스source

불투명도 텍스처 id. (OP 커넥션 TransparentColor 나 TransparencyFactor, 없으면 None)

Opacity texture id. (OP connection TransparentColor or TransparencyFactor, None if absent)

반환ReturnsOption<i64>

FbxNodestruct traits Clone, Debug

소스source

모델 노드. (계층 + 로컬 변환(오일러 도) + 지오메트리/스킨/머티리얼 소속)

  • name 은 원본처럼 FBX 이름에서 종류 꼬리를 뗀 것이다. ("Hips\u{0}\u{1}Model" 은 "Hips", 본 이름 매칭도 이 이름으로 한다)

Model node. (hierarchy + local transform (Euler degrees) + geometry/skin/material membership)

  • name is the FBX name with the kind tail removed, as in the original. ("Hips\u{0}\u{1}Model" becomes "Hips", bone name matching also uses this name)
예제Example루트 본 아래 자식 본 하나와 로컬 이동One child bone under the root bone and a local translation
use vanilla::graphics3d::fbxloader::{FbxLoader, FbxNodeRecord, FbxPropertyValue};

fn record(name: &str, properties: Vec<FbxPropertyValue>, children: Vec<FbxNodeRecord>) -> FbxNodeRecord {
	FbxNodeRecord {
		name: String::from(name),
		properties,
		children,
	}
}

fn text(value: &str) -> FbxPropertyValue {
	FbxPropertyValue::String(String::from(value))
}

fn connect(source_id: i64, destination_id: i64) -> FbxNodeRecord {
	record("C", vec![text("OO"), FbxPropertyValue::Int64(source_id), FbxPropertyValue::Int64(destination_id)], Vec::new())
}

let translation_record = record("P", vec![text("Lcl Translation"), text("Lcl Translation"), text(""), text("A"), FbxPropertyValue::Float64(0.0), FbxPropertyValue::Float64(10.0), FbxPropertyValue::Float64(0.0)], Vec::new());
let hips = record("Model", vec![FbxPropertyValue::Int64(200), text("Hips"), text("LimbNode")], Vec::new());
let spine = record("Model", vec![FbxPropertyValue::Int64(201), text("Spine"), text("LimbNode")], vec![record("Properties70", Vec::new(), vec![translation_record])]);
let objects = record("Objects", Vec::new(), vec![hips, spine]);
let connections = record("Connections", Vec::new(), vec![connect(200, 0), connect(201, 200)]);
let scene_data = FbxLoader::new().interpret(&[objects, connections]).unwrap();
assert_eq!(scene_data.root_node_indices, vec![0]);
assert_eq!(scene_data.node_list[0].child_indices, vec![1]);
let spine = &scene_data.node_list[1];
assert_eq!(spine.parent_id, Some(200));
assert_eq!(spine.translation, [0.0, 10.0, 0.0]);
assert_eq!(spine.scale, [1.0, 1.0, 1.0]);
필드fieldpub id: i64#0.3.2 부터since 0.3.2소스source

오브젝트 id.

Object id.

반환Returnsi64

필드fieldpub name: String#0.3.2 부터since 0.3.2소스source

FBX 이름. (Model 의 두 번째 프로퍼티에서 종류 꼬리 "\u{0}\u{1}Model" 을 뗀 것)

FBX name. (the second property of Model with the kind tail "\u{0}\u{1}Model" removed)

반환ReturnsString

필드fieldpub is_bone: bool#0.3.2 부터since 0.3.2소스source

본인지. (Model 의 세 번째 프로퍼티가 LimbNode 면 true)

Whether it is a bone. (true if the third property of Model is LimbNode)

반환Returnsbool

필드fieldpub translation: [f64; 3]#0.3.2 부터since 0.3.2소스source

로컬 이동. (Lcl Translation, 없으면 0, 0, 0)

Local translation. (Lcl Translation, 0, 0, 0 if absent)

반환Returns[f64; 3]

필드fieldpub rotation_euler_degrees: [f64; 3]#0.3.2 부터since 0.3.2소스source

로컬 회전. (Lcl Rotation, X, Y, Z 오일러 각 도, 없으면 0, 0, 0)

Local rotation. (Lcl Rotation, X, Y, Z Euler angles in degrees, 0, 0, 0 if absent)

반환Returns[f64; 3]

필드fieldpub pre_rotation_degrees: [f64; 3]#0.3.2 부터since 0.3.2소스source

사전 회전. (PreRotation, 오일러 각 도, SkinnedModel 이 로컬 회전 앞에 곱한다. 없으면 0, 0, 0)

Pre-rotation. (PreRotation, Euler angles in degrees, SkinnedModel multiplies it before the local rotation. 0, 0, 0 if absent)

반환Returns[f64; 3]

필드fieldpub scale: [f64; 3]#0.3.2 부터since 0.3.2소스source

로컬 크기. (Lcl Scaling, 없으면 1, 1, 1)

Local scale. (Lcl Scaling, 1, 1, 1 if absent)

반환Returns[f64; 3]

필드fieldpub geometry_id: Option<i64>#0.3.2 부터since 0.3.2소스source

이 노드가 가진 지오메트리 id. (없으면 None)

Id of the geometry this node has. (None if absent)

반환ReturnsOption<i64>

필드fieldpub skin_id: Option<i64>#0.3.2 부터since 0.3.2소스source

이 노드의 지오메트리에 붙은 스킨 id. (없으면 None)

Id of the skin attached to this node's geometry. (None if absent)

반환ReturnsOption<i64>

필드fieldpub material_ids: Vec<i64>#0.3.2 부터since 0.3.2소스source

이 노드에 이어진 머티리얼 id 목록. (커넥션 차례, 지오메트리의 머티리얼 인덱스가 이 목록의 자리다)

List of material ids connected to this node. (in connection order, the geometry's material indices are positions in this list)

반환ReturnsVec<i64>

필드fieldpub child_indices: Vec<usize>#0.3.2 부터since 0.3.2소스source

자식 노드 인덱스 목록. (node_list 안의 자리)

List of child node indices. (positions within node_list)

반환ReturnsVec<usize>

필드fieldpub parent_id: Option<i64>#0.3.2 부터since 0.3.2소스source

부모 노드 id. (루트면 None)

Parent node id. (None for a root)

반환ReturnsOption<i64>

FbxAnimationChannelstruct traits Clone, Debug

소스source

애니메이션 채널. (노드 인덱스 + 경로 + 키 시간(초) + 값, 회전은 오일러 도 3성분)

Animation channel. (node index + path + key times (seconds) + values, rotation is 3 Euler degree components)

예제Example채널의 키를 하나씩 읽기 (키마다 X, Y, Z 3개)Read the channel's keys one at a time (X, Y, Z, 3 per key)
use vanilla::AnimationPath;
use vanilla::graphics3d::fbxloader::FbxAnimationChannel;

let channel = FbxAnimationChannel {
	node_index: 0,
	path: AnimationPath::Translation,
	times: vec![0.0, 1.0],
	values: vec![0.0, 1.0, 0.0, 0.0, 3.0, 0.0],
};
for (key_index, key_time) in channel.times.iter().enumerate() {
	let key_value = &channel.values[key_index * 3..key_index * 3 + 3];
	assert_eq!(key_value[1], 1.0 + 2.0 * key_time);
}
필드fieldpub node_index: usize#0.3.2 부터since 0.3.2소스source

대상 노드 인덱스. (node_list 안의 자리)

Target node index. (position within node_list)

반환Returnsusize

필드fieldpub path: AnimationPath#0.3.2 부터since 0.3.2소스source

채널 경로. (Translation, Rotation, Scale 가운데 하나)

Channel path. (one of Translation, Rotation, Scale)

반환ReturnsAnimationPath

필드fieldpub times: Vec<f64>#0.3.2 부터since 0.3.2소스source

키 시간 목록. (초, 오름차순, X, Y, Z 커브 키 시간의 합집합)

List of key times. (seconds, ascending, the union of the X, Y, Z curve key times)

반환ReturnsVec<f64>

필드fieldpub values: Vec<f64>#0.3.2 부터since 0.3.2소스source

키마다 X, Y, Z 값 3개. (회전은 오일러 각 도, 커브가 없는 축은 0, 그 축의 키가 없는 시간은 선형 보간한 값)

3 values X, Y, Z per key. (rotation is Euler angles in degrees, 0 for an axis without a curve, a linearly interpolated value at times without a key on that axis)

반환ReturnsVec<f64>

FbxAnimationstruct traits Clone, Debug

소스source

애니메이션. (스택 하나)

Animation. (one stack)

예제Example스택, 레이어, 커브노드, 커브를 잇고 Y 이동 채널 하나를 얻는다Connect a stack, layer, curve node and curve and get one Y translation channel
use vanilla::AnimationPath;
use vanilla::graphics3d::fbxloader::{FbxLoader, FbxNodeRecord, FbxPropertyValue, FBX_TIME_UNIT};

fn record(name: &str, properties: Vec<FbxPropertyValue>, children: Vec<FbxNodeRecord>) -> FbxNodeRecord {
	FbxNodeRecord {
		name: String::from(name),
		properties,
		children,
	}
}

fn text(value: &str) -> FbxPropertyValue {
	FbxPropertyValue::String(String::from(value))
}

fn connect(connection_type: &str, source_id: i64, destination_id: i64, property_name: &str) -> FbxNodeRecord {
	record("C", vec![text(connection_type), FbxPropertyValue::Int64(source_id), FbxPropertyValue::Int64(destination_id), text(property_name)], Vec::new())
}

let curve = record("AnimationCurve", vec![FbxPropertyValue::Int64(403)], vec![
	record("KeyTime", vec![FbxPropertyValue::Int64array(vec![0, FBX_TIME_UNIT as i64])], Vec::new()),
	record("KeyValueFloat", vec![FbxPropertyValue::Float32array(vec![1.0, 3.0])], Vec::new()),
]);
let objects = record("Objects", Vec::new(), vec![
	record("Model", vec![FbxPropertyValue::Int64(200), text("Hips"), text("LimbNode")], Vec::new()),
	record("AnimationStack", vec![FbxPropertyValue::Int64(400), text("Walk")], Vec::new()),
	record("AnimationLayer", vec![FbxPropertyValue::Int64(401)], Vec::new()),
	record("AnimationCurveNode", vec![FbxPropertyValue::Int64(402), text("T")], Vec::new()),
	curve,
]);
let connections = record("Connections", Vec::new(), vec![
	connect("OO", 401, 400, ""),
	connect("OO", 402, 401, ""),
	connect("OP", 402, 200, "Lcl Translation"),
	connect("OP", 403, 402, "d|Y"),
]);
let scene_data = FbxLoader::new().interpret(&[objects, connections]).unwrap();
let animation = &scene_data.animation_list[0];
assert_eq!(animation.name, "Walk");
assert_eq!(animation.duration, 1.0);
let channel = &animation.channels[0];
assert_eq!(channel.path, AnimationPath::Translation);
assert_eq!(channel.times, vec![0.0, 1.0]);
assert_eq!(channel.values, vec![0.0, 1.0, 0.0, 0.0, 3.0, 0.0]);
필드fieldpub name: String#0.3.2 부터since 0.3.2소스source

스택 이름. (AnimationStack 의 두 번째 프로퍼티에서 종류 꼬리 "\u{0}\u{1}AnimStack" 을 뗀 것, "Take 001" 같은)

Stack name. (the second property of AnimationStack with the kind tail "\u{0}\u{1}AnimStack" removed, like "Take 001")

반환ReturnsString

필드fieldpub duration: f64#0.3.2 부터since 0.3.2소스source

길이. (초, 채널마다 마지막 키 시간 가운데 가장 큰 것, 채널이 없으면 0)

Length. (seconds, the largest last key time among the channels, 0 when there are no channels)

반환Returnsf64

필드fieldpub channels: Vec<FbxAnimationChannel>#0.3.2 부터since 0.3.2소스source

노드와 경로마다 채널 목록. (스택에 든 레이어의 커브노드만)

Channel list per node and path. (only the curve nodes of the layers in the stack)

반환ReturnsVec<FbxAnimationChannel>

FbxSceneDatastruct traits Clone, Debug, Default

소스source

중간 표현. (원본 sceneData)

Intermediate representation. (the original sceneData)

예제Example이름 앞부분으로 노드 찾기 (FBX 이름은 뒤에 클래스 이름이 붙어 있을 수 있다)Find a node by name prefix (FBX names may have a class name appended)
use vanilla::graphics3d::fbxloader::FbxSceneData;

fn find_node_index(scene_data: &FbxSceneData, name_prefix: &str) -> Option<usize> {
	scene_data.node_list.iter().position(|node| node.name.starts_with(name_prefix))
}

let scene_data = FbxSceneData::default();
assert_eq!(find_node_index(&scene_data, "mixamorig:Hips"), None);
assert!(scene_data.root_node_indices.is_empty());
필드fieldpub node_list: Vec<FbxNode>#0.3.2 부터since 0.3.2소스source

모델 노드 목록. (Objects 의 Model 차례)

Model node list. (in the order of Model entries in Objects)

반환ReturnsVec<FbxNode>

필드fieldpub node_id_to_index: HashMap<i64, usize>#0.3.2 부터since 0.3.2소스source

노드 id 에서 node_list 자리로 가는 표.

Table from node id to position in node_list.

반환ReturnsHashMap<i64, usize>

필드fieldpub root_node_indices: Vec<usize>#0.3.2 부터since 0.3.2소스source

루트 노드 인덱스 목록. (id 0 에 이어진 노드, 커넥션 차례)

Root node index list. (nodes connected to id 0, in connection order)

반환ReturnsVec<usize>

필드fieldpub geometry_by_id: FbxObjectMap<FbxGeometry>#0.3.2 부터since 0.3.2소스source

지오메트리. (id 로 찾는다, Objects 차례)

Geometries. (looked up by id, in Objects order)

반환ReturnsFbxObjectMap<FbxGeometry>

필드fieldpub skin_deformer_by_id: FbxObjectMap<FbxSkinDeformer>#0.3.2 부터since 0.3.2소스source

스킨 디포머. (id 로 찾는다)

Skin deformers. (looked up by id)

반환ReturnsFbxObjectMap<FbxSkinDeformer>

필드fieldpub cluster_by_id: FbxObjectMap<FbxCluster>#0.3.2 부터since 0.3.2소스source

클러스터. (id 로 찾는다)

Clusters. (looked up by id)

반환ReturnsFbxObjectMap<FbxCluster>

필드fieldpub material_by_id: FbxObjectMap<FbxMaterial>#0.3.2 부터since 0.3.2소스source

머티리얼. (id 로 찾는다, 넣은 차례의 자리가 SkinnedModel 머티리얼 서술의 자리다)

Materials. (looked up by id, the insertion position is the position in the SkinnedModel material descriptions)

반환ReturnsFbxObjectMap<FbxMaterial>

필드fieldpub texture_by_id: FbxObjectMap<FbxTexture>#0.3.2 부터since 0.3.2소스source

텍스처. (id 로 찾는다)

Textures. (looked up by id)

반환ReturnsFbxObjectMap<FbxTexture>

필드fieldpub video_by_id: FbxObjectMap<FbxVideo>#0.3.2 부터since 0.3.2소스source

비디오. (id 로 찾는다, 임베디드 이미지)

Videos. (looked up by id, embedded images)

반환ReturnsFbxObjectMap<FbxVideo>

필드fieldpub animation_list: Vec<FbxAnimation>#0.3.2 부터since 0.3.2소스source

애니메이션 목록. (AnimationStack 마다 하나, Objects 차례)

Animation list. (one per AnimationStack, in Objects order)

반환ReturnsVec<FbxAnimation>

FbxLoadHandlestruct traits Clone, Debug, IntoFuture

소스source

FBX 받기 손잡이. (FbxLoader::load_from_url 이 돌려준다. 원본 loadFromUrl 의 Promise 자리)

  • 씬은 get_load_handle 을 SceneBase::track_load_handle 로 맡겨 다 받을 때까지 initialize 를 미룰 수 있다.

FBX load handle. (returned by FbxLoader::load_from_url, stands in for the Promise of the original loadFromUrl)

  • A scene can hand get_load_handle to SceneBase::track_load_handle to defer initialize until loading finishes.
예제Example씬이 받기를 맡기고 initialize 에서 결과 읽기Let the scene track the load and read the result in initialize
use vanilla::{Engine, FbxLoadHandle, Scene, SceneBase};
use vanilla::graphics3d::fbxloader::FbxLoader;

struct AnimationScene {
	scene_base: SceneBase,
	fbx_load_handle: Option<FbxLoadHandle>,
}

impl Scene for AnimationScene {
	fn get_scene_base(&self) -> &SceneBase {
		&self.scene_base
	}

	fn get_scene_base_mut(&mut self) -> &mut SceneBase {
		&mut self.scene_base
	}

	fn load(&mut self, engine: &Engine) {
		let fbx_load_handle = FbxLoader::load_from_url(engine, "anims/walk.fbx");
		self.scene_base.track_load_handle(fbx_load_handle.get_load_handle());
		self.fbx_load_handle = Some(fbx_load_handle);
	}

	fn initialize(&mut self, _engine: &Engine) {
		let scene_data_result = self.fbx_load_handle.as_ref().and_then(|fbx_load_handle| fbx_load_handle.get_scene_data());
		match scene_data_result {
			Some(Ok(scene_data)) => {
				println!("{} animations", scene_data.animation_list.len());
			}
			Some(Err(error_message)) => {
				eprintln!("{}", error_message);
			}
			None => {
			}
		}
	}
}
메서드methodpub fn get_load_handle(&self) -> &AssetLoadHandle#0.4.0 부터since 0.4.0소스source

바이트 읽기 손잡이. (씬에 맡길 때)

Byte read handle. (for handing to a scene)

반환Returns&AssetLoadHandle 바이트 읽기 손잡이. (SceneBase::track_load_handle 에 넘긴다)Byte read handle. (passed to SceneBase::track_load_handle)

메서드methodpub fn is_finished(&self) -> bool#0.4.0 부터since 0.4.0소스source

끝났는지. (받았거나 실패했거나)

Whether it has finished. (loaded or failed)

반환Returnsbool 받기가 끝났으면(받았거나 실패했으면) true.true if loading has finished (loaded or failed).

메서드methodpub fn get_scene_data(&self) -> Option<Result<FbxSceneData, String>>#0.4.0 부터since 0.4.0소스source

파싱한 중간 표현. (받는 중이면 None, 받기나 파싱에 실패하면 Err. 원본 문구 "FbxLoader load failed: url")

  • 끝난 뒤에는 부를 때마다 받은 바이트를 다시 파싱한다. 한 번 받아 두고 쓴다.

Parsed intermediate representation. (None while loading, Err when loading or parsing fails. The original message is "FbxLoader load failed: url")

  • Once finished, every call parses the loaded bytes again. Call it once and keep the result.

반환ReturnsOption<Result<FbxSceneData, String>> 받는 중이면 None. 끝났으면 파싱한 중간 표현, 받기에 실패하면 Err("FbxLoader load failed: 경로"), 파싱에 실패하면 FbxLoader::parse 의 Err.None while loading. When finished, the parsed intermediate representation, Err("FbxLoader load failed: path") when loading fails, and the Err of FbxLoader::parse when parsing fails.

예제Example없는 파일은 Err 로 끝난다 (데스크탑은 부탁한 자리에서 바로 끝난다)A missing file ends with Err (on desktop it finishes right where it is requested)
use vanilla::{Engine, EngineConfiguration};
use vanilla::graphics3d::fbxloader::FbxLoader;

let engine = Engine::new(EngineConfiguration::new());
let fbx_load_handle = FbxLoader::load_from_url(&engine, "missing_model.fbx");
assert!(fbx_load_handle.is_finished());
let scene_data_result = fbx_load_handle.get_scene_data().unwrap();
assert_eq!(scene_data_result.err(), Some(String::from("FbxLoader load failed: missing_model.fbx")));

FbxLoadFuturestruct traits Clone, Debug, Future

소스source

FBX 받기를 기다리는 퓨처. (FbxLoadHandle 을 await 하면 된다. 다 받으면 파싱한 결과, 원본 loadFromUrl 의 Promise 가 풀린 값)

Future that waits for the FBX load. (just await FbxLoadHandle. When loaded, the parsed result, the resolved value of the original loadFromUrl Promise)

예제Example엔진 작업 안에서 손잡이를 퓨처로 바꿔 awaitTurn the handle into a future and await it inside an engine task
use std::future::IntoFuture;
use vanilla::{Engine, FbxLoadFuture};
use vanilla::graphics3d::fbxloader::FbxLoader;

fn start_loading(engine: &Engine) {
	let fbx_load_future: FbxLoadFuture = FbxLoader::load_from_url(engine, "anims/walk.fbx").into_future();
	engine.spawn_task(move |_engine_context| async move {
		match fbx_load_future.await {
			Ok(scene_data) => {
				println!("{} nodes", scene_data.node_list.len());
			}
			Err(error_message) => {
				eprintln!("{}", error_message);
			}
		}
	});
}

FbxLoaderstruct traits Default

소스source

FBX 로더.

  • 바이너리 FBX 만 읽는다. (ASCII FBX 는 Err)

FBX loader.

  • Reads binary FBX only. (ASCII FBX is Err)
예제Example바이너리 FBX 가 아닌 바이트는 ErrBytes that are not binary FBX are Err
use vanilla::graphics3d::fbxloader::FbxLoader;

let mut fbx_loader = FbxLoader::new();
let parse_result = fbx_loader.parse(b"; FBX 7.4.0 project file");
assert_eq!(parse_result.err(), Some(String::from("FbxLoader: not a binary FBX file.")));
생성자constructorpub fn new() -> FbxLoader#0.3.2 부터since 0.3.2소스source

생성.

Constructor.

반환ReturnsFbxLoader 새 로더. (파싱할 때마다 파일 처음부터 읽는다)New loader. (reads the file from the start on every parse)

정적staticpub fn load_from_url(engine: &Engine, url: &str) -> FbxLoadHandle#0.4.0 부터since 0.4.0소스source

애셋 경로(웹은 URL)로부터 받기 부탁. (원본 정적 loadFromUrl, 다 받으면 손잡이의 get_scene_data 가 파싱한다)

Requests a load from an asset path (URL on the web). (the original static loadFromUrl, once loaded the handle's get_scene_data parses it)

engine&Engine
바이트를 부탁할 엔진.Engine to ask for the bytes.
url&str
FBX 애셋 경로. (데스크탑은 애셋 폴더 후보 기준 상대 경로, 웹은 asset_base_url 기준 주소)FBX asset path. (on desktop a path relative to the asset folder candidates, on the web an address relative to asset_base_url)

반환ReturnsFbxLoadHandle 받기 손잡이. (데스크탑은 그 자리에서 읽어 이미 끝나 있다)Load handle. (on desktop it is read on the spot and already finished)

정적staticpub fn read_version(file_bytes: &[u8]) -> Result<u32, String>#0.3.2 부터since 0.3.2소스source

FBX 버전 반환. (머리의 버전 번호, 7400 = 7.4)

Returns the FBX version. (version number in the header, 7400 = 7.4)

file_bytes&[u8]
FBX 파일 바이트. (머리가 맞는지는 보지 않는다)FBX file bytes. (does not check whether the header is valid)

반환ReturnsResult<u32, String> 버전 번호. (바이트 23 ~ 26 의 리틀 엔디언 u32) 27 바이트보다 짧으면 Err.Version number. (little-endian u32 at bytes 23 ~ 26) Err if shorter than 27 bytes.

정적staticpub fn inflate(compressed_bytes: &[u8], expected_byte_length: usize) -> Result<Vec<u8>, String>#0.3.2 부터since 0.3.2소스source

deflate 압축 해제. (zlib 머리가 붙은 deflate, 원본 DecompressionStream("deflate"))

Decompresses deflate. (deflate with a zlib header, the original DecompressionStream("deflate"))

compressed_bytes&[u8]
zlib 머리가 붙은 deflate 바이트.Deflate bytes with a zlib header.
expected_byte_lengthusize
풀린 크기 예상. (미리 잡을 용량일 뿐, 풀린 길이와 맞는지 보지 않는다)Expected decompressed size. (only the capacity to reserve, not checked against the decompressed length)

반환ReturnsResult<Vec<u8>, String> 풀린 바이트. 압축 자료가 깨졌으면 Err.Decompressed bytes. Err if the compressed data is corrupt.

예제Examplezlib 으로 누른 바이트 풀기Decompress zlib-compressed bytes
use std::io::Write;
use vanilla::graphics3d::fbxloader::FbxLoader;

let original_bytes = vec![7u8; 256];
let mut zlib_encoder = flate2::write::ZlibEncoder::new(Vec::new(), flate2::Compression::default());
zlib_encoder.write_all(&original_bytes).unwrap();
let compressed_bytes = zlib_encoder.finish().unwrap();
assert_eq!(FbxLoader::inflate(&compressed_bytes, original_bytes.len()), Ok(original_bytes));
assert!(FbxLoader::inflate(&[1, 2, 3], 3).is_err());
정적staticpub fn extract_file_name(file_path: &str) -> String#0.3.2 부터since 0.3.2소스source

파일 경로에서 파일명 추출. (윈도우/유닉스 구분자 모두 대응)

Extracts the file name from a file path. (handles both Windows/Unix separators)

file_path&str
파일 경로. (/ 와 \ 구분자 모두)File path. (both / and \ separators)

반환ReturnsString 마지막 구분자 뒤의 파일 이름. (구분자가 없으면 경로 그대로)File name after the last separator. (the path as is when there is no separator)

메서드methodpub fn parse(&mut self, file_bytes: &[u8]) -> Result<FbxSceneData, String>#0.3.2 부터since 0.3.2소스source

파싱. (바이너리 → 중간 표현)

Parse. (binary → intermediate representation)

file_bytes&[u8]
바이너리 FBX 파일 바이트 전체.All bytes of the binary FBX file.

반환ReturnsResult<FbxSceneData, String> 중간 표현. 바이너리 FBX 가 아니거나(ASCII FBX 포함), 파일이 잘렸거나, Objects 나 Connections 노드가 없으면 Err.Intermediate representation. Err if it is not binary FBX (including ASCII FBX), the file is truncated, or there is no Objects or Connections node.

메서드methodpub fn parse_node_records(&mut self, file_bytes: &[u8]) -> Result<Vec<FbxNodeRecord>, String>#0.3.2 부터since 0.3.2소스source

최상위 노드 목록 파싱. (머리 확인 + 버전별 오프셋 크기 + 노드 레코드들, 원본 parse 의 앞부분)

  • 버전 7500 부터는 64비트 오프셋으로 읽는다. 끝의 160 바이트 꼬리 앞에서 멈춘다.

Parses the top-level node list. (header check + offset size per version + node records, the first part of the original parse)

  • From version 7500 on, offsets are read as 64-bit. Stops before the 160-byte footer at the end.
file_bytes&[u8]
바이너리 FBX 파일 바이트 전체.All bytes of the binary FBX file.

반환ReturnsResult<Vec<FbxNodeRecord>, String> 최상위 노드 레코드 목록. 머리가 "Kaydara FBX Binary" 가 아니거나, 레코드가 파일 밖을 가리키거나, 모르는 프로퍼티 타입이거나, 압축 배열을 풀 수 없으면 Err.Top-level node record list. Err if the header is not "Kaydara FBX Binary", a record points outside the file, a property type is unknown, or a compressed array cannot be decompressed.

예제Example머리와 빈 Objects 노드 하나뿐인 7.4 파일A 7.4 file with only a header and one empty Objects node
use vanilla::graphics3d::fbxloader::FbxLoader;

let node_name = b"Objects";
let mut file_bytes = Vec::new();
file_bytes.extend_from_slice(b"Kaydara FBX Binary  \x00\x1a\x00");
file_bytes.extend_from_slice(&7400u32.to_le_bytes());
let node_end_offset = file_bytes.len() + 13 + node_name.len();
file_bytes.extend_from_slice(&(node_end_offset as u32).to_le_bytes());
file_bytes.extend_from_slice(&0u32.to_le_bytes());
file_bytes.extend_from_slice(&0u32.to_le_bytes());
file_bytes.push(node_name.len() as u8);
file_bytes.extend_from_slice(node_name);
file_bytes.extend_from_slice(&[0u8; 13]);
file_bytes.extend_from_slice(&[0u8; 160]);
assert_eq!(FbxLoader::read_version(&file_bytes), Ok(7400));
let top_node_list = FbxLoader::new().parse_node_records(&file_bytes).unwrap();
assert_eq!(top_node_list.len(), 1);
assert_eq!(top_node_list[0].name, "Objects");
assert!(FbxLoader::new().interpret(&top_node_list).is_err());
메서드methodpub fn interpret(&self, top_node_list: &[FbxNodeRecord]) -> Result<FbxSceneData, String>#0.3.2 부터since 0.3.2소스source

오브젝트/커넥션 그래프 해석. (중간 표현 구성)

Interprets the object/connection graph. (builds the intermediate representation)

top_node_list&[FbxNodeRecord]
최상위 노드 레코드 목록. (parse_node_records 가 돌려준 것)Top-level node record list. (what parse_node_records returned)

반환ReturnsResult<FbxSceneData, String> 중간 표현. Objects 나 Connections 노드가 없으면 Err.Intermediate representation. Err if there is no Objects or Connections node.

상수Constants

상수constantpub const FBX_TIME_UNIT: f64 = 46186158000.0#0.3.2 부터since 0.3.2소스source

FBX 시간 단위. (1초 = 46186158000 ktime)

FBX time unit. (1 second = 46186158000 ktime)

반환Returnsf64

FbxPropertyValueenum traits Clone, Debug, PartialEq

소스source

프로퍼티 값. (원본 { type, value }, 타입 코드 Y C I F D L f d l i b S R)

Property value. (the original { type, value }, type codes Y C I F D L f d l i b S R)

이름Name값Value설명Description
Int16Int16(i16)16비트 정수. (타입 코드 Y)16-bit integer. (type code Y)
BooleanBoolean(bool)참거짓. (타입 코드 C, 바이트 하나가 0 이 아니면 true)Boolean. (type code C, true if the byte is not 0)
Int32Int32(i32)32비트 정수. (타입 코드 I)32-bit integer. (type code I)
Float32Float32(f64)32비트 실수. (타입 코드 F)32-bit float. (type code F)
Float64Float64(f64)64비트 실수. (타입 코드 D)64-bit float. (type code D)
Int64Int64(i64)64비트 정수. (타입 코드 L, 오브젝트 id)64-bit integer. (type code L, object id)
Float32arrayFloat32array(Vec<f64>)32비트 실수 배열. (타입 코드 f)32-bit float array. (type code f)
Float64arrayFloat64array(Vec<f64>)64비트 실수 배열. (타입 코드 d, 정점 위치 같은 것)64-bit float array. (type code d, such as vertex positions)
Int64arrayInt64array(Vec<i64>)64비트 정수 배열. (타입 코드 l, 키 시간 같은 것)64-bit integer array. (type code l, such as key times)
Int32arrayInt32array(Vec<i32>)32비트 정수 배열. (타입 코드 i, 폴리곤 정점 인덱스 같은 것)32-bit integer array. (type code i, such as polygon vertex indices)
BooleanArrayBooleanArray(Vec<u8>)참거짓 배열. (타입 코드 b, 원소 바이트 그대로)Boolean array. (type code b, element bytes as is)
StringString(String)문자열. (타입 코드 S, UTF-8 로 읽을 수 없는 바이트는 대체 문자로 바꾼다)String. (type code S, bytes that cannot be read as UTF-8 are replaced with the replacement character)
RawRaw(Rc<Vec<u8>>)날 바이트. (타입 코드 R, 임베디드 이미지 같은 것)Raw bytes. (type code R, such as embedded images)
메서드methodpub fn get_type_code(&self) -> char#0.3.2 부터since 0.3.2소스source

타입 코드 반환. (원본 property.type)

Returns the type code. (the original property.type)

반환Returnschar 타입 코드 글자. (Y, C, I, F, D, L, f, d, l, i, b, S, R 가운데 하나)Type code character. (one of Y, C, I, F, D, L, f, d, l, i, b, S, R)

메서드methodpub fn as_number(&self) -> Option<f64>#0.3.2 부터since 0.3.2소스source

수 하나로 읽기. (스칼라 타입만, 아니면 None)

Reads as a single number. (scalar types only, otherwise None)

반환ReturnsOption<f64> 스칼라 값을 f64 로 바꾼 것. (Boolean 은 1 이나 0) 배열, 문자열, 날 바이트면 None.The scalar value converted to f64. (Boolean is 1 or 0) None for arrays, strings and raw bytes.

메서드methodpub fn as_integer(&self) -> Option<i64>#0.3.2 부터since 0.3.2소스source

정수 하나로 읽기. (오브젝트 id 같은 정수 스칼라, 아니면 None)

Reads as a single integer. (integer scalars such as object ids, otherwise None)

반환ReturnsOption<i64> 정수, 실수 스칼라를 i64 로 바꾼 것. (실수는 0 쪽으로 자른다) Boolean, 배열, 문자열, 날 바이트면 None.Integer and float scalars converted to i64. (floats are truncated toward 0) None for Boolean, arrays, strings and raw bytes.

메서드methodpub fn as_string(&self) -> Option<&str>#0.3.2 부터since 0.3.2소스source

문자열로 읽기. (S 타입만)

Reads as a string. (S type only)

반환ReturnsOption<&str> 문자열 조각. String 이 아니면 None.String slice. None if not String.

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

배열 길이 반환. (배열 타입이 아니면 0)

Returns the array length. (0 if not an array type)

반환Returnsusize 원소 개수. 배열이 아니면 0.Element count. 0 if not an array.

메서드methodpub fn get_number_at(&self, index: usize) -> Option<f64>#0.3.2 부터since 0.3.2소스source

배열 원소 하나를 수로 읽기. (배열 밖이거나 배열이 아니면 None)

Reads one array element as a number. (None if outside the array or not an array)

indexusize
원소 자리. (0 부터)Element index. (from 0)

반환ReturnsOption<f64> 그 원소를 f64 로 바꾼 것. 자리가 배열 밖이거나 배열이 아니면 None.That element converted to f64. None if the index is outside the array or it is not an array.

메서드methodpub fn get_integer_at(&self, index: usize) -> Option<i64>#0.3.2 부터since 0.3.2소스source

배열 원소 하나를 정수로 읽기. (배열 밖이거나 배열이 아니면 None)

Reads one array element as an integer. (None if outside the array or not an array)

indexusize
원소 자리. (0 부터)Element index. (from 0)

반환ReturnsOption<i64> 그 원소를 i64 로 바꾼 것. (실수는 0 쪽으로 자른다) 자리가 배열 밖이거나 배열이 아니면 None.That element converted to i64. (floats are truncated toward 0) None if the index is outside the array or it is not an array.

메서드methodpub fn to_number_list(&self) -> Vec<f64>#0.3.2 부터since 0.3.2소스source

수 목록으로 바꾸기. (숫자 배열 타입 무엇이든 f64 로, 아니면 빈 목록)

Converts to a number list. (any numeric array type to f64, otherwise an empty list)

반환ReturnsVec<f64> 모든 원소를 f64 로 담은 새 목록. 배열이 아니면 빈 목록.A new list with every element as f64. An empty list if not an array.

메서드methodpub fn to_integer_list(&self) -> Vec<i64>#0.3.2 부터since 0.3.2소스source

정수 목록으로 바꾸기. (숫자 배열 타입 무엇이든 i64 로, 아니면 빈 목록)

Converts to an integer list. (any numeric array type to i64, otherwise an empty list)

반환ReturnsVec<i64> 모든 원소를 i64 로 담은 새 목록. (실수는 0 쪽으로 자른다) 배열이 아니면 빈 목록.A new list with every element as i64. (floats are truncated toward 0) An empty list if not an array.