# graphics3d/toon/glbmeshreader (vanilla.js 0.4.0)

> https://vanillapunch.com/docs/vanilla.js/0.4.0/api/graphics3d/toon/glbmeshreader/

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.

Example: Read a GLB model and draw it in an animation pose

```js
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 and constants

- `readGlbArrays(arrayBuffer, outlineOptions = null, colorSpace = readEngineColorSpace())` (method, since 0.4.0): One GLB into vertex arrays. (MeshBuilder.readArrays form, plus skeleton if there is one)
  - `arrayBuffer` ArrayBuffer: The whole GLB file.
  - `outlineOptions` object | null: { 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)
  - `colorSpace` string: 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)
  - returns object: The MeshBuilder.readArrays form plus skeleton (null if none), innerOutlineRanges, innerBodyRanges. (Passed to ToonRenderer.createMesh)

  Example: Paint each material range separately

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

- `readGlbImages(arrayBuffer)` (method, since 0.4.0): 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.
  - `arrayBuffer` ArrayBuffer: The whole GLB file.
  - returns Array<object>: [{ name, mimeType, data: Uint8Array }] images in images order.

  Example: Upload the material's base image as a texture and draw

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

- `decodeGlbImage(image)` (method, since 0.4.0): Decodes one image from readGlbImages. (ImageBitmap, no alpha premultiplication and no color space conversion)
  - `image` object: { mimeType, data }
  - returns Promise<ImageBitmap>: The decoded image. (Passed to ToonRenderer.createTexture)

  Example: Decode the first image into a texture

  ```js
  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())` (method, since 0.4.0): 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)
  - `arrayBuffer` ArrayBuffer: The whole GLB file.
  - `outlineOptions` object | null: Same as readGlbArrays.
  - `colorSpace` string: Color space. (Same as readGlbArrays, default is the engine's color space)
  - returns object: { node name: MeshBuilder.readArrays form plus extras, alpha } arrays per part.

  Example: Upload a mesh per part and hide only one

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

- `readGlbNodeInfos(arrayBuffer)` (method, since 0.4.0): 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.
  - `arrayBuffer` ArrayBuffer: The whole GLB file.
  - returns object: { node name: { extras, center [x, y, z], jointIndex } } information per mesh node.

  Example: Read the position of a body part of a walking model

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

- `readAnimationSwing(skeleton, animationName, nodeIndex)` (method, since 0.4.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)
  - `skeleton` object: skeleton from readGlbArrays.
  - `animationName` string: Animation name.
  - `nodeIndex` number: Order in skeleton.nodes.
  - returns number: The largest angle away from the rest pose. (Radians, 0 if none)

  Example: Compute the pose while reducing the tail only as much as it swings widely

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

- `adjustBones(locals, skeleton, modifiers)` (method, since 0.4.0): 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)
  - `locals` Array<object>: Local transform per node { translation, rotation, scale, matrix }. (what writeSkinPose's poseAdjust hook receives, modified values are written here)
  - `skeleton` object: skeleton from readGlbArrays.
  - `modifiers` Array<object>: [{ 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)

  Example: Using table modifications and direct edits together inside the hook

  ```js
  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)` (method, since 0.4.0): 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)
  - `skeleton` object: skeleton from readGlbArrays.
  - `animationName` string: Animation name. (Rest pose if none)
  - `time` number: Seconds. (wraps by the animation length, play-once animations are clamped to the end time)
  - `target` Float32Array: Destination with 16 per joint. (At least skeleton.joints.length x 16, jointMatrices of ToonRenderer.drawMesh)
  - `blend` object | null: { animationName, time, weight } previous pose to blend and its weight. (0 ~ 1)
  - `swingScales` object | null: { animation name: [{ nodeIndex, scale }] } swing scale. (1 keeps as is, 0 gives the rest pose)
  - `poseAdjust` function | Array<object> | null: 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)

  Example: Briefly blend in the previous pose when the animation changes

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

## BoneModifyMode (enum)

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)

Example: Lowering the hips and setting the head forward, discarding its animated value

```js
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 },
	]);
}
```

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