graphics3d/skinnedmodel
스킨드 모델. (모델 인스턴스, 메시/본/스킨/머티리얼/애니메이션 데이터 + 포즈 상태)
Skinned model. (model instance, mesh/bone/skin/material/animation data + pose state)
SkinnedModelextends Object
스킨드 모델. (모델 인스턴스, 메시/본/스킨/머티리얼/애니메이션 데이터 + 포즈 상태)
- GLB(바이너리 glTF)와 바이너리 FBX 를 공통 중립 스키마로 해석해 GL 리소스를 구성한다.
- 스킨 없는 정적 메시는 합성 스킨(조인트 1개)으로, 모프 타깃은 실수 텍스처로 올려 같은 스키닝 경로로 그린다.
- 애니메이션 크로스페이드와 조인트 회전 오프셋(절차 포즈 가공), 모프 가중치(glTF weights / 프로그램)를 지원한다.
- 렌더링은 SkinnedModelRenderer 가 담당한다. (모델은 렌더 기능을 갖지 않는다)
Skinned model. (model instance, mesh/bone/skin/material/animation data + pose state)
- Interprets GLB (binary glTF) and binary FBX into a common neutral schema and builds GL resources.
- Static meshes without a skin are uploaded with a synthetic skin (1 joint) and morph targets as float textures, and drawn through the same skinning path.
- Supports animation crossfade, joint rotation offsets (procedural pose processing), and morph weights (glTF weights / program).
- Rendering is handled by SkinnedModelRenderer. (The model has no rendering functionality)
import { SkinnedModel, SkinnedModelRenderer, Camera3D, Matrix4, Vector3 } from "./build/vanilla.js";
const width = 640;
const height = 360;
const canvas = document.createElement("canvas");
canvas.width = width;
canvas.height = height;
document.body.appendChild(canvas);
const webGL2RenderingContext = canvas.getContext("webgl2");
const skinnedModelRenderer = new SkinnedModelRenderer(webGL2RenderingContext);
const skinnedModel = await SkinnedModel.loadFromUrl(webGL2RenderingContext, "examples/ancientmountain/assets/fox.glb", skinnedModelRenderer);
const animationNameList = skinnedModel.getAnimationNameList();
console.log(animationNameList.join(", "));
skinnedModel.playAnimation("Walk", 0);
const cameraX = 0;
const cameraY = 80;
const cameraZ = 220;
const camera = new Camera3D();
camera.setPerspective(Math.PI / 3, 1, 2000);
camera.setAspectRatio(width / height);
const eyePosition = Vector3.create(cameraX, cameraY, cameraZ);
const targetPosition = Vector3.create(0, 45, 0);
camera.lookAt(eyePosition, targetPosition);
const viewProjectionMatrix = camera.getViewProjectionMatrix();
const viewProjectionElements = viewProjectionMatrix.getElements();
const modelMatrix = Matrix4.createIdentity();
const modelMatrixElements = modelMatrix.getElements();
webGL2RenderingContext.enable(webGL2RenderingContext.DEPTH_TEST);
let previousTime = performance.now();
function drawFrame(currentTime) {
const deltaTime = Math.max(0, currentTime - previousTime) / 1000;
previousTime = currentTime;
skinnedModel.update(deltaTime);
webGL2RenderingContext.viewport(0, 0, width, height);
webGL2RenderingContext.clearColor(0.16, 0.2, 0.26, 1);
webGL2RenderingContext.clear(webGL2RenderingContext.COLOR_BUFFER_BIT | webGL2RenderingContext.DEPTH_BUFFER_BIT);
skinnedModelRenderer.draw(skinnedModel, viewProjectionElements, modelMatrixElements, cameraX, cameraY, cameraZ);
requestAnimationFrame(drawFrame);
}
requestAnimationFrame(drawFrame);생성.
Constructor.
- webGL2RenderingContextWebGL2RenderingContext
- WebGL2 렌더링 컨텍스트. (null 이면 GL 업로드를 하지 않는 모델)WebGL2 rendering context. (when null, the model does no GL upload)
- shaderProgramShaderProgram
- 어트리뷰트 위치와 머티리얼에 쓸 셰이더 프로그램. (보통 렌더러의 getShaderProgram, null 이면 업로드하지 않는다)Shader program used for attribute locations and materials. (usually the renderer's getShaderProgram, no upload when null)
짝Counterpart: vanilla-engine SkinnedModel.new
셰이더 없이 생성. (정적, 해석과 포즈 계산만 하는 모델, uploadMeshesAndMaterials 는 던진다)
- 애니메이션 원본 모델이나 단위 시험처럼 GL 없이 interpretContent / interpretFbxContent 와 update 만 쓴다.
Creates without a shader. (static, a model that only interprets and computes poses, uploadMeshesAndMaterials throws)
- Uses only interpretContent / interpretFbxContent and update without GL, such as for animation source models or unit tests.
반환ReturnsSkinnedModel GL 과 셰이더가 없는 모델.Model without GL or a shader.
짝Counterpart: vanilla-engine SkinnedModel.create_without_shader_program
import { SkinnedModel } from "./build/vanilla.js";
const response = await fetch("examples/ancientmountain/assets/fox.glb");
const arrayBuffer = await response.arrayBuffer();
const glbChunks = SkinnedModel.readGlbChunks(arrayBuffer);
const skinnedModel = SkinnedModel.createWithoutShaderProgram();
const interpretation = skinnedModel.interpretContent(glbChunks.json, glbChunks.binaryBuffer);
skinnedModel.playAnimation("Run", 0);
skinnedModel.update(0.5);
const nodeList = skinnedModel.getNodeList();
console.log(interpretation.meshDescriptionList.length, nodeList.length);URL 로부터 로드. (정적, GLB 바이너리 glTF)
Loads from URL. (static, GLB binary glTF)
- webGL2RenderingContextWebGL2RenderingContext
- WebGL2 렌더링 컨텍스트.WebGL2 rendering context.
- urlstring
- GLB 파일 주소.GLB file URL.
- skinnedModelRendererSkinnedModelRenderer
- 셰이더 프로그램을 빌려 올 렌더러.Renderer to borrow the shader program from.
반환ReturnsPromise<SkinnedModel> GL 리소스까지 올린 모델. (응답이 실패하거나 GLB 가 아니면 오류를 던진다)
- 자산 캐시를 쓴다. 같은 셰이더 프로그램으로 같은 주소(SkinnedModelAsset.normalizeKey)를 이미 받았으면 받지도 풀지도 않고
그 자산을 나눠 쓰는 새 인스턴스를 돌려준다. 함께 받는 중이면 끝나기를 기다려 나눠 쓴다.Model with its GL resources uploaded. (throws if the response fails or the file is not GLB)
- Uses the asset cache. If the same path (SkinnedModelAsset.normalizeKey) was already loaded with the same shader program, returns a new instance sharing that asset without fetching or parsing.
If a load of it is in progress, waits for it and shares the result.
짝Counterpart: vanilla-engine SkinnedModel.load_from_url
자산으로부터 인스턴스 짓기. (정적, 자산의 버퍼, 머티리얼 원형, 클립을 나눠 쓰고 포즈와 재생 상태는 따로, GPU 업로드 없음)
Create an instance from an asset. (static, shares the asset's buffers, material prototypes and clips, keeps its own pose and playback state, no GPU upload)
- skinnedModelAssetSkinnedModelAsset
- 나눠 쓸 자산. (지워진 자산이면 오류를 던진다)Asset to share. (throws if the asset was destroyed)
반환ReturnsSkinnedModel 자산의 참조 수를 하나 늘린 새 인스턴스. (노드는 자산을 올릴 때의 원형에서 베낀다)New instance that added one to the asset's reference count. (nodes are copied from the prototypes taken when the asset was uploaded)
짝Counterpart: vanilla-engine SkinnedModel.create_from_asset
바이트로부터 로드. (정적, GLB 바이너리 glTF, loadFromUrl 의 fetch 뒤 부분)
- 번들에 담긴 바이트나 BlobAsset 처럼 이미 받은 데이터에서 짓는다.
Loads from bytes. (static, GLB binary glTF, the part of loadFromUrl after fetch)
- Builds from data already received, such as bytes included in a bundle or a BlobAsset.
- webGL2RenderingContextWebGL2RenderingContext
- WebGL2 렌더링 컨텍스트.WebGL2 rendering context.
- arrayBufferArrayBuffer
- GLB 파일 바이트.GLB file bytes.
- skinnedModelRendererSkinnedModelRenderer
- 셰이더 프로그램을 빌려 올 렌더러.Renderer to borrow the shader program from.
반환ReturnsPromise<SkinnedModel> GL 리소스까지 올린 모델. (GLB 가 아니면 오류를 던진다)Model with its GL resources uploaded. (throws when the data is not a GLB)
짝Counterpart: vanilla-engine SkinnedModel.load_from_bytes
import { SkinnedModel, SkinnedModelRenderer } from "./build/vanilla.js";
const canvas = document.createElement("canvas");
const webGL2RenderingContext = canvas.getContext("webgl2");
const skinnedModelRenderer = new SkinnedModelRenderer(webGL2RenderingContext);
const response = await fetch("examples/ancientmountain/assets/fox.glb");
const arrayBuffer = await response.arrayBuffer();
const skinnedModel = await SkinnedModel.loadFromBytes(webGL2RenderingContext, arrayBuffer, skinnedModelRenderer);
const drawableList = skinnedModel.getDrawableList();
console.log(drawableList.length);
skinnedModel.destroy();URL 로부터 로드. (정적, 바이너리 FBX)
Loads from URL. (static, binary FBX)
- webGL2RenderingContextWebGL2RenderingContext
- WebGL2 렌더링 컨텍스트.WebGL2 rendering context.
- urlstring
- 바이너리 FBX 파일 주소.Binary FBX file URL.
- skinnedModelRendererSkinnedModelRenderer
- 셰이더 프로그램을 빌려 올 렌더러.Renderer to borrow the shader program from.
반환ReturnsPromise<SkinnedModel> GL 리소스까지 올린 모델. (loadFromUrl 처럼 자산 캐시를 쓴다)Model with its GL resources uploaded. (uses the asset cache like loadFromUrl)
짝Counterpart: vanilla-engine SkinnedModel.load_from_fbx_url
바이트로부터 로드. (정적, 바이너리 FBX, loadFromFbxUrl 의 fetch 뒤 부분)
Loads from bytes. (static, binary FBX, the part of loadFromFbxUrl after fetch)
- webGL2RenderingContextWebGL2RenderingContext
- WebGL2 렌더링 컨텍스트.WebGL2 rendering context.
- arrayBufferArrayBuffer
- 바이너리 FBX 파일 바이트.Binary FBX file bytes.
- skinnedModelRendererSkinnedModelRenderer
- 셰이더 프로그램을 빌려 올 렌더러.Renderer to borrow the shader program from.
반환ReturnsPromise<SkinnedModel> GL 리소스까지 올린 모델.Model with its GL resources uploaded.
짝Counterpart: vanilla-engine SkinnedModel.load_from_fbx_bytes
GLB 청크 읽기. (정적, 머리 확인 + JSON 청크 + BIN 청크, GL 무관)
Reads GLB chunks. (static, header check + JSON chunk + BIN chunk, GL independent)
- arrayBufferArrayBuffer
- GLB 파일 바이트.GLB file bytes.
반환Returns{ json: object, binaryBuffer: ArrayBuffer } JSON 청크를 읽은 객체와 BIN 청크 바이트. (머리가 GLB 가 아니거나 청크가 깨졌거나 JSON, BIN 가운데 하나라도 없으면 오류를 던진다)Object read from the JSON chunk and the BIN chunk bytes. (throws when the header is not GLB, a chunk is broken, or either JSON or BIN is missing)
짝Counterpart: vanilla-engine SkinnedModel.read_glb_chunks
FBX 코너를 머티리얼별로 나누기. (정적, 비인덱스 코너 배열, GL 무관)
- 메시 하나에 머티리얼이 여럿이면 머티리얼마다 부분 메시로 나눠 그린다. (three.js FBXLoader 의 그룹, 유니티와 언리얼의 서브메시)
- 부분 메시는 머티리얼 번호가 작은 것부터, 삼각형 차례는 원래대로. 번호가 하나뿐이면 배열을 그대로 쓴다.
Split FBX corners by material. (Static, non-indexed corner arrays, GL independent)
- 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.
- materialIndexPerTriangleInt32Array
- 삼각형마다 머티리얼 번호. (소유 노드 materialIds 안의 자리)Material number per triangle. (A position in the owner node's materialIds)
- cornerArrays{ positions: Float32Array, normals: Float32Array, textureCoordinates: Float32Array, joints: Uint16Array, weights: Float32Array }
- 코너마다 위치 3, 노멀 3, UV 2, 조인트 4, 가중치 4.Per corner: 3 position, 3 normal, 2 UV, 4 joint and 4 weight values.
반환Returnsobject[] 부분 메시 목록. (localMaterialIndex 와 cornerArrays 와 같은 칸)List of sub-meshes. (localMaterialIndex and the same fields as cornerArrays)
짝Counterpart: vanilla-engine SkinnedModel.split_fbx_corners_by_material
import { SkinnedModel } from "./build/vanilla.js";
const cornerCount = 9;
const subMeshList = SkinnedModel.splitFbxCornersByMaterial(new Int32Array([0, 1, 0]), {
positions: new Float32Array(cornerCount * 3).map((value, index) => index),
normals: new Float32Array(cornerCount * 3),
textureCoordinates: new Float32Array(cornerCount * 2),
joints: new Uint16Array(cornerCount * 4),
weights: new Float32Array(cornerCount * 4),
});
console.log(subMeshList.length, subMeshList[0].localMaterialIndex, subMeshList[0].positions.length / 9, subMeshList[1].positions[0]); // 2 0 2 9와이어프레임 모서리 목록 만들기. (정적, GL 무관, 인덱스 쌍 목록)
Builds the wireframe edge list. (static, GL independent, list of index pairs)
- triangleIndicesUint16Array | Uint32Array | null
- 삼각형 인덱스. (null 이면 정점 셋씩 삼각형으로 본다)Triangle indices. (when null, every three vertices form a triangle)
- vertexCountnumber
- 정점 수.Vertex count.
반환Returnsnumber[] 중복 없는 모서리의 정점 인덱스 쌍을 이어 놓은 목록.Flat list of vertex index pairs for unique edges.
짝Counterpart: vanilla-engine SkinnedModel.build_wireframe_edge_list
모프 텍셀 데이터 만들기. (정적, GL 무관, 텍스처 가로, 타깃당 행 수, RGBA 실수 배열)
Builds morph texel data. (static, GL independent, texture width, rows per target, RGBA float array)
- morphTargetListobject[]
- 모프 타깃 목록. ([{ name, positionDeltas, normalDeltas }])Morph target list. ([{ name, positionDeltas, normalDeltas }])
- vertexCountnumber
- 정점 수.Vertex count.
반환Returns{ textureWidth: number, rowsPerTarget: number, texelData: Float32Array } 텍스처 가로(정점 수와 2048 가운데 작은 값, 최소 1), 타깃당 행 수, RGBA 실수 텍셀 배열.Texture width (the smaller of the vertex count and 2048, at least 1), rows per target, and the RGBA float texel array.
짝Counterpart: vanilla-engine SkinnedModel.build_morph_texel_data
인스턴스 짓기. (이 모델과 같은 자산을 나눠 쓰는 새 모델, 유니티의 Instantiate 처럼 GPU 자원을 다시 올리지 않는다)
Create an instance. (a new model sharing this model's asset; like Unity's Instantiate, GPU resources are not uploaded again)
반환ReturnsSkinnedModel 새 인스턴스. (노드는 자산을 올릴 때의 원형에서 베끼고 재생 상태는 처음부터, 올리기 전이면 오류를 던진다)New instance. (nodes copied from the prototypes taken when the asset was uploaded, playback starts fresh; throws before upload)
짝Counterpart: vanilla-engine SkinnedModel.create_instance
import { SkinnedModel, SkinnedModelRenderer } from "./build/vanilla.js";
const canvas = document.createElement("canvas");
const webGL2RenderingContext = canvas.getContext("webgl2");
const skinnedModelRenderer = new SkinnedModelRenderer(webGL2RenderingContext);
const sourceModel = await SkinnedModel.loadFromUrl(webGL2RenderingContext, "examples/ancientmountain/assets/fox.glb", skinnedModelRenderer);
const modelList = [sourceModel];
for (let modelIndex = 1; modelIndex < 10; ++modelIndex) {
const instanceModel = sourceModel.createInstance();
instanceModel.playAnimation(modelIndex % 2 === 0 ? "Walk" : "Run", 0);
modelList.push(instanceModel);
}
const skinnedModelAsset = sourceModel.getAsset();
console.log(skinnedModelAsset.getReferenceCount(), skinnedModelAsset.getGpuByteCount());
for (const model of modelList) {
model.destroy();
}
console.log(skinnedModelAsset.isDestroyed());자산 반환.
Return the asset.
반환ReturnsSkinnedModelAsset | null 나눠 쓰는 자산. (올리기 전이나 destroy 뒤에는 null)Shared asset. (null before upload or after destroy)
짝Counterpart: vanilla-engine SkinnedModel.get_asset
GLB 바이너리 해석.
Interprets GLB binary.
- arrayBufferArrayBuffer
- GLB 파일 바이트.GLB file bytes.
짝Counterpart: vanilla-engine SkinnedModel.parse_binary
glTF 내용 해석. (노드 / 스킨 / 메시 / 애니메이션 / 텍스처 → GL 업로드)
Parses glTF content. (nodes / skins / meshes / animations / textures → GL upload)
- jsonobject
- glTF JSON.
- binaryBufferArrayBuffer
- GLB 의 BIN 청크.BIN chunk of the GLB.
짝Counterpart: vanilla-engine SkinnedModel.parse_content
glTF 내용 해석. (GL 무관, 노드 / 스킨 / 애니메이션을 채우고 중립 메시 / 머티리얼 서술을 돌려준다)
- 바깥(uri) 이미지는 텍스처 없음, inverseBindMatrices 가 없는 스킨은 단위 행렬, 노드가 없거나 모르는 경로의 채널은 버린다.
- 노멀이 없는 프리미티브는 glTF 2.0 명세대로 평평한 노멀(삼각형마다 하나)이다. 꼭짓점을 삼각형마다 따로 풀어 면 노멀을 주고 indices 는 null 이다.
Parses glTF content. (GL independent, fills nodes / skins / animations and returns neutral mesh / material descriptions)
- External (uri) images get no texture, skins without inverseBindMatrices use identity matrices, channels with no node or an unknown path are dropped.
- A primitive without normals has flat normals (one per triangle) as the glTF 2.0 specification says. Vertices are split per triangle and given the face normal, and indices is null.
- jsonobject
- glTF JSON.
- binaryBufferArrayBuffer
- GLB 의 BIN 청크.BIN chunk of the GLB.
반환Returns{ meshDescriptionList: object[], materialDescriptionList: object[] } 중립 메시 서술 목록과 중립 머티리얼 서술 목록. (uploadMeshesAndMaterials 에 넘긴다)Neutral mesh description list and neutral material description list. (passed to uploadMeshesAndMaterials)
짝Counterpart: vanilla-engine SkinnedModel.interpret_content
FBX 중간 표현 해석. (노드/스킨/메시/텍스처/애니메이션 → 기존 스키닝 파이프라인)
Parses the FBX intermediate representation. (nodes/skins/meshes/textures/animations → existing skinning pipeline)
- sceneDataobject
- FbxLoader 가 읽은 중간 표현.Intermediate representation read by FbxLoader.
짝Counterpart: vanilla-engine SkinnedModel.parse_fbx_content
FBX 중간 표현 해석. (GL 무관, 노드 / 스킨 / 애니메이션을 채우고 중립 메시 / 머티리얼 서술을 돌려준다)
- 본이 없는 클러스터는 단위 조인트, 배열 밖 정점 번호는 건너뛴다. 원본처럼 스킨이 붙은 메시만 담는다.
Parses the FBX intermediate representation. (GL independent, fills nodes / skins / animations and returns neutral mesh / material descriptions)
- Clusters without a bone get an identity joint, vertex indices outside the array are skipped. Like the original, only meshes with a skin attached are kept.
- sceneDataobject
- FbxLoader 가 읽은 중간 표현.Intermediate representation read by FbxLoader.
반환Returns{ meshDescriptionList: object[], materialDescriptionList: object[] } 중립 메시 서술 목록과 중립 머티리얼 서술 목록. (uploadMeshesAndMaterials 에 넘긴다)Neutral mesh description list and neutral material description list. (passed to uploadMeshesAndMaterials)
짝Counterpart: vanilla-engine SkinnedModel.interpret_fbx_content
애니메이션 FBX 추가 로드. (본 이름 매칭 리타게팅, Mixamo 애니메이션 전용 FBX)
- 동일 스켈레톤을 전제로, 채널을 현재 모델의 노드 인덱스로 재지정해 클립을 추가한다.
- ignoreTranslation: 루트 모션이 박힌 클립에서 이동 채널을 버린다. (게임 로직이 위치를 제어할 때)
Loads additional animation FBX. (retargeting by bone name matching, animation-only Mixamo FBX)
- Assuming the same skeleton, remaps channels to the current model's node indices and adds the clips.
- ignoreTranslation: drops translation channels from clips with baked-in root motion. (when game logic controls the position)
- urlstring
- 애니메이션 FBX 파일 주소.Animation FBX file URL.
- clipNamestring
- 더할 클립 이름. (채널이 있는 스택이 하나면 이 이름, 여럿이면 스택마다 "이 이름/스택 이름")Name of the clip to add. (This name when one stack has channels, "this name/stack name" for each stack when there are several)
- ignoreTranslationboolean
- 참이면 이동 채널을 버린다. (기본 false)Drops translation channels when true. (default false)
짝Counterpart: vanilla-engine SkinnedModel.add_animations_from_fbx_url
애니메이션 FBX 추가. (바이트, addAnimationsFromFbxUrl 의 fetch 뒤 부분)
Adds animation FBX. (bytes, the part of addAnimationsFromFbxUrl after fetch)
- arrayBufferArrayBuffer
- 애니메이션 FBX 파일 바이트.Animation FBX file bytes.
- clipNamestring
- 더할 클립 이름. (채널이 있는 스택이 하나면 이 이름, 여럿이면 스택마다 "이 이름/스택 이름")Name of the clip to add. (This name when one stack has channels, "this name/stack name" for each stack when there are several)
- ignoreTranslationboolean
- 참이면 이동 채널을 버린다. (기본 false)Drops translation channels when true. (default false)
짝Counterpart: vanilla-engine SkinnedModel.add_animations_from_fbx_bytes
애니메이션 FBX 추가. (FbxLoader 가 읽은 중간 표현, 본 이름 매칭 리타게팅)
Adds animation FBX. (intermediate representation read by FbxLoader, retargeting by bone name matching)
- sceneDataobject
- FbxLoader 가 읽은 중간 표현.Intermediate representation read by FbxLoader.
- clipNamestring
- 더할 클립 이름. (채널이 있는 스택이 하나면 이 이름, 여럿이면 스택마다 "이 이름/스택 이름")Name of the clip to add. (This name when one stack has channels, "this name/stack name" for each stack when there are several)
- ignoreTranslationboolean
- 참이면 이동 채널을 버린다. (기본 false)Drops translation channels when true. (default false)
짝Counterpart: vanilla-engine SkinnedModel.add_animations_from_fbx_scene_data
중립 메시/머티리얼 서술 업로드. (공용, Material 생성 + VAO/드로어블 구성)
- 예전 자산은 먼저 놓는다. (destroy, 다시 불러도 새지 않는다)
- 올린 버퍼, 머티리얼, 모프 텍스처와 지금 노드, 스킨, 클립을 새 자산(SkinnedModelAsset, 참조 수 1)으로 묶고 이 모델이 그 첫 인스턴스가 된다.
Upload neutral mesh/material descriptions. (shared path, creates Materials and builds VAOs/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.
- meshDescriptionListobject[]
- 중립 메시 서술 목록.Neutral mesh description list.
- materialDescriptionListobject[]
- 중립 머티리얼 서술 목록. (메시의 materialIndex 가 가리키고, 없으면 기본 머티리얼)Neutral material description list. (referenced by each mesh's materialIndex, the default material when missing)
짝Counterpart: vanilla-engine SkinnedModel.upload_meshes_and_materials
와이어프레임 인덱스 업로드. (삼각형 인덱스 → 중복 없는 모서리 선 인덱스, 비인덱스 메시는 삼각형별 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.
- drawableobject
- 선 인덱스를 올릴 드로어블.Drawable to upload line indices for.
짝Counterpart: vanilla-engine SkinnedModel.upload_wireframe_indices
모프 타깃 업로드. (드로어블의 델타 목록 → 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.
- drawableobject
- 모프 텍스처를 올릴 드로어블. (타깃이 없으면 텍스처를 지운다, 자산과 나눠 쓰던 텍스처면 건드리지 않고 이 드로어블 것을 새로 짓는다)Drawable to upload the morph texture for. (deletes the texture when there are no targets; a texture shared with the asset is left alone and this drawable gets its own)
짝Counterpart: vanilla-engine SkinnedModel.upload_morph_targets
모프 타깃 추가. (프로그램 생성, 정점별 위치 델타 [+ 노멀 델타], 다음 update() 에서 업로드)
Adds a morph target. (created in code, per-vertex position deltas [+ normal deltas], uploaded on the next update())
- drawableIndexnumber
- 드로어블 번호. (없으면 오류를 던진다)Drawable index. (throws when missing)
- targetNamestring
- 타깃 이름. (setMorphWeight 가 이 이름으로 찾는다)Target name. (setMorphWeight looks it up by this name)
- positionDeltasFloat32Array
- 정점마다 위치 델타 x, y, z. (길이가 정점 수 x 3 이 아니면 오류를 던진다)Position delta x, y, z per vertex. (throws when the length is not vertex count x 3)
- normalDeltasFloat32Array | null
- 정점마다 노멀 델타 x, y, z. (null 이면 노멀은 그대로)Normal delta x, y, z per vertex. (normals stay unchanged when null)
짝Counterpart: vanilla-engine SkinnedModel.add_morph_target
import { SkinnedModel, SkinnedModelRenderer } from "./build/vanilla.js";
const canvas = document.createElement("canvas");
const webGL2RenderingContext = canvas.getContext("webgl2");
const skinnedModelRenderer = new SkinnedModelRenderer(webGL2RenderingContext);
const skinnedModel = await SkinnedModel.loadFromUrl(webGL2RenderingContext, "examples/ancientmountain/assets/fox.glb", skinnedModelRenderer);
const drawableList = skinnedModel.getDrawableList();
const vertexCount = drawableList[0].vertexCount;
const positionDeltas = new Float32Array(vertexCount * 3);
for (let vertexIndex = 0; vertexIndex < vertexCount; ++vertexIndex) {
positionDeltas[vertexIndex * 3 + 1] = 5;
}
skinnedModel.addMorphTarget(0, "lift", positionDeltas);
skinnedModel.setMorphWeight("lift", 0.5);
skinnedModel.update(0);
const weight = skinnedModel.getMorphWeight("lift");
console.log(weight);모프 가중치 설정. (이름 일치 타깃 전부, 드로어블 여러 개가 같은 이름을 가질 수 있음)
Sets the morph weight. (all targets with a matching name, several drawables can share the same name)
- targetNamestring
- 타깃 이름.Target name.
- weightnumber
- 가중치. (0 이면 꺼지고 1 이면 델타 그대로)Weight. (0 is off, 1 applies the delta as is)
짝Counterpart: vanilla-engine SkinnedModel.set_morph_weight
모프 가중치 반환. (첫 일치 타깃, 없으면 0)
Returns the morph weight. (first matching target, 0 if none)
- targetNamestring
- 타깃 이름.Target name.
반환Returnsnumber 첫 일치 타깃의 가중치. (없으면 0)Weight of the first matching target. (0 when none)
짝Counterpart: vanilla-engine SkinnedModel.get_morph_weight
머티리얼 교체. (드로어블 단위, 외부 텍스처로 만든 머티리얼 인스턴스 적용)
Replaces the material. (per drawable, applies a material instance made from an external texture)
- drawableIndexnumber
- 드로어블 번호. (없으면 오류를 던진다)Drawable index. (throws when missing)
- materialMaterial
- 바꿔 넣을 머티리얼. (destroy 가 지우지 않는다)Material to swap in. (destroy does not delete it)
짝Counterpart: vanilla-engine SkinnedModel.set_material
이 인스턴스의 머티리얼 반환. (유니티 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.
- drawableIndexnumber
- 드로어블 번호. (없으면 오류를 던진다)Drawable index. (throws when missing)
반환ReturnsMaterial 이 인스턴스만 쓰는 머티리얼.Material used only by this instance.
짝Counterpart: vanilla-engine SkinnedModel.get_material
import { SkinnedModel, SkinnedModelRenderer } from "./build/vanilla.js";
const canvas = document.createElement("canvas");
const webGL2RenderingContext = canvas.getContext("webgl2");
const skinnedModelRenderer = new SkinnedModelRenderer(webGL2RenderingContext);
const blueFox = await SkinnedModel.loadFromUrl(webGL2RenderingContext, "examples/ancientmountain/assets/fox.glb", skinnedModelRenderer);
const redFox = blueFox.createInstance();
redFox.getMaterial(0).setBaseColorFactor([1, 0.3, 0.3]);
console.log(blueFox.getSharedMaterial(0).getBaseColorFactor().join(", "), redFox.getSharedMaterial(0).getBaseColorFactor().join(", "));
redFox.destroy();
blueFox.destroy();스무스 노멀 생성. (노멀 미보유 메시, 바인드 포즈 기준, 스키닝 회전은 셰이더에서 적용)
Generates smooth normals. (meshes without normals, based on the bind pose, skinning rotation is applied in the shader)
- positionsFloat32Array
- 정점 위치 x, y, z 배열.Array of vertex positions x, y, z.
- indicesUint16Array | Uint32Array | null
- 삼각형 인덱스. (null 이면 정점 셋씩 삼각형으로 본다)Triangle indices. (when null, every three vertices form a triangle)
반환ReturnsFloat32Array 정점마다 면 노멀을 더해 정규화한 노멀 배열. (positions 와 같은 길이)Normal array made by summing face normals per vertex and normalizing. (same length as positions)
짝Counterpart: vanilla-engine SkinnedModel.generate_smooth_normals
실수형 어트리뷰트 바인드. (신규 버퍼 생성 + 포인터 설정)
Binds a float attribute. (creates a new buffer + sets the pointer)
- shaderProgramShaderProgram
- 어트리뷰트 위치를 찾을 셰이더 프로그램.Shader program to look up the attribute location in.
- attributeNamestring
- 어트리뷰트 이름.Attribute name.
- dataArrayFloat32Array
- 정점 데이터.Vertex data.
- componentCountnumber
- 정점당 성분 수.Components per vertex.
반환ReturnsWebGLBuffer | null 지은 버퍼. (셰이더에 없는 어트리뷰트면 null)The created buffer. (null if the attribute is not in the shader)
짝Counterpart: vanilla-engine SkinnedModel.bind_float_attribute
정수형 어트리뷰트 바인드. (조인트 인덱스)
Binds an integer attribute. (joint indices)
- shaderProgramShaderProgram
- 어트리뷰트 위치를 찾을 셰이더 프로그램.Shader program to look up the attribute location in.
- attributeNamestring
- 어트리뷰트 이름.Attribute name.
- dataArrayUint16Array
- 정점 데이터. (UNSIGNED_SHORT 로 읽는다)Vertex data. (read as UNSIGNED_SHORT)
- componentCountnumber
- 정점당 성분 수.Components per vertex.
반환ReturnsWebGLBuffer | null 지은 버퍼. (셰이더에 없는 어트리뷰트면 null)The created buffer. (null if the attribute is not in the shader)
짝Counterpart: vanilla-engine SkinnedModel.bind_integer_attribute
애니메이션 재생. (크로스페이드)
Plays an animation. (crossfade)
- animationNamestring
- 클립 이름. (지금 클립과 같거나 없으면 아무것도 하지 않는다, 같은 이름이 여럿이면 마지막 것)Clip name. (does nothing when it equals the current clip or does not exist, the last one when several share the name)
- fadeDurationnumber
- 앞 클립에서 넘어가는 시간. (초, 기본 0.25)Time to cross-fade from the previous clip. (seconds, default 0.25)
짝Counterpart: vanilla-engine SkinnedModel.play_animation
import { SkinnedModel } from "./build/vanilla.js";
const response = await fetch("examples/ancientmountain/assets/fox.glb");
const arrayBuffer = await response.arrayBuffer();
const glbChunks = SkinnedModel.readGlbChunks(arrayBuffer);
const skinnedModel = SkinnedModel.createWithoutShaderProgram();
skinnedModel.interpretContent(glbChunks.json, glbChunks.binaryBuffer);
skinnedModel.playAnimation("Walk", 0);
skinnedModel.update(1.0);
skinnedModel.playAnimation("Run", 0.4);
for (let frameIndex = 0; frameIndex < 30; ++frameIndex) {
skinnedModel.update(1 / 60);
}
const skinList = skinnedModel.getSkinList();
console.log(skinList[0].jointMatrixArray[12]);애니메이션 샘플링. (현재 노드 포즈에 가중 블렌딩)
Samples an animation. (weighted blending into the current node pose)
- animationobject
- 애니메이션 클립. ({ name, duration, channels })Animation clip. ({ name, duration, channels })
- timenumber
- 클립 시간. (초, 클립 길이로 되감는다)Clip time. (seconds, wrapped by the clip duration)
- blendWeightnumber
- 지금 포즈에 섞을 가중치. (1 이면 덮어쓴다)Weight to blend into the current pose. (1 overwrites)
짝Counterpart: vanilla-engine SkinnedModel.sample_animation
갱신. (시간 전진 → 포즈 샘플링 → 월드/조인트 행렬 계산)
Update. (advance time → sample pose → compute world/joint matrices)
- deltaTimenumber
- 지난 프레임에서 흐른 시간. (초, 재생 속도를 곱해 클립 시간을 나아간다)Time elapsed since the last frame. (seconds, advances the clip time multiplied by the playback speed)
짝Counterpart: vanilla-engine SkinnedModel.update
조인트 회전 오프셋 설정. (이름 부분 일치 노드에 로컬 회전 누적)
Sets a joint rotation offset. (accumulates local rotation on nodes whose name partially matches)
- jointNamePartstring
- 노드 이름에 든 글. (든 노드 모두)Text contained in the node name. (every node that contains it)
- offsetRotationQuaternion
- 애니메이션 포즈 뒤에 로컬 회전으로 곱할 쿼터니언.Quaternion multiplied as a local rotation after the animation pose.
짝Counterpart: vanilla-engine SkinnedModel.set_joint_rotation_offset
import { SkinnedModel, Quaternion } from "./build/vanilla.js";
const response = await fetch("examples/ancientmountain/assets/fox.glb");
const arrayBuffer = await response.arrayBuffer();
const glbChunks = SkinnedModel.readGlbChunks(arrayBuffer);
const skinnedModel = SkinnedModel.createWithoutShaderProgram();
skinnedModel.interpretContent(glbChunks.json, glbChunks.binaryBuffer);
const headTurn = Quaternion.createFromEuler(0, 0.6, 0);
skinnedModel.setJointRotationOffset("b_Head", headTurn);
skinnedModel.update(1 / 60);
skinnedModel.clearJointRotationOffsets();조인트 회전 오프셋 전체 해제.
Clears all joint rotation offsets.
짝Counterpart: vanilla-engine SkinnedModel.clear_joint_rotation_offsets
애니메이션 이름 목록 반환.
Returns the list of animation names.
반환Returnsstring[] 클립 이름 목록. (클립 차례)List of clip names. (in clip order)
짝Counterpart: vanilla-engine SkinnedModel.get_animation_name_list
재생 속도 설정.
Sets the playback speed.
- timeScalenumber
- 재생 속도 배율. (기본 1, 크로스페이드 시간에는 곱하지 않는다)Playback speed multiplier. (default 1, not applied to the cross-fade time)
짝Counterpart: vanilla-engine SkinnedModel.set_time_scale
렌더링 컨텍스트 반환.
Returns the rendering context.
반환ReturnsWebGL2RenderingContext 렌더링 컨텍스트. (셰이더 없이 지었으면 null)Rendering context. (null when built without a shader)
셰이더 프로그램 반환.
Returns the shader program.
반환ReturnsShaderProgram 셰이더 프로그램. (셰이더 없이 지었으면 null)Shader program. (null when built without a shader)
짝Counterpart: vanilla-engine SkinnedModel.get_shader_program
노드 목록 반환.
Returns the node list.
반환Returnsobject[] 노드 목록. (이름, 자식 번호, 기본과 지금의 이동, 회전, 배율, 월드 행렬)Node list. (name, child indices, base and current translation, rotation, scale, world matrix)
짝Counterpart: vanilla-engine SkinnedModel.get_node_list
루트 노드 인덱스 목록 반환.
Returns the list of root node indices.
반환Returnsnumber[] 장면 루트 노드 번호 목록.List of scene root node indices.
짝Counterpart: vanilla-engine SkinnedModel.get_root_node_indices
스킨 목록 반환.
Returns the skin list.
반환Returnsobject[] 스킨 목록. (조인트 노드 번호, 역바인드 행렬, 조인트 행렬 배열)Skin list. (joint node indices, inverse bind matrices, joint matrix array)
짝Counterpart: vanilla-engine SkinnedModel.get_skin_list
드로어블 목록 반환.
Returns the drawable list.
반환Returnsobject[] 드로어블 목록. (버텍스 어레이, 인덱스, 머티리얼, 스킨 번호, 모프 상태)Drawable list. (vertex array, indices, material, skin index, morph state)
짝Counterpart: vanilla-engine SkinnedModel.get_drawable_list
애니메이션 클립 목록 반환.
Returns the animation clip list.
반환Returnsobject[] 애니메이션 클립 목록. ({ name, duration, channels })Animation clip list. ({ name, duration, channels })
짝Counterpart: vanilla-engine SkinnedModel.get_animation_list
파괴. (이 인스턴스 것을 지우고 자산을 놓는다, 마지막 인스턴스면 자산이 버퍼, 버텍스 어레이, 모프 텍스처, 머티리얼 원형을 지운다)
- 이 인스턴스 것: 와이어프레임 버퍼, addMorphTarget 으로 갈라진 모프 텍스처, getMaterial 로 갈라진 머티리얼.
- setMaterial 로 바깥에서 넣은 머티리얼은 지우지 않는다. 자산의 머티리얼 원형을 다른 모델에 넣어 썼다면 자산이 지워질 때 함께 지워진다.
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 addMorphTarget, materials forked by getMaterial.
- Materials given from outside with setMaterial are not deleted. If the asset's material prototypes were put on another model, they are deleted together when the asset is destroyed.
짝Counterpart: vanilla-engine SkinnedModel.destroy
상수Constants
드로어블당 모프 타깃 최대 개수. (셰이더 유니폼 배열 크기와 일치)
Maximum number of morph targets per drawable. (matches the shader uniform array size)
반환Returnsnumber
짝Counterpart: vanilla-engine MORPH_TARGET_MAXIMUM