mirror of
https://github.com/bilawalsidhu/gods-eye-view.git
synced 2026-11-18 09:12:18 +00:00
Sprites for helicopters, ground vehicles, stations and vessel types; history to live without an empty map; model parts in Cesium
Aircraft icons are one size; helicopters turn a three-frame rotor while airborne or moving; ADS-B ground vehicles share one amber sprite and stations/obstacles one mast; vessels get hull sprites by type and one buoy. Going live keeps contacts until the first live answer and replaces them by id; fast playback holds before the loaded positions end and prefetches ahead. Cesium models move their parts from the optional model part state.
This commit is contained in:
1 parent
624c229bc2
commit
7186f720df
97 files changed
+6586
-343
No files matched your search
@@ -5312,10 +5312,14 @@ export function createCesiumDraw({
|
||||
replaceHost,
|
||||
horizonNow,
|
||||
requestRender,
|
||||
parts: capabilities.has('modelParts'),
|
||||
now,
|
||||
});
|
||||
const buildModels = (record) => modelSets.build(record);
|
||||
// Whether shapes pulsed in the last frame, which draws on in the next.
|
||||
let pulsing = false;
|
||||
// Whether a shown model's parts spun in the last frame, likewise.
|
||||
let spinning = false;
|
||||
const lineWidth = (px) =>
|
||||
typeof scene.clampLineWidth === 'function'
|
||||
? scene.clampLineWidth(px)
|
||||
@@ -5452,7 +5456,7 @@ export function createCesiumDraw({
|
||||
turnInertial(record);
|
||||
record.drapeInertial?.();
|
||||
}
|
||||
modelSets.beforeRender(sets.values());
|
||||
spinning = modelSets.beforeRender(sets.values());
|
||||
quadSets.beforeRender(sets.values());
|
||||
},
|
||||
/** Each frame, after it drew: clamp state, and ground swaps. */
|
||||
@@ -5483,7 +5487,8 @@ export function createCesiumDraw({
|
||||
// Rows moving on a live clock, and flowing lines, draw on in the
|
||||
// frames that follow.
|
||||
const playing = quadSets.afterRender(sets.values());
|
||||
if (anySet(animating) || flowing() || pulsing || playing) requestRender();
|
||||
if (anySet(animating) || flowing() || pulsing || spinning || playing)
|
||||
requestRender();
|
||||
},
|
||||
/**
|
||||
* Let go of the sets; with `removeHosts`, take what they draw out of
|
||||
@@ -5494,6 +5499,8 @@ export function createCesiumDraw({
|
||||
clampListeners.clear();
|
||||
// Fields go with the port, and their frame listeners with them.
|
||||
fieldPart.dispose();
|
||||
// Part shaders and their textures go with it too.
|
||||
modelSets.dispose();
|
||||
// Late model loads find no host and destroy themselves.
|
||||
for (const record of sets.values()) {
|
||||
if (removeHosts && !scene.isDestroyed?.()) {
|
||||
@@ -5538,7 +5545,7 @@ provideUnboundDraw((viewer) => {
|
||||
const part = createCesiumDraw({
|
||||
scene,
|
||||
report: uncaught,
|
||||
capabilities: new Set([...GPU_ICON_CAPABILITIES, 'fields']),
|
||||
capabilities: new Set([...GPU_ICON_CAPABILITIES, 'fields', 'modelParts']),
|
||||
});
|
||||
unboundParts.set(part.port, part);
|
||||
const offs = [
|
||||
|
||||
@@ -26,6 +26,20 @@
|
||||
* `shading: 'thermal'` draws the model unlit and white-hot (its texture
|
||||
* left out), then tinted as asked: a hot target, as the thermal views draw
|
||||
* them. Heights are absolute: models clamp nothing.
|
||||
*
|
||||
* An item's `parts` (with `modelParts`) poses the moving parts of a model
|
||||
* whose mesh carries `_PART` and whose root node carries a part table
|
||||
* (`render/modelParts.js`): its model then draws with a custom shader of
|
||||
* its own whose vertex stage moves each vertex by its part's matrix, read
|
||||
* from a small float texture (`PARTS_VERTEX` says its layout), with the
|
||||
* item's mask, unlit or thermal look in the same shader; a moved part's
|
||||
* material normal turns with it. The texture is written again in place
|
||||
* when the part state changes, and each frame while a part of a model in
|
||||
* view spins (frames are asked for while one does). Spins keep their angle
|
||||
* across a change of rate. A model at rest, or without a part table, draws
|
||||
* exactly as it would without `parts`, on the shared shaders above. Cesium
|
||||
* culls and picks a model by its bounds as its file draws it, so a part
|
||||
* moved outside them is drawn only while those bounds are in view.
|
||||
*/
|
||||
import * as Cesium from 'cesium';
|
||||
import {
|
||||
@@ -34,6 +48,15 @@ import {
|
||||
recedeParams,
|
||||
recededAlpha,
|
||||
} from '../recession.js';
|
||||
import { customShaderTexture } from './internals.js';
|
||||
import {
|
||||
glbJson,
|
||||
gltfMeshMatrix,
|
||||
gltfPartTable,
|
||||
partMatrices,
|
||||
PART_HIGHLIGHT,
|
||||
asksHighlight,
|
||||
} from '../modelParts.js';
|
||||
|
||||
const BLEND_MODES = {
|
||||
highlight: Cesium.ColorBlendMode.HIGHLIGHT,
|
||||
@@ -144,6 +167,366 @@ void fragmentMain(FragmentInput fsInput, inout czm_modelMaterial material) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
/** The colour a part with `highlight: true` is drawn in. */
|
||||
const PART_HIGHLIGHT_COLOR = '#ffc400';
|
||||
|
||||
/** How much of a highlighted part's colour the highlight replaces. */
|
||||
const PART_HIGHLIGHT_MIX = 0.6;
|
||||
|
||||
/** Texels in a part's row of its texture. */
|
||||
const PART_TEXELS = 8;
|
||||
/** Floats in a part's row: `PART_TEXELS` RGBA texels. */
|
||||
const PART_FLOATS = PART_TEXELS * 4;
|
||||
|
||||
/** A texel's centre across a part's row, as a texture coordinate. */
|
||||
const texelAt = (i) => ((i + 0.5) / PART_TEXELS).toFixed(4);
|
||||
|
||||
/**
|
||||
* The vertex stage of a posed model. A part's row of the texture holds the
|
||||
* three rows of its matrix in the mesh's own frame (texels 0..2), the three
|
||||
* rows of that matrix's inverse transpose (3..5; texel 3's alpha is 1 where
|
||||
* the part is moved, 0 where it is at rest), and its highlight colour (6,
|
||||
* alpha 0 for none). Each vertex is moved by its part's matrix; the normal
|
||||
* turn is passed on in eye space, for the fragment stage to turn the
|
||||
* material's own normal (normal maps and back-face flips kept) by it.
|
||||
* Positions are the mesh's own (before its node's transform), as are the
|
||||
* matrices written for it, and as `czm_normal` takes them to eye space.
|
||||
*/
|
||||
const PARTS_VERTEX = `
|
||||
void vertexMain(VertexInput vsInput, inout czm_modelVertexOutput vsOutput) {
|
||||
float row = (floor(vsInput.attributes.part + 0.5) + 0.5) / u_partRows;
|
||||
vec4 r0 = texture(u_partMatrices, vec2(${texelAt(0)}, row));
|
||||
vec4 r1 = texture(u_partMatrices, vec2(${texelAt(1)}, row));
|
||||
vec4 r2 = texture(u_partMatrices, vec2(${texelAt(2)}, row));
|
||||
vec4 n0 = texture(u_partMatrices, vec2(${texelAt(3)}, row));
|
||||
v_partHighlight = texture(u_partMatrices, vec2(${texelAt(6)}, row));
|
||||
vec4 p = vec4(vsOutput.positionMC, 1.0);
|
||||
vsOutput.positionMC = vec3(dot(r0, p), dot(r1, p), dot(r2, p));
|
||||
v_partMoved = n0.a;
|
||||
if (n0.a > 0.5) {
|
||||
vec4 n1 = texture(u_partMatrices, vec2(${texelAt(4)}, row));
|
||||
vec4 n2 = texture(u_partMatrices, vec2(${texelAt(5)}, row));
|
||||
mat3 turn = transpose(mat3(n0.xyz, n1.xyz, n2.xyz));
|
||||
v_partNormalEC = czm_normal * turn * inverse(czm_normal);
|
||||
} else {
|
||||
v_partNormalEC = mat3(1.0);
|
||||
}
|
||||
}`;
|
||||
|
||||
/**
|
||||
* A posed model's custom shader: its parts moved (`PARTS_VERTEX`), drawn in
|
||||
* `shading` with `mask` painted where `_TINT` marks the model (not under
|
||||
* `thermal`), and its highlighted parts in their colour. Lit, a moved
|
||||
* part's material normal is turned with it; the body and parts at rest keep
|
||||
* theirs as the material made them. `data` is the part texture's first
|
||||
* contents, `rows` its parts.
|
||||
*/
|
||||
function partShaderOf(shading, mask, data, rows) {
|
||||
const lit = shading !== 'unlit' && shading !== 'thermal';
|
||||
const masked = Boolean(mask) && shading !== 'thermal';
|
||||
return new Cesium.CustomShader({
|
||||
mode: Cesium.CustomShaderMode.MODIFY_MATERIAL,
|
||||
...(lit ? {} : { lightingModel: Cesium.LightingModel.UNLIT }),
|
||||
uniforms: {
|
||||
u_partMatrices: {
|
||||
type: Cesium.UniformType.SAMPLER_2D,
|
||||
value: partTexture(data, rows),
|
||||
},
|
||||
u_partRows: { type: Cesium.UniformType.FLOAT, value: rows },
|
||||
...(masked
|
||||
? {
|
||||
u_maskColor: {
|
||||
type: Cesium.UniformType.VEC3,
|
||||
value: new Cesium.Cartesian3(mask.red, mask.green, mask.blue),
|
||||
},
|
||||
}
|
||||
: {}),
|
||||
},
|
||||
varyings: {
|
||||
v_partNormalEC: Cesium.VaryingType.MAT3,
|
||||
v_partMoved: Cesium.VaryingType.FLOAT,
|
||||
v_partHighlight: Cesium.VaryingType.VEC4,
|
||||
},
|
||||
vertexShaderText: PARTS_VERTEX,
|
||||
fragmentShaderText: `
|
||||
void fragmentMain(FragmentInput fsInput, inout czm_modelMaterial material) {
|
||||
${
|
||||
lit
|
||||
? ` if (v_partMoved > 0.5)
|
||||
material.normalEC = normalize(v_partNormalEC * material.normalEC);`
|
||||
: ''
|
||||
}
|
||||
${shading === 'thermal' ? ' material.diffuse = vec3(1.0);' : ''}
|
||||
${
|
||||
masked
|
||||
? ` vec3 mask = czm_srgbToLinear(u_maskColor);
|
||||
material.diffuse *= mix(vec3(1.0), mask, fsInput.attributes.tint);`
|
||||
: ''
|
||||
}
|
||||
if (v_partHighlight.a > 0.0) {
|
||||
vec3 highlight = czm_srgbToLinear(v_partHighlight.rgb);
|
||||
material.diffuse = mix(material.diffuse, highlight, ${PART_HIGHLIGHT_MIX.toFixed(2)});
|
||||
material.emissive = max(material.emissive, highlight * 0.5);
|
||||
}
|
||||
}`,
|
||||
});
|
||||
}
|
||||
|
||||
/** A part texture's contents as a texture uniform: `PART_TEXELS` float texels a row, read unfiltered. */
|
||||
function partTexture(data, rows) {
|
||||
return new Cesium.TextureUniform({
|
||||
typedArray: data,
|
||||
width: PART_TEXELS,
|
||||
height: rows,
|
||||
pixelFormat: Cesium.PixelFormat.RGBA,
|
||||
pixelDatatype: Cesium.PixelDatatype.FLOAT,
|
||||
repeat: false,
|
||||
minificationFilter: Cesium.TextureMinificationFilter.NEAREST,
|
||||
magnificationFilter: Cesium.TextureMagnificationFilter.NEAREST,
|
||||
});
|
||||
}
|
||||
|
||||
/** An affine column-major 4×4's inverse. */
|
||||
function inverseAffine(m) {
|
||||
const [a, b, c] = [m[0], m[1], m[2]];
|
||||
const [d, e, f] = [m[4], m[5], m[6]];
|
||||
const [g, h, i] = [m[8], m[9], m[10]];
|
||||
const A = e * i - f * h;
|
||||
const B = -(b * i - c * h);
|
||||
const C = b * f - c * e;
|
||||
const det = a * A + d * B + g * C;
|
||||
if (!(Math.abs(det) > 1e-30)) return null;
|
||||
const r = 1 / det;
|
||||
const out = [
|
||||
A * r,
|
||||
B * r,
|
||||
C * r,
|
||||
0,
|
||||
-(d * i - f * g) * r,
|
||||
(a * i - c * g) * r,
|
||||
-(a * f - c * d) * r,
|
||||
0,
|
||||
(d * h - e * g) * r,
|
||||
-(a * h - b * g) * r,
|
||||
(a * e - b * d) * r,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
1,
|
||||
];
|
||||
for (let row = 0; row < 3; row++)
|
||||
out[12 + row] = -(
|
||||
out[row] * m[12] +
|
||||
out[4 + row] * m[13] +
|
||||
out[8 + row] * m[14]
|
||||
);
|
||||
return out;
|
||||
}
|
||||
|
||||
/** What a glTF document (or GLB) says of its parts: its table and mesh frame; null without a table. */
|
||||
const partInfos = new WeakMap();
|
||||
|
||||
/** `source`'s part table and mesh frame, read once; null for a model without moving parts. */
|
||||
function partInfoOf(source) {
|
||||
if (partInfos.has(source)) return partInfos.get(source);
|
||||
let info = null;
|
||||
try {
|
||||
const json = source instanceof Uint8Array ? glbJson(source) : source;
|
||||
const table = gltfPartTable(json);
|
||||
const mesh = table && gltfMeshMatrix(json);
|
||||
const meshInverse = mesh && inverseAffine(mesh);
|
||||
if (table && table.parts.length > 1 && meshInverse)
|
||||
info = { table, mesh, meshInverse };
|
||||
} catch {
|
||||
// A malformed table: the model draws whole.
|
||||
info = null;
|
||||
}
|
||||
partInfos.set(source, info);
|
||||
return info;
|
||||
}
|
||||
|
||||
/** Whether a part state asks for anything. */
|
||||
const asksParts = (state) =>
|
||||
Boolean(state) &&
|
||||
typeof state === 'object' &&
|
||||
['spin', 'deploy', 'poses'].some(
|
||||
(key) => state[key] && Object.keys(state[key]).length > 0,
|
||||
);
|
||||
|
||||
/** Scratch for one model's part matrices and flags, and one matrix's rows. */
|
||||
let scratchParts = new Float64Array(16 * 32);
|
||||
let scratchFlags = new Uint8Array(32);
|
||||
const scratchRow = new Float64Array(4);
|
||||
const scratchL = new Float64Array(12);
|
||||
|
||||
/** How far from the identity a part's matrix may be and still be at rest. */
|
||||
const AT_REST_EPSILON = 1e-9;
|
||||
|
||||
/** Highlight colours by what was asked, read once (a few at most). */
|
||||
const highlightColors = new Map();
|
||||
|
||||
/**
|
||||
* The colour a part's `highlight` asks for, read once: `true` the
|
||||
* renderer's own, a colour that parses as itself; null for anything else
|
||||
* (drawn without a highlight).
|
||||
*/
|
||||
export function partHighlightColor(value) {
|
||||
if (!asksHighlight(value)) return null;
|
||||
const key = value === true ? PART_HIGHLIGHT_COLOR : String(value);
|
||||
let color = highlightColors.get(key);
|
||||
if (color === undefined) {
|
||||
if (value === true || typeof value === 'string')
|
||||
color = Cesium.Color.fromCssColorString(key.trim()) ?? null;
|
||||
else color = new Cesium.Color(value[0], value[1], value[2], 1);
|
||||
if (highlightColors.size >= 256) highlightColors.clear();
|
||||
highlightColors.set(key, color);
|
||||
}
|
||||
return color;
|
||||
}
|
||||
|
||||
/**
|
||||
* Write a model's part texture into `data` (`PART_FLOATS` a part, the
|
||||
* layout `PARTS_VERTEX` reads) for `state` at `timeS`: for each part the
|
||||
* rows of its matrix in the mesh's own frame, L = meshInverse · X · mesh,
|
||||
* then the rows of L's inverse transpose (normals turn by it, exact under a
|
||||
* stretch or a mesh frame that is not a rotation) with whether the part is
|
||||
* moved, then its highlight colour. Whether any part is not at rest.
|
||||
*/
|
||||
export function writePartTexture(info, state, timeS, scale, data) {
|
||||
const { table, mesh, meshInverse } = info;
|
||||
const n = table.parts.length;
|
||||
if (scratchParts.length < n * 16) {
|
||||
scratchParts = new Float64Array(n * 16);
|
||||
scratchFlags = new Uint8Array(n);
|
||||
}
|
||||
const posed = partMatrices(table, state, timeS, scratchParts, {
|
||||
flags: scratchFlags,
|
||||
scale,
|
||||
});
|
||||
const poses = state?.poses;
|
||||
const x = scratchParts;
|
||||
const ix = scratchRow;
|
||||
const L = scratchL;
|
||||
for (let k = 0; k < n; k++) {
|
||||
const o = k * 16;
|
||||
const d = k * PART_FLOATS;
|
||||
let moved = false;
|
||||
for (let row = 0; row < 3; row++) {
|
||||
// (meshInverse · X) row `row`, as four column entries.
|
||||
for (let col = 0; col < 4; col++) {
|
||||
let sum = 0;
|
||||
for (let j = 0; j < 4; j++)
|
||||
sum += meshInverse[j * 4 + row] * x[o + col * 4 + j];
|
||||
ix[col] = sum;
|
||||
}
|
||||
for (let col = 0; col < 4; col++) {
|
||||
let sum = 0;
|
||||
for (let j = 0; j < 4; j++) sum += ix[j] * mesh[col * 4 + j];
|
||||
L[row * 4 + col] = sum;
|
||||
data[d + row * 4 + col] = sum;
|
||||
if (Math.abs(sum - (row === col ? 1 : 0)) > AT_REST_EPSILON)
|
||||
moved = true;
|
||||
}
|
||||
}
|
||||
// The inverse transpose of L's 3×3: its cofactors over its determinant.
|
||||
const a = L[0];
|
||||
const b = L[1];
|
||||
const c = L[2];
|
||||
const e = L[4];
|
||||
const f = L[5];
|
||||
const g = L[6];
|
||||
const h = L[8];
|
||||
const i = L[9];
|
||||
const j = L[10];
|
||||
const c00 = f * j - g * i;
|
||||
const c01 = -(e * j - g * h);
|
||||
const c02 = e * i - f * h;
|
||||
const c10 = -(b * j - c * i);
|
||||
const c11 = a * j - c * h;
|
||||
const c12 = -(a * i - b * h);
|
||||
const c20 = b * g - c * f;
|
||||
const c21 = -(a * g - c * e);
|
||||
const c22 = a * f - b * e;
|
||||
const det = a * c00 + b * c01 + c * c02;
|
||||
const nd = d + 12;
|
||||
// At rest, or hidden (collapsed to a point): normals as they are.
|
||||
const turned = moved && Math.abs(det) > 1e-12;
|
||||
const r = turned ? 1 / det : 0;
|
||||
data[nd] = turned ? c00 * r : 1;
|
||||
data[nd + 1] = turned ? c01 * r : 0;
|
||||
data[nd + 2] = turned ? c02 * r : 0;
|
||||
data[nd + 3] = turned ? 1 : 0;
|
||||
data[nd + 4] = turned ? c10 * r : 0;
|
||||
data[nd + 5] = turned ? c11 * r : 1;
|
||||
data[nd + 6] = turned ? c12 * r : 0;
|
||||
data[nd + 7] = 0;
|
||||
data[nd + 8] = turned ? c20 * r : 0;
|
||||
data[nd + 9] = turned ? c21 * r : 0;
|
||||
data[nd + 10] = turned ? c22 * r : 1;
|
||||
data[nd + 11] = 0;
|
||||
const color =
|
||||
scratchFlags[k] & PART_HIGHLIGHT
|
||||
? partHighlightColor(poses?.[table.parts[k].name]?.highlight)
|
||||
: null;
|
||||
const hd = d + 24;
|
||||
data[hd] = color ? color.red : 0;
|
||||
data[hd + 1] = color ? color.green : 0;
|
||||
data[hd + 2] = color ? color.blue : 0;
|
||||
data[hd + 3] = color ? 1 : 0;
|
||||
}
|
||||
return posed;
|
||||
}
|
||||
|
||||
/**
|
||||
* A posed model's spins, turned on to `timeS` (seconds): each spinning
|
||||
* part's angle moves on at its rate since it last did, so a change of rate
|
||||
* never makes a part jump. A part that stops spinning keeps its angle.
|
||||
*/
|
||||
export function advanceSpins(spins, timeS) {
|
||||
const dt = timeS - spins.at;
|
||||
spins.at = timeS;
|
||||
if (!(dt > 0)) return;
|
||||
for (const [name, rate] of spins.rates)
|
||||
spins.angles[name] = (spins.angles[name] + rate * dt) % 360;
|
||||
}
|
||||
|
||||
/**
|
||||
* Spins at `state`'s rates from `timeS` on, carrying the angles reached; a
|
||||
* part starting to spin starts at an angle of `startAngle`'s (by default a
|
||||
* random one, so a fleet posed at once does not turn in step).
|
||||
*/
|
||||
export function respin(
|
||||
spins,
|
||||
table,
|
||||
state,
|
||||
timeS,
|
||||
startAngle = () => Math.random() * 360,
|
||||
) {
|
||||
advanceSpins(spins, timeS);
|
||||
spins.rates.clear();
|
||||
for (const [name, rate] of Object.entries(state?.spin ?? {})) {
|
||||
const index = table.byName.get(name);
|
||||
if (
|
||||
index === undefined ||
|
||||
!table.parts[index].axis ||
|
||||
typeof rate !== 'number' ||
|
||||
!Number.isFinite(rate) ||
|
||||
rate === 0
|
||||
)
|
||||
continue;
|
||||
spins.rates.set(name, rate);
|
||||
if (!(name in spins.angles)) spins.angles[name] = startAngle();
|
||||
}
|
||||
}
|
||||
|
||||
/** New spins: none yet, at `timeS`. */
|
||||
export const newSpins = (timeS) => ({
|
||||
rates: new Map(),
|
||||
angles: {},
|
||||
at: timeS,
|
||||
});
|
||||
|
||||
/** A contract distance curve's value at `distance`: linear, clamped. */
|
||||
export function nearFarValue(curve, distance) {
|
||||
if (!curve) return 1;
|
||||
@@ -228,8 +611,11 @@ const focusOf = (item) =>
|
||||
* The models part of a Cesium draw port.
|
||||
* @param {{scene: object, toColor: Function, pickId: Function,
|
||||
* replaceHost: Function, horizonNow: () => object|null,
|
||||
* requestRender: () => void}} options From the draw port: its colour
|
||||
* conversion, pick ids, host swap, horizon and render request.
|
||||
* requestRender: () => void, parts?: boolean,
|
||||
* now?: () => number}} options From the draw port: its colour
|
||||
* conversion, pick ids, host swap, horizon and render request; whether it
|
||||
* poses models' parts (`modelParts`), and the clock (milliseconds) spins
|
||||
* are turned by.
|
||||
*/
|
||||
export function createModelSets({
|
||||
scene,
|
||||
@@ -238,7 +624,238 @@ export function createModelSets({
|
||||
replaceHost,
|
||||
horizonNow,
|
||||
requestRender,
|
||||
parts: posesParts = false,
|
||||
now = () => performance.now(),
|
||||
}) {
|
||||
/** Each Cesium model drawn posed: its part shader, texture and spins. */
|
||||
const posings = new Map();
|
||||
/** The GLB bytes each model was built from, where it was. */
|
||||
const modelBytes = new WeakMap();
|
||||
/** Part shaders let go, destroyed once no draw uses them. */
|
||||
const retired = [];
|
||||
// Float textures carry the part matrices, and WebGL 2's shading language
|
||||
// turns the normals: without them models draw whole.
|
||||
const canPose = () =>
|
||||
scene.context?.floatingPointTexture !== false &&
|
||||
scene.context?.webgl2 !== false;
|
||||
|
||||
/** A model's part table and mesh frame, or null. */
|
||||
function partInfoOfModel(model) {
|
||||
const bytes = modelBytes.get(model);
|
||||
if (bytes) return partInfoOf(bytes);
|
||||
const json = model.loader?.gltfJson;
|
||||
return json ? partInfoOf(json) : null;
|
||||
}
|
||||
|
||||
/** Let go of a model's posing: its shader goes once no draw uses it. */
|
||||
function unpose(model) {
|
||||
const posing = posings.get(model);
|
||||
if (!posing) return;
|
||||
posings.delete(model);
|
||||
retired.push({ shader: posing.shader, frames: 0 });
|
||||
}
|
||||
|
||||
/** Write a posing's texture where its shader reads it. */
|
||||
function upload(posing) {
|
||||
const texture = customShaderTexture(posing.shader, 'u_partMatrices');
|
||||
if (
|
||||
texture &&
|
||||
!texture.isDestroyed?.() &&
|
||||
texture.width === PART_TEXELS &&
|
||||
texture.height === posing.rows
|
||||
)
|
||||
texture.copyFrom({
|
||||
source: {
|
||||
arrayBufferView: posing.data,
|
||||
width: PART_TEXELS,
|
||||
height: posing.rows,
|
||||
},
|
||||
});
|
||||
else
|
||||
posing.shader.setUniform(
|
||||
'u_partMatrices',
|
||||
partTexture(posing.data, posing.rows),
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* The state a posing's texture is written for: its item's deploys and
|
||||
* poses, its spins as the angles they have reached (written at a time of
|
||||
* 1 s, each angle given as a rate).
|
||||
*/
|
||||
function spunState(posing) {
|
||||
const drawn = posing.drawn;
|
||||
drawn.deploy = posing.state.deploy;
|
||||
drawn.poses = posing.state.poses;
|
||||
drawn.spin = posing.spins.angles;
|
||||
return drawn;
|
||||
}
|
||||
|
||||
/** Write a posing's texture for now. Whether any part is not at rest. */
|
||||
function writePosing(posing, timeS) {
|
||||
advanceSpins(posing.spins, timeS);
|
||||
return writePartTexture(
|
||||
posing.info,
|
||||
spunState(posing),
|
||||
1,
|
||||
posing.scale,
|
||||
posing.data,
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* The shader `model` draws its entry's item's `parts` with, its texture
|
||||
* written for them now; undefined when the model draws whole (no `parts`,
|
||||
* no part table, or every part at rest), its posing let go.
|
||||
*/
|
||||
function posedShader(entry, model) {
|
||||
const item = entry.item;
|
||||
const state = posesParts ? item.parts : undefined;
|
||||
const posing = posings.get(model);
|
||||
const info = asksParts(state) && canPose() ? partInfoOfModel(model) : null;
|
||||
if (!info) {
|
||||
unpose(model);
|
||||
return undefined;
|
||||
}
|
||||
const axes = item.axisScale;
|
||||
const scale =
|
||||
axes && (axes[0] !== 1 || axes[1] !== 1 || axes[2] !== 1)
|
||||
? axes
|
||||
: undefined;
|
||||
const key = JSON.stringify(state);
|
||||
const scaleKey = scale ? scale.join(',') : '';
|
||||
const shading = item.shading;
|
||||
const sameLook =
|
||||
posing?.info === info &&
|
||||
posing.shading === shading &&
|
||||
posing.mask === entry.mask;
|
||||
// A fleet re-poses every frame with the same parts: written when they
|
||||
// change (a spin turns in the frame pass).
|
||||
if (sameLook && posing.key === key && posing.scaleKey === scaleKey)
|
||||
return posing.shader;
|
||||
const timeS = now() / 1000;
|
||||
// Spins go on from where they were, whatever else changed.
|
||||
const spins = posing?.info === info ? posing.spins : newSpins(timeS);
|
||||
respin(spins, info.table, state, timeS);
|
||||
const spinning = spins.rates.size > 0;
|
||||
const rows = info.table.parts.length;
|
||||
const next = {
|
||||
info,
|
||||
shader: sameLook ? posing.shader : null,
|
||||
shading,
|
||||
mask: entry.mask,
|
||||
data: sameLook ? posing.data : new Float32Array(rows * PART_FLOATS),
|
||||
rows,
|
||||
key,
|
||||
scaleKey,
|
||||
scale,
|
||||
spinning,
|
||||
state,
|
||||
spins,
|
||||
drawn: posing?.drawn ?? {},
|
||||
};
|
||||
const posed = writePosing(next, timeS);
|
||||
if (!posed && !spinning) {
|
||||
unpose(model);
|
||||
return undefined;
|
||||
}
|
||||
if (sameLook) {
|
||||
Object.assign(posing, next);
|
||||
upload(posing);
|
||||
return posing.shader;
|
||||
}
|
||||
unpose(model);
|
||||
next.shader = partShaderOf(shading, entry.mask, next.data, rows);
|
||||
posings.set(model, next);
|
||||
return next.shader;
|
||||
}
|
||||
|
||||
/** Pixels across a model's bounds under which its spins are not turned. */
|
||||
const MIN_SPIN_PIXELS = 4;
|
||||
const scratchSpinSphere = new Cesium.BoundingSphere();
|
||||
|
||||
/**
|
||||
* Whether a model is worth turning this frame: shown, in the view, and
|
||||
* at least `MIN_SPIN_PIXELS` across.
|
||||
*/
|
||||
function seen(model, culling, width, height) {
|
||||
if (!model.show || !model.ready) return false;
|
||||
const sphere = model.boundingSphere;
|
||||
if (!sphere || !(sphere.radius > 0)) return false;
|
||||
if (
|
||||
culling &&
|
||||
culling.computeVisibility(sphere) === Cesium.Intersect.OUTSIDE
|
||||
)
|
||||
return false;
|
||||
if (!(width > 0 && height > 0)) return true;
|
||||
Cesium.BoundingSphere.clone(sphere, scratchSpinSphere);
|
||||
scratchSpinSphere.radius = 0;
|
||||
const metresPerPixel = scene.camera.getPixelSize(
|
||||
scratchSpinSphere,
|
||||
width,
|
||||
height,
|
||||
);
|
||||
return (
|
||||
!(metresPerPixel > 0) ||
|
||||
!Number.isFinite(metresPerPixel) ||
|
||||
(2 * sphere.radius) / metresPerPixel >= MIN_SPIN_PIXELS
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Before a frame: turn the spinning parts of each model in view to now,
|
||||
* sweep the posings of models gone, and destroy part shaders no draw
|
||||
* uses any more. Whether any model in view spins (frames go on being
|
||||
* asked for; one out of view or too small to see asks for none).
|
||||
*/
|
||||
function turnParts() {
|
||||
for (let i = retired.length - 1; i >= 0; i--)
|
||||
if ((retired[i].frames += 1) > 2) {
|
||||
const [{ shader }] = retired.splice(i, 1);
|
||||
shader.destroy?.();
|
||||
}
|
||||
if (!posings.size) return false;
|
||||
const timeS = now() / 1000;
|
||||
const camera = scene.camera;
|
||||
const culling =
|
||||
camera?.frustum?.computeCullingVolume && camera.positionWC
|
||||
? camera.frustum.computeCullingVolume(
|
||||
camera.positionWC,
|
||||
camera.directionWC,
|
||||
camera.upWC,
|
||||
)
|
||||
: null;
|
||||
const width = scene.drawingBufferWidth ?? scene.canvas?.width ?? 0;
|
||||
const height = scene.drawingBufferHeight ?? scene.canvas?.height ?? 0;
|
||||
let spinning = false;
|
||||
for (const [model, posing] of posings) {
|
||||
if (model.isDestroyed?.()) {
|
||||
unpose(model);
|
||||
continue;
|
||||
}
|
||||
if (!posing.spinning || !seen(model, culling, width, height)) continue;
|
||||
spinning = true;
|
||||
writePosing(posing, timeS);
|
||||
upload(posing);
|
||||
}
|
||||
return spinning;
|
||||
}
|
||||
|
||||
/**
|
||||
* Let go of every posing and part shader now, their textures with them:
|
||||
* the port is done, and no frame comes to retire them. A model still
|
||||
* drawn is left drawing whole.
|
||||
*/
|
||||
function dispose() {
|
||||
for (const [model, posing] of posings) {
|
||||
if (!model.isDestroyed?.() && model.customShader === posing.shader)
|
||||
model.customShader = undefined;
|
||||
posing.shader.destroy?.();
|
||||
}
|
||||
posings.clear();
|
||||
for (const { shader } of retired.splice(0)) shader.destroy?.();
|
||||
}
|
||||
|
||||
/** The set's host, made once: its models are changed where they are. */
|
||||
function hostOf(record) {
|
||||
if (record.host && !record.host.isDestroyed?.()) return record.host;
|
||||
@@ -337,6 +954,7 @@ export function createModelSets({
|
||||
settle(false);
|
||||
return model.destroy();
|
||||
}
|
||||
if (item.gltf) modelBytes.set(model, item.gltf);
|
||||
entry.next = model;
|
||||
entry.styled = null;
|
||||
style(record, entry, model, true);
|
||||
@@ -413,7 +1031,7 @@ export function createModelSets({
|
||||
if (model.minimumPixelSize !== minimum) model.minimumPixelSize = minimum;
|
||||
if (model.maximumScale !== item.maxScale)
|
||||
model.maximumScale = item.maxScale;
|
||||
const shader = entryShader(entry);
|
||||
const shader = posedShader(entry, model) ?? entryShader(entry);
|
||||
if (model.customShader !== shader) model.customShader = shader;
|
||||
const clip = item.clip === 'belowOrigin';
|
||||
if (Boolean(model.clippingPlanes) !== clip)
|
||||
@@ -583,10 +1201,14 @@ export function createModelSets({
|
||||
notePickIds(record);
|
||||
}
|
||||
|
||||
/** Each frame, before it draws: distance curves, pixel caps and the cull. */
|
||||
/**
|
||||
* Each frame, before it draws: distance curves, pixel caps, the cull and
|
||||
* spinning parts. Whether any shown model spins.
|
||||
*/
|
||||
function beforeRender(sets) {
|
||||
const spinning = turnParts();
|
||||
const eye = scene.camera?.positionWC;
|
||||
if (!eye) return;
|
||||
if (!eye) return spinning;
|
||||
const width = scene.drawingBufferWidth ?? scene.canvas?.width ?? 0;
|
||||
const height = scene.drawingBufferHeight ?? scene.canvas?.height ?? 0;
|
||||
let horizon;
|
||||
@@ -677,6 +1299,7 @@ export function createModelSets({
|
||||
if (m) apply(entry, m, frame, hidden);
|
||||
}
|
||||
}
|
||||
return spinning;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -701,5 +1324,5 @@ export function createModelSets({
|
||||
}
|
||||
}
|
||||
|
||||
return { build, upsert, beforeRender, restyle };
|
||||
return { build, upsert, beforeRender, restyle, dispose };
|
||||
}
|
||||
@@ -0,0 +1,180 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import test from 'node:test';
|
||||
|
||||
import {
|
||||
advanceSpins,
|
||||
newSpins,
|
||||
partHighlightColor,
|
||||
respin,
|
||||
writePartTexture,
|
||||
} from './drawModels.js';
|
||||
import { partsModelGlb } from '../conformance/partsModel.js';
|
||||
import { glbJson, gltfMeshMatrix, gltfPartTable } from '../modelParts.js';
|
||||
|
||||
/** Floats a part's row of the texture holds. */
|
||||
const ROW = 32;
|
||||
|
||||
/** The part info `drawModels.js` reads from a model's GLB. */
|
||||
function infoOf(glb) {
|
||||
const json = glbJson(glb);
|
||||
const mesh = gltfMeshMatrix(json);
|
||||
// The test models' node transforms are rotations, uniform scales and moves.
|
||||
const s = Math.hypot(mesh[0], mesh[1], mesh[2]);
|
||||
const r = (i, j) => mesh[j * 4 + i] / s;
|
||||
const t = [mesh[12], mesh[13], mesh[14]];
|
||||
const inv = new Array(16).fill(0);
|
||||
for (let i = 0; i < 3; i++)
|
||||
for (let j = 0; j < 3; j++) inv[j * 4 + i] = r(j, i) / s;
|
||||
for (let i = 0; i < 3; i++)
|
||||
inv[12 + i] = -(inv[i] * t[0] + inv[4 + i] * t[1] + inv[8 + i] * t[2]);
|
||||
inv[15] = 1;
|
||||
return { table: gltfPartTable(json), mesh, meshInverse: inv };
|
||||
}
|
||||
|
||||
const row = (data, k, texel) =>
|
||||
Array.from(data.slice(k * ROW + texel * 4, k * ROW + texel * 4 + 4));
|
||||
|
||||
/** A part's matrix in the mesh frame, as rows of 4. */
|
||||
const matrixOf = (data, k) => [0, 1, 2].map((t) => row(data, k, t));
|
||||
/** Its normal matrix, as rows of 3, and whether it is moved. */
|
||||
const normalsOf = (data, k) => ({
|
||||
rows: [3, 4, 5].map((t) => row(data, k, t).slice(0, 3)),
|
||||
moved: row(data, k, 3)[3],
|
||||
});
|
||||
|
||||
const near = (a, b, eps = 1e-5) => a.every((v, i) => Math.abs(v - b[i]) < eps);
|
||||
|
||||
test('a part moved writes its matrix in the mesh’s own frame, the rest identity', () => {
|
||||
for (const node of [{}, { scale: 4, turnDeg: 90, translation: [3, 2, -1] }]) {
|
||||
const info = infoOf(partsModelGlb(node));
|
||||
const data = new Float32Array(4 * ROW);
|
||||
const posed = writePartTexture(
|
||||
info,
|
||||
{ poses: { body: { offsetM: [15, 0, 0] } } },
|
||||
0,
|
||||
undefined,
|
||||
data,
|
||||
);
|
||||
assert.equal(posed, true);
|
||||
// The body's vertex at model (10, −10, −10) lands 15 m to its right
|
||||
// (−Z): back in the model frame through the node's transform.
|
||||
const m = info.mesh;
|
||||
const inv = info.meshInverse;
|
||||
const toMesh = (p) =>
|
||||
[0, 1, 2].map(
|
||||
(i) =>
|
||||
inv[i] * p[0] + inv[4 + i] * p[1] + inv[8 + i] * p[2] + inv[12 + i],
|
||||
);
|
||||
const toModel = (p) =>
|
||||
[0, 1, 2].map(
|
||||
(i) => m[i] * p[0] + m[4 + i] * p[1] + m[8 + i] * p[2] + m[12 + i],
|
||||
);
|
||||
const L = matrixOf(data, 0);
|
||||
const v = [...toMesh([10, -10, -10]), 1];
|
||||
const moved = toModel(L.map((r) => r.reduce((s, x, i) => s + x * v[i], 0)));
|
||||
assert.ok(near(moved, [10, -10, -25], 1e-4), JSON.stringify(moved));
|
||||
// A move turns no normal, but the part is marked moved.
|
||||
const n = normalsOf(data, 0);
|
||||
assert.equal(n.moved, 1);
|
||||
assert.ok(near(n.rows.flat(), [1, 0, 0, 0, 1, 0, 0, 0, 1]));
|
||||
}
|
||||
});
|
||||
|
||||
test('normals turn by the inverse transpose, exact under a stretch', () => {
|
||||
const info = infoOf(partsModelGlb());
|
||||
const data = new Float32Array(4 * ROW);
|
||||
writePartTexture(
|
||||
info,
|
||||
{ poses: { pod: { yawDeg: 30 } } },
|
||||
0,
|
||||
[2, 1, 1],
|
||||
data,
|
||||
);
|
||||
const L = matrixOf(data, 1).map((r) => r.slice(0, 3));
|
||||
const { rows: N, moved } = normalsOf(data, 1);
|
||||
assert.equal(moved, 1);
|
||||
// N = L⁻ᵀ: Nᵀ · L is the identity.
|
||||
for (let i = 0; i < 3; i++)
|
||||
for (let j = 0; j < 3; j++) {
|
||||
let sum = 0;
|
||||
for (let k = 0; k < 3; k++) sum += N[k][i] * L[k][j];
|
||||
assert.ok(Math.abs(sum - (i === j ? 1 : 0)) < 1e-4, `${i},${j}: ${sum}`);
|
||||
}
|
||||
// A stretched turn is not a rotation: its own 3×3 would turn normals wrong.
|
||||
assert.ok(!near(N.flat(), L.flat(), 1e-3));
|
||||
// The body, at rest, is left as it is.
|
||||
assert.equal(normalsOf(data, 0).moved, 0);
|
||||
});
|
||||
|
||||
test('a highlight that is not true or a colour draws none, and never throws', () => {
|
||||
const info = infoOf(partsModelGlb());
|
||||
const data = new Float32Array(4 * ROW);
|
||||
for (const highlight of ['', 'not a colour', 0, [1, 'x', 0], {}]) {
|
||||
writePartTexture(
|
||||
info,
|
||||
{ poses: { pod: { highlight } } },
|
||||
0,
|
||||
undefined,
|
||||
data,
|
||||
);
|
||||
assert.deepEqual(row(data, 1, 6), [0, 0, 0, 0], String(highlight));
|
||||
}
|
||||
writePartTexture(
|
||||
info,
|
||||
{ poses: { pod: { highlight: true } } },
|
||||
0,
|
||||
undefined,
|
||||
data,
|
||||
);
|
||||
assert.equal(row(data, 1, 6)[3], 1);
|
||||
writePartTexture(
|
||||
info,
|
||||
{ poses: { pod: { highlight: [0, 1, 0] } } },
|
||||
0,
|
||||
undefined,
|
||||
data,
|
||||
);
|
||||
assert.deepEqual(row(data, 1, 6), [0, 1, 0, 1]);
|
||||
assert.equal(partHighlightColor('#00f').blue, 1);
|
||||
assert.equal(partHighlightColor('nope'), null);
|
||||
assert.equal(partHighlightColor(false), null);
|
||||
});
|
||||
|
||||
test('a hidden part collapses, its normals left alone', () => {
|
||||
const info = infoOf(partsModelGlb());
|
||||
const data = new Float32Array(4 * ROW);
|
||||
writePartTexture(
|
||||
info,
|
||||
{ poses: { pod: { hidden: true } } },
|
||||
0,
|
||||
undefined,
|
||||
data,
|
||||
);
|
||||
assert.ok(
|
||||
matrixOf(data, 1)
|
||||
.flat()
|
||||
.every((v) => v === 0),
|
||||
);
|
||||
assert.equal(normalsOf(data, 1).moved, 0);
|
||||
assert.ok(data.every(Number.isFinite));
|
||||
});
|
||||
|
||||
test('spins keep their angle when their rate changes, and stop where they are', () => {
|
||||
const { table } = infoOf(partsModelGlb());
|
||||
const spins = newSpins(0);
|
||||
respin(spins, table, { spin: { pod: 90 } }, 0, () => 10);
|
||||
assert.equal(spins.angles.pod, 10);
|
||||
advanceSpins(spins, 1);
|
||||
assert.equal(spins.angles.pod, 100);
|
||||
// Twice as fast from here: no jump at the change.
|
||||
respin(spins, table, { spin: { pod: 180 } }, 1.5);
|
||||
assert.equal(spins.angles.pod, 145);
|
||||
advanceSpins(spins, 2);
|
||||
assert.equal(spins.angles.pod, 235);
|
||||
// Stopped: the angle stays; a name without an axis or a rate of 0 spins nothing.
|
||||
respin(spins, table, { spin: { body: 50, missing: 5, pod: 0 } }, 3);
|
||||
assert.equal(spins.angles.pod, (235 + 180) % 360);
|
||||
assert.equal(spins.rates.size, 0);
|
||||
advanceSpins(spins, 10);
|
||||
assert.equal(spins.angles.pod, (235 + 180) % 360);
|
||||
});
|
||||
@@ -85,6 +85,7 @@ export const CESIUM_CHECKS = new Set([
|
||||
'draw.models.tint',
|
||||
'draw.models.blend',
|
||||
'draw.models.update',
|
||||
'draw.models.parts',
|
||||
'draw.motion',
|
||||
'draw.motion.arc',
|
||||
'draw.motion.climb',
|
||||
|
||||
@@ -300,3 +300,17 @@ export function creditDisplayContents(display) {
|
||||
export function materialTexture(material, uniform) {
|
||||
return material?._textures?.[uniform];
|
||||
}
|
||||
|
||||
/**
|
||||
* The texture a custom shader holds for a texture uniform, once it has made
|
||||
* it. A custom shader takes a new texture uniform only as a texture it makes
|
||||
* (and the old one it destroys) on its next update; `drawModels.js` writes a
|
||||
* posed model's part matrices into this texture in place instead, each frame
|
||||
* a part spins.
|
||||
* @param {object} shader Cesium CustomShader.
|
||||
* @param {string} uniform The uniform's name.
|
||||
* @returns {object|undefined} Cesium Texture.
|
||||
*/
|
||||
export function customShaderTexture(shader, uniform) {
|
||||
return shader?._textureManager?.getTexture?.(uniform);
|
||||
}
|
||||
@@ -12,6 +12,7 @@ import {
|
||||
closeRenderLoopLatch,
|
||||
commandExtents,
|
||||
creditDisplayContents,
|
||||
customShaderTexture,
|
||||
defaultView,
|
||||
globeTilesDrawn,
|
||||
lastRenderTime,
|
||||
@@ -70,6 +71,7 @@ test('every private field the app reaches is still declared by the installed Ces
|
||||
[ENGINE, 'Scene/CreditDisplay.js', '_currentFrameCredits'],
|
||||
[ENGINE, 'Scene/CreditDisplay.js', '_currentCesiumCredit'],
|
||||
[ENGINE, 'Scene/Material.js', '_textures'],
|
||||
[ENGINE, 'Scene/Model/CustomShader.js', '_textureManager'],
|
||||
];
|
||||
const missing = fields.filter(
|
||||
([root, file, field]) =>
|
||||
@@ -281,6 +283,18 @@ test('private Cesium fields are reached only through internals.js', () => {
|
||||
assert.deepEqual([...new Set(offenders)], []);
|
||||
});
|
||||
|
||||
test('customShaderTexture reads the texture a custom shader made for a uniform', () => {
|
||||
const texture = {};
|
||||
const shader = {
|
||||
_textureManager: {
|
||||
getTexture: (name) => (name === 'u_a' ? texture : undefined),
|
||||
},
|
||||
};
|
||||
assert.equal(customShaderTexture(shader, 'u_a'), texture);
|
||||
assert.equal(customShaderTexture(shader, 'u_b'), undefined);
|
||||
assert.equal(customShaderTexture(undefined, 'u_a'), undefined);
|
||||
});
|
||||
|
||||
test('trimGlobeTiles empties the globe cache of what the frame did not draw', () => {
|
||||
const trims = [];
|
||||
trimGlobeTiles({
|
||||
|
||||
@@ -70,6 +70,8 @@ const GLOBE_CAPABILITIES = [
|
||||
export function cesiumCapabilities(scene, only) {
|
||||
const all = [
|
||||
'models',
|
||||
// Moving parts posed in a custom shader per posed model (`drawModels.js`).
|
||||
'modelParts',
|
||||
// Cesium scatters drawn models through the atmosphere wherever the
|
||||
// scene draws fog (its models' atmosphere stage).
|
||||
'modelAtmosphere',
|
||||
|
||||
@@ -33,7 +33,14 @@ test('capabilities follow what the scene supports', () => {
|
||||
'vectorBase',
|
||||
];
|
||||
const globe = { show: true };
|
||||
const draw = ['models', 'modelAtmosphere', 'quads', 'meshes', 'fields'];
|
||||
const draw = [
|
||||
'models',
|
||||
'modelParts',
|
||||
'modelAtmosphere',
|
||||
'quads',
|
||||
'meshes',
|
||||
'fields',
|
||||
];
|
||||
assert.deepEqual(cesiumCapabilities({}), [...draw, ...effects]);
|
||||
// A scene with a globe reads its visibility back.
|
||||
assert.deepEqual(cesiumCapabilities({ globe }), [
|
||||
|
||||
@@ -14,6 +14,7 @@ import { AUSTIN, SCRIPT_VIEWPORT } from '../cameraScripts.js';
|
||||
import { deepEqual, equal, near, nearVec, ok, throws } from '../expect.js';
|
||||
import { iconPosition } from '../../motion/iconMotion.js';
|
||||
import { encodeVectorTile } from '../../vectorBase/encode.js';
|
||||
import { partsModelGlb } from '../partsModel.js';
|
||||
|
||||
/** 1 × 1 PNGs (red, green, blue), so imagery checks load nothing from the network. */
|
||||
const PIXEL_PNGS = [
|
||||
@@ -4123,6 +4124,183 @@ export function portChecks() {
|
||||
},
|
||||
{ capability: 'models' },
|
||||
),
|
||||
check(
|
||||
'draw.models.parts',
|
||||
'a model’s parts are moved, hidden, clamped and spun live, without loading again',
|
||||
async (h, r) => {
|
||||
await overAustin(h, r, 200);
|
||||
const set = r.draw.models({ id: 'conf:models.parts' });
|
||||
const ready = [];
|
||||
const failed = [];
|
||||
set.on('ready', (id) => ready.push(id));
|
||||
set.on('loadFailed', (id) => failed.push(id));
|
||||
// `partsModel.js`: a body, a pod on it, a ram on that, an arm ahead.
|
||||
const models = {
|
||||
m: partsModelGlb(),
|
||||
// The same model, its mesh node turned, scaled and moved.
|
||||
n: partsModelGlb({ scale: 4, turnDeg: 90, translation: [3, 2, -1] }),
|
||||
};
|
||||
const pos = h.toEcef({ ...AUSTIN, height: 0 });
|
||||
const model = (id, parts, extra = {}) => ({
|
||||
id,
|
||||
pos,
|
||||
url: `conformance:parts-model-${id}.glb`,
|
||||
gltf: models[id],
|
||||
orientation: { heading: 0, pitch: 0, roll: 0 },
|
||||
environmentMap: false,
|
||||
meta: { n: 1 },
|
||||
...extra,
|
||||
...(parts ? { parts } : {}),
|
||||
});
|
||||
const metresPerLon = 111320 * Math.cos((AUSTIN.lat * Math.PI) / 180);
|
||||
/** The point `east`, `north` metres from the model, `up` above it. */
|
||||
const at = ([east, north], metres, up = 0) =>
|
||||
h.toEcef({
|
||||
lon: AUSTIN.lon + (east * metres) / metresPerLon,
|
||||
lat: AUSTIN.lat + (north * metres) / 110574,
|
||||
height: up,
|
||||
});
|
||||
const pickedAt = (p) => {
|
||||
const s = r.query.project(p);
|
||||
return (
|
||||
s !== null &&
|
||||
r.query.drillPick(s.x, s.y).some((hit) => hit.set === set.id)
|
||||
);
|
||||
};
|
||||
// The compass, clockwise seen from above.
|
||||
const COMPASS = [
|
||||
[0, 1],
|
||||
[1, 0],
|
||||
[0, -1],
|
||||
[-1, 0],
|
||||
];
|
||||
const clockwise = ([e, n]) => [n, -e];
|
||||
const same = (a, b) => a[0] === b[0] && a[1] === b[1];
|
||||
/** The compass points 15 m off at which the model is picked. */
|
||||
const pickedAround = (up = 0) =>
|
||||
COMPASS.filter((d) => pickedAt(at(d, 15, up)));
|
||||
const picks = h.pixels !== false;
|
||||
const look = async () => {
|
||||
await drawn(h, r, 3);
|
||||
await settled(r);
|
||||
};
|
||||
const show = async (item) => {
|
||||
set.upsert([item]);
|
||||
await look();
|
||||
};
|
||||
set.set([model('m')]);
|
||||
for (let i = 0; i < 600 && !ready.length && !failed.length; i++)
|
||||
await drawn(h, r, 1);
|
||||
deepEqual(ready, ['m'], 'ready');
|
||||
await look();
|
||||
if (picks) ok(pickedAt(pos), 'drawn whole, at rest');
|
||||
|
||||
await show(model('m', { poses: { pod: { hidden: true } } }));
|
||||
if (picks) ok(pickedAt(pos), 'the pod hidden, the body drawn');
|
||||
await show(model('m', { poses: { body: { hidden: true } } }));
|
||||
if (picks) ok(!pickedAt(pos), 'the body hidden, and all riding it');
|
||||
|
||||
// Moves go where they say: forward, then right of that.
|
||||
await show(model('m', { poses: { body: { offsetM: [0, 15, 0] } } }));
|
||||
const ahead = picks ? pickedAround() : [];
|
||||
if (picks) equal(ahead.length, 1, 'moved forward, drawn 15 m one way');
|
||||
await show(model('m', { poses: { body: { offsetM: [15, 0, 0] } } }));
|
||||
if (picks) {
|
||||
ok(!pickedAt(pos), 'moved right, gone from its place');
|
||||
const right = pickedAround();
|
||||
equal(right.length, 1, 'moved right, drawn 15 m one way');
|
||||
ok(
|
||||
ahead.length === 1 &&
|
||||
right.length === 1 &&
|
||||
same(right[0], clockwise(ahead[0])),
|
||||
'its right is a quarter turn clockwise of its forward',
|
||||
);
|
||||
}
|
||||
const forward = ahead[0] ?? COMPASS[0];
|
||||
const rightward = clockwise(forward);
|
||||
const back = clockwise(clockwise(forward));
|
||||
|
||||
// A mesh node turned, scaled and moved: parts move in the model's
|
||||
// frame all the same.
|
||||
set.set([model('n')]);
|
||||
for (let i = 0; i < 600 && ready.length < 2 && !failed.length; i++)
|
||||
await drawn(h, r, 1);
|
||||
deepEqual(ready, ['m', 'n'], 'the turned-node model ready');
|
||||
await show(model('n', { poses: { body: { offsetM: [15, 0, 0] } } }));
|
||||
if (picks) {
|
||||
ok(
|
||||
!pickedAt(pos),
|
||||
'its node turned: moved right, gone from its place',
|
||||
);
|
||||
ok(pickedAt(at(rightward, 15)), 'and drawn 15 m to its right');
|
||||
}
|
||||
set.set([model('m')]);
|
||||
for (let i = 0; i < 600 && ready.length < 3 && !failed.length; i++)
|
||||
await drawn(h, r, 1);
|
||||
await look();
|
||||
|
||||
// Stretched twice its length: a move along it stretches with it.
|
||||
const stretched = { axisScale: [2, 1, 1] };
|
||||
await show(model('m', undefined, stretched));
|
||||
if (picks) ok(!pickedAt(at(back, 30)), 'stretched, it ends 20 m back');
|
||||
await show(
|
||||
model('m', { poses: { body: { offsetM: [0, -7.5, 0] } } }, stretched),
|
||||
);
|
||||
if (picks)
|
||||
ok(
|
||||
pickedAt(at(back, 30)),
|
||||
'moved 7.5 m back stretched, drawn 15 m back',
|
||||
);
|
||||
|
||||
// A slide's travel stays within its limits: the ram stops at 20 m.
|
||||
const ramAhead = at(forward, 20, 23);
|
||||
await show(model('m'));
|
||||
if (picks) ok(!pickedAt(ramAhead), 'the ram at rest, on top');
|
||||
await show(model('m', { poses: { ram: { offsetM: [0, 40, 0] } } }));
|
||||
if (picks) ok(pickedAt(ramAhead), 'pushed 40 m, the ram stops at 20 m');
|
||||
await show(model('m', { deploy: { ram: 1 } }));
|
||||
if (picks) ok(pickedAt(ramAhead), 'deployed, the ram is out 20 m');
|
||||
|
||||
// A hinge's turn stays within its limits: the arm swings 45° left
|
||||
// at most, and not at all to the right.
|
||||
const left = clockwise(back);
|
||||
const armAt = (d, m = 15) => at(d, m, 3);
|
||||
const diagonal = (side) =>
|
||||
h.toEcef({
|
||||
lon: AUSTIN.lon + ((forward[0] + side[0]) * 10.6) / metresPerLon,
|
||||
lat: AUSTIN.lat + ((forward[1] + side[1]) * 10.6) / 110574,
|
||||
height: 3,
|
||||
});
|
||||
if (picks) ok(pickedAt(armAt(forward)), 'the arm at rest, ahead');
|
||||
await show(model('m', { poses: { arm: { yawDeg: -90 } } }));
|
||||
if (picks) {
|
||||
ok(!pickedAt(armAt(forward)), 'turned left, the arm leaves');
|
||||
ok(!pickedAt(armAt(left)), 'and stops short of a quarter turn');
|
||||
ok(pickedAt(diagonal(left)), 'at 45° ahead and to the left');
|
||||
}
|
||||
await show(model('m', { poses: { arm: { yawDeg: 90 } } }));
|
||||
if (picks) {
|
||||
ok(!pickedAt(armAt(rightward)), 'turned right, the arm does not');
|
||||
ok(pickedAt(armAt(forward)), 'and stays ahead');
|
||||
}
|
||||
|
||||
await show(
|
||||
model('m', {
|
||||
spin: { pod: 90 },
|
||||
deploy: { pod: 1, missing: 1 },
|
||||
poses: { pod: { highlight: true }, missing: { hidden: true } },
|
||||
}),
|
||||
);
|
||||
if (picks) ok(pickedAt(pos), 'spinning and highlighted, where it is');
|
||||
await show(model('m'));
|
||||
if (picks) ok(pickedAt(pos), 'back at rest');
|
||||
deepEqual(ready, ['m', 'n', 'm'], 'posed without loading again');
|
||||
deepEqual(failed, [], 'nothing failed');
|
||||
equal(set.size(), 1, 'one model');
|
||||
set.dispose();
|
||||
},
|
||||
{ capability: ['models', 'modelParts'] },
|
||||
),
|
||||
|
||||
// --- Query -------------------------------------------------------------
|
||||
check(
|
||||
|
||||
@@ -0,0 +1,261 @@
|
||||
/**
|
||||
* @module render/conformance/partsModel
|
||||
* @description A glTF model with moving parts, built in code for the
|
||||
* conformance checks (`PARTS_MODEL_TABLE` says what its parts are). One
|
||||
* mesh whose vertices carry their part index (`_PART`), its node scaled
|
||||
* (by ten unless told otherwise: the mesh is in tenths of the model's
|
||||
* metres), and the part table in that node's `extras`.
|
||||
*/
|
||||
|
||||
/** Each cube face: its normal and two axes across it. */
|
||||
const FACES = [
|
||||
[
|
||||
[1, 0, 0],
|
||||
[0, 1, 0],
|
||||
[0, 0, 1],
|
||||
],
|
||||
[
|
||||
[-1, 0, 0],
|
||||
[0, 0, 1],
|
||||
[0, 1, 0],
|
||||
],
|
||||
[
|
||||
[0, 1, 0],
|
||||
[0, 0, 1],
|
||||
[1, 0, 0],
|
||||
],
|
||||
[
|
||||
[0, -1, 0],
|
||||
[1, 0, 0],
|
||||
[0, 0, 1],
|
||||
],
|
||||
[
|
||||
[0, 0, 1],
|
||||
[1, 0, 0],
|
||||
[0, 1, 0],
|
||||
],
|
||||
[
|
||||
[0, 0, -1],
|
||||
[0, 1, 0],
|
||||
[1, 0, 0],
|
||||
],
|
||||
];
|
||||
|
||||
/**
|
||||
* Append a cube of half size `half` centred at `centre` (the model's glTF
|
||||
* frame, metres) as part `part`, its vertices and normals put into the
|
||||
* mesh's own frame by `toMesh`.
|
||||
*/
|
||||
function cube(mesh, centre, half, part, toMesh) {
|
||||
for (const [n, u, v] of FACES) {
|
||||
const base = mesh.positions.length / 3;
|
||||
for (const [su, sv] of [
|
||||
[-1, -1],
|
||||
[1, -1],
|
||||
[1, 1],
|
||||
[-1, 1],
|
||||
]) {
|
||||
const p = [0, 1, 2].map(
|
||||
(i) => centre[i] + half * (n[i] + su * u[i] + sv * v[i]),
|
||||
);
|
||||
mesh.positions.push(...toMesh.point(p));
|
||||
mesh.normals.push(...toMesh.direction(n));
|
||||
mesh.parts.push(part);
|
||||
}
|
||||
// Counter-clockwise seen from outside: u × v is the normal.
|
||||
mesh.indices.push(base, base + 1, base + 2, base, base + 2, base + 3);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The part table, in the model's glTF frame (forward −X, up +Y, right −Z):
|
||||
* a 20 m cube (`body`) centred on the origin; a 10 m cube on top of it
|
||||
* (`pod`) that spins about the vertical through its centre; a 6 m cube on
|
||||
* top of that (`ram`) that slides forward up to 20 m; and a 6 m cube 15 m
|
||||
* ahead of the body at its foot (`arm`), hinged about the vertical through
|
||||
* the body's centre, turning up to 45° to the left.
|
||||
*/
|
||||
export const PARTS_MODEL_TABLE = Object.freeze([
|
||||
{ name: 'body', kind: 'body' },
|
||||
{ name: 'pod', kind: 'spin', pivot: [0, 15, 0], axis: [0, 1, 0] },
|
||||
{
|
||||
name: 'ram',
|
||||
kind: 'slide',
|
||||
pivot: [0, 23, 0],
|
||||
axis: [-1, 0, 0],
|
||||
limits: [0, 20],
|
||||
rest: 0,
|
||||
},
|
||||
{
|
||||
name: 'arm',
|
||||
kind: 'hinge',
|
||||
pivot: [0, 3, 0],
|
||||
axis: [0, 1, 0],
|
||||
limits: [0, 45],
|
||||
rest: 0,
|
||||
},
|
||||
]);
|
||||
|
||||
/** Each part's cube: its centre (glTF frame, metres) and half size. */
|
||||
const CUBES = [
|
||||
[[0, 0, 0], 10],
|
||||
[[0, 15, 0], 5],
|
||||
[[0, 23, 0], 3],
|
||||
[[-15, 3, 0], 3],
|
||||
];
|
||||
|
||||
/**
|
||||
* The model's GLB bytes. Its mesh node is scaled by `scale`, turned
|
||||
* `turnDeg` about its vertical and moved by `translation`; the mesh is
|
||||
* built in that node's own frame, so the model it draws is the same
|
||||
* whatever the node's transform.
|
||||
* @param {{scale?: number, turnDeg?: number,
|
||||
* translation?: [number, number, number]}} [node]
|
||||
* @returns {Uint8Array}
|
||||
*/
|
||||
export function partsModelGlb({
|
||||
scale = 10,
|
||||
turnDeg = 0,
|
||||
translation = [0, 0, 0],
|
||||
} = {}) {
|
||||
const a = (turnDeg * Math.PI) / 180;
|
||||
const c = Math.cos(a);
|
||||
const sn = Math.sin(a);
|
||||
// The node's turn undone: about +Y by −turnDeg.
|
||||
const unturn = ([x, y, z]) => [c * x - sn * z, y, sn * x + c * z];
|
||||
const toMesh = {
|
||||
point: (p) =>
|
||||
unturn([0, 1, 2].map((i) => p[i] - translation[i])).map((v) => v / scale),
|
||||
direction: unturn,
|
||||
};
|
||||
const mesh = { positions: [], normals: [], parts: [], indices: [] };
|
||||
CUBES.forEach(([centre, half], part) =>
|
||||
cube(mesh, centre, half, part, toMesh),
|
||||
);
|
||||
const count = mesh.parts.length;
|
||||
const positions = new Float32Array(mesh.positions);
|
||||
const normals = new Float32Array(mesh.normals);
|
||||
// A vertex attribute's elements sit on 4-byte boundaries.
|
||||
const parts = new Uint8Array(count * 4);
|
||||
mesh.parts.forEach((part, i) => (parts[i * 4] = part));
|
||||
const indices = new Uint16Array(mesh.indices);
|
||||
const chunks = [positions, normals, parts, indices];
|
||||
const offsets = [];
|
||||
let length = 0;
|
||||
for (const chunk of chunks) {
|
||||
offsets.push(length);
|
||||
length += Math.ceil(chunk.byteLength / 4) * 4;
|
||||
}
|
||||
const bin = new Uint8Array(length);
|
||||
chunks.forEach((chunk, i) =>
|
||||
bin.set(
|
||||
new Uint8Array(chunk.buffer, chunk.byteOffset, chunk.byteLength),
|
||||
offsets[i],
|
||||
),
|
||||
);
|
||||
const min = [Infinity, Infinity, Infinity];
|
||||
const max = [-Infinity, -Infinity, -Infinity];
|
||||
for (let i = 0; i < positions.length; i++) {
|
||||
min[i % 3] = Math.min(min[i % 3], positions[i]);
|
||||
max[i % 3] = Math.max(max[i % 3], positions[i]);
|
||||
}
|
||||
const json = {
|
||||
asset: { version: '2.0' },
|
||||
scene: 0,
|
||||
scenes: [{ nodes: [0] }],
|
||||
nodes: [
|
||||
{
|
||||
name: 'parts',
|
||||
mesh: 0,
|
||||
scale: [scale, scale, scale],
|
||||
rotation: [0, Math.sin(a / 2), 0, Math.cos(a / 2)],
|
||||
translation,
|
||||
extras: { parts: PARTS_MODEL_TABLE },
|
||||
},
|
||||
],
|
||||
meshes: [
|
||||
{
|
||||
primitives: [
|
||||
{
|
||||
attributes: { POSITION: 0, NORMAL: 1, _PART: 2 },
|
||||
indices: 3,
|
||||
material: 0,
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
materials: [
|
||||
{
|
||||
pbrMetallicRoughness: {
|
||||
baseColorFactor: [1, 1, 1, 1],
|
||||
metallicFactor: 0,
|
||||
roughnessFactor: 1,
|
||||
},
|
||||
},
|
||||
],
|
||||
buffers: [{ byteLength: length }],
|
||||
bufferViews: [
|
||||
{
|
||||
buffer: 0,
|
||||
byteOffset: offsets[0],
|
||||
byteLength: positions.byteLength,
|
||||
target: 34962,
|
||||
},
|
||||
{
|
||||
buffer: 0,
|
||||
byteOffset: offsets[1],
|
||||
byteLength: normals.byteLength,
|
||||
target: 34962,
|
||||
},
|
||||
{
|
||||
buffer: 0,
|
||||
byteOffset: offsets[2],
|
||||
byteLength: parts.byteLength,
|
||||
byteStride: 4,
|
||||
target: 34962,
|
||||
},
|
||||
{
|
||||
buffer: 0,
|
||||
byteOffset: offsets[3],
|
||||
byteLength: indices.byteLength,
|
||||
target: 34963,
|
||||
},
|
||||
],
|
||||
accessors: [
|
||||
{
|
||||
bufferView: 0,
|
||||
componentType: 5126,
|
||||
count,
|
||||
type: 'VEC3',
|
||||
min,
|
||||
max,
|
||||
},
|
||||
{ bufferView: 1, componentType: 5126, count, type: 'VEC3' },
|
||||
{ bufferView: 2, componentType: 5121, count, type: 'SCALAR' },
|
||||
{
|
||||
bufferView: 3,
|
||||
componentType: 5123,
|
||||
count: indices.length,
|
||||
type: 'SCALAR',
|
||||
},
|
||||
],
|
||||
};
|
||||
let text = new TextEncoder().encode(JSON.stringify(json));
|
||||
const padded = new Uint8Array(Math.ceil(text.length / 4) * 4).fill(0x20);
|
||||
padded.set(text);
|
||||
text = padded;
|
||||
const total = 12 + 8 + text.length + 8 + bin.length;
|
||||
const out = new Uint8Array(total);
|
||||
const view = new DataView(out.buffer);
|
||||
view.setUint32(0, 0x46546c67, true);
|
||||
view.setUint32(4, 2, true);
|
||||
view.setUint32(8, total, true);
|
||||
view.setUint32(12, text.length, true);
|
||||
view.setUint32(16, 0x4e4f534a, true);
|
||||
out.set(text, 20);
|
||||
const binAt = 20 + text.length;
|
||||
view.setUint32(binAt, bin.length, true);
|
||||
view.setUint32(binAt + 4, 0x004e4942, true);
|
||||
out.set(bin, binAt + 8);
|
||||
return out;
|
||||
}
|
||||
Vendored
+2
@@ -191,6 +191,8 @@ export type Capability =
|
||||
| 'motionSegments'
|
||||
/** glTF models. */
|
||||
| 'models'
|
||||
/** Moving parts of glTF models posed as an item's `parts` says. */
|
||||
| 'modelParts'
|
||||
/** Image, video and canvas planes. */
|
||||
| 'quads'
|
||||
/** Custom meshes in a local east-north-up frame. */
|
||||
|
||||
Vendored
+59
@@ -450,6 +450,65 @@ export interface ModelItem extends Placed {
|
||||
* change live.
|
||||
*/
|
||||
focus?: number;
|
||||
/**
|
||||
* `modelParts`: how the model's moving parts are posed. Applies to a
|
||||
* model whose mesh carries a `_PART` vertex attribute (each vertex's part
|
||||
* index) and whose root node's glTF `extras.parts` is its part table;
|
||||
* ignored for any other. Omitted, or without the capability, the model is
|
||||
* drawn whole, at rest, as its file draws it. Can change live, without
|
||||
* loading the model again.
|
||||
*/
|
||||
parts?: ModelPartState;
|
||||
}
|
||||
|
||||
/**
|
||||
* A model's part state (`ModelItem.parts`), each member by part name; a
|
||||
* part not named is at rest, and a name the model's part table lacks is
|
||||
* ignored. The maths is `render/modelParts`'s `partMatrices`: about each
|
||||
* part's pivot, its deploy fraction first, then its spin, then its pose,
|
||||
* then its parent part's whole motion.
|
||||
*/
|
||||
export interface ModelPartState {
|
||||
/**
|
||||
* Degrees a second about the part's axis, which the renderer advances
|
||||
* itself on its own clock each frame: a turning rotor costs the
|
||||
* application no write per frame. A change of rate goes on from the angle
|
||||
* reached, without a jump; a part that stops spinning stays where it is.
|
||||
*/
|
||||
spin?: Record<string, number>;
|
||||
/**
|
||||
* 0 (stowed, the table's first limit) to 1 (deployed, its second): a
|
||||
* hinge or deploy part turned, a slide or separable part moved along its
|
||||
* axis, that far between its limits. Clamped to 0..1.
|
||||
*/
|
||||
deploy?: Record<string, number>;
|
||||
/** Each part's pose, on top of its spin and deploy fraction. */
|
||||
poses?: Record<string, PartPose>;
|
||||
}
|
||||
|
||||
/**
|
||||
* One part's pose about its pivot, in the model's own frame (in its glTF:
|
||||
* forward −X, up +Y, right −Z). A hinge or deploy part's turn about its
|
||||
* axis stays within its limits, as does a slide part's travel; the rest of
|
||||
* every part's motion is free. A number that is not finite counts as 0.
|
||||
*/
|
||||
export interface PartPose {
|
||||
/** Metres along the model's right, forward and up. */
|
||||
offsetM?: [right: number, forward: number, up: number];
|
||||
/** Degrees clockwise seen from above, as a heading. Applied first. */
|
||||
yawDeg?: number;
|
||||
/** Degrees nose up. Applied after the yaw. */
|
||||
pitchDeg?: number;
|
||||
/** Degrees clockwise looking forward. Applied last. */
|
||||
rollDeg?: number;
|
||||
/** Not drawn, nor any part riding it. */
|
||||
hidden?: boolean;
|
||||
/**
|
||||
* Drawn in a highlight colour: `true` for the renderer's own, or a
|
||||
* colour. Anything else, or a colour the renderer cannot read, draws no
|
||||
* highlight. Not inherited by the parts riding it.
|
||||
*/
|
||||
highlight?: boolean | Color;
|
||||
}
|
||||
|
||||
/** A plane showing an image, a video or a canvas. */
|
||||
|
||||
@@ -34,6 +34,7 @@ export const CAPABILITIES = Object.freeze([
|
||||
'columns',
|
||||
'motionSegments',
|
||||
'models',
|
||||
'modelParts',
|
||||
'quads',
|
||||
'meshes',
|
||||
'fields',
|
||||
|
||||
Vendored
+86
@@ -0,0 +1,86 @@
|
||||
/**
|
||||
* A model's moving parts (`modelParts.js`): its part table and the maths
|
||||
* that turns a model item's `parts` into one matrix per part, so a renderer
|
||||
* that poses parts draws exactly those.
|
||||
*/
|
||||
import type { ModelPartState } from './contract/index';
|
||||
|
||||
/** What a part does: what live data drives and what is offered first. */
|
||||
export type PartKind =
|
||||
'body' | 'spin' | 'hinge' | 'slide' | 'deploy' | 'separable' | 'marker';
|
||||
|
||||
/** `[x, y, z]`. */
|
||||
export type PartVec3 = readonly [number, number, number];
|
||||
|
||||
/** One part of a model, as its table gives it (glTF frame, metres and degrees). */
|
||||
export interface ModelPart {
|
||||
/** Its `_PART` index. */
|
||||
readonly index: number;
|
||||
readonly name: string;
|
||||
readonly kind: PartKind;
|
||||
/** The part it rides, or null for the body. */
|
||||
readonly parent: string | null;
|
||||
/** Its parent's index, or -1 for the body. */
|
||||
readonly parentIndex: number;
|
||||
/** The point it turns about; the origin for the body. */
|
||||
readonly pivot: PartVec3;
|
||||
/** Its axis of motion, unit length; null where the table gives none. */
|
||||
readonly axis: PartVec3 | null;
|
||||
/** `[stowed, deployed]`: degrees for hinge and deploy, metres for slide and separable. */
|
||||
readonly limits: readonly [number, number] | null;
|
||||
/** The value it is drawn at in the file; null without limits. */
|
||||
readonly rest: number | null;
|
||||
}
|
||||
|
||||
/** A model's part table: its parts in `_PART` index order, the body first. */
|
||||
export interface PartTable {
|
||||
readonly parts: readonly ModelPart[];
|
||||
/** A part's index by its name. */
|
||||
readonly byName: ReadonlyMap<string, number>;
|
||||
}
|
||||
|
||||
/** Where and how `partMatrices` writes. */
|
||||
export interface PartMatricesOptions {
|
||||
/** Where in `out` the first matrix goes; 0 by default. */
|
||||
readonly offset?: number;
|
||||
/** Gets each part's `PART_HIDDEN` and `PART_HIGHLIGHT`, from `flagsOffset`. */
|
||||
readonly flags?: Uint8Array;
|
||||
readonly flagsOffset?: number;
|
||||
/** The model's stretch along its glTF axes (`axisScale`): parts then turn rigidly in the stretched model. */
|
||||
readonly scale?: PartVec3 | null;
|
||||
}
|
||||
|
||||
export const PART_KINDS: readonly PartKind[];
|
||||
export const PART_HIDDEN: 1;
|
||||
export const PART_HIGHLIGHT: 2;
|
||||
|
||||
/** Whether a pose's `highlight` asks for one: true, or a colour (a non-empty string, or three or four finite numbers). */
|
||||
export function asksHighlight(value: unknown): boolean;
|
||||
|
||||
/** The part table in a node's glTF `extras`; null when it has none. Throws on a malformed table. */
|
||||
export function partTableOf(extras: unknown): PartTable | null;
|
||||
|
||||
/** The glTF JSON of a GLB. Throws when the bytes are not a GLB. */
|
||||
export function glbJson(glb: Uint8Array | ArrayBuffer): Record<string, unknown>;
|
||||
|
||||
/** The part table of a glTF document; null when no node has one. */
|
||||
export function gltfPartTable(gltf: Record<string, unknown>): PartTable | null;
|
||||
|
||||
/** The part table of a GLB's bytes; null for a model without one. */
|
||||
export function readPartTable(glb: Uint8Array | ArrayBuffer): PartTable | null;
|
||||
|
||||
/** Where the scene's first mesh is drawn: its node's transform with its parents', column-major 4×4. */
|
||||
export function gltfMeshMatrix(gltf: Record<string, unknown>): number[];
|
||||
|
||||
/**
|
||||
* Each part's column-major 4×4 matrix for `state` at `timeS` seconds into
|
||||
* `out`, in `_PART` order, in the model's glTF frame. Whether any part is
|
||||
* not at rest.
|
||||
*/
|
||||
export function partMatrices(
|
||||
table: PartTable,
|
||||
state: ModelPartState | null | undefined,
|
||||
timeS: number,
|
||||
out: Float32Array | Float64Array,
|
||||
options?: PartMatricesOptions,
|
||||
): boolean;
|
||||
@@ -0,0 +1,696 @@
|
||||
/**
|
||||
* @module render/modelParts
|
||||
* @description A model's moving parts: the part table a glTF model carries
|
||||
* and the pure maths that turns a model item's `parts` (`ModelPartState`)
|
||||
* into one matrix per part. Plain JavaScript: no fetch, no DOM, no engine.
|
||||
*
|
||||
* **The model.** One glTF mesh whose vertices carry a part index (`_PART`, an
|
||||
* unsigned byte). The root node's glTF `extras.parts` lists the parts in
|
||||
* `_PART` index order: `{name, kind, pivot, axis, limits, rest, parent}`,
|
||||
* glTF Y-up, metres and degrees; index 0 is the body. A model that is only
|
||||
* its body carries no table.
|
||||
*
|
||||
* **Frames.** The table, and the matrices {@link partMatrices} writes, are
|
||||
* in the model's glTF frame (Y up, nose −X, so right is −Z), applied after
|
||||
* the mesh node's own transform (a packed model's dequantization;
|
||||
* {@link gltfMeshMatrix}). Poses are given in `[right, forward, up]` metres,
|
||||
* with yaw (clockwise from above, as a heading), pitch (nose up) and roll
|
||||
* (clockwise looking forward), applied yaw, then pitch, then roll.
|
||||
*
|
||||
* **A part's motion**, about its pivot, innermost first: its deploy
|
||||
* fraction, then its spin, then its pose, then its parent part's whole
|
||||
* motion, so a child rides its parent. A hinge or deploy part's turn about
|
||||
* its axis is clamped to its limits, as is a slide part's travel along its
|
||||
* axis; a part's other motion, and a spin, separable, marker or body part's,
|
||||
* is free.
|
||||
*/
|
||||
|
||||
/** What a part does: what live data drives and what is offered first. */
|
||||
export const PART_KINDS = Object.freeze([
|
||||
'body',
|
||||
'spin',
|
||||
'hinge',
|
||||
'slide',
|
||||
'deploy',
|
||||
'separable',
|
||||
'marker',
|
||||
]);
|
||||
|
||||
/** {@link partMatrices}'s flags per part: not drawn. */
|
||||
export const PART_HIDDEN = 1;
|
||||
/** {@link partMatrices}'s flags per part: highlighted. */
|
||||
export const PART_HIGHLIGHT = 2;
|
||||
|
||||
const isObject = (value) =>
|
||||
value !== null && typeof value === 'object' && !Array.isArray(value);
|
||||
|
||||
function vec3(value, what) {
|
||||
if (
|
||||
!Array.isArray(value) ||
|
||||
value.length !== 3 ||
|
||||
!value.every((n) => typeof n === 'number' && Number.isFinite(n))
|
||||
)
|
||||
throw new Error(`${what} is not three numbers`);
|
||||
return [value[0], value[1], value[2]];
|
||||
}
|
||||
|
||||
/**
|
||||
* The part table in a node's glTF `extras` (`{parts: [...]}`); null when it
|
||||
* has none (a model that is only its body). Throws on a table that is
|
||||
* malformed: a missing or unknown kind, a repeated name, a parent that is
|
||||
* not an earlier part, a malformed pivot, axis or limits.
|
||||
* @param {unknown} extras
|
||||
* @returns {import('./modelParts').PartTable|null}
|
||||
*/
|
||||
export function partTableOf(extras) {
|
||||
if (!isObject(extras) || extras.parts === undefined) return null;
|
||||
const list = extras.parts;
|
||||
if (!Array.isArray(list) || list.length === 0)
|
||||
throw new Error('parts is not a list of parts');
|
||||
if (list.length > 256)
|
||||
throw new Error(`${list.length} parts: _PART is a byte`);
|
||||
const byName = new Map();
|
||||
const parts = list.map((entry, index) => {
|
||||
if (!isObject(entry)) throw new Error(`part ${index} is not an object`);
|
||||
const { name, kind } = entry;
|
||||
if (typeof name !== 'string' || name === '')
|
||||
throw new Error(`part ${index} has no name`);
|
||||
if (byName.has(name)) throw new Error(`part ${name} is named twice`);
|
||||
if (typeof kind !== 'string' || !PART_KINDS.includes(kind))
|
||||
throw new Error(`part ${name} has kind ${String(kind)}`);
|
||||
if ((index === 0) !== (kind === 'body'))
|
||||
throw new Error(`part ${name}: the body, and only it, is part 0`);
|
||||
const parentName = index === 0 ? null : (entry.parent ?? 'body');
|
||||
if (parentName !== null && typeof parentName !== 'string')
|
||||
throw new Error(`part ${name} has parent ${String(parentName)}`);
|
||||
const parentIndex =
|
||||
parentName === null ? -1 : (byName.get(parentName) ?? -2);
|
||||
if (parentIndex === -2)
|
||||
throw new Error(`part ${name} rides ${parentName}, not an earlier part`);
|
||||
const pivot =
|
||||
entry.pivot === undefined ? [0, 0, 0] : vec3(entry.pivot, name);
|
||||
let axis = null;
|
||||
if (entry.axis !== undefined) {
|
||||
const [x, y, z] = vec3(entry.axis, `${name} axis`);
|
||||
const length = Math.hypot(x, y, z);
|
||||
if (!(length > 0)) throw new Error(`part ${name} has a zero axis`);
|
||||
axis = [x / length, y / length, z / length];
|
||||
}
|
||||
let limits = null;
|
||||
const given = entry.limits;
|
||||
if (given !== undefined) {
|
||||
if (
|
||||
!Array.isArray(given) ||
|
||||
given.length !== 2 ||
|
||||
!given.every((n) => typeof n === 'number' && Number.isFinite(n))
|
||||
)
|
||||
throw new Error(`part ${name} limits are not two numbers`);
|
||||
limits = [given[0], given[1]];
|
||||
}
|
||||
const restGiven = entry.rest;
|
||||
if (
|
||||
restGiven !== undefined &&
|
||||
(typeof restGiven !== 'number' || !Number.isFinite(restGiven))
|
||||
)
|
||||
throw new Error(`part ${name} rest is not a number`);
|
||||
const rest = limits === null ? null : (restGiven ?? limits[0]);
|
||||
byName.set(name, index);
|
||||
return {
|
||||
index,
|
||||
name,
|
||||
kind,
|
||||
parent: parentName,
|
||||
parentIndex,
|
||||
pivot,
|
||||
axis,
|
||||
limits,
|
||||
rest,
|
||||
};
|
||||
});
|
||||
return { parts, byName };
|
||||
}
|
||||
|
||||
/**
|
||||
* The glTF JSON of a GLB (its first chunk). Throws when the bytes are not a
|
||||
* GLB.
|
||||
* @param {Uint8Array|ArrayBuffer} glb
|
||||
* @returns {object}
|
||||
*/
|
||||
export function glbJson(glb) {
|
||||
const bytes = glb instanceof Uint8Array ? glb : new Uint8Array(glb);
|
||||
const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
|
||||
if (bytes.byteLength < 20 || view.getUint32(0, true) !== 0x46546c67)
|
||||
throw new Error('not a GLB');
|
||||
const length = view.getUint32(12, true);
|
||||
if (view.getUint32(16, true) !== 0x4e4f534a || 20 + length > bytes.byteLength)
|
||||
throw new Error('GLB has no JSON chunk');
|
||||
const json = JSON.parse(
|
||||
new TextDecoder().decode(bytes.subarray(20, 20 + length)),
|
||||
);
|
||||
if (!isObject(json)) throw new Error('GLB JSON is not an object');
|
||||
return json;
|
||||
}
|
||||
|
||||
/** The scene's root node indices, then every node's, in order. */
|
||||
function nodeOrder(gltf) {
|
||||
const nodes = Array.isArray(gltf.nodes) ? gltf.nodes : [];
|
||||
const scenes = Array.isArray(gltf.scenes) ? gltf.scenes : [];
|
||||
const scene = scenes[typeof gltf.scene === 'number' ? gltf.scene : 0];
|
||||
const roots =
|
||||
isObject(scene) && Array.isArray(scene.nodes) ? scene.nodes : [];
|
||||
return { nodes, order: [...roots, ...nodes.keys()] };
|
||||
}
|
||||
|
||||
/**
|
||||
* The part table of a glTF document: the first node with `extras.parts`,
|
||||
* the scene's root nodes first. Null when no node has one.
|
||||
* @param {object} gltf
|
||||
* @returns {import('./modelParts').PartTable|null}
|
||||
*/
|
||||
export function gltfPartTable(gltf) {
|
||||
const { nodes, order } = nodeOrder(gltf);
|
||||
for (const index of order) {
|
||||
const node = typeof index === 'number' ? nodes[index] : undefined;
|
||||
if (
|
||||
isObject(node) &&
|
||||
isObject(node.extras) &&
|
||||
node.extras.parts !== undefined
|
||||
)
|
||||
return partTableOf(node.extras);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* The part table of a GLB's bytes; null for a model without one. Throws on
|
||||
* bytes that are not a GLB, or on a malformed table.
|
||||
* @param {Uint8Array|ArrayBuffer} glb
|
||||
* @returns {import('./modelParts').PartTable|null}
|
||||
*/
|
||||
export function readPartTable(glb) {
|
||||
return gltfPartTable(glbJson(glb));
|
||||
}
|
||||
|
||||
/** `a · b`, column-major 4×4, into a new array. */
|
||||
function multiply4(a, b) {
|
||||
const out = new Array(16);
|
||||
for (let col = 0; col < 4; col++)
|
||||
for (let row = 0; row < 4; row++) {
|
||||
let sum = 0;
|
||||
for (let k = 0; k < 4; k++) sum += a[k * 4 + row] * b[col * 4 + k];
|
||||
out[col * 4 + row] = sum;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/** A glTF node's local transform, column-major. */
|
||||
function nodeMatrix(node) {
|
||||
if (Array.isArray(node.matrix) && node.matrix.length === 16)
|
||||
return [...node.matrix];
|
||||
const [tx, ty, tz] = node.translation ?? [0, 0, 0];
|
||||
const [x, y, z, w] = node.rotation ?? [0, 0, 0, 1];
|
||||
const [sx, sy, sz] = node.scale ?? [1, 1, 1];
|
||||
return [
|
||||
(1 - 2 * (y * y + z * z)) * sx,
|
||||
2 * (x * y + z * w) * sx,
|
||||
2 * (x * z - y * w) * sx,
|
||||
0,
|
||||
2 * (x * y - z * w) * sy,
|
||||
(1 - 2 * (x * x + z * z)) * sy,
|
||||
2 * (y * z + x * w) * sy,
|
||||
0,
|
||||
2 * (x * z + y * w) * sz,
|
||||
2 * (y * z - x * w) * sz,
|
||||
(1 - 2 * (x * x + y * y)) * sz,
|
||||
0,
|
||||
tx,
|
||||
ty,
|
||||
tz,
|
||||
1,
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Where the first mesh of a glTF document's scene is drawn: its node's
|
||||
* transform with every parent's, column-major 4×4. A vertex of the mesh is
|
||||
* at this matrix times its position in the model's glTF frame, where part
|
||||
* matrices apply. The identity for a document without a mesh.
|
||||
* @param {object} gltf
|
||||
* @returns {number[]}
|
||||
*/
|
||||
export function gltfMeshMatrix(gltf) {
|
||||
const { nodes } = nodeOrder(gltf);
|
||||
const scenes = Array.isArray(gltf.scenes) ? gltf.scenes : [];
|
||||
const scene = scenes[typeof gltf.scene === 'number' ? gltf.scene : 0];
|
||||
const roots =
|
||||
isObject(scene) && Array.isArray(scene.nodes)
|
||||
? scene.nodes
|
||||
: [...nodes.keys()];
|
||||
const identity = [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1];
|
||||
// Depth first, the scene's own order: the first node with a mesh.
|
||||
const stack = roots
|
||||
.slice()
|
||||
.reverse()
|
||||
.map((index) => [index, identity, 0]);
|
||||
while (stack.length) {
|
||||
const [index, parent, depth] = stack.pop();
|
||||
const node = nodes[index];
|
||||
if (!isObject(node) || depth > 64) continue;
|
||||
const world = multiply4(parent, nodeMatrix(node));
|
||||
if (typeof node.mesh === 'number') return world;
|
||||
const children = Array.isArray(node.children) ? node.children : [];
|
||||
for (let i = children.length - 1; i >= 0; i--)
|
||||
stack.push([children[i], world, depth + 1]);
|
||||
}
|
||||
return identity;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- the maths
|
||||
|
||||
const DEG = Math.PI / 180;
|
||||
|
||||
/** The `[right, forward, up]` axes in the glTF frame (nose −X, Y up, right −Z). */
|
||||
const RIGHT_G = [0, 0, -1];
|
||||
const FORWARD_G = [-1, 0, 0];
|
||||
const UP_G = [0, 1, 0];
|
||||
|
||||
/** Scratch quaternions `[x, y, z, w]` and vectors, reused between calls. */
|
||||
const _q = new Float64Array(4);
|
||||
const _p = new Float64Array(4);
|
||||
const _v = new Float64Array(3);
|
||||
/** A part's axis in the scaled model, and the instance's scale. */
|
||||
const _a = new Float64Array(3);
|
||||
const _s = new Float64Array(3);
|
||||
|
||||
/** `out` = the rotation by `deg` about the unit `axis`, right-handed. */
|
||||
function axisAngle(out, axis, deg) {
|
||||
const half = (deg * DEG) / 2;
|
||||
const s = Math.sin(half);
|
||||
out[0] = axis[0] * s;
|
||||
out[1] = axis[1] * s;
|
||||
out[2] = axis[2] * s;
|
||||
out[3] = Math.cos(half);
|
||||
}
|
||||
|
||||
/** `a` = `a · b`. */
|
||||
function multiplyInto(a, b) {
|
||||
const ax = a[0];
|
||||
const ay = a[1];
|
||||
const az = a[2];
|
||||
const aw = a[3];
|
||||
const bx = b[0];
|
||||
const by = b[1];
|
||||
const bz = b[2];
|
||||
const bw = b[3];
|
||||
a[0] = aw * bx + ax * bw + ay * bz - az * by;
|
||||
a[1] = aw * by - ax * bz + ay * bw + az * bx;
|
||||
a[2] = aw * bz + ax * by - ay * bx + az * bw;
|
||||
a[3] = aw * bw - ax * bx - ay * by - az * bz;
|
||||
}
|
||||
|
||||
/** `v` turned by the unit quaternion `q`, in place. */
|
||||
function rotateInto(q, v) {
|
||||
const x = q[0];
|
||||
const y = q[1];
|
||||
const z = q[2];
|
||||
const w = q[3];
|
||||
const tx = 2 * (y * v[2] - z * v[1]);
|
||||
const ty = 2 * (z * v[0] - x * v[2]);
|
||||
const tz = 2 * (x * v[1] - y * v[0]);
|
||||
v[0] = v[0] + w * tx + (y * tz - z * ty);
|
||||
v[1] = v[1] + w * ty + (z * tx - x * tz);
|
||||
v[2] = v[2] + w * tz + (x * ty - y * tx);
|
||||
}
|
||||
|
||||
/** A pose's number, or 0 where it is missing or not finite. */
|
||||
const finite = (value) =>
|
||||
typeof value === 'number' && Number.isFinite(value) ? value : 0;
|
||||
|
||||
/** Whether a pose turns or moves anything (a value not finite counts as 0). */
|
||||
function isPosed(pose) {
|
||||
const o = pose.offsetM;
|
||||
return (
|
||||
finite(pose.yawDeg) !== 0 ||
|
||||
finite(pose.pitchDeg) !== 0 ||
|
||||
finite(pose.rollDeg) !== 0 ||
|
||||
(Array.isArray(o) &&
|
||||
(finite(o[0]) !== 0 || finite(o[1]) !== 0 || finite(o[2]) !== 0))
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* `q` = a pose's rotation in the glTF frame: yaw clockwise about up, then
|
||||
* pitch about the new right, then roll about the new forward. `t` = its
|
||||
* offset in the glTF frame.
|
||||
*/
|
||||
function poseInto(q, t, pose) {
|
||||
axisAngle(q, UP_G, -finite(pose.yawDeg));
|
||||
axisAngle(_p, RIGHT_G, finite(pose.pitchDeg));
|
||||
multiplyInto(q, _p);
|
||||
axisAngle(_p, FORWARD_G, finite(pose.rollDeg));
|
||||
multiplyInto(q, _p);
|
||||
const o = pose.offsetM;
|
||||
t[0] = 0;
|
||||
t[1] = 0;
|
||||
t[2] = 0;
|
||||
if (!Array.isArray(o)) return;
|
||||
t[0] = -finite(o[1]);
|
||||
t[1] = finite(o[2]);
|
||||
t[2] = -finite(o[0]);
|
||||
}
|
||||
|
||||
/** `angle` (degrees) as the value nearest `[lo, hi]` among its turns, clamped into it. */
|
||||
function clampAngle(angle, lo, hi) {
|
||||
let best = angle;
|
||||
let bestOut = Infinity;
|
||||
for (const turn of [-360, 0, 360]) {
|
||||
const a = angle + turn;
|
||||
const out = a < lo ? lo - a : a > hi ? a - hi : 0;
|
||||
if (out < bestOut) {
|
||||
best = a;
|
||||
bestOut = out;
|
||||
}
|
||||
}
|
||||
return Math.min(hi, Math.max(lo, best));
|
||||
}
|
||||
|
||||
/**
|
||||
* Clamp the rotation `q`'s turn about the unit `axis` (its twist, degrees
|
||||
* from rest) so that `rest` plus it stays within `limits`, leaving the rest
|
||||
* of the rotation (its swing) as it is.
|
||||
*/
|
||||
function clampTwist(q, axis, rest, limits) {
|
||||
const d = q[0] * axis[0] + q[1] * axis[1] + q[2] * axis[2];
|
||||
const w = q[3];
|
||||
if (Math.abs(d) < 1e-12 && Math.abs(w) < 1e-12) return;
|
||||
let twist = (2 * Math.atan2(d, w)) / DEG;
|
||||
if (twist > 180) twist -= 360;
|
||||
else if (twist <= -180) twist += 360;
|
||||
const lo = Math.min(limits[0], limits[1]) - rest;
|
||||
const hi = Math.max(limits[0], limits[1]) - rest;
|
||||
const clamped = clampAngle(twist, lo, hi);
|
||||
if (Math.abs(clamped - twist) < 1e-9) return;
|
||||
// q = swing · twist, so q' = q · twist⁻¹ · twist'.
|
||||
axisAngle(_p, axis, clamped - twist);
|
||||
multiplyInto(q, _p);
|
||||
}
|
||||
|
||||
/** The degrees or metres from rest a deploy fraction puts a part at. */
|
||||
function deployedBy(part, fraction) {
|
||||
const limits = part.limits;
|
||||
const f = Math.min(1, Math.max(0, fraction));
|
||||
return limits[0] + (limits[1] - limits[0]) * f - part.rest;
|
||||
}
|
||||
|
||||
/**
|
||||
* World (model frame) rotation and translation per part, 12 numbers each (R
|
||||
* row-major, then t), and whether each is hidden; reused between calls.
|
||||
*/
|
||||
let _world = new Float64Array(12 * 32);
|
||||
let _hidden = new Uint8Array(32);
|
||||
/** A pose's rotation, its translation, and one part's local affine, scratch. */
|
||||
const _r = new Float64Array(4);
|
||||
const _t = new Float64Array(3);
|
||||
const _local = new Float64Array(12);
|
||||
|
||||
const IDENTITY = Float64Array.of(
|
||||
1,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
1,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
1,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
1,
|
||||
);
|
||||
|
||||
const TURNS = new Set(['spin', 'hinge', 'deploy']);
|
||||
const MOVES = new Set(['slide', 'separable']);
|
||||
|
||||
/** Write the unit quaternion `q` and translation `t` as an affine (R row-major, then t) into `m` at `at`. */
|
||||
function affineInto(q, t, m, at) {
|
||||
const x = q[0];
|
||||
const y = q[1];
|
||||
const z = q[2];
|
||||
const w = q[3];
|
||||
m[at] = 1 - 2 * (y * y + z * z);
|
||||
m[at + 1] = 2 * (x * y - z * w);
|
||||
m[at + 2] = 2 * (x * z + y * w);
|
||||
m[at + 3] = 2 * (x * y + z * w);
|
||||
m[at + 4] = 1 - 2 * (x * x + z * z);
|
||||
m[at + 5] = 2 * (y * z - x * w);
|
||||
m[at + 6] = 2 * (x * z - y * w);
|
||||
m[at + 7] = 2 * (y * z + x * w);
|
||||
m[at + 8] = 1 - 2 * (x * x + y * y);
|
||||
m[at + 9] = t[0];
|
||||
m[at + 10] = t[1];
|
||||
m[at + 11] = t[2];
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether a highlight asks for one: true, or a colour (a non-empty string,
|
||||
* or three or four finite numbers). A renderer that cannot read the
|
||||
* colour draws the part without one.
|
||||
*/
|
||||
export function asksHighlight(value) {
|
||||
if (value === true) return true;
|
||||
if (typeof value === 'string') return value.trim() !== '';
|
||||
return (
|
||||
Array.isArray(value) &&
|
||||
(value.length === 3 || value.length === 4) &&
|
||||
value.every((v) => typeof v === 'number' && Number.isFinite(v))
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Write each part's matrix (4×4, column-major) for a model whose item has
|
||||
* `state` as its `parts`, at `timeS` seconds of the renderer's clock, into
|
||||
* `out`: `table.parts.length` matrices, in `_PART` order, in the model's
|
||||
* glTF frame. A vertex of part k is drawn at matrix k times its position
|
||||
* (after the mesh node's transform). A hidden part's matrix, and every
|
||||
* part's riding it, is all zeros.
|
||||
*
|
||||
* With `options.scale` S (the model drawn stretched along its glTF axes,
|
||||
* `axisScale`), each matrix X is S⁻¹·Part_s·S, where Part_s is the part's
|
||||
* motion worked out in the stretched model (its pivot, axis and moves scaled
|
||||
* by S), so S·X·v = Part_s·S·v: a radar on a hull drawn twice its length
|
||||
* turns without stretching. Limits stay in the model's own units.
|
||||
*
|
||||
* A spin turns its part `rate × timeS` degrees about its axis (any part with
|
||||
* an axis); a deploy fraction puts a hinge or deploy part that far between
|
||||
* its limits, and a slide or separable part as far along its axis. A spin,
|
||||
* deploy or pose naming a part the table does not have is ignored.
|
||||
*
|
||||
* Returns whether any part is not at rest (moved, hidden or highlighted):
|
||||
* false means every matrix written is the identity and every flag 0.
|
||||
* @param {import('./modelParts').PartTable} table
|
||||
* @param {import('./contract/draw').ModelPartState|null|undefined} state
|
||||
* @param {number} timeS
|
||||
* @param {Float32Array|Float64Array} out
|
||||
* @param {import('./modelParts').PartMatricesOptions} [options]
|
||||
* @returns {boolean}
|
||||
*/
|
||||
export function partMatrices(table, state, timeS, out, options = {}) {
|
||||
const { offset = 0, flags, flagsOffset = 0, scale } = options;
|
||||
let scaled = false;
|
||||
if (scale !== undefined && scale !== null) {
|
||||
_s[0] = scale[0];
|
||||
_s[1] = scale[1];
|
||||
_s[2] = scale[2];
|
||||
// A scale that is not positive along an axis cannot be undone: parts
|
||||
// stay unscaled.
|
||||
scaled =
|
||||
(_s[0] !== 1 || _s[1] !== 1 || _s[2] !== 1) &&
|
||||
_s[0] > 0 &&
|
||||
_s[1] > 0 &&
|
||||
_s[2] > 0;
|
||||
}
|
||||
const parts = table.parts;
|
||||
const n = parts.length;
|
||||
if (_world.length < n * 12) {
|
||||
_world = new Float64Array(n * 12);
|
||||
_hidden = new Uint8Array(n);
|
||||
}
|
||||
const world = _world;
|
||||
const posed = state?.poses;
|
||||
const spin = state?.spin;
|
||||
const deploy = state?.deploy;
|
||||
if (posed == null && spin == null && deploy == null) {
|
||||
// Every part at rest.
|
||||
for (let k = 0; k < n; k++) out.set(IDENTITY, offset + k * 16);
|
||||
flags?.fill(0, flagsOffset, flagsOffset + n);
|
||||
return false;
|
||||
}
|
||||
let anyPosed = false;
|
||||
for (let k = 0; k < n; k++) {
|
||||
const part = parts[k];
|
||||
const name = part.name;
|
||||
const pose = posed?.[name];
|
||||
const parentIndex = part.parentIndex;
|
||||
const hidden =
|
||||
pose?.hidden === true || (parentIndex >= 0 && _hidden[parentIndex] === 1);
|
||||
const highlight = asksHighlight(pose?.highlight);
|
||||
_hidden[k] = hidden ? 1 : 0;
|
||||
if (flags !== undefined)
|
||||
flags[flagsOffset + k] =
|
||||
(hidden ? PART_HIDDEN : 0) | (highlight ? PART_HIGHLIGHT : 0);
|
||||
if (hidden) {
|
||||
out.fill(0, offset + k * 16, offset + k * 16 + 16);
|
||||
anyPosed = true;
|
||||
continue;
|
||||
}
|
||||
anyPosed ||= highlight;
|
||||
// The local motion about the pivot, rotation `_q` and translation `_t`,
|
||||
// in the (stretched) model: deploy, spin, then pose. `axis` is the
|
||||
// part's axis there, `stretch` its length over the model's own.
|
||||
let axis = part.axis;
|
||||
let stretch = 1;
|
||||
if (axis !== null && scaled) {
|
||||
_a[0] = axis[0] * _s[0];
|
||||
_a[1] = axis[1] * _s[1];
|
||||
_a[2] = axis[2] * _s[2];
|
||||
stretch = Math.hypot(_a[0], _a[1], _a[2]);
|
||||
_a[0] /= stretch;
|
||||
_a[1] /= stretch;
|
||||
_a[2] /= stretch;
|
||||
axis = _a;
|
||||
}
|
||||
const rate = spin?.[name];
|
||||
const fraction = deploy?.[name];
|
||||
let moves = false;
|
||||
_q.fill(0);
|
||||
_q[3] = 1;
|
||||
_t.fill(0);
|
||||
if (
|
||||
axis !== null &&
|
||||
typeof rate === 'number' &&
|
||||
rate !== 0 &&
|
||||
Number.isFinite(rate * timeS)
|
||||
) {
|
||||
// Reduced in doubles first: a rate times an epoch clock is a large
|
||||
// number of degrees.
|
||||
axisAngle(_q, axis, (rate * timeS) % 360);
|
||||
moves = true;
|
||||
}
|
||||
if (
|
||||
axis !== null &&
|
||||
part.limits !== null &&
|
||||
typeof fraction === 'number' &&
|
||||
Number.isFinite(fraction)
|
||||
) {
|
||||
const by = deployedBy(part, fraction);
|
||||
if (by !== 0 && TURNS.has(part.kind)) {
|
||||
axisAngle(_p, axis, by);
|
||||
multiplyInto(_q, _p);
|
||||
moves = true;
|
||||
} else if (by !== 0 && MOVES.has(part.kind)) {
|
||||
_t[0] = axis[0] * by * stretch;
|
||||
_t[1] = axis[1] * by * stretch;
|
||||
_t[2] = axis[2] * by * stretch;
|
||||
moves = true;
|
||||
}
|
||||
}
|
||||
if (pose !== undefined && pose !== null && isPosed(pose)) {
|
||||
// Pose over the rest: R = Rpose · R, t = tpose + Rpose · t.
|
||||
poseInto(_r, _v, pose);
|
||||
if (scaled) for (let i = 0; i < 3; i++) _v[i] = _v[i] * _s[i];
|
||||
rotateInto(_r, _t);
|
||||
_t[0] = _t[0] + _v[0];
|
||||
_t[1] = _t[1] + _v[1];
|
||||
_t[2] = _t[2] + _v[2];
|
||||
multiplyInto(_r, _q);
|
||||
_q.set(_r);
|
||||
moves = true;
|
||||
}
|
||||
if (moves && part.limits !== null && axis !== null) {
|
||||
if (part.kind === 'hinge' || part.kind === 'deploy')
|
||||
clampTwist(_q, axis, part.rest, part.limits);
|
||||
else if (part.kind === 'slide') {
|
||||
// Along the axis in the model's own metres, which its limits are in.
|
||||
const along =
|
||||
(_t[0] * axis[0] + _t[1] * axis[1] + _t[2] * axis[2]) / stretch;
|
||||
const lo = Math.min(part.limits[0], part.limits[1]) - part.rest;
|
||||
const hi = Math.max(part.limits[0], part.limits[1]) - part.rest;
|
||||
const shift = (Math.min(hi, Math.max(lo, along)) - along) * stretch;
|
||||
_t[0] = _t[0] + axis[0] * shift;
|
||||
_t[1] = _t[1] + axis[1] * shift;
|
||||
_t[2] = _t[2] + axis[2] * shift;
|
||||
}
|
||||
}
|
||||
anyPosed ||= moves;
|
||||
const w = k * 12;
|
||||
if (moves) {
|
||||
// Local L = R and p + t − R p, about the pivot.
|
||||
let [px, py, pz] = part.pivot;
|
||||
if (scaled) {
|
||||
px *= _s[0];
|
||||
py *= _s[1];
|
||||
pz *= _s[2];
|
||||
}
|
||||
_v[0] = px;
|
||||
_v[1] = py;
|
||||
_v[2] = pz;
|
||||
rotateInto(_q, _v);
|
||||
_t[0] = _t[0] + px - _v[0];
|
||||
_t[1] = _t[1] + py - _v[1];
|
||||
_t[2] = _t[2] + pz - _v[2];
|
||||
}
|
||||
if (parentIndex < 0) affineInto(_q, _t, world, w);
|
||||
else if (!moves)
|
||||
world.copyWithin(w, parentIndex * 12, parentIndex * 12 + 12);
|
||||
else {
|
||||
// World = parent's world · local.
|
||||
affineInto(_q, _t, _local, 0);
|
||||
const b = parentIndex * 12;
|
||||
for (let row = 0; row < 3; row++) {
|
||||
const a0 = world[b + row * 3];
|
||||
const a1 = world[b + row * 3 + 1];
|
||||
const a2 = world[b + row * 3 + 2];
|
||||
world[w + row * 3] = a0 * _local[0] + a1 * _local[3] + a2 * _local[6];
|
||||
world[w + row * 3 + 1] =
|
||||
a0 * _local[1] + a1 * _local[4] + a2 * _local[7];
|
||||
world[w + row * 3 + 2] =
|
||||
a0 * _local[2] + a1 * _local[5] + a2 * _local[8];
|
||||
world[w + 9 + row] =
|
||||
a0 * _local[9] +
|
||||
a1 * _local[10] +
|
||||
a2 * _local[11] +
|
||||
world[b + 9 + row];
|
||||
}
|
||||
}
|
||||
if (!scaled) writeMatrix(world, w, out, offset + k * 16);
|
||||
else {
|
||||
// X = S⁻¹ · World · S.
|
||||
for (let row = 0; row < 3; row++) {
|
||||
for (let col = 0; col < 3; col++)
|
||||
_local[row * 3 + col] =
|
||||
(world[w + row * 3 + col] * _s[col]) / _s[row];
|
||||
_local[9 + row] = world[w + 9 + row] / _s[row];
|
||||
}
|
||||
writeMatrix(_local, 0, out, offset + k * 16);
|
||||
}
|
||||
}
|
||||
return anyPosed;
|
||||
}
|
||||
|
||||
/** Write the affine `m` (12 numbers from `at`: R row-major, then t) as a column-major 4×4 into `out` at `to`. */
|
||||
function writeMatrix(m, at, out, to) {
|
||||
for (let col = 0; col < 3; col++) {
|
||||
out[to + col * 4] = m[at + col];
|
||||
out[to + col * 4 + 1] = m[at + 3 + col];
|
||||
out[to + col * 4 + 2] = m[at + 6 + col];
|
||||
out[to + col * 4 + 3] = 0;
|
||||
}
|
||||
out[to + 12] = m[at + 9];
|
||||
out[to + 13] = m[at + 10];
|
||||
out[to + 14] = m[at + 11];
|
||||
out[to + 15] = 1;
|
||||
}
|
||||
@@ -0,0 +1,573 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import { describe, test } from 'node:test';
|
||||
|
||||
import {
|
||||
gltfMeshMatrix,
|
||||
PART_HIDDEN,
|
||||
PART_HIGHLIGHT,
|
||||
partMatrices,
|
||||
partTableOf,
|
||||
readPartTable,
|
||||
asksHighlight,
|
||||
} from './modelParts.js';
|
||||
|
||||
/** `m` (column-major 4×4 at `at`) times the point `p`. */
|
||||
function apply(m, at, p) {
|
||||
const out = [0, 0, 0];
|
||||
for (let row = 0; row < 3; row++)
|
||||
out[row] =
|
||||
m[at + row] * p[0] +
|
||||
m[at + 4 + row] * p[1] +
|
||||
m[at + 8 + row] * p[2] +
|
||||
m[at + 12 + row];
|
||||
return out;
|
||||
}
|
||||
|
||||
function close(actual, expected, digits = 6) {
|
||||
assert.equal(actual.length, expected.length);
|
||||
const tolerance = 10 ** -digits / 2;
|
||||
actual.forEach((value, i) =>
|
||||
assert.ok(
|
||||
Math.abs(value - expected[i]) <= tolerance,
|
||||
`[${i}] ${value} is not ${expected[i]}`,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
const IDENTITY = [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1];
|
||||
|
||||
/** A model in the glTF frame (nose −X, Y up, right −Z). */
|
||||
const TABLE = partTableOf({
|
||||
parts: [
|
||||
{ name: 'body', kind: 'body' },
|
||||
// Nose gear: stowed at 90, down at 0, turning about +Z through a point ahead and below.
|
||||
{
|
||||
name: 'gear_nose',
|
||||
kind: 'hinge',
|
||||
pivot: [-10, -1, 0],
|
||||
axis: [0, 0, 1],
|
||||
limits: [90, 0],
|
||||
},
|
||||
// A flap about the right axis (−Z), 0 to 40 degrees, drawn at 0.
|
||||
{
|
||||
name: 'flap',
|
||||
kind: 'hinge',
|
||||
pivot: [2, 0, -3],
|
||||
axis: [0, 0, -1],
|
||||
limits: [0, 40],
|
||||
},
|
||||
{ name: 'engine', kind: 'marker', pivot: [0, -2, -5] },
|
||||
{
|
||||
name: 'fan',
|
||||
kind: 'spin',
|
||||
parent: 'engine',
|
||||
pivot: [-2, -2, -5],
|
||||
axis: [1, 0, 0],
|
||||
},
|
||||
{
|
||||
name: 'stage_1',
|
||||
kind: 'separable',
|
||||
pivot: [0, 40, 0],
|
||||
axis: [0, -1, 0],
|
||||
limits: [0, 30],
|
||||
},
|
||||
{
|
||||
name: 'leg_1',
|
||||
kind: 'hinge',
|
||||
parent: 'stage_1',
|
||||
pivot: [1, 1, 0],
|
||||
axis: [0, 0, -1],
|
||||
limits: [0, 110],
|
||||
},
|
||||
{
|
||||
name: 'door',
|
||||
kind: 'slide',
|
||||
pivot: [0, 0, 1],
|
||||
axis: [2, 0, 0],
|
||||
limits: [0, 1.5],
|
||||
},
|
||||
{
|
||||
name: 'panel',
|
||||
kind: 'deploy',
|
||||
pivot: [0, 0, 4],
|
||||
axis: [1, 0, 0],
|
||||
limits: [90, 0],
|
||||
rest: 0,
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
function matrices(state, timeS = 0) {
|
||||
const out = new Float64Array(TABLE.parts.length * 16);
|
||||
const flags = new Uint8Array(TABLE.parts.length);
|
||||
const posed = partMatrices(TABLE, state, timeS, out, { flags });
|
||||
const at = (name) => TABLE.byName.get(name) * 16;
|
||||
return { out, flags, posed, at };
|
||||
}
|
||||
|
||||
const slice = (out, at) => Array.from(out.subarray(at, at + 16));
|
||||
|
||||
describe('partTableOf', () => {
|
||||
test('reads a table with its defaults', () => {
|
||||
assert.deepEqual(
|
||||
TABLE.parts.map((p) => p.name),
|
||||
[
|
||||
'body',
|
||||
'gear_nose',
|
||||
'flap',
|
||||
'engine',
|
||||
'fan',
|
||||
'stage_1',
|
||||
'leg_1',
|
||||
'door',
|
||||
'panel',
|
||||
],
|
||||
);
|
||||
const body = TABLE.parts[0];
|
||||
assert.equal(body.kind, 'body');
|
||||
assert.equal(body.parent, null);
|
||||
assert.equal(body.parentIndex, -1);
|
||||
assert.deepEqual(body.pivot, [0, 0, 0]);
|
||||
assert.equal(body.axis, null);
|
||||
assert.equal(body.limits, null);
|
||||
assert.equal(body.rest, null);
|
||||
// `rest` is the stowed limit unless given; `parent` is the body unless given.
|
||||
assert.equal(TABLE.parts[1].parent, 'body');
|
||||
assert.equal(TABLE.parts[1].parentIndex, 0);
|
||||
assert.equal(TABLE.parts[1].rest, 90);
|
||||
assert.deepEqual(TABLE.parts[8].limits, [90, 0]);
|
||||
assert.equal(TABLE.parts[8].rest, 0);
|
||||
assert.equal(TABLE.parts[4].parent, 'engine');
|
||||
assert.equal(TABLE.parts[4].parentIndex, 3);
|
||||
assert.equal(TABLE.parts[4].rest, null);
|
||||
// The axis is made unit length.
|
||||
assert.deepEqual(TABLE.parts[7].axis, [1, 0, 0]);
|
||||
assert.equal(TABLE.byName.get('leg_1'), 6);
|
||||
});
|
||||
|
||||
test('a model without a table has none', () => {
|
||||
assert.equal(partTableOf(undefined), null);
|
||||
assert.equal(partTableOf({}), null);
|
||||
assert.equal(partTableOf({ other: 1 }), null);
|
||||
});
|
||||
|
||||
const body = { name: 'body', kind: 'body' };
|
||||
for (const [extras, message] of [
|
||||
[{ parts: [] }, /list of parts/],
|
||||
[{ parts: [{ name: 'hull', kind: 'marker' }] }, /body/],
|
||||
[{ parts: [body, { name: 'x', kind: 'wobble' }] }, /kind wobble/],
|
||||
[{ parts: [body, { name: 'body', kind: 'marker' }] }, /twice/],
|
||||
[
|
||||
{ parts: [body, { name: 'a', kind: 'marker', parent: 'b' }] },
|
||||
/not an earlier part/,
|
||||
],
|
||||
[{ parts: [body, { name: 'a', kind: 'spin', axis: [0, 0] }] }, /axis/],
|
||||
[
|
||||
{ parts: [body, { name: 'a', kind: 'spin', axis: [0, 0, 0] }] },
|
||||
/zero axis/,
|
||||
],
|
||||
[{ parts: [body, { name: 'a', kind: 'hinge', limits: [0] }] }, /limits/],
|
||||
])
|
||||
test(`refuses a malformed table (${message})`, () => {
|
||||
assert.throws(() => partTableOf(extras), message);
|
||||
});
|
||||
});
|
||||
|
||||
/** A GLB of `json` and no binary chunk. */
|
||||
function glb(json) {
|
||||
let text = new TextEncoder().encode(JSON.stringify(json));
|
||||
const padded = new Uint8Array(Math.ceil(text.length / 4) * 4).fill(0x20);
|
||||
padded.set(text);
|
||||
text = padded;
|
||||
const out = new Uint8Array(20 + text.length);
|
||||
const view = new DataView(out.buffer);
|
||||
view.setUint32(0, 0x46546c67, true);
|
||||
view.setUint32(4, 2, true);
|
||||
view.setUint32(8, out.length, true);
|
||||
view.setUint32(12, text.length, true);
|
||||
view.setUint32(16, 0x4e4f534a, true);
|
||||
out.set(text, 20);
|
||||
return out;
|
||||
}
|
||||
|
||||
describe('readPartTable', () => {
|
||||
test('reads the table of the scene’s root node', () => {
|
||||
const extras = {
|
||||
parts: [
|
||||
{ name: 'body', kind: 'body' },
|
||||
{ name: 'radar', kind: 'spin' },
|
||||
],
|
||||
};
|
||||
const bytes = glb({
|
||||
scene: 0,
|
||||
scenes: [{ nodes: [1] }],
|
||||
nodes: [
|
||||
{ extras: { parts: [{ name: 'body', kind: 'body' }] } },
|
||||
{ mesh: 0, extras },
|
||||
],
|
||||
});
|
||||
assert.deepEqual(
|
||||
readPartTable(bytes).parts.map((p) => p.name),
|
||||
['body', 'radar'],
|
||||
);
|
||||
assert.equal(readPartTable(bytes.buffer).parts.length, 2);
|
||||
});
|
||||
|
||||
test('a model that is only its body has none', () => {
|
||||
assert.equal(
|
||||
readPartTable(glb({ scenes: [{ nodes: [0] }], nodes: [{ mesh: 0 }] })),
|
||||
null,
|
||||
);
|
||||
});
|
||||
|
||||
test('refuses bytes that are not a GLB', () => {
|
||||
assert.throws(
|
||||
() => readPartTable(new TextEncoder().encode('glTF but not really')),
|
||||
/GLB/,
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe('gltfMeshMatrix', () => {
|
||||
test('the mesh node’s transform with its parents’', () => {
|
||||
const m = gltfMeshMatrix({
|
||||
scenes: [{ nodes: [0] }],
|
||||
nodes: [
|
||||
{ translation: [1, 2, 3], children: [1] },
|
||||
// A packed model's dequantization: a scale and an offset.
|
||||
{ mesh: 0, translation: [0, 2, 0], scale: [10, 10, 10] },
|
||||
],
|
||||
});
|
||||
close(apply(m, 0, [1, 0, 0]), [11, 4, 3]);
|
||||
close(apply(m, 0, [0, -1, 0]), [1, -6, 3]);
|
||||
});
|
||||
|
||||
test('turned by a node’s rotation', () => {
|
||||
// 90 degrees about +Y: +X turns to −Z.
|
||||
const s = Math.SQRT1_2;
|
||||
const m = gltfMeshMatrix({
|
||||
nodes: [{ mesh: 0, rotation: [0, s, 0, s] }],
|
||||
});
|
||||
close(apply(m, 0, [1, 0, 0]), [0, 0, -1]);
|
||||
});
|
||||
|
||||
test('the identity without a mesh', () => {
|
||||
assert.deepEqual(gltfMeshMatrix({ nodes: [{}] }), IDENTITY);
|
||||
});
|
||||
});
|
||||
|
||||
describe('partMatrices', () => {
|
||||
test('no state, or an empty one, leaves every part at rest', () => {
|
||||
for (const state of [null, {}, { poses: {}, spin: {}, deploy: {} }]) {
|
||||
const { out, flags, posed } = matrices(state);
|
||||
assert.equal(posed, false);
|
||||
for (let k = 0; k < TABLE.parts.length; k++)
|
||||
assert.deepEqual(slice(out, k * 16), IDENTITY);
|
||||
assert.deepEqual(
|
||||
Array.from(flags),
|
||||
new Array(TABLE.parts.length).fill(0),
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
test('a hinge turns about its pivot, off the origin', () => {
|
||||
// Deployed: from 90 (as drawn) to 0, so −90 degrees about +Z through [-10, -1, 0].
|
||||
const { out, at, posed } = matrices({ deploy: { gear_nose: 1 } });
|
||||
assert.equal(posed, true);
|
||||
close(apply(out, at('gear_nose'), [-10, -1, 0]), [-10, -1, 0]);
|
||||
// 2 m along −Y from the pivot turns to 2 m along −X.
|
||||
close(apply(out, at('gear_nose'), [-10, -3, 0]), [-12, -1, 0]);
|
||||
// Halfway is 45 degrees.
|
||||
const half = matrices({ deploy: { gear_nose: 0.5 } });
|
||||
const s = Math.SQRT1_2 * 2;
|
||||
close(apply(half.out, half.at('gear_nose'), [-10, -3, 0]), [
|
||||
-10 - s,
|
||||
-1 - s,
|
||||
0,
|
||||
]);
|
||||
// Other parts stay at rest.
|
||||
assert.deepEqual(slice(out, at('flap')), IDENTITY);
|
||||
});
|
||||
|
||||
test('a hinge’s pose is clamped to its limits, its swing left free', () => {
|
||||
// The flap's axis is the model's right, so pitch turns it: 0 to 40 degrees.
|
||||
const tip = [3, 0, -3];
|
||||
const turned = (deg) => [
|
||||
2 + Math.cos(deg * (Math.PI / 180)),
|
||||
// Nose up: what is behind the hinge goes down.
|
||||
-Math.sin(deg * (Math.PI / 180)),
|
||||
-3,
|
||||
];
|
||||
for (const [pitch, expected] of [
|
||||
[25, 25],
|
||||
[60, 40],
|
||||
[-10, 0],
|
||||
[400, 40],
|
||||
]) {
|
||||
const { out, at } = matrices({ poses: { flap: { pitchDeg: pitch } } });
|
||||
close(apply(out, at('flap'), tip), turned(expected));
|
||||
}
|
||||
// A roll is about the forward axis, not the hinge's: kept as posed.
|
||||
const rolled = matrices({ poses: { flap: { rollDeg: 90 } } });
|
||||
close(apply(rolled.out, rolled.at('flap'), [2, 1, -3]), [2, 0, -4]);
|
||||
});
|
||||
|
||||
test('the deploy fraction is clamped to 0..1, and a pose adds to it within limits', () => {
|
||||
const over = matrices({ deploy: { gear_nose: 3 } });
|
||||
const full = matrices({ deploy: { gear_nose: 1 } });
|
||||
close(Array.from(over.out), Array.from(full.out));
|
||||
// The gear down (0) and pitched 30 more (−30 about its +Z axis): still
|
||||
// 0, its limit; pitched the other way, it comes 30 back up.
|
||||
const past = matrices({
|
||||
deploy: { gear_nose: 1 },
|
||||
poses: { gear_nose: { pitchDeg: 30 } },
|
||||
});
|
||||
close(Array.from(past.out), Array.from(full.out));
|
||||
const back = matrices({
|
||||
deploy: { gear_nose: 1 },
|
||||
poses: { gear_nose: { pitchDeg: -30 } },
|
||||
});
|
||||
const thirty = matrices({ deploy: { gear_nose: 1 - 30 / 90 } });
|
||||
close(Array.from(back.out), Array.from(thirty.out));
|
||||
// A deploy part drawn deployed (rest 0) stows to 90 about +X.
|
||||
const stowed = matrices({ deploy: { panel: 0 } });
|
||||
close(apply(stowed.out, stowed.at('panel'), [0, 1, 4]), [0, 0, 5]);
|
||||
});
|
||||
|
||||
test('a child part rides its parent', () => {
|
||||
// The engine moved 1 m up: its fan, at rest about its own hub, moves with it.
|
||||
const { out, at } = matrices({ poses: { engine: { offsetM: [0, 0, 1] } } });
|
||||
close(apply(out, at('engine'), [0, -2, -5]), [0, -1, -5]);
|
||||
close(apply(out, at('fan'), [-2, -2, -5]), [-2, -1, -5]);
|
||||
// Spinning too: the hub stays on the moved axis, a blade tip turns about it.
|
||||
const spun = matrices(
|
||||
{ poses: { engine: { offsetM: [0, 0, 1] } }, spin: { fan: 90 } },
|
||||
1,
|
||||
);
|
||||
close(apply(spun.out, spun.at('fan'), [-2, -2, -5]), [-2, -1, -5]);
|
||||
// +90 about +X: +Y turns to +Z.
|
||||
close(apply(spun.out, spun.at('fan'), [-2, -1, -5]), [-2, -1, -4]);
|
||||
});
|
||||
|
||||
test('a child hinge turns about its pivot as carried by its parent', () => {
|
||||
const { out, at } = matrices({ deploy: { stage_1: 1, leg_1: 1 } });
|
||||
// The stage leaves 30 m along −Y; the leg's hinge goes with it and turns 110 about −Z there.
|
||||
close(apply(out, at('leg_1'), [1, 1, 0]), [1, -29, 0]);
|
||||
const deg = 110 * (Math.PI / 180);
|
||||
close(apply(out, at('leg_1'), [1, 2, 0]), [
|
||||
1 + Math.sin(deg),
|
||||
-29 + Math.cos(deg),
|
||||
0,
|
||||
]);
|
||||
});
|
||||
|
||||
test('a spin turns at its rate over time', () => {
|
||||
const tip = [-2, -1, -5];
|
||||
const at = (timeS) => {
|
||||
const m = matrices({ spin: { fan: 90 } }, timeS);
|
||||
return apply(m.out, m.at('fan'), tip);
|
||||
};
|
||||
close(at(0), tip);
|
||||
close(at(1), [-2, -2, -4]);
|
||||
close(at(2), [-2, -3, -5]);
|
||||
close(at(4), tip);
|
||||
// A rate times an epoch clock still lands where it should.
|
||||
close(at(1_700_000_000), tip, 4);
|
||||
close(at(1_700_000_001), [-2, -2, -4], 4);
|
||||
// A spin driving a part with no axis does nothing.
|
||||
assert.equal(matrices({ spin: { engine: 90 } }, 1).posed, false);
|
||||
});
|
||||
|
||||
test('a separable part moves freely: its limits bound only the deploy fraction', () => {
|
||||
const half = matrices({ deploy: { stage_1: 0.5 } });
|
||||
close(apply(half.out, half.at('stage_1'), [0, 40, 0]), [0, 25, 0]);
|
||||
// Posed 500 m right and turned, past any limit (right is −Z).
|
||||
const { out, at } = matrices({
|
||||
poses: { stage_1: { offsetM: [500, 0, -200], yawDeg: 30 } },
|
||||
});
|
||||
close(apply(out, at('stage_1'), [0, 40, 0]), [0, -160, -500]);
|
||||
});
|
||||
|
||||
test('a slide is clamped along its axis, free across it', () => {
|
||||
// The door slides along +X (the model's back) 0 to 1.5 m; offsetM is [right, forward, up].
|
||||
const back = (metres) =>
|
||||
matrices({ poses: { door: { offsetM: [0, -metres, 0] } } });
|
||||
close(apply(back(1).out, back(1).at('door'), [0, 0, 1]), [1, 0, 1]);
|
||||
close(apply(back(9).out, back(9).at('door'), [0, 0, 1]), [1.5, 0, 1]);
|
||||
close(apply(back(-2).out, back(-2).at('door'), [0, 0, 1]), [0, 0, 1]);
|
||||
const up = matrices({ poses: { door: { offsetM: [0, -9, 2] } } });
|
||||
close(apply(up.out, up.at('door'), [0, 0, 1]), [1.5, 2, 1]);
|
||||
});
|
||||
|
||||
test('hidden hides the part and every part riding it', () => {
|
||||
const { out, flags, at, posed } = matrices({
|
||||
poses: { engine: { hidden: true } },
|
||||
});
|
||||
assert.equal(posed, true);
|
||||
assert.deepEqual(slice(out, at('engine')), new Array(16).fill(0));
|
||||
assert.deepEqual(slice(out, at('fan')), new Array(16).fill(0));
|
||||
assert.equal(flags[TABLE.byName.get('engine')], PART_HIDDEN);
|
||||
assert.equal(flags[TABLE.byName.get('fan')], PART_HIDDEN);
|
||||
assert.equal(flags[TABLE.byName.get('flap')], 0);
|
||||
assert.deepEqual(slice(out, at('flap')), IDENTITY);
|
||||
});
|
||||
|
||||
test('highlight marks the part alone, and does not move it', () => {
|
||||
const { out, flags, posed } = matrices({
|
||||
poses: { engine: { highlight: '#ff0' } },
|
||||
});
|
||||
assert.equal(posed, true);
|
||||
assert.equal(flags[TABLE.byName.get('engine')], PART_HIGHLIGHT);
|
||||
assert.equal(flags[TABLE.byName.get('fan')], 0);
|
||||
for (let k = 0; k < TABLE.parts.length; k++)
|
||||
assert.deepEqual(slice(out, k * 16), IDENTITY);
|
||||
assert.equal(
|
||||
matrices({ poses: { engine: { highlight: false } } }).posed,
|
||||
false,
|
||||
);
|
||||
});
|
||||
|
||||
test('a highlight is true or a colour; anything else asks for none', () => {
|
||||
for (const value of [true, '#ff0', 'red', [1, 0.5, 0], [1, 0, 0, 0.5]])
|
||||
assert.equal(asksHighlight(value), true, String(value));
|
||||
for (const value of [
|
||||
false,
|
||||
'',
|
||||
' ',
|
||||
0,
|
||||
1,
|
||||
null,
|
||||
undefined,
|
||||
{},
|
||||
[1, 0],
|
||||
[1, 'x', 0],
|
||||
[NaN, 0, 0],
|
||||
])
|
||||
assert.equal(asksHighlight(value), false, String(value));
|
||||
assert.equal(
|
||||
matrices({ poses: { engine: { highlight: '' } } }).posed,
|
||||
false,
|
||||
);
|
||||
assert.equal(
|
||||
matrices({ poses: { engine: { highlight: 0 } } }).posed,
|
||||
false,
|
||||
);
|
||||
});
|
||||
|
||||
test('a pose value that is not finite counts as 0', () => {
|
||||
const { out, posed } = matrices({
|
||||
poses: {
|
||||
engine: {
|
||||
yawDeg: NaN,
|
||||
pitchDeg: Infinity,
|
||||
rollDeg: -Infinity,
|
||||
offsetM: [NaN, Infinity, undefined],
|
||||
},
|
||||
},
|
||||
});
|
||||
assert.equal(posed, false);
|
||||
for (let k = 0; k < TABLE.parts.length; k++)
|
||||
assert.deepEqual(slice(out, k * 16), IDENTITY);
|
||||
// Beside a finite one, it is still 0 and no NaN is written.
|
||||
const mixed = matrices({
|
||||
poses: { engine: { yawDeg: 90, pitchDeg: NaN, offsetM: [NaN, 0, 1] } },
|
||||
});
|
||||
assert.equal(mixed.posed, true);
|
||||
assert.ok(mixed.out.every(Number.isFinite));
|
||||
});
|
||||
|
||||
test('names the table does not have are ignored', () => {
|
||||
const { posed } = matrices({
|
||||
poses: { rotor_main: { yawDeg: 30, hidden: true } },
|
||||
spin: { rotor_main: 100 },
|
||||
deploy: { gear_main: 1 },
|
||||
});
|
||||
assert.equal(posed, false);
|
||||
});
|
||||
|
||||
test('writes from an offset, into float32', () => {
|
||||
const out = new Float32Array(16 + TABLE.parts.length * 16).fill(7);
|
||||
const flags = new Uint8Array(3 + TABLE.parts.length).fill(9);
|
||||
partMatrices(TABLE, { poses: { flap: { hidden: true } } }, 0, out, {
|
||||
offset: 16,
|
||||
flags,
|
||||
flagsOffset: 3,
|
||||
});
|
||||
assert.deepEqual(Array.from(out.subarray(0, 16)), new Array(16).fill(7));
|
||||
assert.deepEqual(Array.from(out.subarray(16, 32)), IDENTITY);
|
||||
assert.deepEqual(Array.from(flags.subarray(0, 3)), [9, 9, 9]);
|
||||
assert.equal(flags[3 + TABLE.byName.get('flap')], PART_HIDDEN);
|
||||
});
|
||||
});
|
||||
|
||||
describe('partMatrices on a stretched model', () => {
|
||||
/** Where `p` is drawn by a model stretched `scale` whose part is `out`'s matrix at `at`: S · X · p. */
|
||||
const drawnAt = (out, at, scale, p) => {
|
||||
const x = apply(out, at, p);
|
||||
return [x[0] * scale[0], x[1] * scale[1], x[2] * scale[2]];
|
||||
};
|
||||
const RADAR = partTableOf({
|
||||
parts: [
|
||||
{ name: 'body', kind: 'body' },
|
||||
{ name: 'radar', kind: 'spin', pivot: [5, 3, 0], axis: [0, 1, 0] },
|
||||
],
|
||||
});
|
||||
const length = (a, b) => Math.hypot(a[0] - b[0], a[1] - b[1], a[2] - b[2]);
|
||||
|
||||
test('a radar on a hull drawn twice its length keeps its length at every angle', () => {
|
||||
const scale = [2, 1, 1];
|
||||
const hub = [5, 3, 0];
|
||||
const tip = [6, 3, 0];
|
||||
const state = { spin: { radar: 30 } };
|
||||
for (let timeS = 0; timeS < 12; timeS++) {
|
||||
const out = new Float64Array(32);
|
||||
partMatrices(RADAR, state, timeS, out, { scale });
|
||||
const h = drawnAt(out, 16, scale, hub);
|
||||
const t = drawnAt(out, 16, scale, tip);
|
||||
// The hub stays where the stretched hull draws it; the 1 m arm is drawn 2 m long.
|
||||
close(h, [10, 3, 0]);
|
||||
assert.ok(Math.abs(length(t, h) - 2) < 1e-9);
|
||||
}
|
||||
// Unscaled matrices under the same stretch distort it: 1 m long across the hull.
|
||||
const naive = new Float64Array(32);
|
||||
partMatrices(RADAR, state, 3, naive);
|
||||
const h = drawnAt(naive, 16, scale, hub);
|
||||
const t = drawnAt(naive, 16, scale, tip);
|
||||
assert.ok(Math.abs(length(t, h) - 1) < 1e-9);
|
||||
});
|
||||
|
||||
test('a hinge turns rigidly about its stretched pivot', () => {
|
||||
const scale = [1, 3, 1];
|
||||
const out = new Float64Array(TABLE.parts.length * 16);
|
||||
partMatrices(TABLE, { deploy: { gear_nose: 1 } }, 0, out, { scale });
|
||||
const at = TABLE.byName.get('gear_nose') * 16;
|
||||
close(drawnAt(out, at, scale, [-10, -1, 0]), [-10, -3, 0]);
|
||||
close(drawnAt(out, at, scale, [-10, -3, 0]), [-16, -3, 0]);
|
||||
});
|
||||
|
||||
test('a slide keeps its limits in the model’s own metres', () => {
|
||||
const scale = [2, 1, 1];
|
||||
const out = new Float64Array(TABLE.parts.length * 16);
|
||||
// Offsets are stretched with the model: 9 m back asked, 1.5 m allowed, drawn 3 m.
|
||||
partMatrices(TABLE, { poses: { door: { offsetM: [0, -9, 0] } } }, 0, out, {
|
||||
scale,
|
||||
});
|
||||
close(
|
||||
drawnAt(out, TABLE.byName.get('door') * 16, scale, [0, 0, 1]),
|
||||
[3, 0, 1],
|
||||
);
|
||||
});
|
||||
|
||||
test('a scale of one, or none, writes the same matrices', () => {
|
||||
const state = {
|
||||
deploy: { gear_nose: 0.3, stage_1: 1, leg_1: 0.5 },
|
||||
spin: { fan: 33 },
|
||||
poses: { engine: { offsetM: [1, 2, 3], yawDeg: 10 } },
|
||||
};
|
||||
const a = new Float64Array(TABLE.parts.length * 16);
|
||||
const b = new Float64Array(TABLE.parts.length * 16);
|
||||
partMatrices(TABLE, state, 1.5, a);
|
||||
partMatrices(TABLE, state, 1.5, b, { scale: [1, 1, 1] });
|
||||
assert.deepEqual(Array.from(b), Array.from(a));
|
||||
});
|
||||
});
|
||||
@@ -29,6 +29,7 @@ const NEUTRAL = [
|
||||
'./render/vectorBase',
|
||||
'./render/iconSegment',
|
||||
'./render/recession',
|
||||
'./render/modelParts',
|
||||
'./render/windStreamlines',
|
||||
'./render/weather',
|
||||
'./weather/effects',
|
||||
|
||||
Reference in new issue
Block a user