graphics3d/toon/glbmeshreader
점토 모형(GLB) 읽기와 뼈대 자세. (툰 3D 의 MeshBuilder 꼭짓점 배열로, 외계행성 광부 키우기에서 왔다) 재질 색으로 칠하는 모형을 읽는다. 텍스처 좌표와 재질 텍스처가 있으면 그것도 읽는다.
- 부품 하나가 노드 하나이고, 노드의 메시는 색마다 프리미티브 하나이다. 꼭짓점은 위치와 노멀, 뼈대가 있으면 본 번호와 무게이다. 노멀이 없는 프리미티브는 glTF 2.0 명세대로 평평한 노멀(삼각형마다 하나)로 읽는다. 꼭짓점을 삼각형마다 따로 풀어 면 노멀을 준다. (새로 짓는 바깥선 껍데기도 같다)
- 재질의 baseColorFactor 는 선형 색이라 sRGB 로 바꿔 담고(감마 색 공간은 pow 1 / 2.2, 선형 색 공간은 sRGB 표준 곡선, 셰이더가 푸는 곡선의 역), emissiveFactor 가 있으면 빛남으로 담는다. (emissiveTexture 가 있으면 빛남은 재질 범위로만 넘긴다)
- TEXCOORD_0 이 있으면 uvData 로, TEXCOORD_1 이 있으면 uv1Data(2 번 UV, 천사 고리)로 담는다. 프리미티브마다 재질 범위(materialRanges)를 담는다. { name 재질 이름, materialIndex, nodeName, indexStart, indexCount, extras 재질 extras, alphaMode, alphaCutoff, baseColorFactor 선형, emissiveFactor 선형, baseColorImage, emissiveImage (images 차례, 없으면 -1), hasUv } 부품 안에서 칸을 갈라 칠할 때(강조색 칸, 표시판) 재질 이름이나 extras 로 고르고 ToonRenderer.drawMesh 의 indexStart, indexCount 로 그 칸만 그린다.
- 그림은 readGlbImages 로 읽고 decodeGlbImage 로 풀어 ToonRenderer.createTexture 에 넘긴다.
- 재질 extras 의 outline 은 바깥선 껍데기(뒷면만 그림), basic 은 빛을 받지 않는 부품이다. outlineOptions 를 주면 그 껍데기는 담지 않고, ".outline" 짝이 있는 노드의 몸으로 점마다 같은 굵기의 껍데기를 새로 짓는다. (MeshBuilder.addTriangleShell)
- 뼈대(skin)가 있으면 본 노드와 그 거꾸로 묶는 행렬, 움직임(animations)과 그 extras(치기의 hitAt, 한 번만 트는 loop "once" 등)를 함께 읽는다. 자세는 writeSkinPose 가 셈한다.
- 부품을 따로 숨기거나 칠하는 모형(무더기의 결정 여럿처럼)은 readGlbNodeArrays 로 노드마다 따로 읽는다. 노드 extras(문과 다리가 도는 자리 pivot 등)는 그 부품의 extras 로 함께 담는다.
- 한 덩이로 읽은 뼈대 모형(탈것 같은)의 노드 extras 와 부품의 자리, 따르는 본은 readGlbNodeInfos 로 따로 읽는다.
- 꼭짓점 속성을 정수로 담은 GLB(KHR_mesh_quantization)도 읽는다. 정규화 정수는 glTF 명세의 공식으로 나누고, 텍스처 좌표는 재질 텍스처의 KHR_texture_transform 을 구워 넣는다. 이름 없는 메시 노드는 이름 있는 부모 노드의 부품에 든다. (양자화 도구가 되풀이 변환을 맡기는 잎 노드) extensionsRequired 에 읽지 못하는 확장(meshopt 압축 등)이 있으면 오류를 던진다.
엔진의 GLB 읽기는 엔진의 PBR 모형(SkinnedModel) 안에 묶여 있어, 툰 그리기에 쓸 꼭짓점 배열만 여기서 뽑는다.
Reading clay models (GLB) and skeleton poses. (Into toon 3D MeshBuilder vertex arrays, came from webgame-rimminer) Reads models painted with material colors. Texture coordinates and material textures are read too if present.
- One part is one node, and a node's mesh is one primitive per color. Vertices are position and normal, plus joint indices and weights if there is a skeleton. A primitive without normals is read with flat normals (one per triangle) as the glTF 2.0 specification says. Vertices are split per triangle and given the face normal. (The same goes for the rebuilt outline shell)
- The material's baseColorFactor is a linear color, so it is converted to sRGB (pow 1 / 2.2 in the gamma color space, the sRGB standard curve in the linear color space, the inverse of the curve the shader decodes with), and emissiveFactor, if present, is stored as glow. (If there is an emissiveTexture, glow is passed only through the material range)
- TEXCOORD_0, if present, goes into uvData and TEXCOORD_1 into uv1Data (second UV, angel ring). A material range (materialRanges) is stored per primitive. { name material name, materialIndex, nodeName, indexStart, indexCount, extras material extras, alphaMode, alphaCutoff, baseColorFactor linear, emissiveFactor linear, baseColorImage, emissiveImage (images order, -1 if none), hasUv } When painting split areas inside a part (accent color areas, display panels), pick them by material name or extras and draw only that area with indexStart and indexCount of ToonRenderer.drawMesh.
- Images are read with readGlbImages, decoded with decodeGlbImage and passed to ToonRenderer.createTexture.
- outline in material extras is an outline shell (only back faces drawn), and basic is a part that does not receive light. If outlineOptions is given, that shell is not stored, and a shell of uniform thickness per point is newly built from the body of each node that has a ".outline" pair. (MeshBuilder.addTriangleShell)
- If there is a skeleton (skin), the joint nodes and their inverse bind matrices, the animations and their extras (hitAt of an attack, loop "once" that plays only once, and so on) are read together. Poses are computed by writeSkinPose.
- Models whose parts are hidden or painted separately (like a cluster of several crystals) are read per node with readGlbNodeArrays. Node extras (pivot where doors and legs rotate, and so on) are stored as that part's extras.
- For a skeletal model read as one lump (like a vehicle), node extras, part positions and the joints they follow are read separately with readGlbNodeInfos.
- GLB files whose vertex attributes are stored as integers (KHR_mesh_quantization) are read too. Normalized integers are divided with the glTF spec formulas, and texture coordinates get the material texture KHR_texture_transform baked in. An unnamed mesh node belongs to the part of its named parent node. (the leaf node a quantizer adds for the dequantization transform) If extensionsRequired lists an extension that cannot be read (meshopt compression and others), an error is thrown.
The engine's GLB reader is tied inside the engine's PBR model (SkinnedModel), so only the vertex arrays used for toon drawing are extracted here.
import { ToonRenderer, readGlbArrays, writeSkinPose, Camera3D, Matrix4, Vector3 } from "./vanilla.js";
const webGL2RenderingContext = document.createElement("canvas").getContext("webgl2");
const renderer = new ToonRenderer(webGL2RenderingContext);
const arrayBuffer = await (await fetch("examples/ancientmountain/assets/fox.glb")).arrayBuffer();
const arrays = readGlbArrays(arrayBuffer, { width: 1.5, addedParts: ["fox"] });
const mesh = renderer.createMesh(arrays);
const skeleton = arrays.skeleton;
const jointMatrices = skeleton !== null ? new Float32Array(skeleton.joints.length * 16) : null;
if (skeleton !== null) {
writeSkinPose(skeleton, "Survey", 0.5, jointMatrices);
}
const camera = new Camera3D();
camera.setPerspective(0.8, 0.1, 100);
camera.lookAt(Vector3.create(0, 1, 3), Vector3.create(0, 0.4, 0), Vector3.create(0, 1, 0));
renderer.beginFrameWithCamera(camera);
renderer.drawMesh(mesh, Matrix4.createScale(0.01, 0.01, 0.01), { jointMatrices: jointMatrices });
renderer.endFrame();함수Functions
GLB 하나를 꼭짓점 배열로. (MeshBuilder.readArrays 의 꼴, 뼈대가 있으면 skeleton 도)
One GLB into vertex arrays. (MeshBuilder.readArrays form, plus skeleton if there is one)
- arrayBufferArrayBuffer
- GLB 파일 전체.The whole GLB file.
- outlineOptionsobject | null
- { width, partWidths, addedParts, innerParts, innerOverParts, innerWidth } 주면 GLB 의 바깥선 껍데기 대신 ".outline" 짝이 있는 노드의 몸으로 껍데기를 새로 짓는다. (모형 좌표의 굵기, partWidths 는 노드 이름마다, addedParts 는 짝이 없어도 껍데기를 지을 노드 이름) width 가 0 이면 껍데기를 하나도 짓지 않는다. (GLB 의 껍데기도 담지 않음) innerParts(노드 이름들)는 innerWidth 가 0 보다 크면 그 굵기의 껍데기를 하나 더 지어 바깥선 껍데기 끝에 담고, 그 자리를 innerOutlineRanges({ start, count } 들)로 돌려준다. (몸을 그린 뒤 그 부위를 둘레의 가는 선과 함께 한 번 더 그림) innerParts 와 그 위에 얹힌 innerOverParts(노드 이름들, 유리 위의 빛 반사 등)의 몸이 든 자리는 GLB 의 노드 차례대로 innerBodyRanges 로 돌려준다. (innerParts 가 없으면 빔){ width, partWidths, addedParts, innerParts, innerOverParts, innerWidth } If given, builds new shells from the body of nodes that have a ".outline" pair instead of the GLB's outline shells. (width in model coordinates, partWidths per node name, addedParts are node names to build shells for even without a pair) If width is 0, no shells are built at all. (the GLB's shells are not stored either) For innerParts (node names), if innerWidth is greater than 0, one more shell of that width is built and stored at the end of the outline shells, and its span is returned as innerOutlineRanges ({ start, count } list). (after drawing the body, that part is drawn once more together with a thin line around it) The body spans of innerParts and the innerOverParts placed on them (node names, light reflections on glass, etc.) are returned as innerBodyRanges in GLB node order. (empty if there are no innerParts)
- colorSpacestring
- 색 공간. (ColorSpace, 기본은 엔진의 색 공간, 그릴 ToonRenderer 의 getColorSpace 와 같은 값. 선형 baseColorFactor 를 꼭짓점 sRGB 색으로 바꾸는 곡선을 고른다)Color space. (ColorSpace, default is the engine's color space, the same value as getColorSpace of the ToonRenderer that draws it. Chooses the curve that converts the linear baseColorFactor to the sRGB vertex color)
반환Returnsobject MeshBuilder.readArrays 의 꼴과 skeleton (없으면 null), innerOutlineRanges, innerBodyRanges. (ToonRenderer.createMesh 에 넘긴다)The MeshBuilder.readArrays form plus skeleton (null if none), innerOutlineRanges, innerBodyRanges. (Passed to ToonRenderer.createMesh)
짝Counterpart: vanilla-engine read_glb_arrays
import { ToonRenderer, readGlbArrays, Camera3D, Matrix4, Vector3 } from "./vanilla.js";
const webGL2RenderingContext = document.createElement("canvas").getContext("webgl2");
const renderer = new ToonRenderer(webGL2RenderingContext);
const arrayBuffer = await (await fetch("examples/ancientmountain/assets/mannequin_female.glb")).arrayBuffer();
const arrays = readGlbArrays(arrayBuffer, { width: 1.5, partWidths: { Mannequin_F: 0.8 }, addedParts: ["Mannequin_F"] });
const mesh = renderer.createMesh(arrays);
const modelMatrix = Matrix4.createIdentity();
const camera = new Camera3D();
camera.setPerspective(0.8, 0.1, 100);
camera.lookAt(Vector3.create(0, 1.5, 4), Vector3.create(0, 1, 0), Vector3.create(0, 1, 0));
renderer.beginFrameWithCamera(camera);
for (const materialRange of arrays.materialRanges) {
const tintColor = materialRange.name === "M_Joints.001" ? [1, 0.4, 0.3, 1] : [1, 1, 1, 1];
renderer.drawMesh(mesh, modelMatrix, { indexStart: materialRange.indexStart, indexCount: materialRange.indexCount, tintColor: tintColor, hasOutline: false });
}
renderer.drawMeshOutline(mesh, modelMatrix);
renderer.endFrame();GLB 에 든 그림들. ([{ name, mimeType, data: Uint8Array }], images 의 차례, 재질 범위의 baseColorImage, emissiveImage 가 가리킴)
- 바이너리 덩어리의 bufferView 로 담긴 그림만 읽는다. (바깥 파일 uri 는 data 가 빈 배열)
- 텍스처로 쓰려면 decodeGlbImage 로 풀어 ToonRenderer.createTexture 에 넘긴다.
Images in a GLB. ([{ name, mimeType, data: Uint8Array }], in images order, pointed to by the material range's baseColorImage, emissiveImage)
- Only reads images stored as a bufferView of the binary chunk. (for external file uri, data is an empty array)
- To use as a texture, decode with decodeGlbImage and pass to ToonRenderer.createTexture.
- arrayBufferArrayBuffer
- GLB 파일 전체.The whole GLB file.
반환ReturnsArray<object> [{ name, mimeType, data: Uint8Array }] images 차례의 그림.[{ name, mimeType, data: Uint8Array }] images in images order.
짝Counterpart: vanilla-engine read_glb_images
import { ToonRenderer, readGlbArrays, readGlbImages, decodeGlbImage, Matrix4 } from "./vanilla.js";
const webGL2RenderingContext = document.createElement("canvas").getContext("webgl2");
const renderer = new ToonRenderer(webGL2RenderingContext);
const arrayBuffer = await (await fetch("examples/ancientmountain/assets/mannequin_female.glb")).arrayBuffer();
const arrays = readGlbArrays(arrayBuffer);
const mesh = renderer.createMesh(arrays);
const images = readGlbImages(arrayBuffer);
const textures = await Promise.all(images.map(async (image) => image.data.length > 0 ? renderer.createTexture(await decodeGlbImage(image)) : null));
const texturedRange = arrays.materialRanges.find((materialRange) => materialRange.hasUv && materialRange.baseColorImage >= 0);
if (texturedRange !== undefined) {
renderer.drawMesh(mesh, Matrix4.createIdentity(), { indexStart: texturedRange.indexStart, indexCount: texturedRange.indexCount, baseColorTexture: textures[texturedRange.baseColorImage] });
}readGlbImages 의 그림 하나를 풀기. (ImageBitmap, 알파를 미리 곱하지 않고 색 공간을 바꾸지 않음)
Decodes one image from readGlbImages. (ImageBitmap, no alpha premultiplication and no color space conversion)
- imageobject
- { mimeType, data }
반환ReturnsPromise<ImageBitmap> 풀어 낸 그림. (ToonRenderer.createTexture 에 넘긴다)The decoded image. (Passed to ToonRenderer.createTexture)
짝Counterpart: vanilla-engine decode_glb_image
import { ToonRenderer, readGlbImages, decodeGlbImage } from "./vanilla.js";
const renderer = new ToonRenderer(document.createElement("canvas").getContext("webgl2"));
const arrayBuffer = await (await fetch("examples/ancientmountain/assets/mannequin_female.glb")).arrayBuffer();
const images = readGlbImages(arrayBuffer);
if (images.length > 0 && images[0].data.length > 0) {
const imageBitmap = await decodeGlbImage(images[0]);
const texture = renderer.createTexture(imageBitmap, { isRepeated: false });
}readGlbNodeArrays(arrayBuffer, outlineOptions = null, colorSpace = readEngineColorSpace())#GLB 하나를 노드 이름마다의 꼭짓점 배열로. ({ 이름: MeshBuilder.readArrays 의 꼴 }, 뼈대는 읽지 않음)
- 이름 끝의 ".outline" 노드(바깥선 껍데기)는 그 앞 이름의 노드에 함께 담는다. (crystal1 과 crystal1.outline 은 crystal1 하나)
- 부품마다 그 노드의 extras 를 extras 로 담는다. (없으면 빈 것)
- 부품마다 비치는 재질(alphaMode BLEND)의 가장 작은 불투명도를 alpha 로 담는다. (없으면 1)
One GLB into vertex arrays per node name. ({ name: MeshBuilder.readArrays form }, skeleton not read)
- Nodes whose name ends in ".outline" (outline shells) are stored together with the node of the preceding name. (crystal1 and crystal1.outline become a single crystal1)
- For each part, the node's extras are stored as extras. (empty if none)
- For each part, the smallest opacity of its translucent materials (alphaMode BLEND) is stored as alpha. (1 if none)
- arrayBufferArrayBuffer
- GLB 파일 전체.The whole GLB file.
- outlineOptionsobject | null
- readGlbArrays 와 같음.Same as readGlbArrays.
- colorSpacestring
- 색 공간. (readGlbArrays 와 같음, 기본은 엔진의 색 공간)Color space. (Same as readGlbArrays, default is the engine's color space)
반환Returnsobject { 노드 이름: MeshBuilder.readArrays 의 꼴과 extras, alpha } 부품마다의 배열.{ node name: MeshBuilder.readArrays form plus extras, alpha } arrays per part.
짝Counterpart: vanilla-engine read_glb_node_arrays
import { ToonRenderer, readGlbNodeArrays, Camera3D, Matrix4, Vector3 } from "./vanilla.js";
const renderer = new ToonRenderer(document.createElement("canvas").getContext("webgl2"));
const arrayBuffer = await (await fetch("examples/ancientmountain/assets/mannequin_female.glb")).arrayBuffer();
const partArrays = readGlbNodeArrays(arrayBuffer, { width: 1.5, addedParts: ["Mannequin_F"] });
const parts = Object.entries(partArrays).map(([partName, arrays]) => {
return { name: partName, mesh: renderer.createMesh(arrays), pivot: arrays.extras.pivot, alpha: arrays.alpha };
});
const camera = new Camera3D();
camera.setPerspective(0.8, 0.1, 100);
camera.lookAt(Vector3.create(0, 1.5, 4), Vector3.create(0, 1, 0), Vector3.create(0, 1, 0));
renderer.beginFrameWithCamera(camera);
for (const part of parts) {
if (part.name === "Mannequin_F") {
continue;
}
const modelMatrix = Matrix4.createScale(0.01, 0.01, 0.01);
if (Array.isArray(part.pivot)) {
modelMatrix.multiply(Matrix4.createTranslation(part.pivot[0], part.pivot[1], part.pivot[2]));
}
renderer.drawMesh(part.mesh, modelMatrix);
}
renderer.endFrame();GLB 의 메시 노드마다의 extras, 가운데, 따르는 본. ({ 이름: { extras, center, jointIndex } }, 이름 끝이 ".outline" 인 노드와 바깥선 재질은 뺌, 이름 없는 메시 노드는 이름 있는 부모 부품에 모음)
- readGlbArrays 로 한 덩이에 읽은 뼈대 모형에서 노드 extras(body 의 height 등)와 부품의 자리(헬멧 불 등)를 따로 읽을 때 쓴다.
- center 는 꼭짓점이 놓인 범위의 가운데이다. (모형 좌표, 뼈대로 움직이는 노드는 쉬는 자세의 자리, 꼭짓점이 없으면 원점)
- jointIndex 는 그 노드의 꼭짓점이 가장 무겁게 딸린 본의 skin 안 차례이다. (writeSkinPose 가 쓴 본 행렬의 차례, 뼈대가 없으면 -1) 자세를 세운 뒤의 자리는 그 본 행렬로 center 를 옮긴 것이다.
Extras, center and followed bone for each mesh node of a GLB. ({ name: { extras, center, jointIndex } }, excludes nodes whose name ends in ".outline" and outline materials, an unnamed mesh node is gathered into its named parent part)
- Used to read node extras (body's height, etc.) and part positions (helmet light, etc.) separately from a skinned model read as one chunk with readGlbArrays.
- center is the center of the range the vertices occupy. (model coordinates, rest pose position for nodes moved by the skeleton, origin if there are no vertices)
- jointIndex is the index within skin of the bone the node's vertices are most heavily weighted to. (index of the bone matrix written by writeSkinPose, -1 if no skeleton) The position after posing is center transformed by that bone matrix.
- arrayBufferArrayBuffer
- GLB 파일 전체.The whole GLB file.
반환Returnsobject { 노드 이름: { extras, center [x, y, z], jointIndex } } 메시 노드마다의 정보.{ node name: { extras, center [x, y, z], jointIndex } } information per mesh node.
짝Counterpart: vanilla-engine read_glb_node_infos
import { readGlbArrays, readGlbNodeInfos, writeSkinPose, Matrix4 } from "./vanilla.js";
const arrayBuffer = await (await fetch("examples/ancientmountain/assets/mannequin_female.glb")).arrayBuffer();
const skeleton = readGlbArrays(arrayBuffer).skeleton;
const bodyInfo = readGlbNodeInfos(arrayBuffer)["Mannequin_F"];
if (skeleton !== null && bodyInfo !== undefined && bodyInfo.jointIndex >= 0) {
const jointMatrices = new Float32Array(skeleton.joints.length * 16);
writeSkinPose(skeleton, "Walk", 0.25, jointMatrices);
const jointMatrix = Matrix4.createIdentity();
jointMatrix.getElements().set(jointMatrices.subarray(bodyInfo.jointIndex * 16, bodyInfo.jointIndex * 16 + 16));
const bodyPosition = jointMatrix.transformPoint(bodyInfo.center[0], bodyInfo.center[1], bodyInfo.center[2]);
}움직임에서 한 노드의 돌림이 쉬는 자세에서 가장 벗어난 각. (라디안, 열쇠 프레임마다 보고, 그 노드의 돌림이 없으면 0)
The largest angle by which one node's rotation deviates from the rest pose in an animation. (radians, checked per keyframe, 0 if that node has no rotation)
- skeletonobject
- readGlbArrays 의 skeleton.skeleton from readGlbArrays.
- animationNamestring
- 움직임 이름.Animation name.
- nodeIndexnumber
- skeleton.nodes 의 차례.Order in skeleton.nodes.
반환Returnsnumber 쉬는 자세에서 가장 벗어난 각. (라디안, 없으면 0)The largest angle away from the rest pose. (Radians, 0 if none)
짝Counterpart: vanilla-engine read_animation_swing
import { readGlbArrays, readAnimationSwing, writeSkinPose } from "./vanilla.js";
const arrayBuffer = await (await fetch("examples/ancientmountain/assets/fox.glb")).arrayBuffer();
const skeleton = readGlbArrays(arrayBuffer).skeleton;
if (skeleton !== null) {
const tailIndex = skeleton.nodes.findIndex((node) => node.name === "b_Tail01_012");
const swing = readAnimationSwing(skeleton, "Run", tailIndex);
const swingScale = swing > 0.5 ? 0.5 / swing : 1;
const jointMatrices = new Float32Array(skeleton.joints.length * 16);
writeSkinPose(skeleton, "Run", 0.3, jointMatrices, null, { Run: [{ nodeIndex: tailIndex, scale: swingScale }] });
}섞은 자세의 뼈마다 지역 변환 고치기. (writeSkinPose 가 움직임을 읽어 섞은 뒤, 스킨 행렬을 짓기 전에 부르는 꼴, 행렬로 둔 노드는 건너뜀)
- modifiers 의 고침 하나: { nodeIndex 또는 name, translation, rotation, scale, mode, weight } 준 칸만 건다.
- 고침은 차례대로 걸린다. (같은 뼈에 둘을 주면 앞 고침 위에 뒤 고침)
- weight 는 고치기 앞과 뒤 사이의 몫이다. (0 이면 그대로, 1 이면 다 고침, 돌림은 가까운 쪽으로 섞어 정규화)
Modifies the local transform of bones in a blended pose. (the step writeSkinPose runs after sampling and blending the animation and before building the skin matrices, nodes given as matrices are skipped)
- One modification in modifiers: { nodeIndex or name, translation, rotation, scale, mode, weight } only the given fields are applied.
- Modifications apply in order. (two on the same bone stack the later on top of the earlier)
- weight is the ratio between before and after the modification. (0 leaves it as is, 1 applies it fully, rotation is blended along the shorter arc and normalized)
- localsArray<object>
- 노드마다의 { translation, rotation, scale, matrix }. (writeSkinPose 의 poseAdjust 고리가 받는 것, 고친 값을 여기에 씀)Local transform per node { translation, rotation, scale, matrix }. (what writeSkinPose's poseAdjust hook receives, modified values are written here)
- skeletonobject
- readGlbArrays 의 skeleton.skeleton from readGlbArrays.
- modifiersArray<object>
- [{ nodeIndex, name, translation, rotation, scale, mode, weight }] 뼈마다의 고침. (nodeIndex 가 없으면 name 으로 찾음, 못 찾으면 건너뜀, mode 는 BoneModifyMode 기본 add, weight 기본 1)[{ nodeIndex, name, translation, rotation, scale, mode, weight }] modifications per bone. (looked up by name when nodeIndex is absent, skipped when not found, mode is BoneModifyMode with add as default, weight defaults to 1)
짝Counterpart: vanilla-engine adjust_bones
import { readGlbArrays, writeSkinPose, adjustBones } from "./vanilla.js";
const arrayBuffer = await (await fetch("examples/ancientmountain/assets/fox.glb")).arrayBuffer();
const skeleton = readGlbArrays(arrayBuffer).skeleton;
if (skeleton !== null) {
const jointMatrices = new Float32Array(skeleton.joints.length * 16);
const crouch = 0.6;
const half = crouch / 2;
writeSkinPose(skeleton, "Survey", 0, jointMatrices, null, null, (locals, poseSkeleton) => {
adjustBones(locals, poseSkeleton, [{ name: "b_Spine01_02", rotation: [Math.sin(half), 0, 0, Math.cos(half)] }]);
const tailIndex = poseSkeleton.nodes.findIndex((node) => node.name === "b_Tail01_012");
locals[tailIndex].scale[1] *= 1.2;
});
}writeSkinPose(skeleton, animationName, time, target, blend = null, swingScales = null, poseAdjust = null)#뼈대 자세 셈하기. (움직임을 그 시각에서 읽어 본마다 행렬을 target 에 16 씩 씀, 움직임이 없으면 쉬는 자세)
- blend 를 주면 앞 움직임의 자세를 그 무게만큼 섞는다. (움직임이 바뀔 때 잠깐)
- swingScales 를 주면 그 움직임의 그 노드는 돌림을 쉬는 자세 쪽으로 줄인다. (움직임을 다시 뽑지 않고 흔들림만 줄일 때, 섞는 앞 자세에도 같이)
- poseAdjust 를 주면 섞은 뒤, 스킨 행렬을 짓기 전에 뼈마다의 지역 변환을 고친다. (움직임에 없는 자세, 머리 돌리기, 웅크림 같은 뼈 덮어쓰기) 함수면 (locals, skeleton) 으로 불러 그 함수가 locals 를 고치고, 배열이면 adjustBones 의 뼈마다 고침 표로 건다. (없으면 움직임 그대로)
Computes the skeleton pose. (samples the animation at that time and writes a matrix per bone into target, 16 each, rest pose if no animation)
- If blend is given, blends in the previous animation's pose by that weight. (briefly, when the animation changes)
- If swingScales is given, that node in that animation has its rotation reduced toward the rest pose. (to reduce only the swing without re-exporting the animation, also applied to the blended previous pose)
- If poseAdjust is given, modifies each bone's local transform after blending and before building the skin matrices. (poses not in the animation, turning the head, crouching and other bone overrides) A function is called with (locals, skeleton) and modifies locals, an array is applied as adjustBones' per-bone modification table. (the animation is left as is when absent)
- skeletonobject
- readGlbArrays 의 skeleton.skeleton from readGlbArrays.
- animationNamestring
- 움직임 이름. (없으면 쉬는 자세)Animation name. (Rest pose if none)
- timenumber
- 초. (움직임 길이로 되풀이, 한 번만 트는 움직임은 끝 시각에 묶음)Seconds. (wraps by the animation length, play-once animations are clamped to the end time)
- targetFloat32Array
- 본마다 16 씩 쓸 곳. (skeleton.joints.length x 16 이상, ToonRenderer.drawMesh 의 jointMatrices)Destination with 16 per joint. (At least skeleton.joints.length x 16, jointMatrices of ToonRenderer.drawMesh)
- blendobject | null
- { animationName, time, weight } 섞을 앞 자세와 그 무게. (0 ~ 1){ animationName, time, weight } previous pose to blend and its weight. (0 ~ 1)
- swingScalesobject | null
- { 움직임 이름: [{ nodeIndex, scale }] } 흔들림 배율. (1 이면 그대로, 0 이면 쉬는 자세){ animation name: [{ nodeIndex, scale }] } swing scale. (1 keeps as is, 0 gives the rest pose)
- poseAdjustfunction | Array<object> | null
- (locals, skeleton) 로 노드마다의 { translation, rotation, scale } 을 고치는 고리, 또는 adjustBones 의 고침 표. (locals 의 배열은 이 부름만의 것이라 제자리에서 고쳐도 된다)A hook (locals, skeleton) that modifies each node's { translation, rotation, scale }, or a modification table for adjustBones. (the arrays in locals belong to this call only, so they may be modified in place)
짝Counterpart: vanilla-engine write_skin_pose
import { readGlbArrays, writeSkinPose } from "./vanilla.js";
const arrayBuffer = await (await fetch("examples/ancientmountain/assets/fox.glb")).arrayBuffer();
const skeleton = readGlbArrays(arrayBuffer).skeleton;
if (skeleton !== null) {
const jointMatrices = new Float32Array(skeleton.joints.length * 16);
const blendDuration = 0.2;
const timeSinceChange = 0.05;
const blend = { animationName: "Survey", time: 1.4, weight: 1 - timeSinceChange / blendDuration };
writeSkinPose(skeleton, "Run", timeSinceChange, jointMatrices, blend);
}BoneModifyModeenum
뼈 고치기의 꼴. (adjustBones 와 writeSkinPose 의 poseAdjust 표에서 고침 하나가 움직임 값에 어떻게 걸리는지)
- add: 움직임 위에 덧붙인다. 자리는 부모 공간에서 더하고, 돌림은 그 뼈의 공간에서 뒤에 곱하고(q x 준 돌림), 크기는 곱한다.
- replace: 준 값으로 바꾼다. (자리, 돌림, 크기 모두 부모 공간의 지역 값)
How a bone modification is applied. (how one modification in adjustBones and writeSkinPose's poseAdjust table is applied to the animated value)
- add: added on top of the animation. Translation is added in parent space, rotation is multiplied after in the bone's own space (q x given rotation), scale is multiplied.
- replace: replaced with the given value. (translation, rotation and scale are all local values in parent space)
import { readGlbArrays, writeSkinPose, BoneModifyMode } from "./vanilla.js";
const arrayBuffer = await (await fetch("examples/ancientmountain/assets/fox.glb")).arrayBuffer();
const skeleton = readGlbArrays(arrayBuffer).skeleton;
if (skeleton !== null) {
const jointMatrices = new Float32Array(skeleton.joints.length * 16);
writeSkinPose(skeleton, "Survey", 0.5, jointMatrices, null, null, [
{ name: "b_Hip_01", translation: [0, -2, 0], mode: BoneModifyMode.add },
{ name: "b_Head_05", rotation: [0, 0, 0, 1], mode: BoneModifyMode.replace },
]);
}| 이름Name | 값Value | 설명Description |
|---|---|---|
add | 0 | 움직임 위에 덧붙임. (자리는 더함, 돌림은 그 뼈의 공간에서 뒤에 곱함, 크기는 곱함)Added on top of the animation. (translation is added, rotation is multiplied after in the bone's own space, scale is multiplied) |
replace | 1 | 준 값으로 바꿈. (부모 공간의 지역 값)Replaced with the given value. (local value in parent space) |