# graphics3d/fbxloader (vanilla-engine 0.4.0)

> https://vanillapunch.com/docs/vanilla-engine/0.4.0/api/graphics3d/fbxloader/

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

```rust
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());
```

## FbxNodeRecord (struct) (Clone, Debug, PartialEq)

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

Example: Read children and properties

```rust
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());
```

- `pub name: String` (field, since 0.3.2): Node name. (like Objects, Model, Vertices)
  - returns String
- `pub properties: Vec<FbxPropertyValue>` (field, since 0.3.2): List of property values. (in the order written in the file)
  - returns Vec<FbxPropertyValue>
- `pub children: Vec<FbxNodeRecord>` (field, since 0.3.2): List of child node records.
  - returns Vec<FbxNodeRecord>
- `pub fn find_child(&self, child_name: &str) -> Option<&FbxNodeRecord>` (method, since 0.3.2): 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)
  - returns Option<&FbxNodeRecord>: The first child with the same name. None if absent.
- `pub fn get_property(&self, property_index: usize) -> Option<&FbxPropertyValue>` (method, since 0.3.2): Returns a property. (None if missing)
  - `property_index` usize: Property position. (from 0)
  - returns Option<&FbxPropertyValue>: The property at that position. None if the position is out of range.
- `pub fn get_object_id(&self) -> Option<i64>` (method, since 0.3.2): Returns the first property as an integer. (object id)
  - returns Option<i64>: The first property read as an integer. (as_integer) None if there is no property or it cannot be read as an integer.
- `pub fn get_string_property(&self, property_index: usize) -> String` (method, since 0.3.2): Returns a property as a string. (an empty string if absent or not a string)
  - `property_index` usize: Property position. (from 0)
  - returns String: Copy of the string at that position. An empty string if the position is out of range or it is not a string.

## FbxObjectMap (struct) (Clone, Debug, Default)

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

Example: Iterate in insertion order (inserting the same id again keeps its position and changes only the value)

```rust
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);
```

- `pub fn new() -> FbxObjectMap<T>` (constructor, since 0.3.2): Constructor. (empty)
  - returns FbxObjectMap<T>: Empty map.
- `pub fn insert(&mut self, id: i64, value: T)` (method, since 0.3.2): Inserts. (the original Map.set, for an existing id keeps the position and changes only the value)
  - `id` i64: Object id.
  - `value` T: Value to insert. (for an existing id, replaces the value at that position)
- `pub fn get(&self, id: i64) -> Option<&T>` (method, since 0.3.2): Returns a value. (the original Map.get)
  - `id` i64: Object id to find.
  - returns Option<&T>: The value for that id. None if absent.
- `pub fn get_mut(&mut self, id: i64) -> Option<&mut T>` (method, since 0.3.2): Returns a value. (mutable)
  - `id` i64: Object id to find.
  - returns Option<&mut T>: Mutable value for that id. None if absent.
- `pub fn contains(&self, id: i64) -> bool` (method, since 0.3.2): Whether it exists. (the original Map.has)
  - `id` i64: Object id to find.
  - returns bool: true if it exists.
- `pub fn index_of(&self, id: i64) -> Option<usize>` (method, since 0.3.2): Returns the position in insertion order. (the original Array.from(map.keys()).index_of)
  - `id` i64: Object id to find.
  - returns Option<usize>: Position in the order it was first inserted. (from 0, the position in keys and values) None if absent.
- `pub fn keys(&self) -> &[i64]` (method, since 0.3.2): Returns the id list. (insertion order)
  - returns &[i64]: Id list. (in insertion order)
- `pub fn values(&self) -> &[T]` (method, since 0.3.2): Returns the value list. (insertion order)
  - returns &[T]: Value list. (in insertion order, same positions as keys)
- `pub fn values_mut(&mut self) -> &mut [T]` (method, since 0.3.2): Returns the value list. (mutable)
  - returns &mut [T]: Mutable value list. (in insertion order)
- `pub fn iter(&self) -> impl Iterator<Item = (i64, &T)>` (method, since 0.3.2): Iterates (id, value). (insertion order)
  - returns impl Iterator<Item = (i64, &T)>: Iterator of (id, value reference). (in insertion order)
- `pub fn len(&self) -> usize` (method, since 0.3.2): Returns the count.
  - returns usize: Number of inserted ids.
- `pub fn is_empty(&self) -> bool` (method, since 0.3.2): Whether it is empty.
  - returns bool: true if there are none.

## FbxGeometry (struct) (Clone, Debug, Default)

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

Example: One quad polygon expands into two triangles (6 corners)

```rust
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]);
```

- `pub positions: Vec<f64>` (field, since 0.3.2): Per corner positions. (x, y, z per corner, in triangle corner order)
  - returns Vec<f64>
- `pub normals: Vec<f64>` (field, since 0.3.2): Per corner normals. (3 per corner, 0 if there is no normal layer)
  - returns Vec<f64>
- `pub texture_coordinates: Vec<f64>` (field, since 0.3.2): Per corner UVs. (2 per corner, 0 if there is no UV layer)
  - returns Vec<f64>
- `pub original_vertex_indices: Vec<i32>` (field, since 0.3.2): Original vertex index per corner. (used when expanding skin weights to corners)
  - returns Vec<i32>
- `pub material_index_per_triangle: Vec<i32>` (field, since 0.3.2): Material index per triangle. (position within the node's material_ids, 0 if there is no material layer)
  - returns Vec<i32>
- `pub corner_count: usize` (field, since 0.3.2): Number of corners. (triangle count x 3)
  - returns usize
- `pub original_vertex_count: usize` (field, since 0.3.2): Number of original vertices. (Vertices array length / 3)
  - returns usize

## FbxSkinDeformer (struct) (Clone, Debug, Default)

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

Example: A skin connects to clusters and a geometry

```rust
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));
```

- `pub cluster_ids: Vec<i64>` (field, since 0.3.2): List of cluster ids of this skin. (in connection order, one cluster is one bone)
  - returns Vec<i64>
- `pub geometry_id: Option<i64>` (field, since 0.3.2): Id of the geometry the skin is attached to. (None if there is no connection)
  - returns Option<i64>

## FbxCluster (struct) (Clone, Debug, Default)

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

```rust
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());
```

- `pub vertex_indices: Vec<i64>` (field, since 0.3.2): List of affected original vertex indices. (Indexes)
  - returns Vec<i64>
- `pub weights: Vec<f64>` (field, since 0.3.2): Weight per vertex. (Weights, same positions as vertex_indices)
  - returns Vec<f64>
- `pub transform: Option<Vec<f64>>` (field, since 0.3.2): Cluster Transform matrix. (16 values in column major, used as is as the inverse bind matrix. None if absent)
  - returns Option<Vec<f64>>
- `pub transform_link: Option<Vec<f64>>` (field, since 0.3.2): The bone's bind global matrix TransformLink. (16 values in column major, its inverse is used as the inverse bind when transform is absent. None if absent)
  - returns Option<Vec<f64>>
- `pub bone_node_id: Option<i64>` (field, since 0.3.2): Id of the bone node that moves this cluster. (None if there is no connection)
  - returns Option<i64>

## FbxVideo (struct) (Clone, Debug, Default)

Video. (embedded image bytes)

Example: An empty Content that references the same file twice shares the bytes that came first

```rust
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]));
```

- `pub content_bytes: Option<Rc<Vec<u8>>>` (field, since 0.3.2): 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)
  - returns Option<Rc<Vec<u8>>>
- `pub filename: String` (field, since 0.3.2): File path. (RelativeFilename or Filename, an empty string if absent)
  - returns String

## FbxTexture (struct) (Clone, Debug, Default)

Texture. (video connection)

Example: Find the video connected to a texture

```rust
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));
```

- `pub video_id: Option<i64>` (field, since 0.3.2): Id of the video connected to this texture. (None if there is no connection)
  - returns Option<i64>
- `pub filename: String` (field, since 0.3.2): File path. (RelativeFilename or FileName, an empty string if absent)
  - returns String

## FbxMaterial (struct) (Clone, Debug)

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

Example: Colors from Properties70 and texture slots from OP connections

```rust
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);
```

- `pub name: String` (field, since 0.4.0): Material name. (The FBX name with the type suffix removed, an empty string if none)
  - returns String
- `pub diffuse_color: [f64; 3]` (field, since 0.3.2): Diffuse color. (RGB, DiffuseColor or Diffuse, 1, 1, 1 if absent)
  - returns [f64; 3]
- `pub specular_color: [f64; 3]` (field, since 0.3.2): Specular color. (RGB, SpecularColor or Specular, 0.5, 0.5, 0.5 if absent)
  - returns [f64; 3]
- `pub shininess: f64` (field, since 0.3.2): Shininess exponent. (Shininess or ShininessExponent, 20 if absent)
  - returns f64
- `pub diffuse_texture_id: Option<i64>` (field, since 0.3.2): Diffuse texture id. (OP connection DiffuseColor, None if absent)
  - returns Option<i64>
- `pub normal_texture_id: Option<i64>` (field, since 0.3.2): Normal map texture id. (OP connection NormalMap or Bump, None if absent)
  - returns Option<i64>
- `pub specular_texture_id: Option<i64>` (field, since 0.3.2): Specular texture id. (OP connection SpecularColor or SpecularFactor, None if absent)
  - returns Option<i64>
- `pub gloss_texture_id: Option<i64>` (field, since 0.3.2): Shininess texture id. (OP connection Shininess or ShininessExponent, None if absent)
  - returns Option<i64>
- `pub opacity_texture_id: Option<i64>` (field, since 0.3.2): Opacity texture id. (OP connection TransparentColor or TransparencyFactor, None if absent)
  - returns Option<i64>

## FbxNode (struct) (Clone, Debug)

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

```rust
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]);
```

- `pub id: i64` (field, since 0.3.2): Object id.
  - returns i64
- `pub name: String` (field, since 0.3.2): FBX name. (the second property of Model with the kind tail "\u{0}\u{1}Model" removed)
  - returns String
- `pub is_bone: bool` (field, since 0.3.2): Whether it is a bone. (true if the third property of Model is LimbNode)
  - returns bool
- `pub translation: [f64; 3]` (field, since 0.3.2): Local translation. (Lcl Translation, 0, 0, 0 if absent)
  - returns [f64; 3]
- `pub rotation_euler_degrees: [f64; 3]` (field, since 0.3.2): Local rotation. (Lcl Rotation, X, Y, Z Euler angles in degrees, 0, 0, 0 if absent)
  - returns [f64; 3]
- `pub pre_rotation_degrees: [f64; 3]` (field, since 0.3.2): Pre-rotation. (PreRotation, Euler angles in degrees, SkinnedModel multiplies it before the local rotation. 0, 0, 0 if absent)
  - returns [f64; 3]
- `pub scale: [f64; 3]` (field, since 0.3.2): Local scale. (Lcl Scaling, 1, 1, 1 if absent)
  - returns [f64; 3]
- `pub geometry_id: Option<i64>` (field, since 0.3.2): Id of the geometry this node has. (None if absent)
  - returns Option<i64>
- `pub skin_id: Option<i64>` (field, since 0.3.2): Id of the skin attached to this node's geometry. (None if absent)
  - returns Option<i64>
- `pub material_ids: Vec<i64>` (field, since 0.3.2): List of material ids connected to this node. (in connection order, the geometry's material indices are positions in this list)
  - returns Vec<i64>
- `pub child_indices: Vec<usize>` (field, since 0.3.2): List of child node indices. (positions within node_list)
  - returns Vec<usize>
- `pub parent_id: Option<i64>` (field, since 0.3.2): Parent node id. (None for a root)
  - returns Option<i64>

## FbxAnimationChannel (struct) (Clone, Debug)

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

Example: Read the channel's keys one at a time (X, Y, Z, 3 per key)

```rust
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);
}
```

- `pub node_index: usize` (field, since 0.3.2): Target node index. (position within node_list)
  - returns usize
- `pub path: AnimationPath` (field, since 0.3.2): Channel path. (one of Translation, Rotation, Scale)
  - returns AnimationPath
- `pub times: Vec<f64>` (field, since 0.3.2): List of key times. (seconds, ascending, the union of the X, Y, Z curve key times)
  - returns Vec<f64>
- `pub values: Vec<f64>` (field, since 0.3.2): 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)
  - returns Vec<f64>

## FbxAnimation (struct) (Clone, Debug)

Animation. (one stack)

Example: Connect a stack, layer, curve node and curve and get one Y translation channel

```rust
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]);
```

- `pub name: String` (field, since 0.3.2): Stack name. (the second property of AnimationStack with the kind tail "\u{0}\u{1}AnimStack" removed, like "Take 001")
  - returns String
- `pub duration: f64` (field, since 0.3.2): Length. (seconds, the largest last key time among the channels, 0 when there are no channels)
  - returns f64
- `pub channels: Vec<FbxAnimationChannel>` (field, since 0.3.2): Channel list per node and path. (only the curve nodes of the layers in the stack)
  - returns Vec<FbxAnimationChannel>

## FbxSceneData (struct) (Clone, Debug, Default)

Intermediate representation. (the original sceneData)

Example: Find a node by name prefix (FBX names may have a class name appended)

```rust
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());
```

- `pub node_list: Vec<FbxNode>` (field, since 0.3.2): Model node list. (in the order of Model entries in Objects)
  - returns Vec<FbxNode>
- `pub node_id_to_index: HashMap<i64, usize>` (field, since 0.3.2): Table from node id to position in node_list.
  - returns HashMap<i64, usize>
- `pub root_node_indices: Vec<usize>` (field, since 0.3.2): Root node index list. (nodes connected to id 0, in connection order)
  - returns Vec<usize>
- `pub geometry_by_id: FbxObjectMap<FbxGeometry>` (field, since 0.3.2): Geometries. (looked up by id, in Objects order)
  - returns FbxObjectMap<FbxGeometry>
- `pub skin_deformer_by_id: FbxObjectMap<FbxSkinDeformer>` (field, since 0.3.2): Skin deformers. (looked up by id)
  - returns FbxObjectMap<FbxSkinDeformer>
- `pub cluster_by_id: FbxObjectMap<FbxCluster>` (field, since 0.3.2): Clusters. (looked up by id)
  - returns FbxObjectMap<FbxCluster>
- `pub material_by_id: FbxObjectMap<FbxMaterial>` (field, since 0.3.2): Materials. (looked up by id, the insertion position is the position in the SkinnedModel material descriptions)
  - returns FbxObjectMap<FbxMaterial>
- `pub texture_by_id: FbxObjectMap<FbxTexture>` (field, since 0.3.2): Textures. (looked up by id)
  - returns FbxObjectMap<FbxTexture>
- `pub video_by_id: FbxObjectMap<FbxVideo>` (field, since 0.3.2): Videos. (looked up by id, embedded images)
  - returns FbxObjectMap<FbxVideo>
- `pub animation_list: Vec<FbxAnimation>` (field, since 0.3.2): Animation list. (one per AnimationStack, in Objects order)
  - returns Vec<FbxAnimation>

## FbxLoadHandle (struct) (Clone, Debug, IntoFuture)

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: Let the scene track the load and read the result in initialize

```rust
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 => {
			}
		}
	}
}
```

- `pub fn get_load_handle(&self) -> &AssetLoadHandle` (method, since 0.4.0): Byte read handle. (for handing to a scene)
  - returns &AssetLoadHandle: Byte read handle. (passed to SceneBase::track_load_handle)
- `pub fn is_finished(&self) -> bool` (method, since 0.4.0): Whether it has finished. (loaded or failed)
  - returns bool: true if loading has finished (loaded or failed).
- `pub fn get_scene_data(&self) -> Option<Result<FbxSceneData, String>>` (method, since 0.4.0): 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.
  - returns Option<Result<FbxSceneData, String>>: 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: A missing file ends with Err (on desktop it finishes right where it is requested)

  ```rust
  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")));
  ```

## FbxLoadFuture (struct) (Clone, Debug, Future)

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

Example: Turn the handle into a future and await it inside an engine task

```rust
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);
			}
		}
	});
}
```

## FbxLoader (struct) (Default)

FBX loader.
- Reads binary FBX only. (ASCII FBX is Err)

Example: Bytes that are not binary FBX are Err

```rust
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.")));
```

- `pub fn new() -> FbxLoader` (constructor, since 0.3.2): Constructor.
  - returns FbxLoader: New loader. (reads the file from the start on every parse)
- `pub fn load_from_url(engine: &Engine, url: &str) -> FbxLoadHandle` (static, since 0.4.0): 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 path. (on desktop a path relative to the asset folder candidates, on the web an address relative to asset_base_url)
  - returns FbxLoadHandle: Load handle. (on desktop it is read on the spot and already finished)
- `pub fn parse(&mut self, file_bytes: &[u8]) -> Result<FbxSceneData, String>` (method, since 0.3.2): Parse. (binary → intermediate representation)
  - `file_bytes` &[u8]: All bytes of the binary FBX file.
  - returns Result<FbxSceneData, String>: Intermediate representation. Err if it is not binary FBX (including ASCII FBX), the file is truncated, or there is no Objects or Connections node.
- `pub fn parse_node_records(&mut self, file_bytes: &[u8]) -> Result<Vec<FbxNodeRecord>, String>` (method, since 0.3.2): 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]: All bytes of the binary FBX file.
  - returns Result<Vec<FbxNodeRecord>, String>: 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: A 7.4 file with only a header and one empty Objects node

  ```rust
  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());
  ```

- `pub fn read_version(file_bytes: &[u8]) -> Result<u32, String>` (static, since 0.3.2): Returns the FBX version. (version number in the header, 7400 = 7.4)
  - `file_bytes` &[u8]: FBX file bytes. (does not check whether the header is valid)
  - returns Result<u32, String>: Version number. (little-endian u32 at bytes 23 ~ 26) Err if shorter than 27 bytes.
- `pub fn inflate(compressed_bytes: &[u8], expected_byte_length: usize) -> Result<Vec<u8>, String>` (static, since 0.3.2): Decompresses deflate. (deflate with a zlib header, the original DecompressionStream("deflate"))
  - `compressed_bytes` &[u8]: Deflate bytes with a zlib header.
  - `expected_byte_length` usize: Expected decompressed size. (only the capacity to reserve, not checked against the decompressed length)
  - returns Result<Vec<u8>, String>: Decompressed bytes. Err if the compressed data is corrupt.

  Example: Decompress zlib-compressed bytes

  ```rust
  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());
  ```

- `pub fn interpret(&self, top_node_list: &[FbxNodeRecord]) -> Result<FbxSceneData, String>` (method, since 0.3.2): Interprets the object/connection graph. (builds the intermediate representation)
  - `top_node_list` &[FbxNodeRecord]: Top-level node record list. (what parse_node_records returned)
  - returns Result<FbxSceneData, String>: Intermediate representation. Err if there is no Objects or Connections node.
- `pub fn extract_file_name(file_path: &str) -> String` (static, since 0.3.2): Extracts the file name from a file path. (handles both Windows/Unix separators)
  - `file_path` &str: File path. (both / and \ separators)
  - returns String: File name after the last separator. (the path as is when there is no separator)

## Functions and constants

- `pub const FBX_TIME_UNIT: f64 = 46186158000.0` (field, since 0.3.2): FBX time unit. (1 second = 46186158000 ktime)
  - returns f64

## FbxPropertyValue (enum) (Clone, Debug, PartialEq)

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

- `Int16` = `Int16(i16)`: 16-bit integer. (type code Y)
- `Boolean` = `Boolean(bool)`: Boolean. (type code C, true if the byte is not 0)
- `Int32` = `Int32(i32)`: 32-bit integer. (type code I)
- `Float32` = `Float32(f64)`: 32-bit float. (type code F)
- `Float64` = `Float64(f64)`: 64-bit float. (type code D)
- `Int64` = `Int64(i64)`: 64-bit integer. (type code L, object id)
- `Float32array` = `Float32array(Vec<f64>)`: 32-bit float array. (type code f)
- `Float64array` = `Float64array(Vec<f64>)`: 64-bit float array. (type code d, such as vertex positions)
- `Int64array` = `Int64array(Vec<i64>)`: 64-bit integer array. (type code l, such as key times)
- `Int32array` = `Int32array(Vec<i32>)`: 32-bit integer array. (type code i, such as polygon vertex indices)
- `BooleanArray` = `BooleanArray(Vec<u8>)`: Boolean array. (type code b, element bytes as is)
- `String` = `String(String)`: String. (type code S, bytes that cannot be read as UTF-8 are replaced with the replacement character)
- `Raw` = `Raw(Rc<Vec<u8>>)`: Raw bytes. (type code R, such as embedded images)

- `pub fn get_type_code(&self) -> char` (method, since 0.3.2): Returns the type code. (the original property.type)
  - returns char: Type code character. (one of Y, C, I, F, D, L, f, d, l, i, b, S, R)
- `pub fn as_number(&self) -> Option<f64>` (method, since 0.3.2): Reads as a single number. (scalar types only, otherwise None)
  - returns Option<f64>: The scalar value converted to f64. (Boolean is 1 or 0) None for arrays, strings and raw bytes.
- `pub fn as_integer(&self) -> Option<i64>` (method, since 0.3.2): Reads as a single integer. (integer scalars such as object ids, otherwise None)
  - returns Option<i64>: Integer and float scalars converted to i64. (floats are truncated toward 0) None for Boolean, arrays, strings and raw bytes.
- `pub fn as_string(&self) -> Option<&str>` (method, since 0.3.2): Reads as a string. (S type only)
  - returns Option<&str>: String slice. None if not String.
- `pub fn get_array_length(&self) -> usize` (method, since 0.3.2): Returns the array length. (0 if not an array type)
  - returns usize: Element count. 0 if not an array.
- `pub fn get_number_at(&self, index: usize) -> Option<f64>` (method, since 0.3.2): Reads one array element as a number. (None if outside the array or not an array)
  - `index` usize: Element index. (from 0)
  - returns Option<f64>: That element converted to f64. None if the index is outside the array or it is not an array.
- `pub fn get_integer_at(&self, index: usize) -> Option<i64>` (method, since 0.3.2): Reads one array element as an integer. (None if outside the array or not an array)
  - `index` usize: Element index. (from 0)
  - returns Option<i64>: That element converted to i64. (floats are truncated toward 0) None if the index is outside the array or it is not an array.
- `pub fn to_number_list(&self) -> Vec<f64>` (method, since 0.3.2): Converts to a number list. (any numeric array type to f64, otherwise an empty list)
  - returns Vec<f64>: A new list with every element as f64. An empty list if not an array.
- `pub fn to_integer_list(&self) -> Vec<i64>` (method, since 0.3.2): Converts to an integer list. (any numeric array type to i64, otherwise an empty list)
  - returns Vec<i64>: A new list with every element as i64. (floats are truncated toward 0) An empty list if not an array.
