graphics3d/skinnedmodel
스킨드 모델. (원본 graphics3d/skinnedmodel.js)
- 모델 인스턴스, 메시/본/스킨/머티리얼/애니메이션 데이터 + 포즈 상태. 렌더링은 SkinnedModelRenderer 가 맡는다.
- GLB(바이너리 glTF)와 바이너리 FBX 를 공통 중립 스키마(MeshDescription + MaterialDescription)로 해석해 GL 리소스를 구성한다. (임포터는 파싱만 → 중립 스키마 → 공용 GL 업로드 upload_meshes_and_materials)
- 스킨 없는 정적 메시는 합성 스킨(조인트 1개)으로, 모프 타깃은 실수 텍스처로 올려 같은 스키닝 경로로 그린다.
- 애니메이션 크로스페이드와 조인트 회전 오프셋(절차 포즈 가공), 모프 가중치(glTF weights / 프로그램)를 원본처럼 지원한다.
- 원본과 다른 것:
- 원본은 async 이고 URL 을 fetch 한다(loadFromUrl, 바이트는 loadFromBytes). 러스트 판의 바이트 함수 load_from_bytes / load_from_fbx_bytes / add_animations_from_fbx_bytes 는 그 자리에서 끝난다. URL 함수 load_from_url / load_from_fbx_url 은 ImageAsset 처럼 엔진의 애셋 받기(데스크탑은 애셋 폴더 후보, 웹은 asset_base_url 에서 fetch)로 바이트를 부탁하고 받기 손잡이(SkinnedModelLoadHandle)를 돌려준다. 다 받으면 손잡이의 create_model(gl, 렌더러)이 모델을 짓는다. (await 없는 꼴) 원본 await SkinnedModel.loadFromUrl(gl, url, renderer) 자리는 엔진 작업 안에서 load_from_url_async(엔진, 경로, 렌더러).await 다. (fbx 는 load_from_fbx_url_async) 다 받으면 작업을 폴링하는 엔진의 GL 로 모델을 짓는다. (렌더러는 부를 때 셰이더 프로그램만 나눠 들어 빌리지 않는다) add_animations_from_fbx_url 은 받기를 부탁하고 await 할 수 있는 AnimationLoadHandle 을 돌려준다. 원본처럼 await 가 끝날 때는 클립이 이미 더해져 있다. (클립 목록을 손잡이와 나눠 들어, 다 받으면 await 하는 퓨처나 다음 update, play_animation 가운데 먼저 닿는 쪽이 더한다. 원본처럼 받은 차례로 더한다)
- GL 을 쓰는 함수는 gl 을 받는다. update(delta_time) 는 GL 을 쓰지 않는다. 원본 update 6단계(바뀐 모프 타깃 업로드)는 렌더러의 draw / draw_depth / draw_wireframe 가 upload_pending_morph_targets 로 대신한다. (그래서 그리기 함수가 &mut 모델을 받는다) 덕분에 씬의 tick 에서 update 를 부를 수 있다.
- 원본 노드 / 드로어블 / 스킨 / 클립 객체는 SkinnedModelNode / Drawable / Skin / AnimationClip 구조체다. 드로어블의 머티리얼은
Rc<Material>이다. 클립은 인덱스로 가리키고, sample_animation 도 클립 인덱스를 받는다. upload_wireframe_indices / upload_morph_targets 는 원본의 드로어블 객체 대신 드로어블 인덱스를 받는다. (모델을 &mut 로 빌린 채 드로어블을 넘길 수 없어서다) - 드로어블의 mesh_description 은 모프 타깃을 morph_target_list 로 옮긴 뒤라 morph_targets 가 비어 있다. (큰 델타 배열을 두 벌 들지 않는다)
- 원본처럼 노드 matrix 와 CUBICSPLINE 보간, 프리미티브 mode 는 보지 않는다. FBX 는 원본처럼 스킨이 붙은 메시만 그린다.
- 올린 버퍼, 머티리얼 원형, 모프 텍스처, 노드와 스킨 원형, 클립은 SkinnedModelAsset 이 한 벌 들고, 모델은 그 인스턴스다. (원본과 같다) create_instance, create_from_asset 은 GPU 업로드 없이 인스턴스를 짓고, 받기(create_model, load_from_url_async)는 자산 캐시를 쓴다. destroy 는 이 인스턴스 것(와이어프레임 버퍼, 갈라진 모프 텍스처, get_material 로 갈라진 머티리얼)을 지우고 자산을 놓는다. set_material 로 바깥에서 넣은 머티리얼은 지우지 않는다. (원본과 같다)
Skinned model. (the original graphics3d/skinnedmodel.js)
- Model instance, mesh/bone/skin/material/animation data + pose state. Rendering is handled by SkinnedModelRenderer.
- Interprets GLB (binary glTF) and binary FBX into a common neutral schema (MeshDescription + MaterialDescription) and builds GL resources. (importers only parse → neutral schema → shared GL upload upload_meshes_and_materials)
- Static meshes without a skin use a synthetic skin (1 joint), and morph targets are uploaded as float textures, so they draw through the same skinning path.
- Supports animation cross-fades, joint rotation offsets (procedural pose adjustment) and morph weights (glTF weights / code) like the original.
- Differences from the original:
- The original is async and fetches URLs (loadFromUrl, loadFromBytes for bytes). The byte functions of the Rust version load_from_bytes / load_from_fbx_bytes / add_animations_from_fbx_bytes finish on the spot. The URL functions load_from_url / load_from_fbx_url, like ImageAsset, use the engine's asset loading (asset folder candidates on desktop, fetch from asset_base_url on the web) to request the bytes and return a load handle (SkinnedModelLoadHandle). Once loaded, the handle's create_model(gl, renderer) builds the model. (the form without await) The original await SkinnedModel.loadFromUrl(gl, url, renderer) becomes load_from_url_async(engine, path, renderer).await inside an engine task. (load_from_fbx_url_async for fbx) Once loaded, the model is built with the GL of the engine polling the task. (the renderer only shares its shader program at the call and is not borrowed) add_animations_from_fbx_url requests the load and returns an awaitable AnimationLoadHandle. Like the original, the clips are already added when await finishes. (the clip list is shared with the handle, and once loaded, whichever comes first among the awaiting future, the next update or play_animation adds them. They are added in load order like the original)
- Functions that use GL take gl. update(delta_time) does not use GL. Step 6 of the original update (uploading changed morph targets) is done instead by the renderer's draw / draw_depth / draw_wireframe through upload_pending_morph_targets. (that is why the draw functions take a &mut model) Thanks to this, update can be called in the scene's tick.
- The original node / drawable / skin / clip objects are the SkinnedModelNode / Drawable / Skin / AnimationClip structs. A drawable's material is
Rc<Material>. Clips are referred to by index, and sample_animation also takes a clip index. upload_wireframe_indices / upload_morph_targets take a drawable index instead of the original drawable object. (a drawable cannot be passed while the model is borrowed as &mut) - A drawable's mesh_description has empty morph_targets because the morph targets were moved to morph_target_list. (the large delta arrays are not held twice)
- Like the original, node matrix, CUBICSPLINE interpolation and primitive mode are ignored. Like the original, FBX draws only meshes with a skin attached.
- The uploaded buffers, material prototypes, morph textures, node and skin prototypes and clips are held once by SkinnedModelAsset, and the model is its instance. (same as the original) create_instance and create_from_asset build instances without a GPU upload, and loads (create_model, load_from_url_async) use the asset cache. destroy deletes this instance's resources (wireframe buffers, forked morph textures, materials forked by get_material) and releases the asset. Materials given from outside with set_material are not deleted. (same as the original)
use serde_json::json;
use vanilla::SkinnedModel;
let positions: [f32; 9] = [0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0, 0.0];
let binary_buffer: Vec<u8> = positions.iter().flat_map(|value| value.to_le_bytes()).collect();
let json = json!({
"scenes": [{ "nodes": [0] }],
"nodes": [{ "name": "Triangle", "mesh": 0, "translation": [0.0, 2.0, 0.0] }],
"meshes": [{ "primitives": [{ "attributes": { "POSITION": 0 } }] }],
"accessors": [{ "bufferView": 0, "componentType": 5126, "count": 3, "type": "VEC3" }],
"bufferViews": [{ "buffer": 0, "byteOffset": 0, "byteLength": 36 }]
});
let mut skinned_model = SkinnedModel::create_without_shader_program();
let (mesh_description_list, material_description_list) = skinned_model.interpret_content(&json, &binary_buffer).unwrap();
assert_eq!(mesh_description_list.len(), 1);
assert!(material_description_list.is_empty());
skinned_model.update(0.0);
let joint_matrix_array = &skinned_model.get_skin_list()[0].joint_matrix_array;
assert_eq!(joint_matrix_array[13], 2.0);SkinnedModelNodestruct traits Clone, Debug
모델 노드. (본 계층 + 포즈 상태, 원본 nodeList 원소)
Model node. (bone hierarchy + pose state, an element of the original nodeList)
use vanilla::{SkinnedModel, SkinnedModelNode};
fn find_world_position(skinned_model: &SkinnedModel, node_name: &str) -> Option<[f64; 3]> {
let node: &SkinnedModelNode = skinned_model.get_node_list().iter().find(|node| node.name == node_name)?;
let elements = node.world_matrix.read_elements();
Some([elements[12], elements[13], elements[14]])
}
let skinned_model = SkinnedModel::create_without_shader_program();
assert_eq!(find_world_position(&skinned_model, "Head"), None);노드 이름. (glTF 노드 name, FBX 는 종류 꼬리를 뗀 Model 이름, 없으면 빈 문자열)
Node name. (glTF node name, the Model name with the kind tail removed for FBX, an empty string if missing)
반환ReturnsString
glTF 메시 인덱스. (메시가 없거나 FBX 면 None)
glTF mesh index. (None if there is no mesh or for FBX)
반환ReturnsOption<usize>
스킨 인덱스. (skin_list 안의 자리, 스킨 없는 glTF 메시 노드에는 합성 스킨이 붙는다. 없으면 None)
Skin index. (position in skin_list, glTF mesh nodes without a skin get a synthetic skin. None if missing)
반환ReturnsOption<usize>
기본 포즈 이동. (update 가 매번 이 값에서 시작한다)
Base pose translation. (update starts from this value every time)
반환Returns[f64; 3]
기본 포즈 회전. (FBX 는 사전 회전까지 곱한 것)
Base pose rotation. (for FBX, with the pre-rotation multiplied in)
반환ReturnsQuaternion
지금 포즈 이동. (마지막 update 가 기본 포즈에 클립을 샘플링한 값)
Current pose translation. (the value the last update sampled from the clip on top of the base pose)
반환Returns[f64; 3]
지금 포즈 회전. (조인트 회전 오프셋까지 곱한 값)
Current pose rotation. (with the joint rotation offset multiplied in)
반환ReturnsQuaternion
모델 공간 월드 행렬. (update 가 루트부터 계산한다, 루트에 닿지 않는 노드는 그대로)
Model-space world matrix. (update computes it from the root, nodes not reachable from a root are left as is)
반환ReturnsMatrix4
Skinstruct traits Clone, Debug
스킨. (조인트 노드 인덱스 + 역바인드 행렬 + 셰이더로 올릴 조인트 행렬 배열)
Skin. (joint node indices + inverse bind matrices + joint matrix array to upload to the shader)
use vanilla::{Matrix4, Skin};
fn read_joint_matrix(skin: &Skin, joint_index: usize) -> Option<Matrix4> {
let elements = skin.joint_matrix_array.get(joint_index * 16..joint_index * 16 + 16)?;
let mut matrix = Matrix4::create_identity();
matrix.elements.copy_from_slice(elements);
Some(matrix)
}
let skin = Skin {
joint_node_indices: vec![0],
inverse_bind_matrices: vec![Matrix4::create_identity()],
joint_matrix_array: Matrix4::create_translation(1.0, 2.0, 3.0).get_elements().to_vec(),
};
assert_eq!(read_joint_matrix(&skin, 0).unwrap().elements[13], 2.0);
assert!(read_joint_matrix(&skin, 1).is_none());조인트마다 노드 인덱스. (노드가 없는 조인트는 usize::MAX 로 두고 단위 행렬을 쓴다)
Node index per joint. (joints without a node are set to usize::MAX and use the identity matrix)
반환ReturnsVec<usize>
조인트마다 역바인드 행렬. (joint_node_indices 와 같은 자리)
Inverse bind matrix per joint. (same positions as joint_node_indices)
반환ReturnsVec<Matrix4>
셰이더로 올릴 조인트 행렬. (조인트마다 열 우선 16개, 월드 x 역바인드, update 가 채운다)
Joint matrices to upload to the shader. (16 column-major values per joint, world x inverse bind, filled by update)
반환ReturnsVec<f32>
MorphTargetstruct traits Clone, Debug, PartialEq
모프 타깃. (정점별 위치 델타 + 선택 노멀 델타)
Morph target. (per-vertex position deltas + optional normal deltas)
use vanilla::{MorphTarget, SkinnedModel};
let morph_target = MorphTarget {
name: String::from("smile"),
position_deltas: vec![1.0, 2.0, 3.0, 4.0, 5.0, 6.0],
normal_deltas: None,
};
let (texture_width, rows_per_target, texel_data) = SkinnedModel::build_morph_texel_data(&[morph_target], 2);
assert_eq!((texture_width, rows_per_target), (2, 1));
assert_eq!(texel_data.len(), 2 * 2 * 4);
assert_eq!(&texel_data[0..8], &[1.0, 2.0, 3.0, 0.0, 4.0, 5.0, 6.0, 0.0]);타깃 이름. (glTF mesh.extras.targetNames, 없으면 "target0" 꼴)
Target name. (glTF mesh.extras.targetNames, in the form "target0" if missing)
반환ReturnsString
정점마다 위치 델타. (x, y, z 3개씩)
Position delta per vertex. (3 each: x, y, z)
반환ReturnsVec<f64>
정점마다 노멀 델타. (3개씩, 없으면 None)
Normal delta per vertex. (3 each, None if missing)
반환ReturnsOption<Vec<f64>>
FbxCornerArraysstruct traits Clone, Debug, Default
FBX 코너 배열. (원본 splitFbxCornersByMaterial 의 cornerArrays, 비인덱스 코너마다 값)
FBX corner arrays. (cornerArrays of the original splitFbxCornersByMaterial, values per non-indexed corner)
use vanilla::SkinnedModel;
use vanilla::graphics3d::skinnedmodel::FbxCornerArrays;
let corner_arrays = FbxCornerArrays {
positions: vec![0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0, 0.0],
normals: vec![0.0; 9],
texture_coordinates: vec![0.0; 6],
joints: vec![0; 12],
weights: vec![1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0],
};
let sub_mesh_list = SkinnedModel::split_fbx_corners_by_material(&[3], corner_arrays);
assert_eq!(sub_mesh_list.len(), 1);
assert_eq!(sub_mesh_list[0].0, 3);
assert_eq!(sub_mesh_list[0].1.positions.len(), 9);코너 위치. (코너마다 x, y, z)
Corner positions. (x, y, z per corner)
반환ReturnsVec<f64>
코너 UV. (코너마다 2개)
Corner UVs. (2 per corner)
반환ReturnsVec<f64>
코너마다 조인트 4개. (스킨 joint_node_indices 안의 자리)
4 joints per corner. (Positions in the skin's joint_node_indices)
반환ReturnsVec<u16>
MeshDescriptionstruct traits Clone, Debug
중립 메시 서술. (원본 meshDescription, 순수 CPU 배열)
- joints / weights 는 정점마다 4개, material_index 가 None 이면 기본 머티리얼, node_index 는 모프 가중치 채널의 대상 노드.
Neutral mesh description. (the original meshDescription, pure CPU arrays)
- joints / weights are 4 per vertex, the default material if material_index is None, node_index is the target node of the morph weight channel.
use serde_json::json;
use vanilla::SkinnedModel;
let positions: [f32; 9] = [0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0, 0.0];
let binary_buffer: Vec<u8> = positions.iter().flat_map(|value| value.to_le_bytes()).collect();
let json = json!({
"scenes": [{ "nodes": [0] }],
"nodes": [{ "name": "Triangle", "mesh": 0 }],
"meshes": [{ "primitives": [{ "attributes": { "POSITION": 0 } }] }],
"accessors": [{ "bufferView": 0, "componentType": 5126, "count": 3, "type": "VEC3" }],
"bufferViews": [{ "buffer": 0, "byteOffset": 0, "byteLength": 36 }]
});
let mut skinned_model = SkinnedModel::create_without_shader_program();
let (mesh_description_list, _material_description_list) = skinned_model.interpret_content(&json, &binary_buffer).unwrap();
let mesh_description = &mesh_description_list[0];
assert_eq!(mesh_description.positions.len(), 9);
assert_eq!(mesh_description.normals.as_deref(), Some(&[0.0, 0.0, 1.0, 0.0, 0.0, 1.0, 0.0, 0.0, 1.0][..]));
assert!(mesh_description.indices.is_none());
assert_eq!(&mesh_description.weights[0..4], &[1.0, 0.0, 0.0, 0.0]);
assert_eq!(mesh_description.material_index, None);
assert_eq!(skinned_model.get_skin_list()[mesh_description.skin_index].joint_node_indices, vec![0]);정점 위치. (정점마다 x, y, z)
Vertex positions. (x, y, z per vertex)
반환ReturnsVec<f64>
정점 노멀. (3개씩, None 이면 업로드할 때 스무스 노멀을 지어 쓴다, glTF 는 노멀이 없으면 평평한 노멀을 지어 늘 Some)
Vertex normals. (3 each, smooth normals are built and used at upload when None, always Some for glTF because flat normals are built when normals are missing)
반환ReturnsOption<Vec<f64>>
정점 UV. (2개씩, 없으면 None)
Vertex UVs. (2 each, None if missing)
반환ReturnsOption<Vec<f64>>
정점마다 조인트 4개. (스킨 joint_node_indices 안의 자리)
4 joints per vertex. (positions in the skin's joint_node_indices)
반환ReturnsVec<u16>
정점마다 조인트 가중치 4개. (0 ~ 1)
4 joint weights per vertex. (0 ~ 1)
반환ReturnsVec<f64>
삼각형 인덱스. (None 이면 정점 3개씩 삼각형으로 그린다)
Triangle indices. (when None, every 3 vertices are drawn as a triangle)
반환ReturnsOption<IndexArray>
쓰는 스킨 인덱스. (모델 skin_list 안의 자리)
Skin index used. (position in the model's skin_list)
반환Returnsusize
머티리얼 서술 인덱스. (None 이면 기본 머티리얼)
Material description index. (the default material when None)
반환ReturnsOption<usize>
머티리얼 이름. (glTF materials 의 name, FBX 는 Material 이름, 없으면 빈 문자열)
Material name. (name in glTF materials, the Material name in FBX, an empty string if none)
반환ReturnsString
이 메시를 가진 노드 인덱스. (모프 가중치 채널의 대상, 없으면 None)
Index of the node that owns this mesh. (target of the morph weight channel, None if missing)
반환ReturnsOption<usize>
타깃마다 기본 가중치. (glTF 노드나 메시의 weights, 없으면 0)
Default weight per target. (weights of the glTF node or mesh, 0 if missing)
반환ReturnsVec<f32>
Drawablestruct traits Clone
드로어블. (원본 drawableList 원소, 버텍스 어레이, 인덱스, 스킨, 머티리얼 참조, 모프 상태)
Drawable. (an element of the original drawableList, vertex array, indices, skin, material reference, morph state)
use vanilla::SkinnedModel;
fn find_drawable_index(skinned_model: &SkinnedModel, material_name: &str) -> Option<usize> {
skinned_model.get_drawable_list().iter().position(|drawable| drawable.material_name == material_name)
}
let skinned_model = SkinnedModel::create_without_shader_program();
assert_eq!(find_drawable_index(&skinned_model, "Body"), None);버텍스 어레이. (정점 버퍼와 인덱스 버퍼를 묶은 것)
Vertex array. (vertex buffers and index buffer bound together)
반환ReturnsGlVertexArray
정점 버퍼 목록. (셰이더가 쓰는 어트리뷰트만)
Vertex buffer list. (only the attributes the shader uses)
반환ReturnsVec<GlBuffer>
인덱스로 그리는지. (false 면 drawArrays)
Whether it draws with indices. (drawArrays when false)
반환Returnsbool
인덱스 버퍼. (인덱스가 없으면 None)
Index buffer. (None if there are no indices)
반환ReturnsOption<GlBuffer>
인덱스 GL 타입. (UNSIGNED_SHORT 나 UNSIGNED_INT, 인덱스가 없으면 0)
Index GL type. (UNSIGNED_SHORT or UNSIGNED_INT, 0 if there are no indices)
반환Returnsu32
인덱스 버퍼 시작 바이트. (업로드는 0 으로 둔다)
Index buffer start byte. (upload sets it to 0)
반환Returnsi32
와이어프레임 선 인덱스 버퍼. (처음 draw_wireframe 할 때 짓는다, 그 전에는 None)
Wireframe line index buffer. (built on the first draw_wireframe, None before that)
반환ReturnsOption<GlBuffer>
선 인덱스 개수. (모서리 수 x 2)
Line index count. (edge count x 2)
반환Returnsusize
선 인덱스 GL 타입. (정점이 65535 개를 넘으면 UNSIGNED_INT)
Line index GL type. (UNSIGNED_INT when there are more than 65535 vertices)
반환Returnsu32
머티리얼. (같은 모델의 다른 드로어블이나 다른 곳과 Rc 로 나눠 들 수 있다)
Material. (can be shared with Rc with other drawables of the same model or elsewhere)
반환ReturnsRc<Material>
머티리얼 이름. (MeshDescription 의 material_name)
Material name. (material_name of MeshDescription)
반환ReturnsString
메시를 가진 노드 인덱스. (모프 가중치 채널의 대상)
Index of the node that owns the mesh. (target of the morph weight channel)
반환ReturnsOption<usize>
업로드한 메시 서술. (모프 타깃은 morph_target_list 로 옮겨 비어 있다, 같은 자산의 인스턴스들이 나눠 든다)
Uploaded mesh description. (empty morph targets because they were moved to morph_target_list; shared by the instances of the same asset)
반환ReturnsRc<MeshDescription>
모프 타깃 목록. (MORPH_TARGET_MAXIMUM 개까지, 자산과 나눠 들고 add_morph_target 하면 이 드로어블 것으로 갈라진다)
Morph target list. (up to MORPH_TARGET_MAXIMUM, shared with the asset and forked into this drawable's own on add_morph_target)
반환ReturnsRc<Vec<MorphTarget>>
타깃마다 가중치. (morph_target_list 와 같은 자리)
Weight per target. (same positions as morph_target_list)
반환ReturnsVec<f32>
모프 델타 텍스처. (RGBA32F, 타깃이 없거나 올리기 전이면 None)
Morph delta texture. (RGBA32F, None if there are no targets or before upload)
반환ReturnsOption<GlTexture>
타깃 블록 하나의 행 수. (위치 블록과 노멀 블록이 각각 이만큼)
Row count of one target block. (the position block and the normal block each have this many)
반환Returnsi32
모프 텍스처 가로. (텍셀, 정점 수를 1 ~ 2048 로 자른 값)
Morph texture width. (texels, the vertex count clamped to 1 ~ 2048)
반환Returnsi32
모프 타깃을 다시 올려야 하는지. (렌더러가 그리기 전에 upload_pending_morph_targets 로 올린다)
Whether the morph targets need to be uploaded again. (the renderer uploads them with upload_pending_morph_targets before drawing)
반환Returnsbool
AnimationChannelstruct traits Clone, Debug
애니메이션 채널. (노드 인덱스 + 경로 + 시간/값 커브 + 키프레임 커서)
Animation channel. (node index + path + time/value curve + keyframe cursor)
use vanilla::{AnimationClip, AnimationPath};
use vanilla::graphics3d::skinnedmodel::AnimationChannel;
let animation_clip = AnimationClip {
name: String::from("Rise"),
duration: 2.0,
channels: vec![AnimationChannel {
node_index: 0,
path: AnimationPath::Translation,
times: vec![0.0, 2.0],
values: vec![0.0, 0.0, 0.0, 0.0, 4.0, 0.0],
cursor: 0,
}],
};
let rotation_channel_count = animation_clip.channels.iter().filter(|channel| channel.path == AnimationPath::Rotation).count();
assert_eq!(rotation_channel_count, 0);
assert_eq!(animation_clip.channels[0].times.last().copied(), Some(animation_clip.duration));키마다 값. (이동과 크기는 3개, 회전은 쿼터니언 4개, 모프 가중치는 타깃 수만큼)
Value per key. (3 for translation and scale, 4 quaternion values for rotation, as many as the target count for morph weights)
반환ReturnsVec<f64>
키프레임 커서. (지난 샘플링의 키 자리, 시간이 뒤로 가면 0 부터 다시 찾는다)
Keyframe cursor. (key position of the last sampling, searched again from 0 when time goes backward)
반환Returnsusize
AnimationClipstruct traits Clone, Debug
애니메이션 클립.
Animation clip.
use vanilla::SkinnedModel;
fn find_longest_clip_name(skinned_model: &SkinnedModel) -> Option<String> {
let animation_list = skinned_model.get_animation_list();
let longest_clip = animation_list.iter().max_by(|left, right| left.duration.total_cmp(&right.duration))?;
Some(longest_clip.name.clone())
}
let skinned_model = SkinnedModel::create_without_shader_program();
assert_eq!(find_longest_clip_name(&skinned_model), None);클립 이름. (glTF 애니메이션 name, FBX 는 스택 이름이나 붙일 때 준 이름)
Clip name. (glTF animation name, for FBX the stack name or the name given when adding)
반환ReturnsString
길이. (초, 채널 마지막 키 시간 가운데 가장 큰 것, 이 길이로 반복한다)
Length. (seconds, the largest last key time among the channels, loops with this length)
반환Returnsf64
SkinnedModelstruct
스킨드 모델.
Skinned model.
use serde_json::json;
use vanilla::SkinnedModel;
let float_values: [f32; 23] = [
0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0, 0.0,
0.0, 2.0,
0.0, 0.0, 0.0, 0.0, 4.0, 0.0,
0.0, 1.0, 0.0, 0.0, 1.0, 0.0,
];
let binary_buffer: Vec<u8> = float_values.iter().flat_map(|value| value.to_le_bytes()).collect();
let json = json!({
"scenes": [{ "nodes": [0] }],
"nodes": [{ "name": "Triangle", "mesh": 0 }],
"meshes": [{ "primitives": [{ "attributes": { "POSITION": 0 } }] }],
"accessors": [
{ "bufferView": 0, "componentType": 5126, "count": 3, "type": "VEC3" },
{ "bufferView": 1, "componentType": 5126, "count": 2, "type": "SCALAR" },
{ "bufferView": 2, "componentType": 5126, "count": 2, "type": "VEC3" },
{ "bufferView": 3, "componentType": 5126, "count": 2, "type": "VEC3" }
],
"bufferViews": [
{ "buffer": 0, "byteOffset": 0, "byteLength": 36 },
{ "buffer": 0, "byteOffset": 36, "byteLength": 8 },
{ "buffer": 0, "byteOffset": 44, "byteLength": 24 },
{ "buffer": 0, "byteOffset": 68, "byteLength": 24 }
],
"animations": [
{ "name": "Rise", "samplers": [{ "input": 1, "output": 2 }], "channels": [{ "sampler": 0, "target": { "node": 0, "path": "translation" } }] },
{ "name": "Hold", "samplers": [{ "input": 1, "output": 3 }], "channels": [{ "sampler": 0, "target": { "node": 0, "path": "translation" } }] }
]
});
let mut skinned_model = SkinnedModel::create_without_shader_program();
skinned_model.interpret_content(&json, &binary_buffer).unwrap();
assert_eq!(skinned_model.get_animation_name_list(), vec![String::from("Rise"), String::from("Hold")]);
skinned_model.update(1.0);
assert_eq!(skinned_model.get_node_list()[0].current_translation, [0.0, 2.0, 0.0]);
skinned_model.play_animation("Hold", 1.0);
skinned_model.update(0.5);
assert_eq!(skinned_model.get_node_list()[0].current_translation, [0.0, 2.0, 0.0]);
skinned_model.update(0.5);
assert_eq!(skinned_model.get_node_list()[0].current_translation, [0.0, 1.0, 0.0]);생성. (셰이더 프로그램은 렌더러의 템플릿, renderer.get_shader_program())
Constructor. (the shader program is the renderer's template, renderer.get_shader_program())
- shader_programRc<ShaderProgram>
- 업로드와 그리기에 쓸 셰이더 프로그램. (renderer.get_shader_program())Shader program used for upload and drawing. (renderer.get_shader_program())
반환ReturnsSkinnedModel 노드, 드로어블, 클립이 없는 빈 모델. (재생 속도 1)An empty model with no nodes, drawables or clips. (playback speed 1)
짝Counterpart: vanilla.js SkinnedModel.constructor
셰이더 없이 생성. (해석과 포즈 계산만 하는 모델, upload_meshes_and_materials 는 오류)
Creates without a shader. (a model that only interprets and computes poses, upload_meshes_and_materials is an error)
반환ReturnsSkinnedModel 셰이더 없는 빈 모델. (interpret_content, interpret_fbx_content, update 는 되고 upload_meshes_and_materials 는 Err)An empty model without a shader. (interpret_content, interpret_fbx_content and update work, upload_meshes_and_materials is Err)
짝Counterpart: vanilla.js SkinnedModel.createWithoutShaderProgram
pub fn load_from_bytes(gl: &crate::GlContext, bytes: &[u8], skinned_model_renderer: &SkinnedModelRenderer) -> Result<SkinnedModel, String>#바이트로부터 로드. (GLB 바이너리 glTF, 원본 정적 loadFromUrl 의 fetch 뒤 부분)
Loads from bytes. (GLB binary glTF, the part after fetch in the original static loadFromUrl)
- gl&crate::GlContext
- 모델을 지을 GL 컨텍스트.GL context to build the model in.
- bytes&[u8]
- GLB 파일 바이트 전체.All bytes of the GLB file.
- skinned_model_renderer&SkinnedModelRenderer
- 셰이더 프로그램을 나눠 줄 렌더러.Renderer that shares its shader program.
반환ReturnsResult<SkinnedModel, String> 업로드까지 마친 모델. (클립이 있으면 첫 클립을 재생 중으로 둔다) GLB 가 아니거나 해석, 업로드에 실패하면 Err.A fully uploaded model. (if there are clips, the first clip is set as playing) Err if it is not GLB or interpretation or upload fails.
짝Counterpart: vanilla.js SkinnedModel.loadFromBytes
use vanilla::{SkinnedModel, SkinnedModelRenderer};
fn create_model(gl: &vanilla::GlContext, skinned_model_renderer: &SkinnedModelRenderer, glb_bytes: &[u8]) -> Result<SkinnedModel, String> {
let mut skinned_model = SkinnedModel::load_from_bytes(gl, glb_bytes, skinned_model_renderer)?;
skinned_model.update(0.0);
Ok(skinned_model)
}pub fn load_from_fbx_bytes(gl: &crate::GlContext, bytes: &[u8], skinned_model_renderer: &SkinnedModelRenderer) -> Result<SkinnedModel, String>#바이트로부터 로드. (바이너리 FBX, 원본 정적 loadFromFbxUrl 의 fetch 뒤 부분)
Loads from bytes. (binary FBX, the part after fetch in the original static loadFromFbxUrl)
- gl&crate::GlContext
- 모델을 지을 GL 컨텍스트.GL context to build the model in.
- bytes&[u8]
- 바이너리 FBX 파일 바이트 전체.All bytes of the binary FBX file.
- skinned_model_renderer&SkinnedModelRenderer
- 셰이더 프로그램을 나눠 줄 렌더러.Renderer that shares its shader program.
반환ReturnsResult<SkinnedModel, String> 업로드까지 마친 모델. (스킨이 붙은 메시만 드로어블이 된다) 파싱, 해석, 업로드에 실패하면 Err.A fully uploaded model. (only meshes with a skin attached become drawables) Err if parsing, interpretation or upload fails.
짝Counterpart: vanilla.js SkinnedModel.loadFromFbxBytes
use vanilla::{SkinnedModel, SkinnedModelRenderer};
fn create_character(gl: &vanilla::GlContext, skinned_model_renderer: &SkinnedModelRenderer, character_bytes: &[u8], walk_bytes: &[u8]) -> Result<SkinnedModel, String> {
let mut skinned_model = SkinnedModel::load_from_fbx_bytes(gl, character_bytes, skinned_model_renderer)?;
skinned_model.add_animations_from_fbx_bytes(walk_bytes, "Walk", true)?;
skinned_model.play_animation("Walk", 0.0);
Ok(skinned_model)
}애셋 경로(웹은 URL)로부터 받기 부탁. (GLB, 원본 정적 loadFromUrl, 다 받으면 손잡이의 create_model 이 짓는다)
Requests a load from an asset path (URL on the web). (GLB, the original static loadFromUrl, once loaded the handle's create_model builds it)
- engine&Engine
- 바이트를 부탁할 엔진.Engine to ask for the bytes.
- url&str
- GLB 애셋 경로. (데스크탑은 애셋 폴더 후보 기준 상대 경로, 웹은 asset_base_url 기준 주소)GLB asset path. (on desktop a path relative to the asset folder candidates, on the web an address relative to asset_base_url)
반환ReturnsSkinnedModelLoadHandle 받기 손잡이. (다 받으면 create_model 로 짓는다)Load handle. (once loaded, build with create_model)
짝Counterpart: vanilla.js SkinnedModel.loadFromUrl
애셋 경로(웹은 URL)로부터 받기 부탁. (바이너리 FBX, 원본 정적 loadFromFbxUrl)
Requests a load from an asset path (URL on the web). (binary FBX, the original static loadFromFbxUrl)
- engine&Engine
- 바이트를 부탁할 엔진.Engine to ask for the bytes.
- url&str
- 바이너리 FBX 애셋 경로. (데스크탑은 애셋 폴더 후보 기준 상대 경로, 웹은 asset_base_url 기준 주소)Binary FBX asset path. (on desktop a path relative to the asset folder candidates, on the web an address relative to asset_base_url)
반환ReturnsSkinnedModelLoadHandle 받기 손잡이. (다 받으면 create_model 로 짓는다)Load handle. (once loaded, build with create_model)
짝Counterpart: vanilla.js SkinnedModel.loadFromFbxUrl
pub fn load_from_url_async(engine: &Engine, url: &str, skinned_model_renderer: &SkinnedModelRenderer) -> impl Future<Output = Result<SkinnedModel, String>> + 'static#애셋 경로(웹은 URL)로부터 모델 받기. (GLB, 원본 await SkinnedModel.loadFromUrl(gl, url, renderer), 엔진 작업 안에서 await 한다)
- 다 받으면 작업을 폴링하는 엔진의 GL 로 짓는다. 렌더러는 지금 셰이더 프로그램만 나눠 들어, 퓨처가 렌더러를 빌리지 않는다.
Loads a model from an asset path (URL on the web). (GLB, the original await SkinnedModel.loadFromUrl(gl, url, renderer), awaited inside an engine task)
- Once loaded, it is built with the GL of the engine polling the task. The renderer only shares its current shader program, so the future does not borrow the renderer.
- engine&Engine
- 바이트를 부탁할 엔진.Engine to ask for the bytes.
- url&str
- GLB 애셋 경로.GLB asset path.
- skinned_model_renderer&SkinnedModelRenderer
- 셰이더 프로그램을 나눠 줄 렌더러.Renderer that shares its shader program.
반환Returnsimpl Future<Output = Result<SkinnedModel, String>> + 'static 엔진 작업 안에서 await 하는 퓨처. 받기에 실패하면 Err("SkinnedModel load failed: 경로"), 그래픽이 붙은 엔진의 작업 밖에서 폴링하면 Err, 해석이나 업로드에 실패하면 그 Err.Future awaited inside an engine task. Err("SkinnedModel load failed: path") if loading fails, Err if polled outside a task of an engine with graphics attached, and that Err if interpretation or upload fails.
짝Counterpart: vanilla.js SkinnedModel.loadFromUrl
use std::cell::RefCell;
use std::rc::Rc;
use vanilla::{Engine, SkinnedModel, SkinnedModelRenderer};
fn start_model_load(engine: &Engine, skinned_model_renderer: &SkinnedModelRenderer, model_slot: Rc<RefCell<Option<SkinnedModel>>>) {
let model_future = SkinnedModel::load_from_url_async(engine, "fox.glb", skinned_model_renderer);
engine.spawn_task(move |_engine_context| async move {
match model_future.await {
Ok(skinned_model) => {
*model_slot.borrow_mut() = Some(skinned_model);
}
Err(error_message) => {
eprintln!("{}", error_message);
}
}
});
}pub fn load_from_fbx_url_async(engine: &Engine, url: &str, skinned_model_renderer: &SkinnedModelRenderer) -> impl Future<Output = Result<SkinnedModel, String>> + 'static#애셋 경로(웹은 URL)로부터 모델 받기. (바이너리 FBX, 원본 await SkinnedModel.loadFromFbxUrl(gl, url, renderer))
Loads a model from an asset path (URL on the web). (binary FBX, the original await SkinnedModel.loadFromFbxUrl(gl, url, renderer))
- engine&Engine
- 바이트를 부탁할 엔진.Engine to ask for the bytes.
- url&str
- 바이너리 FBX 애셋 경로.Binary FBX asset path.
- skinned_model_renderer&SkinnedModelRenderer
- 셰이더 프로그램을 나눠 줄 렌더러.Renderer that shares its shader program.
반환Returnsimpl Future<Output = Result<SkinnedModel, String>> + 'static 엔진 작업 안에서 await 하는 퓨처. 받기에 실패하면 Err("FbxLoader load failed: 경로"), 그래픽이 붙은 엔진의 작업 밖에서 폴링하면 Err, 파싱, 해석, 업로드에 실패하면 그 Err.Future awaited inside an engine task. Err("FbxLoader load failed: path") if loading fails, Err if polled outside a task of an engine with graphics attached, and that Err if parsing, interpretation or upload fails.
짝Counterpart: vanilla.js SkinnedModel.loadFromFbxUrl
GLB 청크 읽기. (머리 확인 + JSON 청크 + BIN 청크, GL 무관)
Reads GLB chunks. (header check + JSON chunk + BIN chunk, GL independent)
- bytes&[u8]
- GLB 파일 바이트 전체.All bytes of the GLB file.
반환ReturnsResult<(Value, Vec<u8>), String> (glTF JSON, BIN 청크 바이트). 머리가 glTF 가 아니거나, 청크가 파일 밖을 가리키거나, JSON 이 깨졌거나, JSON 과 BIN 청크 가운데 하나라도 없으면 Err.(glTF JSON, BIN chunk bytes). Err if the header is not glTF, a chunk points outside the file, the JSON is broken, or either the JSON or BIN chunk is missing.
짝Counterpart: vanilla.js SkinnedModel.readGlbChunks
use vanilla::SkinnedModel;
let json_bytes = br#"{"asset":{"version":"2.0"}}"#;
let binary_bytes = [1u8, 2, 3, 4];
let mut glb_bytes = Vec::new();
glb_bytes.extend_from_slice(b"glTF");
glb_bytes.extend_from_slice(&2u32.to_le_bytes());
glb_bytes.extend_from_slice(&((12 + 8 + json_bytes.len() + 8 + binary_bytes.len()) as u32).to_le_bytes());
glb_bytes.extend_from_slice(&(json_bytes.len() as u32).to_le_bytes());
glb_bytes.extend_from_slice(b"JSON");
glb_bytes.extend_from_slice(json_bytes);
glb_bytes.extend_from_slice(&(binary_bytes.len() as u32).to_le_bytes());
glb_bytes.extend_from_slice(b"BIN\0");
glb_bytes.extend_from_slice(&binary_bytes);
let (json, binary_buffer) = SkinnedModel::read_glb_chunks(&glb_bytes).unwrap();
assert_eq!(json["asset"]["version"], "2.0");
assert_eq!(binary_buffer, vec![1, 2, 3, 4]);
assert!(SkinnedModel::read_glb_chunks(b"not a glb").is_err());pub fn create_from_asset(skinned_model_asset: &Rc<SkinnedModelAsset>) -> Result<SkinnedModel, String>#자산으로부터 인스턴스 짓기. (자산의 버퍼, 머티리얼 원형, 클립을 나눠 쓰고 포즈와 재생 상태는 따로, GPU 업로드 없음)
Create an instance from an asset. (shares the asset's buffers, material prototypes and clips, keeps its own pose and playback state, no GPU upload)
- skinned_model_asset&Rc<SkinnedModelAsset>
- 나눠 쓸 자산.Asset to share.
반환ReturnsResult<SkinnedModel, String> 자산의 참조 수를 하나 늘린 새 인스턴스. (노드는 자산을 올릴 때의 원형에서 베낀다) 지워진 자산이면 Err.New instance that added one to the asset's reference count. (nodes are copied from the prototypes taken when the asset was uploaded) Err if the asset was destroyed.
짝Counterpart: vanilla.js SkinnedModel.createFromAsset
pub fn split_fbx_corners_by_material(material_index_per_triangle: &[i32], corner_arrays: FbxCornerArrays) -> Vec<(usize, FbxCornerArrays)>#FBX 코너를 머티리얼별로 나누기. (GL 무관, 비인덱스 코너 배열)
- 메시 하나에 머티리얼이 여럿이면 머티리얼마다 부분 메시로 나눠 그린다. (three.js FBXLoader 의 그룹, 유니티와 언리얼의 서브메시)
- 부분 메시는 머티리얼 번호가 작은 것부터, 삼각형 차례는 원래대로. 번호가 하나뿐이면 배열을 그대로 쓴다.
Split FBX corners by material. (GL independent, non-indexed corner arrays)
- When one mesh has several materials, it is drawn as one sub-mesh per material. (Groups in three.js FBXLoader, sub-meshes in Unity and Unreal)
- Sub-meshes come in ascending material number and keep the original triangle order. With only one material number the arrays are used as they are.
- material_index_per_triangle&[i32]
- 삼각형마다 머티리얼 번호. (소유 노드 material_ids 안의 자리, 음수는 0)Material number per triangle. (A position in the owner node's material_ids, negative values count as 0)
- corner_arraysFbxCornerArrays
- 코너마다 위치 3, 노멀 3, UV 2, 조인트 4, 가중치 4.Per corner: 3 position, 3 normal, 2 UV, 4 joint and 4 weight values.
반환ReturnsVec<(usize, FbxCornerArrays)> (머티리얼 번호, 그 번호의 코너 배열) 목록.List of (material number, corner arrays for that number).
짝Counterpart: vanilla.js SkinnedModel.splitFbxCornersByMaterial
use vanilla::SkinnedModel;
use vanilla::graphics3d::skinnedmodel::FbxCornerArrays;
let corner_count = 9;
let corner_arrays = FbxCornerArrays {
positions: (0..corner_count * 3).map(|index| index as f64).collect(),
normals: vec![0.0; corner_count * 3],
texture_coordinates: vec![0.0; corner_count * 2],
joints: vec![0; corner_count * 4],
weights: vec![0.0; corner_count * 4],
};
let sub_mesh_list = SkinnedModel::split_fbx_corners_by_material(&[0, 1, 0], corner_arrays);
assert_eq!(sub_mesh_list.len(), 2);
assert_eq!(sub_mesh_list[0].0, 0);
assert_eq!(sub_mesh_list[0].1.positions.len() / 9, 2);
assert_eq!(sub_mesh_list[1].1.positions[0], 9.0);pub fn build_wireframe_edge_list(triangle_indices: Option<&IndexArray>, vertex_count: usize) -> Vec<usize>#와이어프레임 모서리 목록 만들기. (GL 무관, 인덱스 쌍 목록)
Builds the wireframe edge list. (GL independent, list of index pairs)
- triangle_indicesOption<&IndexArray>
- 삼각형 인덱스. (None 이면 정점 3개씩 삼각형)Triangle indices. (when None, every 3 vertices form a triangle)
- vertex_countusize
- 정점 개수.Vertex count.
반환ReturnsVec<usize> 선 인덱스 쌍 목록. (작은 인덱스, 큰 인덱스 차례, 겹친 모서리는 한 번만)List of line index pairs. (smaller index first, then larger, shared edges only once)
짝Counterpart: vanilla.js SkinnedModel.buildWireframeEdgeList
use vanilla::SkinnedModel;
use vanilla::graphics3d::skinnedmodel::IndexArray;
let quad_indices = IndexArray::UnsignedShort(vec![0, 1, 2, 2, 1, 3]);
let edge_list = SkinnedModel::build_wireframe_edge_list(Some(&quad_indices), 4);
assert_eq!(edge_list, vec![0, 1, 1, 2, 0, 2, 1, 3, 2, 3]);
assert_eq!(SkinnedModel::build_wireframe_edge_list(None, 3), vec![0, 1, 1, 2, 2, 0]);pub fn build_morph_texel_data(morph_target_list: &[MorphTarget], vertex_count: usize) -> (usize, usize, Vec<f32>)#모프 텍셀 데이터 만들기. (GL 무관, 텍스처 가로, 타깃당 행 수, RGBA 실수 배열)
Builds morph texel data. (GL independent, texture width, rows per target, RGBA float array)
- morph_target_list&[MorphTarget]
- 모프 타깃 목록.Morph target list.
- vertex_countusize
- 정점 개수.Vertex count.
반환Returns(usize, usize, Vec<f32>) (텍스처 가로, 타깃당 행 수, RGBA 실수 배열). (가로는 정점 수를 1 ~ 2048 로 자른 값, 높이는 행 수 x 2 x 타깃 수, 알파는 0)(texture width, rows per target, RGBA float array). (the width is the vertex count clamped to 1 ~ 2048, the height is rows x 2 x target count, alpha is 0)
짝Counterpart: vanilla.js SkinnedModel.buildMorphTexelData
pub fn generate_smooth_normals(positions: &[f64], indices: Option<&IndexArray>) -> Vec<f64>#스무스 노멀 생성. (노멀 미보유 메시, 바인드 포즈 기준, 스키닝 회전은 셰이더에서 적용)
Generates smooth normals. (meshes without normals, based on the bind pose, skinning rotation is applied in the shader)
- positions&[f64]
- 정점 위치. (3개씩)Vertex positions. (3 each)
- indicesOption<&IndexArray>
- 삼각형 인덱스. (None 이면 정점 3개씩 삼각형)Triangle indices. (when None, every 3 vertices form a triangle)
반환ReturnsVec<f64> 정점마다 단위 노멀. (positions 와 같은 길이, 면 노멀을 넓이 가중으로 더해 정규화한다. 삼각형에 쓰이지 않은 정점은 0)Unit normal per vertex. (same length as positions, face normals are added with area weighting and normalized. 0 for vertices not used by any triangle)
짝Counterpart: vanilla.js SkinnedModel.generateSmoothNormals
use vanilla::SkinnedModel;
let positions = [0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0, 0.0];
let normals = SkinnedModel::generate_smooth_normals(&positions, None);
assert_eq!(normals, vec![0.0, 0.0, 1.0, 0.0, 0.0, 1.0, 0.0, 0.0, 1.0]);pub fn bind_float_attribute(gl: &crate::GlContext, shader_program: &ShaderProgram, attribute_name: &str, data_array: &[f64], component_count: i32) -> Result<Option<GlBuffer>, String>#실수형 어트리뷰트 바인드. (신규 버퍼 생성 + 포인터 설정, 셰이더가 안 쓰는 어트리뷰트면 None)
- 지금 묶인 버텍스 어레이에 붙는다.
Binds a float attribute. (creates a new buffer + sets the pointer, None if the shader does not use the attribute)
- Attaches to the currently bound vertex array.
- gl&crate::GlContext
- GL 컨텍스트.GL context.
- shader_program&ShaderProgram
- 어트리뷰트 위치를 찾을 셰이더.Shader to look up the attribute location in.
- attribute_name&str
- 어트리뷰트 이름. (vertexPosition 같은 것)Attribute name. (such as vertexPosition)
- data_array&[f64]
- 정점 자료.Vertex data.
- component_counti32
- 정점당 성분 수. (1 ~ 4)Components per vertex. (1 ~ 4)
반환ReturnsResult<Option<GlBuffer>, String> 새로 지은 정점 버퍼. 셰이더가 그 어트리뷰트를 쓰지 않으면 Ok(None), 버퍼를 지을 수 없으면 Err.Newly built vertex buffer. Ok(None) if the shader does not use that attribute, Err if the buffer cannot be built.
짝Counterpart: vanilla.js SkinnedModel.bindFloatAttribute
pub fn bind_integer_attribute(gl: &crate::GlContext, shader_program: &ShaderProgram, attribute_name: &str, data_array: &[u16], component_count: i32) -> Result<Option<GlBuffer>, String>#정수형 어트리뷰트 바인드. (조인트 인덱스, 셰이더가 안 쓰는 어트리뷰트면 None)
- 지금 묶인 버텍스 어레이에 붙는다. 셰이더에서는 정수 어트리뷰트(uvec4 같은)로 읽는다.
Binds an integer attribute. (joint indices, None if the shader does not use the attribute)
- Attaches to the currently bound vertex array. The shader reads it as an integer attribute (such as uvec4).
- gl&crate::GlContext
- GL 컨텍스트.GL context.
- shader_program&ShaderProgram
- 어트리뷰트 위치를 찾을 셰이더.Shader to look up the attribute location in.
- attribute_name&str
- 어트리뷰트 이름. (vertexJoints 같은 것)Attribute name. (such as vertexJoints)
- data_array&[u16]
- u16 정점 자료.u16 vertex data.
- component_counti32
- 정점당 성분 수. (1 ~ 4)Components per vertex. (1 ~ 4)
반환ReturnsResult<Option<GlBuffer>, String> 새로 지은 정점 버퍼. 셰이더가 그 어트리뷰트를 쓰지 않으면 Ok(None), 버퍼를 지을 수 없으면 Err.Newly built vertex buffer. Ok(None) if the shader does not use that attribute, Err if the buffer cannot be built.
짝Counterpart: vanilla.js SkinnedModel.bindIntegerAttribute
GLB 바이너리 해석. (청크 읽기 → 내용 해석 → GL 업로드)
Interprets GLB binary. (chunk reading → content interpretation → GL upload)
- gl&crate::GlContext
- 업로드할 GL 컨텍스트.GL context to upload to.
- bytes&[u8]
- GLB 파일 바이트 전체.All bytes of the GLB file.
반환ReturnsResult<(), String> 다 되면 Ok. 청크 읽기, 해석, 업로드의 Err.Ok when done. The Err of chunk reading, interpretation or upload.
짝Counterpart: vanilla.js SkinnedModel.parseBinary
pub fn parse_content(&mut self, gl: &crate::GlContext, json: &Value, binary_buffer: &[u8]) -> Result<(), String>#glTF 내용 해석. (노드 / 스킨 / 메시 / 애니메이션 / 텍스처 → GL 업로드)
Parses glTF content. (nodes / skins / meshes / animations / textures → GL upload)
- gl&crate::GlContext
- 업로드할 GL 컨텍스트.GL context to upload to.
- json&Value
- glTF JSON 전체.The whole glTF JSON.
- binary_buffer&[u8]
- BIN 청크 바이트.BIN chunk bytes.
반환ReturnsResult<(), String> 다 되면 Ok. 해석이나 업로드의 Err.Ok when done. The Err of interpretation or upload.
짝Counterpart: vanilla.js SkinnedModel.parseContent
pub fn interpret_content(&mut self, json: &Value, binary_buffer: &[u8]) -> Result<(Vec<MeshDescription>, Vec<MaterialDescription>), String>#glTF 내용 해석. (GL 무관, 노드 / 스킨 / 애니메이션을 채우고 중립 메시 / 머티리얼 서술을 돌려준다)
- 모델의 노드, 루트, 스킨, 클립을 이 내용으로 바꾼다. 클립이 있으면 첫 클립을 재생 중으로 둔다.
- 노멀이 없는 프리미티브는 glTF 2.0 명세대로 평평한 노멀(삼각형마다 하나)이다. 꼭짓점을 삼각형마다 따로 풀어 면 노멀을 주고 indices 는 None 이다.
Parses glTF content. (GL independent, fills nodes / skins / animations and returns neutral mesh / material descriptions)
- Replaces the model's nodes, roots, skins and clips with this content. If there are clips, the first clip is set as playing.
- A primitive without normals has flat normals (one per triangle) as the glTF 2.0 specification says. The vertices are split per triangle and given the face normal, and indices is None.
- json&Value
- glTF JSON 전체.The whole glTF JSON.
- binary_buffer&[u8]
- BIN 청크 바이트.BIN chunk bytes.
반환ReturnsResult<(Vec<MeshDescription>, Vec<MaterialDescription>), String> (메시 서술 목록, 머티리얼 서술 목록). 노드나 씬이 없거나, 없는 메시를 가리키거나, 프리미티브에 POSITION 이 없거나, 스킨 메시에 JOINTS_0 이나 WEIGHTS_0 이 없거나, 접근자를 읽을 수 없으면 Err.(mesh description list, material description list). Err if there is no node or scene, a missing mesh is referenced, a primitive has no POSITION, a skinned mesh has no JOINTS_0 or WEIGHTS_0, or an accessor cannot be read.
짝Counterpart: vanilla.js SkinnedModel.interpretContent
pub fn parse_fbx_content(&mut self, gl: &crate::GlContext, scene_data: &FbxSceneData) -> Result<(), String>#FBX 중간 표현 해석. (노드/스킨/메시/텍스처/애니메이션 → 기존 스키닝 파이프라인)
Parses the FBX intermediate representation. (nodes/skins/meshes/textures/animations → existing skinning pipeline)
- gl&crate::GlContext
- 업로드할 GL 컨텍스트.GL context to upload to.
- scene_data&FbxSceneData
- FbxLoader 가 낸 중간 표현.Intermediate representation produced by FbxLoader.
반환ReturnsResult<(), String> 다 되면 Ok. 업로드의 Err.Ok when done. The Err of upload.
짝Counterpart: vanilla.js SkinnedModel.parseFbxContent
pub fn interpret_fbx_content(&mut self, scene_data: &FbxSceneData) -> Result<(Vec<MeshDescription>, Vec<MaterialDescription>), String>#FBX 중간 표현 해석. (GL 무관, 노드 / 스킨 / 애니메이션을 채우고 중립 메시 / 머티리얼 서술을 돌려준다)
- 모델의 노드, 루트, 스킨, 클립을 이 내용으로 바꾼다. 클립이 있으면 첫 클립을 재생 중으로 둔다.
Parses the FBX intermediate representation. (GL independent, fills nodes / skins / animations and returns neutral mesh / material descriptions)
- Replaces the model's nodes, roots, skins and clips with this content. If there are clips, the first clip is set as playing.
- scene_data&FbxSceneData
- FbxLoader 가 낸 중간 표현.Intermediate representation produced by FbxLoader.
반환ReturnsResult<(Vec<MeshDescription>, Vec<MaterialDescription>), String> (메시 서술 목록, 머티리얼 서술 목록). (지오메트리가 이어진 스킨 디포머마다, 그 지오메트리가 쓰는 머티리얼마다 메시 하나, 지금은 Err 를 내지 않는다)(Mesh description list, material description list). (One mesh per skin deformer with a connected geometry and per material that geometry uses, currently never returns Err)
짝Counterpart: vanilla.js SkinnedModel.interpretFbxContent
pub fn add_animations_from_fbx_scene_data(&mut self, scene_data: &FbxSceneData, clip_name: &str, ignore_translation: bool)#애니메이션 FBX 추가. (본 이름 매칭 리타게팅, Mixamo 애니메이션 전용 FBX 의 중간 표현)
- 동일 스켈레톤을 전제로, 채널을 현재 모델의 노드 인덱스로 재지정해 클립을 추가한다.
- ignore_translation: 루트 모션이 박힌 클립에서 이동 채널을 버린다. (게임 로직이 위치를 제어할 때)
- clip_name: 채널이 있는 스택이 하나면 이 이름, 여럿이면 스택마다 "이 이름/스택 이름" 이다.
Adds an animation FBX. (retargeting by bone name matching, intermediate representation of an animation-only Mixamo FBX)
- Assuming the same skeleton, adds clips by remapping channels to node indices of the current model.
- ignore_translation: drops translation channels in clips with baked root motion. (when game logic controls the position)
- clip_name: this name if there is one stack with channels, and "this name/stack name" per stack if there are several.
- scene_data&FbxSceneData
- 애니메이션 FBX 의 중간 표현.Intermediate representation of the animation FBX.
- clip_name&str
- 더할 클립 이름. (스택이 여럿이면 모두 이 이름이 된다)Name of the clip to add. (if there are several stacks, they all get this name)
- ignore_translationbool
- true 면 이동 채널을 버린다.If true, translation channels are dropped.
짝Counterpart: vanilla.js SkinnedModel.addAnimationsFromFbxSceneData
pub fn add_animations_from_fbx_bytes(&mut self, bytes: &[u8], clip_name: &str, ignore_translation: bool) -> Result<(), String>#애니메이션 FBX 추가. (바이트, 원본 addAnimationsFromFbxUrl 의 fetch 뒤 부분)
Adds animation FBX. (bytes, the part after fetch in the original addAnimationsFromFbxUrl)
- bytes&[u8]
- 애니메이션 FBX 파일 바이트 전체.All bytes of the animation FBX file.
- clip_name&str
- 더할 클립 이름.Name of the clip to add.
- ignore_translationbool
- true 면 이동 채널을 버린다.If true, translation channels are dropped.
반환ReturnsResult<(), String> 더했으면 Ok. 파싱에 실패하면 클립을 더하지 않고 Err.Ok if added. If parsing fails, no clip is added and Err is returned.
짝Counterpart: vanilla.js SkinnedModel.addAnimationsFromFbxBytes
use vanilla::SkinnedModel;
let mut skinned_model = SkinnedModel::create_without_shader_program();
assert!(skinned_model.add_animations_from_fbx_bytes(b"not an fbx", "Walk", true).is_err());
assert!(skinned_model.get_animation_name_list().is_empty());pub fn add_animations_from_fbx_url(&mut self, engine: &Engine, url: &str, clip_name: &str, ignore_translation: bool) -> AnimationLoadHandle#애니메이션 FBX 추가. (애셋 경로, 원본 addAnimationsFromFbxUrl, await 할 수 있는 손잡이를 돌려준다)
- await 하면 다 받아 클립을 더할 때까지 기다린다. (원본처럼 await 가 끝날 때는 클립이 이미 더해져 있다) await 하지 않아도 다 받은 뒤 다음 update 나 play_animation 에서 더한다. 받은 차례로 더한다. (원본 async 함수가 끝나는 차례)
- 받기나 파싱에 실패하면 클립을 더하지 않고 오류를 찍고, await 는 까닭으로 끝난다. (원본은 Promise 가 거부된다)
- 노드 이름은 부르는 때의 노드로 맞춘다. 모델을 지은 뒤에 부른다.
Adds animation FBX. (asset path, the original addAnimationsFromFbxUrl, returns an awaitable handle)
- Awaiting waits until loading finishes and the clips are added. (like the original, the clips are already added when await finishes) Even without await, they are added on the next update or play_animation after loading. They are added in load order. (the order in which the original async functions finish)
- If loading or parsing fails, no clip is added, an error is printed, and await ends with the reason. (the original Promise is rejected)
- Node names are matched against the nodes at the time of the call. Call it after the model is built.
- engine&Engine
- 바이트를 부탁할 엔진.Engine to ask for the bytes.
- url&str
- 애니메이션 FBX 애셋 경로.Animation FBX asset path.
- clip_name&str
- 더할 클립 이름.Name of the clip to add.
- ignore_translationbool
- true 면 이동 채널을 버린다.If true, translation channels are dropped.
반환ReturnsAnimationLoadHandle await 할 수 있는 받기 손잡이. (버려도 모델이 들고 있어 클립은 더해진다)Awaitable load handle. (even if dropped, the model holds it and the clips are added)
짝Counterpart: vanilla.js SkinnedModel.addAnimationsFromFbxUrl
pub fn upload_meshes_and_materials(&mut self, gl: &crate::GlContext, mesh_description_list: Vec<MeshDescription>, material_description_list: Vec<MaterialDescription>) -> Result<(), String>#중립 메시/머티리얼 서술 업로드. (공용, Material 생성 + 버텍스 어레이/드로어블 구성)
- 예전 자산은 먼저 놓는다. (destroy, 다시 불러도 새지 않는다)
- 올린 버퍼, 머티리얼, 모프 텍스처와 지금 노드, 스킨, 클립을 새 자산(SkinnedModelAsset, 참조 수 1)으로 묶고 이 모델이 그 첫 인스턴스가 된다.
Upload neutral mesh/material descriptions. (shared path, creates Materials and builds vertex arrays/drawables)
- Releases the previous asset first. (destroy, so calling it again does not leak)
- Bundles the uploaded buffers, materials and morph textures with the current nodes, skins and clips into a new asset (SkinnedModelAsset, reference count 1), and this model becomes its first instance.
- gl&crate::GlContext
- 업로드할 GL 컨텍스트.GL context to upload to.
- mesh_description_listVec<MeshDescription>
- 메시 서술 목록.Mesh description list.
- material_description_listVec<MaterialDescription>
- 머티리얼 서술 목록. (material_index 가 가리키는 자리)Material description list. (the positions material_index points to)
반환ReturnsResult<(), String> 다 되면 Ok. 셰이더 없이 만든 모델이거나, 머티리얼이나 GL 객체를 지을 수 없으면 Err.Ok when done. Err if the model was made without a shader, or a material or GL object cannot be built.
짝Counterpart: vanilla.js SkinnedModel.uploadMeshesAndMaterials
인스턴스 짓기. (이 모델과 같은 자산을 나눠 쓰는 새 모델, 유니티의 Instantiate 처럼 GPU 자원을 다시 올리지 않는다)
Create an instance. (a new model sharing this model's asset; like Unity's Instantiate, GPU resources are not uploaded again)
반환ReturnsResult<SkinnedModel, String> 새 인스턴스. (노드는 자산을 올릴 때의 원형에서 베끼고 재생 상태는 처음부터) 올리기 전이면 Err.New instance. (nodes copied from the prototypes taken when the asset was uploaded, playback starts fresh) Err before upload.
짝Counterpart: vanilla.js SkinnedModel.createInstance
use vanilla::SkinnedModel;
fn spawn_foxes(source_model: &SkinnedModel) -> Result<Vec<SkinnedModel>, String> {
let mut model_list = Vec::new();
for model_index in 1..10 {
let mut instance_model = source_model.create_instance()?;
instance_model.play_animation(if model_index % 2 == 0 { "Walk" } else { "Run" }, 0.0);
model_list.push(instance_model);
}
Ok(model_list)
}
fn destroy_foxes(gl: &vanilla::GlContext, source_model: &mut SkinnedModel, model_list: &mut Vec<SkinnedModel>) {
let skinned_model_asset = source_model.get_asset().cloned();
for model in model_list.iter_mut() {
model.destroy(gl);
}
source_model.destroy(gl);
assert!(skinned_model_asset.is_some_and(|skinned_model_asset| skinned_model_asset.is_destroyed()));
}자산 반환.
Return the asset.
반환ReturnsOption<&Rc<SkinnedModelAsset>> 나눠 쓰는 자산. (올리기 전이나 destroy 뒤에는 None)Shared asset. (None before upload or after destroy)
짝Counterpart: vanilla.js SkinnedModel.getAsset
pub fn upload_wireframe_indices(&mut self, gl: &crate::GlContext, drawable_index: usize) -> Result<(), String>#와이어프레임 인덱스 업로드. (삼각형 인덱스 → 중복 없는 모서리 선 인덱스, 비인덱스 메시는 삼각형별 3변)
- 드로어블의 버텍스 어레이와 무관한 별도 엘리먼트 버퍼. 렌더러가 선 출력 시 잠시 바꿔 끼운다.
- 이미 올린 선 버퍼가 있으면 지우고 새로 올린다.
Upload wireframe indices. (Triangle indices → unique edge line indices, three edges per triangle for non-indexed meshes)
- A separate element buffer independent of the drawable's vertex array. The renderer swaps it in briefly when drawing lines.
- An already uploaded line buffer is deleted and uploaded again.
- gl&crate::GlContext
- 업로드할 GL 컨텍스트.GL context to upload to.
- drawable_indexusize
- 드로어블 자리.Drawable index.
반환ReturnsResult<(), String> 올렸으면 Ok. 드로어블이 없거나 버퍼를 지을 수 없으면 Err.Ok if uploaded. Err if there is no drawable or a buffer cannot be built.
짝Counterpart: vanilla.js SkinnedModel.uploadWireframeIndices
pub fn upload_morph_targets(&mut self, gl: &crate::GlContext, drawable_index: usize) -> Result<(), String>#모프 타깃 업로드. (드로어블의 델타 목록 → RGBA32F 텍스처, 타깃마다 위치 블록 + 노멀 블록)
- 텍셀 인덱스 = 정점 인덱스. 블록 시작 행 = 타깃 인덱스 x 2 x 타깃당 행 수.
Uploads morph targets. (drawable's delta list → RGBA32F texture, position block + normal block per target)
- texel index = vertex index. block start row = target index x 2 x rows per target.
- gl&crate::GlContext
- 업로드할 GL 컨텍스트.GL context to upload to.
- drawable_indexusize
- 드로어블 자리.Drawable index.
반환ReturnsResult<(), String> 올렸으면 Ok. (타깃이 없으면 텍스처를 지우고 Ok) 드로어블이 없거나 텍스처를 지을 수 없으면 Err.Ok if uploaded. (if there are no targets, the texture is deleted and Ok) Err if there is no drawable or the texture cannot be built.
짝Counterpart: vanilla.js SkinnedModel.uploadMorphTargets
바뀐 모프 타깃 업로드. (원본 update 6단계, 추가/변경된 드로어블만, 렌더러가 그리기 전에 부른다)
- 올리다 실패한 드로어블은 오류를 찍고 다시 올리지 않는다.
Uploads changed morph targets. (step 6 of the original update, only added/changed drawables, called by the renderer before drawing)
- A drawable that fails to upload prints an error and is not uploaded again.
- gl&crate::GlContext
- 업로드할 GL 컨텍스트.GL context to upload to.
pub fn add_morph_target(&mut self, drawable_index: usize, target_name: &str, position_deltas: Vec<f64>, normal_deltas: Option<Vec<f64>>) -> Result<(), String>#모프 타깃 추가. (프로그램 생성, 정점별 위치 델타 [+ 노멀 델타], 다음 그리기 전에 업로드)
Adds a morph target. (created in code, per-vertex position deltas [+ normal deltas], uploaded before the next draw)
- drawable_indexusize
- 드로어블 자리.Drawable index.
- target_name&str
- 타깃 이름. (set_morph_weight 가 이 이름으로 찾는다)Target name. (set_morph_weight looks it up by this name)
- position_deltasVec<f64>
- 정점마다 위치 델타. (정점 수 x 3 개여야 한다)Position delta per vertex. (must be vertex count x 3)
- normal_deltasOption<Vec<f64>>
- 정점마다 노멀 델타. (None 이면 노멀은 그대로)Normal delta per vertex. (normals are left as is when None)
반환ReturnsResult<(), String> 더했으면 Ok. (가중치 0 으로 시작) 드로어블이 없거나, 타깃이 이미 MORPH_TARGET_MAXIMUM 개이거나, 델타 개수가 맞지 않으면 Err.Ok if added. (starts at weight 0) Err if there is no drawable, there are already MORPH_TARGET_MAXIMUM targets, or the delta count does not match.
짝Counterpart: vanilla.js SkinnedModel.addMorphTarget
use vanilla::SkinnedModel;
fn add_lift_target(skinned_model: &mut SkinnedModel) -> Result<(), String> {
let vertex_count = skinned_model.get_drawable_list().first().map(|drawable| drawable.vertex_count).unwrap_or(0);
let mut position_deltas = vec![0.0; vertex_count * 3];
for vertex_index in 0..vertex_count {
position_deltas[vertex_index * 3 + 1] = 0.1;
}
skinned_model.add_morph_target(0, "Lift", position_deltas, None)?;
skinned_model.set_morph_weight("Lift", 0.5);
Ok(())
}
let mut skinned_model = SkinnedModel::create_without_shader_program();
assert!(add_lift_target(&mut skinned_model).is_err());모프 가중치 설정. (이름 일치 타깃 전부, 드로어블 여러 개가 같은 이름을 가질 수 있음)
Sets the morph weight. (all targets with a matching name, several drawables can share the same name)
- target_name&str
- 타깃 이름. (이름이 같은 타깃 모두)Target name. (all targets with the same name)
- weightf64
- 가중치. (0 = 없음, 1 = 델타 그대로, 자르지 않는다)Weight. (0 = none, 1 = the full delta, not clamped)
짝Counterpart: vanilla.js SkinnedModel.setMorphWeight
모프 가중치 반환. (첫 일치 타깃, 없으면 0)
Returns the morph weight. (first matching target, 0 if none)
- target_name&str
- 타깃 이름.Target name.
반환Returnsf64 처음 맞는 타깃의 가중치. 없으면 0.Weight of the first matching target. 0 if none.
짝Counterpart: vanilla.js SkinnedModel.getMorphWeight
pub fn set_material(&mut self, drawable_index: usize, material: Rc<Material>) -> Result<(), String>#머티리얼 교체. (드로어블 단위, 외부 텍스처로 만든 머티리얼 인스턴스 적용)
Replaces the material. (per drawable, applies a material instance made from an external texture)
- drawable_indexusize
- 드로어블 자리.Drawable index.
- materialRc<Material>
- 바꿔 낄 머티리얼.Material to swap in.
반환ReturnsResult<(), String> 바꿨으면 Ok. 드로어블이 없으면 Err.Ok if swapped. Err if there is no drawable.
짝Counterpart: vanilla.js SkinnedModel.setMaterial
이 인스턴스의 머티리얼 반환. (유니티 Renderer.material, 처음 부르면 지금 머티리얼의 사본으로 갈라져 이 드로어블에 낀다)
- 사본은 텍스처를 빌려 쓰고 값만 따로다. 값을 바꿔도 같은 자산을 쓰는 다른 인스턴스는 그대로다. 사본은 이 모델의 destroy 가 지운다.
- 이미 이 인스턴스의 사본이면 그것을 돌려준다.
Return this instance's material. (Unity Renderer.material: the first call forks a copy of the current material and puts it on this drawable)
- The copy borrows the textures and keeps its own values. Changing them leaves other instances of the same asset as they are. This model's destroy deletes the copy.
- If it is already this instance's copy, returns it.
- drawable_indexusize
- 드로어블 자리.Drawable index.
반환ReturnsResult<Rc<Material>, String> 이 인스턴스만 쓰는 머티리얼. 드로어블이 없으면 Err.Material used only by this instance. Err if the drawable does not exist.
짝Counterpart: vanilla.js SkinnedModel.getMaterial
use vanilla::SkinnedModel;
fn tint_red(blue_fox: &SkinnedModel) -> Result<SkinnedModel, String> {
let mut red_fox = blue_fox.create_instance()?;
red_fox.get_material(0)?.set_base_color_factor([1.0, 0.3, 0.3]);
assert_ne!(blue_fox.get_shared_material(0)?.get_base_color_factor(), red_fox.get_shared_material(0)?.get_base_color_factor());
Ok(red_fox)
}애니메이션 재생. (크로스페이드, 같은 이름이 여럿이면 원본처럼 마지막 것, 원본 fadeDuration 기본값 0.25. 다 받은 애니메이션 FBX 의 클립을 먼저 더한다)
Plays an animation. (crossfade, the last one like the original if several have the same name, the original fadeDuration default 0.25. Adds the clips of fully received animation FBX first)
- animation_name&str
- 틀 클립 이름. (없는 이름이거나 지금 클립과 같으면 무시)Name of the clip to play. (ignored if the name does not exist or is the same as the current clip)
- fade_durationf64
- 크로스페이드 시간. (초, 0 이면 다음 update 에서 바로 바뀐다)Cross-fade time. (seconds, at 0 it switches right away on the next update)
짝Counterpart: vanilla.js SkinnedModel.playAnimation
애니메이션 샘플링. (클립 인덱스, 현재 노드 포즈에 가중 블렌딩)
Samples an animation. (clip index, weighted blend into the current node pose)
- animation_indexusize
- 클립 인덱스. (밖이면 무시)Clip index. (ignored if out of range)
- timef64
- 클립 시간. (초, 클립 길이로 나눈 나머지로 반복한다)Clip time. (seconds, loops using the remainder of division by the clip length)
- blend_weightf64
- 섞는 비율. (0 ~ 1, 0 이면 지금 포즈 그대로, 1 이면 클립 값)Blend ratio. (0 ~ 1, 0 keeps the current pose, 1 is the clip value)
짝Counterpart: vanilla.js SkinnedModel.sampleAnimation
갱신. (다 받은 애니메이션 FBX 의 클립 더하기 → 시간 전진 → 포즈 샘플링 → 월드/조인트 행렬 계산, GL 무관)
Update. (adds clips of loaded animation FBX → advances time → samples the pose → computes world/joint matrices, GL independent)
- delta_timef64
- 지난 시간. (초, 클립 시간에는 재생 속도를 곱하고 크로스페이드 시간에는 곱하지 않는다)Elapsed time. (seconds, the playback speed is multiplied into the clip time but not into the cross-fade time)
짝Counterpart: vanilla.js SkinnedModel.update
pub fn set_joint_rotation_offset(&mut self, joint_name_part: &str, offset_rotation: Quaternion)#조인트 회전 오프셋 설정. (이름 부분 일치 노드에 로컬 회전 누적)
Sets a joint rotation offset. (accumulates local rotation on nodes whose name partially matches)
- joint_name_part&str
- 노드 이름에 든 글자. (부분 일치, 맞는 노드 모두)Text contained in the node name. (partial match, all matching nodes)
- offset_rotationQuaternion
- 샘플링한 로컬 회전 뒤에 곱할 회전. (같은 노드에 다시 주면 바꾼다)Rotation multiplied after the sampled local rotation. (giving it again for the same node replaces it)
짝Counterpart: vanilla.js SkinnedModel.setJointRotationOffset
use vanilla::{Quaternion, SkinnedModel};
let mut skinned_model = SkinnedModel::create_without_shader_program();
skinned_model.set_joint_rotation_offset("Head", Quaternion::create_from_euler(0.0, 30.0f64.to_radians(), 0.0));
skinned_model.update(0.0);
skinned_model.clear_joint_rotation_offsets();조인트 회전 오프셋 전체 해제.
Clears all joint rotation offsets.
짝Counterpart: vanilla.js SkinnedModel.clearJointRotationOffsets
애니메이션 이름 목록 반환.
Returns the list of animation names.
반환ReturnsVec<String> 클립 이름 목록. (클립 차례, 같은 이름이 여럿일 수 있다)List of clip names. (in clip order, several may share a name)
짝Counterpart: vanilla.js SkinnedModel.getAnimationNameList
재생 속도 설정.
Sets the playback speed.
- time_scalef64
- 재생 속도 배수. (기본 1, 0 이면 멈춘다, 크로스페이드 시간에는 걸리지 않는다)Playback speed multiplier. (default 1, stops at 0, not applied to the cross-fade time)
짝Counterpart: vanilla.js SkinnedModel.setTimeScale
셰이더 프로그램 반환. (셰이더 없이 만든 모델이면 None)
Returns the shader program. (None for a model made without a shader)
반환ReturnsOption<&Rc<ShaderProgram>> 업로드에 쓰는 셰이더 프로그램. 셰이더 없이 만든 모델이면 None.Shader program used for upload. None for a model made without a shader.
짝Counterpart: vanilla.js SkinnedModel.getShaderProgram
노드 목록 반환.
Returns the node list.
반환Returns&[SkinnedModelNode] 노드 목록. (노드 인덱스 차례)Node list. (in node index order)
짝Counterpart: vanilla.js SkinnedModel.getNodeList
노드 목록 반환. (변경용, 원본은 살아 있는 배열을 내준다)
Returns the node list. (for modification, the original hands out the live array)
반환Returns&mut [SkinnedModelNode] 바꿀 수 있는 노드 목록. (base_ 값을 바꾸면 다음 update 부터 기본 포즈가 바뀐다)Mutable node list. (changing the base_ values changes the base pose from the next update)
짝Counterpart: vanilla.js SkinnedModel.getNodeList
루트 노드 인덱스 목록 반환.
Returns the list of root node indices.
반환Returns&[usize] 루트 노드 인덱스 목록.Root node index list.
짝Counterpart: vanilla.js SkinnedModel.getRootNodeIndices
스킨 목록 반환.
Returns the skin list.
반환Returns&[Skin] 스킨 목록. (조인트 행렬은 마지막 update 의 것)Skin list. (the joint matrices are from the last update)
짝Counterpart: vanilla.js SkinnedModel.getSkinList
드로어블 목록 반환.
Returns the drawable list.
반환Returns&[Drawable] 드로어블 목록. (업로드 전이나 셰이더 없이 만든 모델이면 비어 있다)Drawable list. (empty before upload or for a model made without a shader)
짝Counterpart: vanilla.js SkinnedModel.getDrawableList
드로어블 목록 반환. (변경용)
Returns the drawable list. (for modification)
반환Returns&mut [Drawable] 바꿀 수 있는 드로어블 목록.Mutable drawable list.
짝Counterpart: vanilla.js SkinnedModel.getDrawableList
애니메이션 클립 목록 반환. (길이, 채널 보기. 애니메이션 FBX 받기 손잡이와 나눠 드는 목록이라 빌린 값으로 준다)
Returns the animation clip list. (for viewing lengths and channels. The list is shared with animation FBX load handles, so it is given as a borrowed value)
반환Returnsstd::cell::Ref<'_, [AnimationClip]> 클립 목록을 빌린 값. (Ref 를 든 동안 await 중인 AnimationLoadFuture 는 클립을 더하지 못하고 기다린다)Borrowed value of the clip list. (while the Ref is held, an AnimationLoadFuture being awaited cannot add clips and waits)
짝Counterpart: vanilla.js SkinnedModel.getAnimationList
파괴. (이 인스턴스 것을 지우고 자산을 놓는다, 마지막 인스턴스면 자산이 버퍼, 버텍스 어레이, 모프 텍스처, 머티리얼 원형을 지운다)
- 이 인스턴스 것: 와이어프레임 버퍼, add_morph_target 으로 갈라진 모프 텍스처, get_material 로 갈라진 머티리얼.
- set_material 로 바깥에서 넣은 머티리얼은 지우지 않는다. 자산의 머티리얼 원형을 다른 모델에 넣어 썼다면 자산이 지워질 때 함께 지워진다.
Destroy. (deletes this instance's resources and releases the asset; for the last instance the asset deletes its buffers, vertex arrays, morph textures and material prototypes)
- This instance's resources: wireframe buffers, morph textures forked by add_morph_target, materials forked by get_material.
- Materials given from outside with set_material are not deleted. If the asset's material prototypes were put on another model, they are deleted together when the asset is destroyed.
- gl&crate::GlContext
- 드로어블을 지은 GL 컨텍스트.GL context the drawables were built in.
짝Counterpart: vanilla.js SkinnedModel.destroy
AnimationLoadHandlestruct traits Clone, std::fmt::Debug, IntoFuture
애니메이션 FBX 받기 손잡이. (SkinnedModel::add_animations_from_fbx_url 이 돌려준다. 원본 addAnimationsFromFbxUrl 의 Promise 자리)
- await 하면 다 받아 클립을 모델에 더할 때까지 기다린다. 받기나 파싱에 실패하면 까닭으로 끝난다. (원본 reject)
Animation FBX load handle. (returned by SkinnedModel::add_animations_from_fbx_url, stands in for the Promise of the original addAnimationsFromFbxUrl)
- Awaiting waits until loading finishes and the clips are added to the model. If loading or parsing fails, it ends with the reason. (the original reject)
use std::cell::RefCell;
use std::rc::Rc;
use vanilla::{Engine, SkinnedModel};
fn add_walk_clip(engine: &Engine, skinned_model: Rc<RefCell<SkinnedModel>>) {
let animation_load_handle = skinned_model.borrow_mut().add_animations_from_fbx_url(engine, "anims/walk.fbx", "Walk", true);
engine.spawn_task(move |_engine_context| async move {
if animation_load_handle.await.is_ok() {
skinned_model.borrow_mut().play_animation("Walk", 0.25);
}
});
}바이트 읽기 손잡이. (씬에 맡길 때)
Byte read handle. (for handing to a scene)
반환Returns&AssetLoadHandle FBX 바이트 읽기 손잡이. (SceneBase::track_load_handle 에 넘긴다)FBX byte read handle. (passed to SceneBase::track_load_handle)
끝났는지. (클립을 더했거나 실패했거나)
Whether it has finished. (clips added or failed)
반환Returnsbool 클립을 더했거나 받기, 파싱에 실패했으면 true. (바이트를 다 받아도 update, play_animation, await 가운데 하나가 더하기 전에는 false)true if the clips were added or loading or parsing failed. (even after all bytes are loaded, false until one of update, play_animation or await adds them)
AnimationLoadFuturestruct traits Clone, Future
애니메이션 FBX 받기를 기다리는 퓨처. (다 받으면 클립을 더하고 끝난다)
Future that waits for the animation FBX load. (once loaded, it adds the clips and finishes)
use std::future::IntoFuture;
use vanilla::{AnimationLoadFuture, Engine, SkinnedModel};
fn request_idle_clip(engine: &Engine, skinned_model: &mut SkinnedModel) {
let animation_load_future: AnimationLoadFuture = skinned_model.add_animations_from_fbx_url(engine, "anims/idle.fbx", "Idle", false).into_future();
engine.spawn_task(move |_engine_context| async move {
if let Err(error_message) = animation_load_future.await {
eprintln!("{}", error_message);
}
});
}SkinnedModelLoadHandlestruct traits Clone, Debug
모델 받기 손잡이. (SkinnedModel::load_from_url, load_from_fbx_url 이 돌려준다. 원본 loadFromUrl, loadFromFbxUrl 의 Promise 자리)
- 씬은 get_load_handle 을 SceneBase::track_load_handle 로 맡겨 다 받을 때까지 initialize 를 미룰 수 있다.
- 모델은 GL 이 있는 자리에서 create_model(gl, 렌더러)로 짓는다.
Model load handle. (returned by SkinnedModel::load_from_url and load_from_fbx_url, stands in for the Promise of the original loadFromUrl and loadFromFbxUrl)
- A scene can hand get_load_handle to SceneBase::track_load_handle to defer initialize until loading finishes.
- The model is built with create_model(gl, renderer) where GL is available.
use vanilla::{Engine, Graphic, Scene, SceneBase, SkinnedModel, SkinnedModelLoadHandle, SkinnedModelRenderer};
struct CharacterScene {
scene_base: SceneBase,
model_load_handle: Option<SkinnedModelLoadHandle>,
skinned_model_renderer: Option<SkinnedModelRenderer>,
skinned_model: Option<SkinnedModel>,
}
impl Scene for CharacterScene {
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 model_load_handle = SkinnedModel::load_from_url(engine, "fox.glb");
self.scene_base.track_load_handle(model_load_handle.get_load_handle());
self.model_load_handle = Some(model_load_handle);
}
fn tick(&mut self, time_delta: f64) {
self.scene_base.tick(time_delta);
if let Some(skinned_model) = &mut self.skinned_model {
skinned_model.update(time_delta);
}
}
fn draw(&mut self, graphic: &mut Graphic) {
let gl = graphic.get_gl();
if self.skinned_model_renderer.is_none() {
self.skinned_model_renderer = SkinnedModelRenderer::new(gl, None, None).ok();
}
let model_result = match (&self.skinned_model_renderer, &self.model_load_handle) {
(Some(skinned_model_renderer), Some(model_load_handle)) => {
model_load_handle.create_model(gl, skinned_model_renderer)
}
_ => {
None
}
};
if let Some(model_result) = model_result {
self.model_load_handle = None;
match model_result {
Ok(skinned_model) => {
self.skinned_model = Some(skinned_model);
}
Err(error_message) => {
eprintln!("{}", error_message);
}
}
}
}
}바이트 읽기 손잡이. (씬에 맡길 때)
Byte read handle. (for handing to a scene)
반환Returns&AssetLoadHandle 바이트 읽기 손잡이. (SceneBase::track_load_handle 에 넘긴다)Byte read handle. (passed to SceneBase::track_load_handle)
끝났는지. (받았거나 실패했거나)
Whether it has finished. (loaded or failed)
반환Returnsbool 받기가 끝났으면(받았거나 실패했으면) true.true if loading has finished (loaded or failed).
pub fn create_model(&self, gl: &crate::GlContext, skinned_model_renderer: &SkinnedModelRenderer) -> Option<Result<SkinnedModel, String>>#받은 바이트로 모델 짓기. (받는 중이면 None, 받기나 해석에 실패하면 Err. 원본 문구 "SkinnedModel load failed: url")
- 자산 캐시를 쓴다. 같은 셰이더 프로그램으로 같은 주소(SkinnedModelAsset::normalize_key)의 자산이 있으면 풀지도 올리지도 않고 그 자산을 나눠 쓰는 새 인스턴스를 돌려준다. 없으면 받은 바이트로 지어 캐시에 넣는다. (끝난 뒤 다시 불러도 인스턴스가 하나 더 생긴다)
- 손잡이는 부탁할 때 렌더러를 모르므로 바이트는 읽는다. (같은 파일을 함께 받는 중이면 한 번만 읽는다)
Builds a model from the loaded bytes. (None while loading, Err when loading or interpretation fails. The original message is "SkinnedModel load failed: url")
- Uses the asset cache. If an asset for the same path (SkinnedModelAsset::normalize_key) exists with the same shader program, returns a new instance sharing it without parsing or uploading. Otherwise builds from the loaded bytes and adds it to the cache. (calling again after it finished creates one more instance)
- A handle does not know the renderer when the load is requested, so it reads the bytes. (concurrent loads of the same file read once)
- gl&crate::GlContext
- 모델을 지을 GL 컨텍스트. (graphic.get_gl())GL context to build the model in. (graphic.get_gl())
- skinned_model_renderer&SkinnedModelRenderer
- 셰이더 프로그램을 나눠 줄 렌더러.Renderer that shares its shader program.
반환ReturnsOption<Result<SkinnedModel, String>> 받는 중이면 None. 끝났으면 지은 모델, 받기에 실패하면 Err("SkinnedModel load failed: 경로", FBX 는 "FbxLoader load failed: 경로"), 해석이나 업로드에 실패하면 그 Err.None while loading. When finished, the built model, Err("SkinnedModel load failed: path", for FBX "FbxLoader load failed: path") when loading fails, and that Err when interpretation or upload fails.
함수Functions
pub fn create_quaternion_from_fbx_euler(x_degree: f64, y_degree: f64, z_degree: f64) -> Quaternion#FBX 오일러(도) → 쿼터니언. (eEulerXYZ = X 먼저 적용, 열벡터 기준 Rz x Ry x Rx 합성)
FBX Euler (degrees) → quaternion. (eEulerXYZ = X applied first, composed as Rz x Ry x Rx for column vectors)
- x_degreef64
- X 축 회전. (도)Rotation around the X axis. (degrees)
- y_degreef64
- Y 축 회전. (도)Rotation around the Y axis. (degrees)
- z_degreef64
- Z 축 회전. (도)Rotation around the Z axis. (degrees)
반환ReturnsQuaternion X, Y, Z 차례로 적용한 회전.Rotation applied in X, Y, Z order.
use vanilla::Matrix4;
use vanilla::graphics3d::skinnedmodel::create_quaternion_from_fbx_euler;
let rotation = create_quaternion_from_fbx_euler(90.0, 0.0, 90.0);
let rotated_x = Matrix4::create_rotation_from_quaternion(rotation).transform_direction(1.0, 0.0, 0.0);
assert!((rotated_x.y - 1.0).abs() < 1.0e-5);pub fn read_accessor_array(json: &Value, binary_buffer: &[u8], accessor_index: usize) -> Result<AccessorArray, String>#접근자 CPU 읽기. (촘촘한 배치 + 인터리브(byte_stride) 배치 + 희소(sparse) 접근자 지원)
Reads an accessor on the CPU. (supports tightly packed + interleaved (byte_stride) + sparse accessors)
- json&Value
- glTF JSON 전체.The whole glTF JSON.
- binary_buffer&[u8]
- BIN 청크 바이트.BIN chunk bytes.
- accessor_indexusize
- 접근자 인덱스.Accessor index.
반환ReturnsResult<AccessorArray, String> 컴포넌트 타입 그대로의 배열. (정규화하지 않는다, bufferView 가 없는 접근자는 0 으로 채운다) 접근자가 없거나, 타입을 모르거나, 버퍼 밖을 가리키거나, 바이너리 덩어리(buffers[0]) 밖의 버퍼를 가리키면 Err.Array in the component type as is. (not normalized, accessors without a bufferView are filled with 0) Err if the accessor does not exist, the type is unknown, it points outside the buffer, or it points to a buffer outside the binary chunk (buffers[0]).
use serde_json::json;
use vanilla::graphics3d::skinnedmodel::{read_accessor_array, AccessorArray};
let binary_buffer: Vec<u8> = [0.5f32, 1.0, 1.5, 2.0].iter().flat_map(|value| value.to_le_bytes()).collect();
let json = json!({
"accessors": [{ "bufferView": 0, "componentType": 5126, "count": 2, "type": "VEC2" }],
"bufferViews": [{ "buffer": 0, "byteOffset": 0, "byteLength": 16 }]
});
assert_eq!(read_accessor_array(&json, &binary_buffer, 0), Ok(AccessorArray::Float(vec![0.5, 1.0, 1.5, 2.0])));
assert!(read_accessor_array(&json, &binary_buffer, 1).is_err());pub fn read_float_accessor_array(json: &Value, binary_buffer: &[u8], accessor_index: usize) -> Result<Vec<f64>, String>#실수로 쓰는 접근자 CPU 읽기. (위치, 노멀, 텍스처 좌표, 모프 델타, 애니메이션 값, KHR_mesh_quantization 의 정수 속성을 실수로 되풀이)
- 정규화(normalized) 정수는 glTF 명세의 공식으로 나눈다. (부호 없는 것은 c / 255, c / 65535, 부호 있는 것은 max(c / 127, -1), max(c / 32767, -1))
- 정규화가 아닌 정수는 값 그대로 실수로 옮긴다. (위치의 크기와 자리는 노드 변환이나 inverseBindMatrices 가, 텍스처 좌표의 것은 KHR_texture_transform 이 맡는다)
CPU read of an accessor used as floats. (positions, normals, texture coordinates, morph deltas, animation values, dequantizing KHR_mesh_quantization integer attributes into floats)
- Normalized integers are divided with the glTF spec formulas. (unsigned ones as c / 255, c / 65535, signed ones as max(c / 127, -1), max(c / 32767, -1))
- Non-normalized integers are moved to floats as is. (the node transform or inverseBindMatrices takes care of position scale and offset, KHR_texture_transform takes care of texture coordinates)
- json&Value
- glTF JSON 전체.The whole glTF JSON.
- binary_buffer&[u8]
- BIN 청크 바이트.BIN chunk bytes.
- accessor_indexusize
- 접근자 인덱스.Accessor index.
반환ReturnsResult<Vec<f64>, String> 32비트 실수로 반올림한 값을 f64 로 담은 새 목록. (원본 Float32Array 와 같은 값) read_accessor_array 가 Err 면 그 Err.A new list of values rounded to 32-bit floats, stored as f64. (the same values as the original's Float32Array) If read_accessor_array returns Err, that Err.
use serde_json::json;
use vanilla::graphics3d::skinnedmodel::read_float_accessor_array;
let binary_buffer: Vec<u8> = [-32768i16, 32767, 0, 16384].iter().flat_map(|value| value.to_le_bytes()).collect();
let json = json!({
"accessors": [{ "bufferView": 0, "componentType": 5122, "normalized": true, "count": 2, "type": "VEC2" }],
"bufferViews": [{ "buffer": 0, "byteOffset": 0, "byteLength": 8 }]
});
let values = read_float_accessor_array(&json, &binary_buffer, 0).unwrap();
assert_eq!(values[..3], [-1.0, 1.0, 0.0]);
assert_eq!(values[3], (16384.0f64 / 32767.0) as f32 as f64);상수Constants
부호 있는 8비트 정수. (glTF componentType 5120, KHR_mesh_quantization 의 노멀 같은 것)
Signed 8-bit integer. (glTF componentType 5120, such as KHR_mesh_quantization normals)
반환Returnsu32
접근자 컴포넌트 타입. (원본 COMPONENT_ARRAY_TABLE 의 키)
Accessor component type. (the keys of the original COMPONENT_ARRAY_TABLE)
반환Returnsu32
부호 있는 16비트 정수. (glTF componentType 5122, KHR_mesh_quantization 의 위치, 노멀, 돌림 움직임 같은 것)
Signed 16-bit integer. (glTF componentType 5122, such as KHR_mesh_quantization positions, normals and rotation animations)
반환Returnsu32
부호 없는 16비트 정수. (glTF componentType 5123)
Unsigned 16-bit integer. (glTF componentType 5123)
반환Returnsu32
부호 없는 32비트 정수. (glTF componentType 5125)
Unsigned 32-bit integer. (glTF componentType 5125)
반환Returnsu32
32비트 실수. (glTF componentType 5126)
32-bit float. (glTF componentType 5126)
반환Returnsu32
드로어블당 모프 타깃 최대 개수. (셰이더 유니폼 배열 크기와 일치)
Maximum morph targets per drawable. (matches the shader uniform array size)
반환Returnsusize
짝Counterpart: vanilla.js MORPH_TARGET_MAXIMUM
AnimationPathenum traits Clone, Copy, Debug, PartialEq, Eq, Hash
애니메이션 채널 경로. (원본 문자열 "translation" / "rotation" / "scale" / "weights")
Animation channel path. (the original strings "translation" / "rotation" / "scale" / "weights")
| 이름Name | 설명Description |
|---|---|
Translation | 이동. (키마다 x, y, z 3개)Translation. (3 per key: x, y, z) |
Rotation | 회전. (키마다 쿼터니언 x, y, z, w 4개)Rotation. (4 per key: quaternion x, y, z, w) |
Scale | 크기. (키마다 x, y, z 3개)Scale. (3 per key: x, y, z) |
Weights | 모프 가중치. (키마다 모프 타깃 수만큼)Morph weights. (as many per key as there are morph targets) |
glTF 경로 문자열로부터. (모르는 경로면 None)
From a glTF path string. (None for an unknown path)
- path_name&str
- glTF 채널 경로. ("translation", "rotation", "scale", "weights", 대소문자까지 같아야 한다)glTF channel path. ("translation", "rotation", "scale", "weights", the case must match too)
반환ReturnsOption<AnimationPath> 맞는 경로. 모르는 문자열이면 None.The matching path. None for an unknown string.
IndexArrayenum traits Clone, Debug, PartialEq
인덱스 배열. (원본 Uint16Array / Uint32Array)
Index array. (the original Uint16Array / Uint32Array)
| 이름Name | 값Value | 설명Description |
|---|---|---|
UnsignedShort | UnsignedShort(Vec<u16>) | 16비트 인덱스. (GL UNSIGNED_SHORT)16-bit indices. (GL UNSIGNED_SHORT) |
UnsignedInt | UnsignedInt(Vec<u32>) | 32비트 인덱스. (GL UNSIGNED_INT)32-bit indices. (GL UNSIGNED_INT) |
비었는지.
Whether it is empty.
반환Returnsbool 비었으면 true.true if empty.
인덱스 하나 반환.
Returns one index.
- positionusize
- 인덱스 자리. (0 부터, 밖이면 패닉)Index position. (from 0, panics if out of range)
반환Returnsusize 그 자리의 인덱스 값.Index value at that position.
GL 원소 타입. (UNSIGNED_SHORT / UNSIGNED_INT)
GL element type. (UNSIGNED_SHORT / UNSIGNED_INT)
반환Returnsu32 glow::UNSIGNED_SHORT 나 glow::UNSIGNED_INT.glow::UNSIGNED_SHORT or glow::UNSIGNED_INT.
AccessorArrayenum traits Clone, Debug, PartialEq
접근자 배열. (원본 readAccessorArray 가 돌려주는 타입 배열, 컴포넌트 타입 그대로)
Accessor array. (the typed array returned by the original readAccessorArray, component type as is)
| 이름Name | 값Value | 설명Description |
|---|---|---|
Byte | Byte(Vec<i8>) | 부호 있는 8비트. (componentType 5120)Signed 8-bit. (componentType 5120) |
UnsignedByte | UnsignedByte(Vec<u8>) | 부호 없는 8비트. (componentType 5121)Unsigned 8-bit. (componentType 5121) |
Short | Short(Vec<i16>) | 부호 있는 16비트. (componentType 5122)Signed 16-bit. (componentType 5122) |
UnsignedShort | UnsignedShort(Vec<u16>) | 부호 없는 16비트. (componentType 5123)Unsigned 16-bit. (componentType 5123) |
UnsignedInt | UnsignedInt(Vec<u32>) | 부호 없는 32비트. (componentType 5125)Unsigned 32-bit. (componentType 5125) |
Float | Float(Vec<f32>) | 32비트 실수. (componentType 5126)32-bit float. (componentType 5126) |
원소(컴포넌트) 개수.
Element (component) count.
반환Returnsusize 컴포넌트 개수. (원소 수 x 원소당 컴포넌트 수)Component count. (element count x components per element)
비었는지.
Whether it is empty.
반환Returnsbool 비었으면 true.true if empty.
컴포넌트 타입. (5120 / 5121 / 5122 / 5123 / 5125 / 5126)
Component type. (5120 / 5121 / 5122 / 5123 / 5125 / 5126)
반환Returnsu32 glTF 컴포넌트 타입 번호. (COMPONENT_TYPE_UNSIGNED_BYTE 같은 상수)glTF component type number. (constants such as COMPONENT_TYPE_UNSIGNED_BYTE)
실수 목록으로. (원본 new Float32Array(typedArray), 정수는 정규화하지 않고 값 그대로)
To a float list. (the original new Float32Array(typedArray), integers are not normalized and keep their values)
반환ReturnsVec<f64> f64 로 바꾼 새 목록.A new list converted to f64.
16비트 정수 목록으로. (원본 new Uint16Array(typedArray))
To a 16-bit integer list. (the original new Uint16Array(typedArray))
반환ReturnsVec<u16> u16 으로 바꾼 새 목록. (부호 있는 정수와 u32 는 아래 16비트만 남고, 실수는 소수점 아래를 버리고 0 ~ 65535 로 자른다)A new list converted to u16. (signed integers and u32 keep only the lower 16 bits, floats drop the fractional part and are clamped to 0 ~ 65535)
인덱스 배열로. (원본: Uint8 은 Uint16 으로 넓히고 나머지는 그대로)
To an index array. (the original: Uint8 is widened to Uint16, the rest as is)
반환ReturnsIndexArray 인덱스 배열. (UnsignedInt 는 32비트 그대로, 나머지는 16비트)Index array. (UnsignedInt stays 32-bit, the rest 16-bit)