Skip to content

A lightweight 2.5D character player for the web, with lip sync and webcam face tracking.

VRM: arms down and the right nod on 0.x, eyes the right way up, framed in the model's own units, clear refusals (#1)

LivLiv50d92f8cf544
diff --git a/.github/workflows/pages.yml b/.github/workflows/pages.yml
index f7ee8a8..e15296e 100644
--- a/.github/workflows/pages.yml
+++ b/.github/workflows/pages.yml
@@ -41,6 +41,14 @@ jobs:
echo "64184e229b263107bc2b804c6625db1341ff2bb731874b0bcc2fe6544e0bc9ff _site/mediapipe/face_landmarker.task" | sha256sum -c -
sed -i 's#https://cdn.jsdelivr.net/npm/@mediapipe/tasks-vision@[^/]*/vision_bundle.mjs#../mediapipe/vision_bundle.mjs#' _site/example/demo.html _site/example/png.html _site/example/vrm.html
grep -q '"../mediapipe/vision_bundle.mjs"' _site/example/demo.html
+ # three.js and three-vrm too, for the VRM page, so opening a .vrm online does not depend on a CDN either
+ mkdir -p _site/vendor/three/build _site/vendor/three/examples/jsm/loaders _site/vendor/three/examples/jsm/utils _site/vendor/three-vrm
+ cp node_modules/three/build/three.module.js node_modules/three/build/three.core.js _site/vendor/three/build/
+ cp node_modules/three/examples/jsm/loaders/GLTFLoader.js _site/vendor/three/examples/jsm/loaders/
+ cp node_modules/three/examples/jsm/utils/*.js _site/vendor/three/examples/jsm/utils/
+ cp node_modules/@pixiv/three-vrm/lib/three-vrm.module.min.js _site/vendor/three-vrm/
+ sed -i -e 's#https://cdn.jsdelivr.net/npm/three@[^/]*/build/three.module.js#../vendor/three/build/three.module.js#' -e 's#https://cdn.jsdelivr.net/npm/three@[^/]*/examples/jsm/#../vendor/three/examples/jsm/#' -e 's#https://cdn.jsdelivr.net/npm/@pixiv/three-vrm@[^/]*/lib/three-vrm.module.min.js#../vendor/three-vrm/three-vrm.module.min.js#' _site/example/vrm.html
+ grep -q '"../vendor/three/build/three.module.js"' _site/example/vrm.html
- uses: actions/configure-pages@v5
- uses: actions/upload-pages-artifact@v3
with:
diff --git a/API.md b/API.md
index ed21a4c..8da87de 100644
--- a/API.md
+++ b/API.md
@@ -294,11 +294,15 @@ await vrm.load('/avatars/me.vrm') // a URL, a File, or files picked
- **VRM** (`@livliv/player/vrm`): VRM 0.x and 1.0, drawn with [three.js](https://threejs.org) and
[three-vrm](https://github.com/pixiv/three-vrm), which you install (`npm install three @pixiv/three-vrm`; optional
peer dependencies, so the rest of the package does not need them). The head and neck turn, the spine sways, the eyes
- blink and look, the mouth takes the visemes (`aa`, `ee`, `ou` from `mouthOpen` and `vowel`), and the expressions
- are the model's `happy`, `angry`, `sad`, `relaxed` and `surprised` where it has them; hair and clothes swing by the
- model's own spring bones. Framed from the head to the hips with the arms down; no hands, no full body, no camera
+ blink and look, the mouth takes the visemes (`aa`, `ee`, `ou`, or `ih`, `oh` where those are missing, from `mouthOpen` and `vowel`),
+ and the expressions are the model's `happy`, `angry`, `sad`, `relaxed` and `surprised` where it has them, then any
+ of its own under the names it gives them; hair and clothes swing by the model's own spring bones, and its constraints apply. Framed from the head to the hips with the arms down; no hands, no full body, no camera
control. Without a bundler, map `three`, `three/examples/jsm/` and `@pixiv/three-vrm` in an import map, as
`example/vrm.html` does.
+ A VRM carries its author's terms, and `load()` gives them in `model.meta` (`VrmTerms`), 1.0 and 0.x said alike: `author`,
+ `license`, `use` (who may play it), `commercial`, `violence`, `sexual`, `redistribution` and `modification` (1.0 only), the
+ file's own words in `raw`. The player does not enforce them. A page playing other people's avatars should show them and
+ keep to them, as you would with a LivLiv package's `meta.license`.
- **Your own**: anything with `load(files)`, `render(canvas, pose, w, h, dt)`, `head()` and `dispose()` (the `Body`
type), and if it cares which canvas it gets, `attach(canvas)`. `pose` has the params after the idle motion and the
drivers, the picture's `move` and each expression's weight.
@@ -323,7 +327,10 @@ an error and the model before stays. Before anything reaches the GPU:
- A name, an expression's label and the mark's text are the author's text: show them with `textContent`, not as HTML.
These limits are `LIMITS` in `src/runtime/format.ts`; the largest model LivLiv has built uses a tenth of them or less.
-VRM files are parsed by three.js's glTF loader. Security reports: [SECURITY.md](SECURITY.md).
+A VRM is looked through before three.js's glTF loader parses it (`VRM_LIMITS` in `@livliv/player/vrm`): a binary glTF, with
+nothing outside itself (a file naming an outside URL is refused, so it cannot make the page fetch anything), 32 MB of
+JSON, 16 777 216 vertices, pictures of 8192 px a side and 536 870 912 pixels in all, read from their headers before they are
+decoded. Security reports: [SECURITY.md](SECURITY.md).
## Format version
diff --git a/example/demo.html b/example/demo.html
index e327c52..374579d 100644
--- a/example/demo.html
+++ b/example/demo.html
@@ -42,7 +42,9 @@
controls(m)
} catch (e) {
status.textContent = e.message
- controls(null)
+ // a VRM has its own page here
+ if (/VRM/.test(e.message)) { const a = document.createElement('a'); a.href = 'vrm.html'; a.style.color = 'inherit'; a.textContent = ' Open the VRM page'; status.append(a) }
+ controls(player.model)
}
done()
}
@@ -53,7 +55,7 @@
pick.innerHTML = 'open a folder… <input type="file" webkitdirectory hidden>'
pick.querySelector('input').onchange = (e) => e.target.files.length && show(e.target.files)
const one = document.createElement('label') // a .livliv package (one file)
- one.innerHTML = 'open a .livliv… <input type="file" accept=".livliv,.zip" hidden>'
+ one.innerHTML = 'open a .livliv… <input type="file" accept=".livliv,.zip,.vrm,.glb" hidden>'
one.querySelector('input').onchange = (e) => e.target.files.length && show(e.target.files[0])
bar.append(pick, one)
if (!m) return
diff --git a/example/vrm.html b/example/vrm.html
index 3dd25d1..63d24d0 100644
--- a/example/vrm.html
+++ b/example/vrm.html
@@ -38,7 +38,9 @@
status.textContent = 'Loading…'
try {
const m = await player.load(source)
- status.textContent = `${m.name} · ${m.format}`
+ // the author's terms come with the file: a page playing other people's avatars should show them
+ const t = m.meta
+ status.textContent = [m.name, m.format, t?.author && `by ${t.author.name}`, t?.license && (t.license.id || t.license.url), t?.commercial && `commercial use: ${t.commercial}`].filter(Boolean).join(' · ')
bar.querySelectorAll('.x').forEach((b) => b.remove())
for (const x of [{ id: null, label: 'neutral' }, ...m.expressions]) {
const b = document.createElement('button'); b.className = 'x'; b.textContent = x.label
diff --git a/src/body.ts b/src/body.ts
index 7f45526..abe6fe8 100644
--- a/src/body.ts
+++ b/src/body.ts
@@ -24,7 +24,7 @@ export interface Body {
attach?(canvas: HTMLCanvasElement): void
/** loads from its files (by file name); its name and the expressions it can show. If it rejects, the character before
* must stay as it is */
- load(files: Map<string, Blob>): Promise<{ name: string; expressions: BodyExpression[] }>
+ load(files: Map<string, Blob>): Promise<{ name: string; expressions: BodyExpression[]; meta?: BodyMeta }>
/** draws the pose into the canvas, w × h device pixels, dt seconds after the last frame */
render(canvas: HTMLCanvasElement, pose: Pose, w: number, h: number, dt: number): void
/** where the head is, in shares of the canvas (from the top left) and its radii */
@@ -32,6 +32,9 @@ export interface Body {
dispose(): void
}
+/** who made a body character and under what terms, as its file says */
+export interface BodyMeta { author?: { name: string } | null; license?: { id?: string; url?: string } | null }
+
/** a loaded body character */
export interface BodyInfo {
name: string
@@ -39,6 +42,8 @@ export interface BodyInfo {
format: string
/** what setExpression() takes (smile is always there: a param, not an expression) */
expressions: { id: string; label: string; labels: Labels }[]
+ /** what the file says about itself, where it does: a VRM's author and terms (VrmTerms). null otherwise */
+ meta: BodyMeta | null
}
/** its files: a URL (one file, a .vrm say), a File / Blob, a FileList / File[], or a map or object of file name -> Blob
@@ -139,7 +144,7 @@ export class BodyPlayer implements Host {
stillHere()
const ex = [{ id: 'smile', label: '', labels: SMILE }, ...got.expressions.filter((e) => e.id !== 'smile')
.map((e) => ({ id: e.id, label: e.label, labels: e.labels ?? { en: e.label } }))]
- this.info = { name: got.name, format: this.body.format,
+ this.info = { name: got.name, format: this.body.format, meta: got.meta ?? null,
expressions: ex.map((e) => ({ id: e.id, label: pickLabel(e.labels, this.lang, e.label || e.id), labels: e.labels })) }
this.expr = {}; this.smile = 0; this.pose.expr = {}
if (!this.playing) this.draw(0)
diff --git a/src/index.ts b/src/index.ts
index 16eff57..4bef823 100644
--- a/src/index.ts
+++ b/src/index.ts
@@ -352,6 +352,10 @@ function explain(e: unknown, where: string): Error {
return new Error(msg.startsWith('LivLiv') ? msg : `LivLiv: ${msg}`)
}
+/** a file a Player cannot take but a BodyPlayer can: the words that say so */
+const VRM_HERE = 'LivLiv: this is a VRM or glTF file, and a Player plays LivLiv models: use a BodyPlayer with VrmBody (@livliv/player/vrm)'
+const isGlb = async (b: Blob) => { const d = new DataView(await b.slice(0, 4).arrayBuffer()); return d.byteLength === 4 && d.getUint32(0, true) === 0x46546c67 }
+
/** a .livliv package from a URL, as a Blob. One file is one connection to lose where a folder has dozens, and a dropped one
* breaks in the body as often as at the start: tried once more, unless the server said no (4xx). What the page gets is
* our words, never the browser's ("Failed to fetch", "Load failed") */
@@ -376,6 +380,7 @@ async function fromFiles(source: Exclude<ModelSource, string | URL>) {
const files = new Map<string, Blob>()
const norm = (k: string) => k.replace(/\\/g, '/').replace(/^(\.\/|\/)+/, '')
const unpack = async (b: Blob) => {
+ if (await isGlb(b)) throw new Error(VRM_HERE)
if (!(await isZip(b))) throw new Error('LivLiv: this file is not a .livliv package (not a ZIP)')
return unzip(b).catch((e) => { throw explain(e, 'the package') })
}
@@ -390,6 +395,7 @@ async function fromFiles(source: Exclude<ModelSource, string | URL>) {
}
}
const json = [...files.keys()].filter(isJson).sort((a, b) => a.length - b.length)[0]
+ if (!json && [...files.keys()].some((k) => /\.(vrm|glb)$/i.test(k))) throw new Error(VRM_HERE)
if (!json) throw new Error('LivLiv: no model.json among the files')
const dir = json.slice(0, json.length - 'model.json'.length)
if (files.get(json)!.size > ZIP_LIMITS.modelJson) throw new Error(`LivLiv: ${json} is larger than ${ZIP_LIMITS.modelJson} bytes`)
diff --git a/src/vrm.ts b/src/vrm.ts
index bf8ba70..54db1d8 100644
--- a/src/vrm.ts
+++ b/src/vrm.ts
@@ -3,10 +3,12 @@
// shared params become its pose: the head and neck turn and tilt (angleX / Y / Z), the spine sways (bodyX / Z), the
// eyes blink (eyeLOpen / ROpen) and look (eyeBallX / Y), the mouth takes the visemes (mouthOpen with its vowel: aa open,
// ee wide, ou round), the face its expressions (happy with smile; angry, sad, relaxed, surprised); its hair and clothes
-// swing by the model's own spring bones. Framed from the head down to the hips, arms down.
+// swing by the model's own spring bones. Framed from the head down to the hips, arms down. VRM 1.0 and 0.x, whoever
+// exported them; a file is looked through before three.js parses it (checkGlb).
import type * as T from 'three'
import type { VRM } from '@pixiv/three-vrm'
-import type { Body, BodyExpression, Pose } from './body'
+import type { GLTFLoader } from 'three/examples/jsm/loaders/GLTFLoader.js'
+import type { Body, BodyExpression, BodyMeta, Pose } from './body'
const FEELINGS = ['happy', 'angry', 'sad', 'relaxed', 'surprised'] as const
const LABELS: Record<(typeof FEELINGS)[number], Record<string, string>> = {
@@ -18,8 +20,41 @@ const LABELS: Record<(typeof FEELINGS)[number], Record<string, string>> = {
}
const D = Math.PI / 180
+/** what a VRM may hold before it is decoded: a real avatar stays far below these (VRoid: about 27 M pixels) */
+export const VRM_LIMITS = { json: 32 * 2 ** 20, textureSide: 8192, texels: 512 * 2 ** 20, vertices: 16 * 2 ** 20 }
+
+export interface VrmBodyOptions {
+ /** given the GLTFLoader before it reads a file: for compressed files, register your decoders here (setDRACOLoader,
+ * setMeshoptDecoder, setKTX2Loader). The player itself ships none */
+ configureLoader?: (loader: GLTFLoader) => void
+}
+
+/** the terms a VRM's author set (its meta, 1.0 and 0.x said alike, the file's own words in `raw`). A page playing other
+ * people's avatars should show them and keep to them */
+export interface VrmTerms extends BodyMeta {
+ /** the spec the file follows: '1' or '0' */
+ spec: string
+ /** who may play the avatar: only its author, people the author licensed, or everyone */
+ use: 'author' | 'licensed' | 'everyone' | null
+ /** the avatar in commercial work. 1.0 has grades, 0.x only allow and disallow */
+ commercial: 'disallow' | 'personal non-profit' | 'personal profit' | 'allow' | 'corporation' | null
+ violence: boolean | null
+ sexual: boolean | null
+ /** passing the file on, and changing it (1.0; null in 0.x, whose terms are in its licence) */
+ redistribution: boolean | null
+ modification: string | null
+ raw: Record<string, unknown>
+}
+
export class VrmBody implements Body {
readonly format = 'vrm'
+ private options: VrmBodyOptions
+ /** VRM 0.x stands facing the other way, turned round by three-vrm: rotations about X and Z count the other way round */
+ private flip = 1
+ /** the file has only one blink, for both eyes */
+ private blinkBoth = false
+ /** the expressions the file adds to the preset ones: the id it goes by here -> its name in the file */
+ private custom = new Map<string, string>()
private THREE!: typeof T
private vrm: VRM | null = null
private scene!: T.Scene
@@ -31,6 +66,9 @@ export class VrmBody implements Body {
private has = new Set<string>()
private canvas: HTMLCanvasElement | null = null
private headAt = { x: 0.5, y: 0.25 }
+ private width = 0.6
+
+ constructor(options: VrmBodyOptions = {}) { this.options = options }
attach(canvas: HTMLCanvasElement) {
// the attributes render() gives three.js, which then finds this same context
@@ -42,13 +80,15 @@ export class VrmBody implements Body {
async load(files: Map<string, Blob>) {
const entry = [...files].find(([n]) => /\.(vrm|glb)$/i.test(n))
if (!entry) throw new Error('LivLiv: no .vrm file among the files')
+ await checkGlb(entry[1], entry[0], !this.options.configureLoader)
const [THREE, { GLTFLoader }, { VRMLoaderPlugin, VRMUtils }] = await Promise.all([
import('three'), import('three/examples/jsm/loaders/GLTFLoader.js'), import('@pixiv/three-vrm')]).catch((e) => {
- throw new Error(`LivLiv: a VRM needs the three and @pixiv/three-vrm packages (${(e as Error).message})`)
+ throw new Error(`LivLiv: could not load three or @pixiv/three-vrm, which a VRM needs: are they installed, and can this page reach them? (${(e as Error).message})`)
})
this.THREE = THREE
const loader = new GLTFLoader()
loader.register((parser) => new VRMLoaderPlugin(parser))
+ this.options.configureLoader?.(loader)
const url = URL.createObjectURL(entry[1])
let gltf
try {
@@ -61,7 +101,13 @@ export class VrmBody implements Body {
const vrm = gltf.userData.vrm as VRM | undefined
if (!vrm) {
VRMUtils.deepDispose(gltf.scene)
- throw new Error(`LivLiv: ${entry[0]} is a glTF without VRM data`)
+ throw new Error(`LivLiv: ${entry[0]} is a glTF without VRM data (exported as plain glTF? VRM exporters write a .vrm)`)
+ }
+ let meshes = 0
+ vrm.scene.traverse((o) => { if ((o as T.Mesh).isMesh) meshes++ })
+ if (!meshes) {
+ VRMUtils.deepDispose(gltf.scene)
+ throw new Error(`LivLiv: ${entry[0]} has a skeleton but no mesh, so there is nothing to draw (export the armature together with its meshes)`)
}
// the new character, apart from the one shown (a failed load leaves that on the canvas): it takes over at the end
VRMUtils.removeUnnecessaryVertices(gltf.scene)
@@ -69,12 +115,13 @@ export class VrmBody implements Body {
VRMUtils.rotateVRM0(vrm) // VRM 0.x faces the other way
vrm.scene.traverse((o) => { o.frustumCulled = false })
const h = vrm.humanoid
+ const flip = vrm.meta?.metaVersion === '0' ? -1 : 1
const bones: typeof this.bones = {}
for (const b of ['head', 'neck', 'spine', 'chest'] as const) bones[b] = h.getNormalizedBoneNode(b) ?? undefined
// arms down from the T pose, a little forward
const lu = h.getNormalizedBoneNode('leftUpperArm'), ru = h.getNormalizedBoneNode('rightUpperArm')
- if (lu) lu.rotation.set(0, 0, -1.2)
- if (ru) ru.rotation.set(0, 0, 1.2)
+ if (lu) lu.rotation.set(0, 0, -1.2 * flip)
+ if (ru) ru.rotation.set(0, 0, 1.2 * flip)
const ll = h.getNormalizedBoneNode('leftLowerArm'), rl = h.getNormalizedBoneNode('rightLowerArm')
if (ll) ll.rotation.set(0, -0.25, 0)
if (rl) rl.rotation.set(0, 0.25, 0)
@@ -87,32 +134,50 @@ export class VrmBody implements Body {
light.position.set(1, 1, 1).normalize()
scene.add(light, new THREE.AmbientLight(0xffffff, 0.6))
// the head's top to the hips: what a LivLiv character's canvas shows of a person
- const at = (b: 'head' | 'hips') => { const v = new THREE.Vector3(); h.getNormalizedBoneNode(b)?.getWorldPosition(v); return v }
- const head = at('head'), hips = at('hips')
- const top = head.y + 0.2, bottom = hips.y
+ // in the model's own units, whatever they are (an exporter's unit can make a character 170 long), and its own shape
+ // (a head as big as the rest of it)
+ const at = (b: 'head' | 'hips' | 'leftUpperArm' | 'rightUpperArm') => { const v = new THREE.Vector3(); h.getNormalizedBoneNode(b)?.getWorldPosition(v); return v }
+ const head = at('head'), hips = at('hips'), torso = Math.max(1e-3, head.y - hips.y)
+ const box = new THREE.Box3().setFromObject(vrm.scene)
+ const crown = Number.isFinite(box.max.y) ? box.max.y : head.y
+ const top = Math.max(head.y + torso / 3, Math.min(crown + torso / 20, head.y + torso)), bottom = hips.y
+ const shoulders = at('leftUpperArm').distanceTo(at('rightUpperArm'))
const has = new Set((vrm.expressionManager?.expressions ?? []).map((e) => e.expressionName))
const meta = vrm.meta as { name?: string; title?: string } | undefined
const expressions: BodyExpression[] = FEELINGS.filter((f) => f !== 'happy' && has.has(f)).map((f) => ({ id: f, label: LABELS[f].en, labels: LABELS[f] }))
if (has.has('happy')) expressions.unshift({ id: 'happy', label: LABELS.happy.en, labels: LABELS.happy })
- const name = (meta?.name || meta?.title || entry[0].replace(/\.(vrm|glb)$/i, '')).slice(0, 200)
+ // what the file adds of its own, under the name it gives; a feeling 0.x has no preset for (VRoid's Surprised) by our id
+ const custom = new Map<string, string>()
+ for (const n of Object.keys(vrm.expressionManager?.customExpressionMap ?? {})) {
+ const lower = n.toLowerCase(), id = (FEELINGS as readonly string[]).includes(lower) ? lower : n
+ custom.set(id, n)
+ if (!expressions.some((x) => x.id === id)) expressions.push(id === lower && id in LABELS ? { id, label: LABELS[id as keyof typeof LABELS].en, labels: LABELS[id as keyof typeof LABELS] } : { id, label: n })
+ }
+ // an exporter's placeholder is no name ("undefined": VRM Add-on for Blender, until it is filled in)
+ const given = (meta?.name || meta?.title || '').trim()
+ const name = (given && given !== 'undefined' ? given : entry[0].replace(/\.(vrm|glb)$/i, '')).slice(0, 200)
const old = this.vrm
this.vrm = vrm
this.scene = scene
this.bones = bones
this.has = has
- this.frame = { height: Math.max(0.1, top - bottom), y: (top + bottom) / 2 }
- this.camera = new THREE.PerspectiveCamera(20, 2 / 3, 0.05, 30)
+ this.custom = custom
+ this.blinkBoth = has.has('blink') && !(has.has('blinkLeft') && has.has('blinkRight'))
+ this.flip = flip
+ this.frame = { height: Math.max(1e-3, top - bottom), y: (top + bottom) / 2 }
+ this.width = Math.max(shoulders * 1.5, this.frame.height / 2)
+ this.camera = new THREE.PerspectiveCamera(20, 2 / 3, this.frame.height / 100, this.frame.height * 100)
this.place(2 / 3) // render() gives it the canvas's aspect
if (old) VRMUtils.deepDispose(old.scene)
- return { name, expressions }
+ return { name, expressions, meta: vrmTerms(vrm.meta as unknown as Record<string, unknown>) }
}
/** the camera where the framing fits the canvas's aspect */
private place(aspect: number) {
const c = this.camera, half = this.frame.height / 2
// tall enough for the height, wide enough for the shoulders and arms on narrow canvases
- const dist = Math.max(half, 0.3 / aspect) / Math.tan((c.fov * D) / 2)
+ const dist = Math.max(half, this.width / 2 / aspect) / Math.tan((c.fov * D) / 2)
c.aspect = aspect
c.position.set(0, this.frame.y, dist)
c.lookAt(0, this.frame.y, 0)
@@ -130,26 +195,32 @@ export class VrmBody implements Body {
}
if (canvas.width !== w || canvas.height !== h) this.renderer.setSize(w, h, false)
if (this.camera.aspect !== w / h) this.place(w / h) // a new character's camera, on a canvas already this size too
- const b = this.bones
- // the head turns most, the neck some (yaw: to the screen's right; pitch: up; roll: toward the screen's left)
- b.neck?.rotation.set(-P.angleY * D * 0.35, P.angleX * D * 0.35, -P.angleZ * D * 0.35)
- b.head?.rotation.set(-P.angleY * D * 0.65, P.angleX * D * 0.65, -P.angleZ * D * 0.65)
- b.spine?.rotation.set(0, P.bodyX * D * 0.8, -P.bodyZ * D * 0.8)
- b.chest?.rotation.set(-(P.breath - 0.5) * 0.02, 0, 0)
+ const b = this.bones, s = this.flip
+ // the head turns most, the neck some (yaw: to the screen's right; pitch: up; roll: its top to the screen's right, as a
+ // Player's does). The neck is optional in VRM: without one the head takes it all
+ const hk = b.neck ? 0.65 : 1
+ b.neck?.rotation.set(-s * P.angleY * D * 0.35, P.angleX * D * 0.35, -s * P.angleZ * D * 0.35)
+ b.head?.rotation.set(-s * P.angleY * D * hk, P.angleX * D * hk, -s * P.angleZ * D * hk)
+ b.spine?.rotation.set(0, P.bodyX * D * 0.8, -s * P.bodyZ * D * 0.8)
+ b.chest?.rotation.set(-s * (P.breath - 0.5) * 0.02, 0, 0)
vrm.scene.position.set(move.x * this.frame.height * 0.5, move.y * this.frame.height, 0)
vrm.scene.scale.setScalar(move.s)
const em = vrm.expressionManager
if (em) {
const set = (n: string, v: number) => { if (this.has.has(n)) em.setValue(n, Math.max(0, Math.min(1, v))) }
- set('blinkLeft', 1 - P.eyeLOpen); set('blinkRight', 1 - P.eyeROpen)
+ if (this.blinkBoth) set('blink', 1 - Math.max(P.eyeLOpen, P.eyeROpen))
+ else { set('blinkLeft', 1 - P.eyeLOpen); set('blinkRight', 1 - P.eyeROpen) }
const o = P.mouthOpen, v = P.vowel
- set('aa', o * (1 - Math.abs(v) * 0.6)); set('ee', o * Math.max(0, v) * 0.7); set('ou', o * Math.max(0, -v) * 0.7)
- // the smile param is a small one (the idle motion's, the face tracker's): half the model's happy, which often
- // closes the eyes
- set('happy', Math.max(P.smile * 0.5, expr.happy ?? 0))
- for (const f of FEELINGS) if (f !== 'happy') set(f, expr[f] ?? 0)
+ // wide and round: the file's ee and ou, or else its ih and oh
+ set('aa', o * (1 - Math.abs(v) * 0.6)); set(this.has.has('ee') ? 'ee' : 'ih', o * Math.max(0, v) * 0.7); set(this.has.has('ou') ? 'ou' : 'oh', o * Math.max(0, -v) * 0.7)
+ // the smile param is a small one (the idle motion's, the face tracker's): a little over half the model's happy, which
+ // often closes the eyes. Over half: an expression marked isBinary is off below it
+ set('happy', Math.max(P.smile * 0.6, expr.happy ?? 0))
+ for (const f of FEELINGS) if (f !== 'happy' && !this.custom.has(f)) set(f, expr[f] ?? 0)
+ for (const [id, n] of this.custom) set(n, expr[id] ?? 0)
}
- if (vrm.lookAt) { vrm.lookAt.yaw = P.eyeBallX * 25; vrm.lookAt.pitch = P.eyeBallY * 15 }
+ // three-vrm's pitch is positive looking down
+ if (vrm.lookAt) { vrm.lookAt.yaw = P.eyeBallX * 25; vrm.lookAt.pitch = -P.eyeBallY * 15 }
vrm.update(dt)
this.renderer.render(this.scene, this.camera)
// where the head is now, for the pointer
@@ -169,3 +240,86 @@ export class VrmBody implements Body {
if (vrm) void import('@pixiv/three-vrm').then(({ VRMUtils }) => VRMUtils.deepDispose(vrm.scene))
}
}
+
+/** the VRM's meta in one shape, whichever spec wrote it */
+function vrmTerms(m: Record<string, unknown> | undefined): VrmTerms | undefined {
+ if (!m) return undefined
+ const text = (v: unknown) => (typeof v === 'string' && v.trim() && v !== 'undefined' ? v.trim() : undefined)
+ const yes = (v: unknown) => (typeof v === 'boolean' ? v : v === 'Allow' ? true : v === 'Disallow' ? false : null)
+ if (m.metaVersion === '0') {
+ const url = text(m.otherLicenseUrl), id = text(m.licenseName)
+ return {
+ spec: '0', author: text(m.author) ? { name: text(m.author)! } : null, license: id || url ? { id, url } : null,
+ use: m.allowedUserName === 'Everyone' ? 'everyone' : m.allowedUserName === 'ExplicitlyLicensedPerson' ? 'licensed' : m.allowedUserName === 'OnlyAuthor' ? 'author' : null,
+ commercial: m.commercialUssageName === 'Allow' ? 'allow' : m.commercialUssageName === 'Disallow' ? 'disallow' : null,
+ violence: yes(m.violentUssageName), sexual: yes(m.sexualUssageName), redistribution: null, modification: null, raw: m,
+ }
+ }
+ const authors = (Array.isArray(m.authors) ? m.authors : []).map(text).filter(Boolean)
+ const url = text(m.licenseUrl)
+ return {
+ spec: '1', author: authors.length ? { name: authors.join(', ') } : null, license: url ? { url } : null,
+ use: m.avatarPermission === 'everyone' ? 'everyone' : m.avatarPermission === 'onlySeparatelyLicensedPerson' ? 'licensed' : m.avatarPermission === 'onlyAuthor' ? 'author' : null,
+ commercial: m.commercialUsage === 'corporation' ? 'corporation' : m.commercialUsage === 'personalProfit' ? 'personal profit' : m.commercialUsage === 'personalNonProfit' ? 'personal non-profit' : null,
+ violence: yes(m.allowExcessivelyViolentUsage), sexual: yes(m.allowExcessivelySexualUsage), redistribution: yes(m.allowRedistribution),
+ modification: text(m.modification) ?? null, raw: m,
+ }
+}
+
+const COMPRESSED: Record<string, string> = { KHR_draco_mesh_compression: 'Draco', EXT_meshopt_compression: 'Meshopt', KHR_texture_basisu: 'KTX2' }
+
+/** a .vrm looked through before three.js sees it, as any file from anyone: a GLB, no outside files (it would make the page
+ * fetch them), its compression one the page can decode, and images and meshes within VRM_LIMITS, read from the file's
+ * headers before anything is decoded */
+async function checkGlb(file: Blob, name: string, noDecoders: boolean) {
+ const bad = (why: string): never => { throw new Error(`LivLiv: ${name} ${why}`) }
+ const head = new DataView(await file.slice(0, 20).arrayBuffer())
+ if (head.byteLength < 20 || head.getUint32(0, true) !== 0x46546c67) bad('is not a VRM: it should begin as a binary glTF does')
+ if (head.getUint32(4, true) !== 2) bad(`is a glTF of version ${head.getUint32(4, true)}, and VRM uses 2`)
+ const jsonLen = head.getUint32(12, true)
+ if (head.getUint32(16, true) !== 0x4e4f534a) bad('is damaged (no JSON where a binary glTF has it)')
+ if (jsonLen > VRM_LIMITS.json) bad(`is not one this player reads: its JSON has ${jsonLen} bytes, more than ${VRM_LIMITS.json}`)
+ if (20 + jsonLen > file.size) bad('is damaged or cut short')
+ let gltf: { buffers?: { uri?: string }[]; images?: { uri?: string; bufferView?: number }[]; bufferViews?: { byteOffset?: number; byteLength?: number }[]
+ accessors?: { count?: number }[]; meshes?: { primitives?: { attributes?: { POSITION?: number } }[] }[]; extensionsUsed?: string[] }
+ try { gltf = JSON.parse(await file.slice(20, 20 + jsonLen).text()) } catch { return bad('is damaged (its JSON does not parse)') }
+ for (const o of [...(gltf.buffers ?? []), ...(gltf.images ?? [])]) {
+ if (o?.uri && !o.uri.startsWith('data:')) bad(`names a file outside itself (${String(o.uri).slice(0, 80)}), and a .vrm has to hold everything it needs`)
+ }
+ if (noDecoders) {
+ for (const [ext, what] of Object.entries(COMPRESSED)) {
+ if (gltf.extensionsUsed?.includes(ext)) bad(`is compressed with ${what}, and this page has no decoder for that. Export it uncompressed, or pass VrmBody a configureLoader`)
+ }
+ }
+ const positions = new Set<number>()
+ for (const m of gltf.meshes ?? []) for (const p of m?.primitives ?? []) if (typeof p?.attributes?.POSITION === 'number') positions.add(p.attributes.POSITION)
+ let vertices = 0
+ for (const i of positions) vertices += gltf.accessors?.[i]?.count ?? 0
+ if (vertices > VRM_LIMITS.vertices) bad(`has ${vertices} vertices, more than ${VRM_LIMITS.vertices}`)
+ // where the binary chunk starts, and each picture's size from its first bytes
+ const binary = 20 + jsonLen + 8
+ let texels = 0
+ for (const im of gltf.images ?? []) {
+ const bv = typeof im?.bufferView === 'number' ? gltf.bufferViews?.[im.bufferView] : undefined
+ if (!bv) continue
+ const size = await pictureSize(file.slice(binary + (bv.byteOffset ?? 0), binary + (bv.byteOffset ?? 0) + (bv.byteLength ?? 0)))
+ if (!size) continue
+ if (size[0] > VRM_LIMITS.textureSide || size[1] > VRM_LIMITS.textureSide || (texels += size[0] * size[1]) > VRM_LIMITS.texels) {
+ bad(`has pictures too large for this player (${size[0]} x ${size[1]}; ${VRM_LIMITS.textureSide} px a side and ${VRM_LIMITS.texels} pixels in all at most)`)
+ }
+ }
+}
+
+/** width and height from the start of a PNG or a JPEG (other kinds: unknown, left to the browser) */
+async function pictureSize(b: Blob): Promise<[number, number] | null> {
+ const d = new DataView(await b.slice(0, 64 * 1024).arrayBuffer())
+ if (d.byteLength >= 24 && d.getUint32(0) === 0x89504e47) return [d.getUint32(16), d.getUint32(20)]
+ if (d.byteLength < 4 || d.getUint16(0) !== 0xffd8) return null
+ for (let i = 2; i + 9 < d.byteLength;) {
+ if (d.getUint8(i) !== 0xff) { i++; continue }
+ const m = d.getUint8(i + 1)
+ if (m >= 0xc0 && m <= 0xcf && m !== 0xc4 && m !== 0xc8 && m !== 0xcc) return [d.getUint16(i + 7), d.getUint16(i + 5)]
+ i += 2 + d.getUint16(i + 2)
+ }
+ return null
+}
diff --git a/test/bodies.html b/test/bodies.html
index 37e6bd2..a220436 100644
--- a/test/bodies.html
+++ b/test/bodies.html
@@ -45,6 +45,57 @@
return new Blob([b.buffer], { type: 'audio/wav' })
}
+ /** what a VRM player says of a file it cannot play, keeping the character before */
+ window.runVrmRefusals = async (urls) => {
+ const c = document.createElement('canvas')
+ const p = new BodyPlayer(c, new VrmBody(), { autoplay: false, idle: false, followPointer: false })
+ await p.load('/__tiny.vrm')
+ const out = {}
+ for (const [k, u] of Object.entries(urls)) out[k] = await p.load(u).then(() => 'loaded', (e) => e.message)
+ out.plainFile = await p.load(new File([new Blob(['not a glb at all, a text file'])], 'x.vrm')).then(() => 'loaded', (e) => e.message)
+ out.kept = p.model?.name
+ p.dispose()
+ return out
+ }
+
+ /** how much of the canvas a VRM covers */
+ window.runVrmShare = async (url) => {
+ const c = document.createElement('canvas')
+ c.style.cssText = 'width: 300px; height: 400px'
+ document.body.append(c)
+ const p = new BodyPlayer(c, new VrmBody(), { autoplay: false, idle: false, followPointer: false })
+ await p.load(url)
+ p.resize()
+ const share = covered(c)
+ p.dispose(); c.remove()
+ return share
+ }
+
+ /** which way a VRM stands and moves, 1.0 and 0.x alike: arms down, head turning right and up, top of the head to the right
+ * on a positive roll, eyes up and to the character's left (the screen's right) */
+ window.runVrmPose = async (url) => {
+ const THREE = await import('three')
+ const c = document.createElement('canvas')
+ c.style.cssText = 'width: 300px; height: 400px'
+ document.body.append(c)
+ const p = new BodyPlayer(c, new VrmBody(), { autoplay: false, idle: false, followPointer: false })
+ await p.load(url)
+ const vrm = p.body.vrm, H = vrm.humanoid, em = vrm.expressionManager
+ const set = (o) => { Object.assign(p.params, { angleX: 0, angleY: 0, angleZ: 0, eyeBallX: 0, eyeBallY: 0, bodyZ: 0 }, o); p.draw(0); p.draw(0) }
+ const world = (b) => { const v = new THREE.Vector3(); H.getRawBoneNode(b).getWorldPosition(v); return v }
+ const q = (b) => { const r = new THREE.Quaternion(); H.getRawBoneNode(b).getWorldQuaternion(r); return r }
+ set({})
+ const rest = q('head'), turned = (v) => new THREE.Vector3(...v).applyQuaternion(q('head').multiply(rest.clone().invert()))
+ const out = { spec: vrm.meta.metaVersion, hand: world('leftHand').y - world('leftUpperArm').y, terms: p.model.meta }
+ set({ angleX: 20 }); out.yaw = turned([0, 0, 1]).x
+ set({ angleY: 20 }); out.pitch = turned([0, 0, 1]).y
+ set({ angleZ: 20 }); out.roll = turned([0, 1, 0]).x
+ set({ eyeBallY: 1 }); out.up = em.getValue('lookUp'); out.down = em.getValue('lookDown')
+ set({ eyeBallX: 1 }); out.right = em.getValue('lookLeft') // the character's left, seen from the front
+ p.dispose(); c.remove()
+ return out
+ }
+
window.runBodies = async () => {
const out = {}
try {
diff --git a/test/smoke.html b/test/smoke.html
index db94e7e..9db659c 100644
--- a/test/smoke.html
+++ b/test/smoke.html
@@ -118,6 +118,10 @@
packaged.push({ id: p, changed: changed(a.d, b.d), keys: [a.keys, b.keys] })
}
+ // a VRM handed to a Player: refused, saying where it belongs
+ const vrmHere = await player.load(new File([await (await fetch('/__tiny.vrm')).blob()], 'x.vrm')).then(() => 'loaded', (e) => e.message)
+ const vrmFolder = await player.load(new Map([['a/x.vrm', new Blob(['x'])]])).then(() => 'loaded', (e) => e.message)
+
// a newer format: refused, and the model before stays
let newer
try {
@@ -142,7 +146,7 @@
} catch (e) {
legacy = { error: String(e.message || e) }
}
- return { out, fromFiles, newer, legacy, packaged }
+ return { out, fromFiles, newer, legacy, packaged, vrmHere, vrmFolder }
}
/** disposing while something runs: a load rejects and leaves nothing on the GPU or the canvas; a driver added to a
diff --git a/test/smoke.mjs b/test/smoke.mjs
index a563b41..45f1850 100644
--- a/test/smoke.mjs
+++ b/test/smoke.mjs
@@ -53,6 +53,8 @@ const server = createServer((req, res) => {
return
}
if (req.url === '/__tiny.vrm') { res.writeHead(200, { 'content-type': 'model/gltf-binary' }).end(vrm); return }
+ const spoiled = req.url.match(/^\/__tiny\/([^/]+)\.vrm$/)
+ if (spoiled) { res.writeHead(200, { 'content-type': 'model/gltf-binary' }).end(tinyVrm(JSON.parse(decodeURIComponent(spoiled[1])))); return }
if (req.url === '/__bomb.png') { res.writeHead(200, { 'content-type': 'image/png' }).end(bomb); return }
const p = normalize(decodeURIComponent(new URL(req.url, 'http://x').pathname)).replace(/^([/\\])+/, '')
const f = join(root, p)
@@ -70,7 +72,10 @@ try {
page.on('pageerror', (e) => errors.push(e.message))
await page.goto(`http://127.0.0.1:${server.address().port}/test/smoke.html`)
await page.waitForFunction(() => typeof window.run === 'function')
- const { out, fromFiles, newer, legacy, packaged } = await page.evaluate((a) => window.run(a), { ids, files })
+ const { out, fromFiles, newer, legacy, packaged, vrmHere, vrmFolder } = await page.evaluate((a) => window.run(a), { ids, files })
+ const vrmHereOk = /BodyPlayer/.test(vrmHere) && /BodyPlayer/.test(vrmFolder)
+ if (!vrmHereOk) failed++
+ console.log(`${vrmHereOk ? 'ok ' : 'FAIL'} a VRM handed to a Player: ${vrmHere}`)
for (const r of out) {
// the featured characters carry the LivLiv mark in the corner only: the player must draw it there and nowhere else
const ok = !r.error && r.share > 0.05 && r.glError === 0 && r.watermark === 'LivLiv' && r.mark > 0.001 && r.outside < 0.0003 && r.noise < 0.0005
@@ -129,9 +134,35 @@ try {
if (!pngOk) failed++
console.log(`${pngOk ? 'ok ' : 'FAIL'} PNGTuber: ${png.error ?? `pictures ${['closed', 'open', 'blink', 'blinkOpen'].map((k) => png.shown[k].join(',')).join(' / ')}, face tracked ${png.tracked} (turn ${png.angle.toFixed(2)}°), speech opens the mouth to ${png.mouth.toFixed(2)}`}`)
const vrmOk = !v.error && v.format === 'vrm' && v.share > 0.02 && v.happy && v.smile && !v.unknown && v.tracked && v.head
- && ['Smile', 'Happy', 'Sad'].every((l) => v.expressions.includes(l))
+ && ['Smile', 'Happy', 'Sad', 'Surprised', 'Wink'].every((l) => v.expressions.includes(l))
if (!vrmOk) failed++
console.log(`${vrmOk ? 'ok ' : 'FAIL'} VRM: ${v.error ?? `${v.name}, ${v.expressions.join(' / ')}, covers ${(v.share * 100).toFixed(1)} %, face tracked ${v.tracked}`}`)
+ for (const spec of [1, 0]) {
+ const u = encodeURIComponent(JSON.stringify({ spec }))
+ const r = await page.evaluate((url) => window.runVrmPose(url), `/__tiny/${u}.vrm`)
+ const ok = String(r.spec) === String(spec) && r.hand < -0.1 && r.yaw > 0.1 && r.pitch > 0.1 && r.roll > 0.1 && r.up > 0.05 && r.down === 0 && r.right > 0.05
+ && r.terms.spec === String(spec) && r.terms.author.name === 'LivLiv Player tests' && r.terms.use === 'everyone' && r.terms.commercial === (spec ? 'personal non-profit' : 'allow') && r.terms.license
+ if (!ok) failed++
+ console.log(`${ok ? 'ok ' : 'FAIL'} VRM ${spec === 0 ? '0.x' : '1.0'} stands and moves: hand ${r.hand.toFixed(2)} below the shoulder, turn ${r.yaw.toFixed(2)}, nod ${r.pitch.toFixed(2)}, roll ${r.roll.toFixed(2)}, gaze up ${r.up.toFixed(2)} down ${r.down.toFixed(2)} right ${r.right.toFixed(2)}; terms ${r.terms.author.name}, ${r.terms.commercial}`)
+ }
+ // files a VRM player refuses, saying why; one naming an outside file must not make the page ask for it
+ const tiny = (o) => `/__tiny/${encodeURIComponent(JSON.stringify(o))}.vrm`
+ let outsideAsked = 0
+ page.on('request', (r) => { if (new URL(r.url()).pathname === '/__outside.png') outsideAsked++ })
+ const no = await page.evaluate((urls) => window.runVrmRefusals(urls), { noMesh: tiny({ noMesh: true }), draco: tiny({ draco: true }), bigImage: tiny({ bigImage: true }),
+ outside: tiny({ outsideImage: `http://127.0.0.1:${server.address().port}/__outside.png` }) })
+ const noOk = /no mesh/.test(no.noMesh) && /Draco/.test(no.draco) && /too large/.test(no.bigImage) && /outside itself/.test(no.outside) && outsideAsked === 0 && /not a VRM/.test(no.plainFile) && no.kept === 'Tiny'
+ if (!noOk) failed++
+ console.log(`${noOk ? 'ok ' : 'FAIL'} VRM files refused, the character before kept (${no.kept}), outside requests ${outsideAsked}: ${[no.noMesh, no.draco, no.bigImage, no.outside, no.plainFile].map((m) => m.replace(/^LivLiv: \S+ /, '').slice(0, 34)).join(' | ')}`)
+
+ // in any units: a character 100 times too big, or a tenth of the size, still fills the frame
+ for (const unit of [100, 0.1]) {
+ const u = encodeURIComponent(JSON.stringify({ unit }))
+ const share = await page.evaluate((url) => window.runVrmShare(url), `/__tiny/${u}.vrm`)
+ const ok = share > 0.1
+ if (!ok) failed++
+ console.log(`${ok ? 'ok ' : 'FAIL'} VRM in units of ${unit}: covers ${(share * 100).toFixed(1)} % of the canvas`)
+ }
const pfOk = /needs at least/.test(pngFailed?.refused) && pngFailed.kept === 'First' && is(pngFailed.pixel, [255, 0, 0]) && /own/.test(pngOnGl)
if (!pfOk) failed++
console.log(`${pfOk ? 'ok ' : 'FAIL'} PNGTuber, a failed load: ${pngFailed?.refused} (kept ${pngFailed?.kept}, pixel ${pngFailed?.pixel}); on a WebGL canvas: ${pngOnGl}`)
diff --git a/test/tiny-vrm.mjs b/test/tiny-vrm.mjs
index a03950d..5dace5e 100644
--- a/test/tiny-vrm.mjs
+++ b/test/tiny-vrm.mjs
@@ -1,7 +1,12 @@
// A tiny VRM 1.0 for the tests, made here so the repository needs no one else's model: a humanoid skeleton (the bones
// VRM requires, plus neck and chest), a box for the head and one for the body, and the expressions the player sets
-// (happy, sad, aa, ee, ou, blinkLeft, blinkRight; no morphs behind them). Returns the .vrm (GLB) bytes.
-export function tinyVrm() {
+// (happy, sad, aa, ee, ou, blinkLeft, blinkRight; no morphs behind them), and looking done by expressions. Returns the
+// .vrm (GLB) bytes. spec 0 writes it as VRM 0.x, mirrored as those files are (facing -Z, the left arm at -X). unit scales
+// every length, as an exporter's unit setting can. A file can be spoiled for the tests of what the player refuses:
+// noMesh (a skeleton alone), draco (says it is compressed), outsideImage (a picture by URL), bigImage (a PNG header
+// claiming 9000 x 9000 px)
+export function tinyVrm({ spec = 1, unit = 1, noMesh = false, draco = false, outsideImage = '', bigImage = false } = {}) {
+ const mirror = spec === 0 ? -1 : 1
// [bone, parent, translation]
const bones = [
['hips', -1, [0, 1, 0]], ['spine', 'hips', [0, 0.12, 0]], ['chest', 'spine', [0, 0.15, 0]], ['neck', 'chest', [0, 0.22, 0]],
@@ -12,28 +17,56 @@ export function tinyVrm() {
['rightUpperLeg', 'hips', [-0.09, -0.05, 0]], ['rightLowerLeg', 'rightUpperLeg', [0, -0.42, 0]], ['rightFoot', 'rightLowerLeg', [0, -0.42, 0]],
]
const index = Object.fromEntries(bones.map(([n], i) => [n, i]))
- const nodes = bones.map(([name, , t]) => ({ name, translation: t, children: [] }))
+ const nodes = bones.map(([name, , t]) => ({ name, translation: [t[0] * mirror * unit, t[1] * unit, t[2] * unit], children: [] }))
bones.forEach(([n, p]) => { if (p !== -1) nodes[index[p]].children.push(index[n]) })
// the boxes: the head's on the head bone, the body's (scaled) on the chest
- nodes.push({ name: 'headBox', mesh: 0, translation: [0, 0.1, 0], scale: [0.2, 0.22, 0.2] })
- nodes.push({ name: 'bodyBox', mesh: 1, translation: [0, -0.05, 0], scale: [0.36, 0.5, 0.2] })
- nodes[index.head].children.push(nodes.length - 2)
- nodes[index.chest].children.push(nodes.length - 1)
+ if (!noMesh) {
+ nodes.push({ name: 'headBox', mesh: 0, translation: [0, 0.1 * unit, 0], scale: [0.2 * unit, 0.22 * unit, 0.2 * unit] })
+ nodes.push({ name: 'bodyBox', mesh: 1, translation: [0, -0.05 * unit, 0], scale: [0.36 * unit, 0.5 * unit, 0.2 * unit] })
+ nodes[index.head].children.push(nodes.length - 2)
+ nodes[index.chest].children.push(nodes.length - 1)
+ }
for (const n of nodes) if (!n.children?.length) delete n.children
// a unit box: 8 corners, 12 triangles
const P = new Float32Array([-.5, -.5, -.5, .5, -.5, -.5, .5, .5, -.5, -.5, .5, -.5, -.5, -.5, .5, .5, -.5, .5, .5, .5, .5, -.5, .5, .5])
const I = new Uint16Array([0, 2, 1, 0, 3, 2, 4, 5, 6, 4, 6, 7, 0, 1, 5, 0, 5, 4, 3, 7, 6, 3, 6, 2, 0, 4, 7, 0, 7, 3, 1, 2, 6, 1, 6, 5])
- const bin = new Uint8Array(P.byteLength + I.byteLength + ((4 - (I.byteLength % 4)) % 4))
+ // a PNG's first bytes, claiming a picture far too big (the player reads the size, never decodes it)
+ const pngHead = new Uint8Array(24)
+ pngHead.set([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0, 0, 0, 13, 0x49, 0x48, 0x44, 0x52])
+ new DataView(pngHead.buffer).setUint32(16, 9000); new DataView(pngHead.buffer).setUint32(20, 9000)
+ const pad = (4 - (I.byteLength % 4)) % 4
+ const bin = new Uint8Array(P.byteLength + I.byteLength + pad + (bigImage ? pngHead.length : 0))
bin.set(new Uint8Array(P.buffer), 0)
bin.set(new Uint8Array(I.buffer), P.byteLength)
+ if (bigImage) bin.set(pngHead, P.byteLength + I.byteLength + pad)
const prim = (material) => ({ attributes: { POSITION: 0 }, indices: 1, material })
const empty = {}
+ const range = { inputMaxValue: 90, outputScale: 1 }
+ const lookAt = { type: 'expression', rangeMapHorizontalInner: range, rangeMapHorizontalOuter: range, rangeMapVerticalDown: range, rangeMapVerticalUp: range }
+ const curve = { curve: [0, 0, 0, 1, 1, 1, 1, 0], xRange: 90, yRange: 1 }
+ const VRM0 = {
+ exporterVersion: 'LivLiv Player tests', specVersion: '0.0',
+ meta: { title: 'Tiny 0', author: 'LivLiv Player tests', allowedUserName: 'Everyone', violentUssageName: 'Disallow', sexualUssageName: 'Disallow', commercialUssageName: 'Allow', licenseName: 'CC0' },
+ humanoid: { humanBones: bones.map(([bone]) => ({ bone, node: index[bone] })) },
+ firstPerson: { lookAtTypeName: 'BlendShape', lookAtHorizontalInner: curve, lookAtHorizontalOuter: curve, lookAtVerticalDown: curve, lookAtVerticalUp: curve },
+ blendShapeMaster: { blendShapeGroups: [['joy', 'Joy'], ['sorrow', 'Sorrow'], ['a', 'A'], ['e', 'E'], ['u', 'U'], ['blink', 'Blink'], ['lookup', 'LookUp'], ['lookdown', 'LookDown'], ['lookleft', 'LookLeft'], ['lookright', 'LookRight']].map(([presetName, name]) => ({ name, presetName, binds: [] })) },
+ }
+ const VRM1 = {
+ specVersion: '1.0',
+ meta: { name: 'Tiny', version: '1', authors: ['LivLiv Player tests'], licenseUrl: 'https://vrm.dev/licenses/1.0/', avatarPermission: 'everyone', commercialUsage: 'personalNonProfit' },
+ humanoid: { humanBones: Object.fromEntries(bones.map(([n]) => [n, { node: index[n] }])) },
+ lookAt,
+ expressions: { preset: { happy: empty, sad: empty, aa: empty, ee: empty, ou: empty, blinkLeft: empty, blinkRight: empty, lookUp: empty, lookDown: empty, lookLeft: empty, lookRight: empty }, custom: { Surprised: empty, Wink: empty } },
+ }
+ const compressed = draco ? ['KHR_draco_mesh_compression'] : []
const json = {
asset: { version: '2.0', generator: 'LivLiv Player tests' },
- extensionsUsed: ['VRMC_vrm'],
+ extensionsUsed: [spec === 0 ? 'VRM' : 'VRMC_vrm', ...compressed],
+ ...(compressed.length ? { extensionsRequired: compressed } : {}),
+ ...(outsideImage ? { images: [{ uri: outsideImage }] } : bigImage ? { images: [{ bufferView: 2, mimeType: 'image/png' }] } : {}),
scene: 0, scenes: [{ nodes: [index.hips] }], nodes,
- meshes: [{ primitives: [prim(0)] }, { primitives: [prim(1)] }],
+ ...(noMesh ? {} : { meshes: [{ primitives: [prim(0)] }, { primitives: [prim(1)] }] }),
materials: [
{ pbrMetallicRoughness: { baseColorFactor: [1, 0.82, 0.74, 1], metallicFactor: 0, roughnessFactor: 1 } },
{ pbrMetallicRoughness: { baseColorFactor: [0.3, 0.45, 0.9, 1], metallicFactor: 0, roughnessFactor: 1 } },
@@ -42,19 +75,13 @@ export function tinyVrm() {
bufferViews: [
{ buffer: 0, byteOffset: 0, byteLength: P.byteLength, target: 34962 },
{ buffer: 0, byteOffset: P.byteLength, byteLength: I.byteLength, target: 34963 },
+ ...(bigImage ? [{ buffer: 0, byteOffset: P.byteLength + I.byteLength + pad, byteLength: pngHead.length }] : []),
],
accessors: [
{ bufferView: 0, componentType: 5126, count: 8, type: 'VEC3', min: [-0.5, -0.5, -0.5], max: [0.5, 0.5, 0.5] },
{ bufferView: 1, componentType: 5123, count: I.length, type: 'SCALAR' },
],
- extensions: {
- VRMC_vrm: {
- specVersion: '1.0',
- meta: { name: 'Tiny', version: '1', authors: ['LivLiv Player tests'], licenseUrl: 'https://vrm.dev/licenses/1.0/', avatarPermission: 'everyone', commercialUsage: 'corporation' },
- humanoid: { humanBones: Object.fromEntries(bones.map(([n]) => [n, { node: index[n] }])) },
- expressions: { preset: { happy: empty, sad: empty, aa: empty, ee: empty, ou: empty, blinkLeft: empty, blinkRight: empty } },
- },
- },
+ extensions: spec === 0 ? { VRM: VRM0 } : { VRMC_vrm: VRM1 },
}
const text = new TextEncoder().encode(JSON.stringify(json))
const jlen = text.length + ((4 - (text.length % 4)) % 4)