# graphics3d/skinnedmodelasset (vanilla-engine 0.4.0)

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

Skinned model asset. (original graphics3d/skinnedmodelasset.js)
- Decoded data and GPU resources shared by the model instances built from the same file. Holds one copy of the mesh buffers and vertex arrays, the material prototypes and their textures,
  the morph textures, the node and skin prototypes and the animation clips. (the same as clones sharing Unity's mesh and sharedMaterial, or three.js BufferGeometry and Material)
- Instances (SkinnedModel) share it by reference count. Each instance keeps its own pose, animation playback state, morph weights,
  forked materials (get_material), wireframe buffers and morph textures forked by add_morph_target.
- When the last instance calls destroy (reference count 0), the GPU resources are deleted and the asset leaves the cache. The reference count is kept by retain / release, not by the Rc count.
  (the same count as the original; holding more Rc through get_asset does not extend the resource lifetime beyond the instances)
- The cache is looked up by shader program and asset key (a path or asset name normalized with normalize_key). Loads such as the load handle's create_model
  and load_from_url_async use it. There is one cache per thread. (because a GL context is bound to a thread)

Example: Key normalization and an empty cache

```rust
use vanilla::SkinnedModelAsset;

assert_eq!(SkinnedModelAsset::normalize_key("./assets/models/../fox.glb"), "assets/fox.glb");
SkinnedModelAsset::clear_cache();
assert_eq!(SkinnedModelAsset::get_cached_count(), 0);
```

## SkinnedModelAssetContent (struct)

Data to put in an asset. (filled by SkinnedModel::upload_meshes_and_materials after uploading, the original constructor's content object)

Example: Reading the root node count of the data (the data is filled by SkinnedModel::upload_meshes_and_materials)

```rust
use vanilla::SkinnedModelAssetContent;

fn read_root_count(content: &SkinnedModelAssetContent) -> usize {
	content.root_node_indices.len()
}
let _ = read_root_count;
```

- `pub drawable_list: Vec<Drawable>` (field, since 0.4.0): Prototype drawable list. (instances copy it to share the buffers and material prototypes)
  - returns Vec<Drawable>
- `pub material_list: Vec<Rc<Material>>` (field, since 0.4.0): Material prototype list. (the default material is last, deleted when the last instance calls destroy)
  - returns Vec<Rc<Material>>
- `pub node_list: Vec<SkinnedModelNode>` (field, since 0.4.0): Node prototype list. (the nodes at upload)
  - returns Vec<SkinnedModelNode>
- `pub root_node_indices: Vec<usize>` (field, since 0.4.0): Root node index list.
  - returns Vec<usize>
- `pub skin_list: Vec<Skin>` (field, since 0.4.0): Skin prototype list.
  - returns Vec<Skin>
- `pub animation_list: Rc<RefCell<Vec<AnimationClip>>>` (field, since 0.4.0): Animation clip list. (all instances share the same list)
  - returns Rc<RefCell<Vec<AnimationClip>>>
- `pub buffer_byte_count: usize` (field, since 0.4.0): GPU bytes of the vertex and index buffers and morph textures.
  - returns usize

## SkinnedModelAsset (struct)

Skinned model asset. (decoded data and GPU resources shared by the model instances built from the same file, lifetime counted by reference count)

Example: Spawn ten from a loaded model and check that they share one asset

```rust
use vanilla::{SkinnedModel, SkinnedModelAsset};

fn spawn_herd(gl: &vanilla::GlContext, source_model: &SkinnedModel) -> Result<Vec<SkinnedModel>, String> {
	let mut model_list = Vec::new();
	for _ in 0..10 {
		model_list.push(source_model.create_instance()?);
	}
	let skinned_model_asset = source_model.get_asset().ok_or("no asset")?;
	assert_eq!(skinned_model_asset.get_reference_count(), 11);
	println!("{} bytes on GPU", skinned_model_asset.get_gpu_byte_count());
	let _ = gl;
	Ok(model_list)
}
```

- `pub fn new(shader_program: Rc<ShaderProgram>, content: SkinnedModelAssetContent) -> SkinnedModelAsset` (constructor, since 0.4.0): Constructor. (built by SkinnedModel::upload_meshes_and_materials after uploading, reference count 1)
  - `shader_program` Rc<ShaderProgram>: Shader program used by the vertex arrays and materials.
  - `content` SkinnedModelAssetContent: Data to share. (drawables stay as prototypes that instances copy)
  - returns SkinnedModelAsset: Asset with reference count 1, outside the cache.
- `pub fn normalize_key(path: &str) -> String` (static, since 0.4.0): Normalize an asset key. (backslashes become /, "." and ".." segments are resolved and empty segments dropped; a leading "scheme://" and a trailing ? or # part stay as they are)
  - The same file written differently, such as "./a/b.glb" and "a/c/../b.glb", gets the same key. It does not resolve against a base URL into an absolute one.
  - `path` &str: Asset path or name.
  - returns String: Normalized key.

  Example: The same path written differently

  ```rust
  use vanilla::SkinnedModelAsset;
  
  assert_eq!(SkinnedModelAsset::normalize_key("./assets/models/../fox.glb"), "assets/fox.glb");
  assert_eq!(SkinnedModelAsset::normalize_key("assets\\fox.glb"), "assets/fox.glb");
  assert_eq!(SkinnedModelAsset::normalize_key("https://example.com/a/./b/../fox.glb?v=2"), "https://example.com/a/fox.glb?v=2");
  ```

- `pub fn find(asset_key: &str, shader_program: &Rc<ShaderProgram>) -> Option<Rc<SkinnedModelAsset>>` (static, since 0.4.0): Find in the cache. (a live asset with the same shader program and key)
  - `asset_key` &str: Asset key. (normalized with normalize_key)
  - `shader_program` &Rc<ShaderProgram>: Shader program the model is drawn with. (the renderer's get_shader_program)
  - returns Option<Rc<SkinnedModelAsset>>: Asset found. (None if none)
- `pub fn register(asset_key: &str, asset: &Rc<SkinnedModelAsset>) -> Result<(), String>` (static, since 0.4.0): Add to the cache. (gives the asset the key. An asset that held the same slot only leaves the cache, and instances using it keep working)
  - `asset_key` &str: Asset key. (normalized with normalize_key)
  - `asset` &Rc<SkinnedModelAsset>: Asset to add.
  - returns Result<(), String>: Ok if added. Err if the asset was destroyed.

  Example: Share a model built from bundled bytes by name

  ```rust
  use vanilla::{SkinnedModel, SkinnedModelAsset, SkinnedModelRenderer};
  
  fn load_named_model(gl: &vanilla::GlContext, bytes: &[u8], skinned_model_renderer: &SkinnedModelRenderer) -> Result<SkinnedModel, String> {
  	if let Some(found_asset) = SkinnedModelAsset::find("fox", &skinned_model_renderer.get_shader_program()) {
  		return SkinnedModel::create_from_asset(&found_asset);
  	}
  	let skinned_model = SkinnedModel::load_from_bytes(gl, bytes, skinned_model_renderer)?;
  	SkinnedModelAsset::register("fox", skinned_model.get_asset().ok_or("no asset")?)?;
  	Ok(skinned_model)
  }
  ```

- `pub fn clear_cache()` (static, since 0.4.0): Clear the cache. (removes every asset from the cache. Instances in use keep drawing, and the GPU resources are deleted when the last instance calls destroy)
  - The next load parses the file again into a new asset.

  Example: Clear the cache when switching stages

  ```rust
  use vanilla::SkinnedModelAsset;
  
  SkinnedModelAsset::clear_cache();
  assert_eq!(SkinnedModelAsset::get_cached_count(), 0);
  ```

- `pub fn get_cached_count() -> usize` (static, since 0.4.0): Number of assets in the cache. (sum over all shader programs)
  - returns usize: Number of assets in the cache.
- `pub fn retain(&self) -> Result<(), String>` (method, since 0.4.0): Add a reference. (when an instance starts sharing the asset, called by SkinnedModel::create_from_asset)
  - returns Result<(), String>: Ok if added. Err if the asset was destroyed.
- `pub fn release(&self, gl: &GlContext) -> bool` (method, since 0.4.0): Remove a reference. (when an instance calls destroy; at 0 the GPU resources are deleted and the asset leaves the cache)
  - `gl` &GlContext: GL context the resources were created with.
  - returns bool: true if this call deleted the resources.
- `pub fn get_key(&self) -> Option<String>` (method, since 0.4.0): Return the asset key.
  - returns Option<String>: Key added to the cache. (None if never added or removed from the cache)
- `pub fn get_reference_count(&self) -> usize` (method, since 0.4.0): Return the reference count. (number of live instances sharing this asset)
  - returns usize: Reference count. (0 once destroyed)
- `pub fn is_destroyed(&self) -> bool` (method, since 0.4.0): Whether destroyed.
  - returns bool: true if the last instance called destroy and the GPU resources were deleted.
- `pub fn get_gpu_byte_count(&self) -> usize` (method, since 0.4.0): GPU byte count. (vertex and index buffers, morph textures and material prototype textures including mipmaps, one copy regardless of the instance count)
  - returns usize: Bytes this asset uploaded to the GPU. (0 once destroyed)
- `pub fn get_shader_program(&self) -> &Rc<ShaderProgram>` (method, since 0.4.0): Returns the shader program.
  - returns &Rc<ShaderProgram>: Shader program used by the vertex arrays and materials.
- `pub fn get_drawable_list(&self) -> Ref<'_, Vec<Drawable>>` (method, since 0.4.0): Return the prototype drawable list. (instances copy it to share the buffers and material prototypes)
  - returns Ref<'_, Vec<Drawable>>: Prototype drawable list. (empty once destroyed)
- `pub fn get_material_list(&self) -> Ref<'_, Vec<Rc<Material>>>` (method, since 0.4.0): Return the material prototype list. (the default material is last; this asset created them and deletes them when the last instance calls destroy)
  - returns Ref<'_, Vec<Rc<Material>>>: Material prototype list. (sharedMaterial; changing a value changes every instance using this asset)
- `pub fn get_node_list(&self) -> &[SkinnedModelNode]` (method, since 0.4.0): Return the node prototype list. (the nodes at upload; instances copy them and keep their own pose)
  - returns &[SkinnedModelNode]: Node prototype list.
- `pub fn get_root_node_indices(&self) -> &[usize]` (method, since 0.4.0): Return the root node list.
  - returns &[usize]: Root node index list.
- `pub fn get_skin_list(&self) -> &[Skin]` (method, since 0.4.0): Return the skin prototype list. (instances copy the joints and inverse bind matrices)
  - returns &[Skin]: Skin prototype list.
- `pub fn get_animation_list(&self) -> &Rc<RefCell<Vec<AnimationClip>>>` (method, since 0.4.0): Return the animation clip list. (all instances share the same list; clips added with add_animations_from_fbx_* are visible to all)
  - returns &Rc<RefCell<Vec<AnimationClip>>>: Shared clip list.
