@margoengine/animation 0.0.0-stage → 1.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +201 -0
- package/NOTICE +4 -0
- package/README.md +1172 -2
- package/dist/batch.d.ts +162 -0
- package/dist/clip-utils.d.ts +50 -0
- package/dist/clip-utils.js +1 -0
- package/dist/clone.d.ts +15 -0
- package/dist/cor.d.ts +52 -0
- package/dist/cor.js +17 -0
- package/dist/deform-readers-DmYAkvBK.js +1 -0
- package/dist/deform-readers.d.ts +5 -0
- package/dist/deformed-points.d.ts +87 -0
- package/dist/deformed-points.js +17 -0
- package/dist/discrete-tracks.d.ts +102 -0
- package/dist/discrete-tracks.js +1 -0
- package/dist/dqs.d.ts +42 -0
- package/dist/dqs.js +29 -0
- package/dist/errors-t1ewumJS.js +1 -0
- package/dist/geometry-cache.d.ts +208 -0
- package/dist/geometry-cache.js +4 -0
- package/dist/gltf-C2HVNxzB.js +1 -0
- package/dist/gltf.d.ts +63 -0
- package/dist/group.d.ts +97 -0
- package/dist/hdr-format-cmvLFubB.js +1 -0
- package/dist/index.d.ts +203 -0
- package/dist/index.js +1 -0
- package/dist/instanced-morph.d.ts +82 -0
- package/dist/instanced-morph.js +13 -0
- package/dist/instanced-skin.d.ts +82 -0
- package/dist/instanced-skin.js +43 -0
- package/dist/interactivity.d.ts +71 -0
- package/dist/interactivity.js +4 -0
- package/dist/key-cursor.d.ts +23 -0
- package/dist/keyframes-YpidiYS4.js +4 -0
- package/dist/keyframes.d.ts +204 -0
- package/dist/lod.d.ts +87 -0
- package/dist/lod.js +4 -0
- package/dist/material-animation.d.ts +29 -0
- package/dist/mixer.d.ts +226 -0
- package/dist/mixer.js +4 -0
- package/dist/morph-gpu.d.ts +94 -0
- package/dist/morph-gpu.js +50 -0
- package/dist/morph-table.d.ts +29 -0
- package/dist/playback.d.ts +94 -0
- package/dist/playback.js +4 -0
- package/dist/point-cache.d.ts +28 -0
- package/dist/point-cache.js +1 -0
- package/dist/pointer-DyWpFsQi.js +1 -0
- package/dist/pointer.d.ts +43 -0
- package/dist/pointer.js +1 -0
- package/dist/pose-source-MuCl8VDd.js +1 -0
- package/dist/pose.d.ts +12 -0
- package/dist/require-webgpu-Jrqt3Xy4.js +1 -0
- package/dist/retarget.d.ts +115 -0
- package/dist/rigid.d.ts +42 -0
- package/dist/sampling-DjDWYqt2.js +1 -0
- package/dist/sampling.d.ts +112 -0
- package/dist/sampling.js +1 -0
- package/dist/shader-DuGkHFKx.js +73 -0
- package/dist/shader.d.ts +62 -0
- package/dist/skeleton-utils.d.ts +2 -0
- package/dist/skeleton-utils.js +4 -0
- package/dist/skin.d.ts +163 -0
- package/dist/src-fuuIJ3rU.js +4 -0
- package/dist/vat-SpfL7y9U.js +53 -0
- package/dist/vat.d.ts +194 -0
- package/dist/vat.js +1 -0
- package/dist/vertex-map-BC_WH7ER.js +1 -0
- package/dist/weight-buffer.d.ts +1 -0
- package/package.json +139 -4
package/dist/batch.d.ts
ADDED
|
@@ -0,0 +1,162 @@
|
|
|
1
|
+
import type { PBRPrimitive } from '@margoengine/gltf/pbr';
|
|
2
|
+
import { type SkinningMode } from './shader.js';
|
|
3
|
+
/** A run of elements in one pool. */
|
|
4
|
+
interface Range {
|
|
5
|
+
offset: number;
|
|
6
|
+
size: number;
|
|
7
|
+
/** Slots naming this range: a bone palette is shared by the primitives of one skinned node (see `add`). */
|
|
8
|
+
refs?: number;
|
|
9
|
+
}
|
|
10
|
+
/** Immutable data every copy of a primitive reads (bind-pose vertices, morph deltas, skin influences), held once. */
|
|
11
|
+
interface Block {
|
|
12
|
+
range: Range;
|
|
13
|
+
refs: number;
|
|
14
|
+
key: string;
|
|
15
|
+
owner: Map<string, Block>;
|
|
16
|
+
/** The two keys above `owner` in the page's `blocks`, dropped with the last block so the page holds no dead asset. */
|
|
17
|
+
asset: object;
|
|
18
|
+
holder: object;
|
|
19
|
+
}
|
|
20
|
+
/** One storage buffer of a page and the ranges living in it. */
|
|
21
|
+
declare class Pool {
|
|
22
|
+
readonly bytes: number;
|
|
23
|
+
readonly usage: number;
|
|
24
|
+
/** Ranges start on a multiple of this many elements. */
|
|
25
|
+
readonly align: number;
|
|
26
|
+
buffer?: GPUBuffer;
|
|
27
|
+
capacity: number;
|
|
28
|
+
top: number;
|
|
29
|
+
readonly ranges: Set<Range>;
|
|
30
|
+
constructor(bytes: number, usage: number,
|
|
31
|
+
/** Ranges start on a multiple of this many elements. */
|
|
32
|
+
align?: number);
|
|
33
|
+
get live(): number;
|
|
34
|
+
}
|
|
35
|
+
/** What one deformed primitive needs; the arrays are read once, when the primitive is placed. */
|
|
36
|
+
export interface SlotSpec {
|
|
37
|
+
primitive: PBRPrimitive;
|
|
38
|
+
/** Vertices (80 bytes each). */
|
|
39
|
+
count: number;
|
|
40
|
+
/** Morph targets. */
|
|
41
|
+
targets: number;
|
|
42
|
+
/** 32-bit words of the morph table (morph-table.ts), a multiple of 4; 0 without targets. */
|
|
43
|
+
morphWords: number;
|
|
44
|
+
/** Words per morph table entry: 8, or 12 with tangents. */
|
|
45
|
+
morphStride: number;
|
|
46
|
+
/** Skin joints; 0 for a morph-only primitive. */
|
|
47
|
+
joints: number;
|
|
48
|
+
/** Eight influences per vertex (JOINTS_1/WEIGHTS_1) rather than four. */
|
|
49
|
+
extra: boolean;
|
|
50
|
+
/** How the bones blend; unset is linear. Bones of a mode are the 16 floats it encodes. */
|
|
51
|
+
mode?: SkinningMode;
|
|
52
|
+
/** Identity of the asset data the deltas and influences come from: equal keys share one copy. */
|
|
53
|
+
asset: object;
|
|
54
|
+
definition: object;
|
|
55
|
+
skin: number | undefined;
|
|
56
|
+
/** The morph table's words; read once, when the first copy of the primitive is placed on a page. */
|
|
57
|
+
deltas(): Uint32Array;
|
|
58
|
+
influences(): Uint32Array;
|
|
59
|
+
}
|
|
60
|
+
/** A placed primitive: where its inputs and its deformed output live. */
|
|
61
|
+
export interface Slot {
|
|
62
|
+
readonly page: Page;
|
|
63
|
+
readonly primitive: PBRPrimitive;
|
|
64
|
+
readonly count: number;
|
|
65
|
+
readonly targets: number;
|
|
66
|
+
/** Words per morph table entry. */
|
|
67
|
+
readonly morphStride: number;
|
|
68
|
+
readonly joints: number;
|
|
69
|
+
readonly extra: boolean;
|
|
70
|
+
readonly mode?: SkinningMode;
|
|
71
|
+
readonly source: Block;
|
|
72
|
+
readonly output: Range;
|
|
73
|
+
readonly weights: Range;
|
|
74
|
+
readonly bones: Range;
|
|
75
|
+
readonly morphs?: Block;
|
|
76
|
+
readonly influences?: Block;
|
|
77
|
+
/** Index into the page's slot records, valid for the page's current `version`. */
|
|
78
|
+
index: number;
|
|
79
|
+
}
|
|
80
|
+
/** One set of shared buffers, all within the device's storage-binding limit. */
|
|
81
|
+
declare class Page {
|
|
82
|
+
readonly source: Pool;
|
|
83
|
+
readonly output: Pool;
|
|
84
|
+
readonly morphs: Pool;
|
|
85
|
+
readonly influences: Pool;
|
|
86
|
+
readonly weights: Pool;
|
|
87
|
+
readonly bones: Pool;
|
|
88
|
+
readonly slots: Set<Slot>;
|
|
89
|
+
readonly blocks: Map<object, Map<object, Map<string, Block>>>;
|
|
90
|
+
/** Changes whenever a slot or buffer of the page does. */
|
|
91
|
+
version: number;
|
|
92
|
+
info?: {
|
|
93
|
+
buffer: GPUBuffer;
|
|
94
|
+
version: number;
|
|
95
|
+
};
|
|
96
|
+
constructor(alignment: number);
|
|
97
|
+
get pools(): Pool[];
|
|
98
|
+
}
|
|
99
|
+
/** A dispatch the encoder records: one per page and pipeline. */
|
|
100
|
+
interface Dispatch {
|
|
101
|
+
pipeline: GPUComputePipeline;
|
|
102
|
+
group: GPUBindGroup;
|
|
103
|
+
table: GPUBuffer;
|
|
104
|
+
x: number;
|
|
105
|
+
y: number;
|
|
106
|
+
}
|
|
107
|
+
/** The dispatches of one set of owners, rebuilt when the set or the arena changes. */
|
|
108
|
+
export interface DispatchCache {
|
|
109
|
+
owners: readonly object[];
|
|
110
|
+
version: number;
|
|
111
|
+
dispatches: Dispatch[];
|
|
112
|
+
}
|
|
113
|
+
/** Weights live in a region of at least four floats, the size of the per-primitive buffer they used to have. */
|
|
114
|
+
export declare const weightRegion: (targets: number) => number;
|
|
115
|
+
/** Every deformed primitive of one device, packed into pages of shared buffers. */
|
|
116
|
+
export declare class DeformArena {
|
|
117
|
+
readonly device: GPUDevice;
|
|
118
|
+
readonly pages: Page[];
|
|
119
|
+
version: number;
|
|
120
|
+
private pipelines;
|
|
121
|
+
/** Skinning modes seen, linear first: a pipeline's index is twice its mode's index, plus one for eight influences. */
|
|
122
|
+
private readonly modes;
|
|
123
|
+
private readonly limit;
|
|
124
|
+
private readonly alignment;
|
|
125
|
+
private constructor();
|
|
126
|
+
static of(device: GPUDevice): DeformArena;
|
|
127
|
+
private variant;
|
|
128
|
+
pipeline(extra: boolean, mode?: SkinningMode): GPUComputePipeline;
|
|
129
|
+
/**
|
|
130
|
+
* Places the primitives of one owner, growing a page at most once; returns their slots in order. Skinned primitives
|
|
131
|
+
* of one node and skin (glTF gives every primitive of a skinned mesh node the same joints and inverse binds, so the
|
|
132
|
+
* same palette) share one bone range when they land on one page: the owner computes and uploads it once.
|
|
133
|
+
*/
|
|
134
|
+
add(specs: readonly SlotSpec[]): Slot[];
|
|
135
|
+
/** Frees a slot; an emptied page releases its buffers at once. */
|
|
136
|
+
remove(slot: Slot): void;
|
|
137
|
+
/**
|
|
138
|
+
* The dispatches that deform `slots` (grouped by owner in `owners`), cached in `cache` while the owners and the
|
|
139
|
+
* arena stay the same.
|
|
140
|
+
*/
|
|
141
|
+
dispatches(owners: readonly object[], slotsOf: (owner: object) => readonly Slot[], cache: DispatchCache): Dispatch[];
|
|
142
|
+
/** Destroys a cache's tables now (its owners are going away). */
|
|
143
|
+
drop(cache: DispatchCache): void;
|
|
144
|
+
private block;
|
|
145
|
+
private needs;
|
|
146
|
+
private fits;
|
|
147
|
+
/** Makes room for `need` more elements in each pool of `page`: compacts and grows its buffers when they are full. */
|
|
148
|
+
private reserve;
|
|
149
|
+
private place;
|
|
150
|
+
private published;
|
|
151
|
+
private publish;
|
|
152
|
+
private write;
|
|
153
|
+
/** The page's slot records (where each slot's data is), rebuilt when the page changed. */
|
|
154
|
+
private records;
|
|
155
|
+
private mapped;
|
|
156
|
+
/**
|
|
157
|
+
* Destroys buffers an open frame may still have recorded, once the work submitted so far is done (a frame encodes and
|
|
158
|
+
* submits synchronously, so it has been submitted by then).
|
|
159
|
+
*/
|
|
160
|
+
private retire;
|
|
161
|
+
}
|
|
162
|
+
export {};
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
import { type KeyframeClip } from './keyframes.js';
|
|
2
|
+
import type { Skeleton } from './skin.js';
|
|
3
|
+
/** Options for {@link subclip}. */
|
|
4
|
+
export interface SubclipOptions {
|
|
5
|
+
/** Name of the new clip. Default the source's name. */
|
|
6
|
+
name?: string;
|
|
7
|
+
/** Keys per second where a cut lands inside an eased or cubic segment, whose curve cannot be cut at one key. Default 60. */
|
|
8
|
+
fps?: number;
|
|
9
|
+
}
|
|
10
|
+
/** The reference pose for {@link makeAdditive}. */
|
|
11
|
+
export interface AdditiveReference {
|
|
12
|
+
/** The clip holding the reference pose, with a track for every track being converted. Default the clip itself. */
|
|
13
|
+
clip?: KeyframeClip;
|
|
14
|
+
/** Seconds into the reference clip. Default 0. */
|
|
15
|
+
time?: number;
|
|
16
|
+
/** Name of the new clip. Default the source's name plus ` (additive)`. */
|
|
17
|
+
name?: string;
|
|
18
|
+
}
|
|
19
|
+
/**
|
|
20
|
+
* A new clip holding `start` to `end` seconds of `clip`, re-timed to start at 0: both ends are sampled, so the cut plays
|
|
21
|
+
* exactly as the source did there. Keys and their interpolation are kept; only a curved segment the cut passes through
|
|
22
|
+
* becomes short straight keys at `fps`. Markers in the range come along, and property tracks stay bound to their targets.
|
|
23
|
+
*
|
|
24
|
+
* @example
|
|
25
|
+
* ```ts
|
|
26
|
+
* const stride = subclip(walk, 0.5, 1.5, {name: 'Stride'});
|
|
27
|
+
* ```
|
|
28
|
+
*/
|
|
29
|
+
export declare function subclip(clip: KeyframeClip, start: number, end: number, { name, fps }?: SubclipOptions): KeyframeClip;
|
|
30
|
+
/** {@link subclip} by frame numbers at `frameRate` frames per second, `first` and `last` included. */
|
|
31
|
+
export declare function subclipFrames(clip: KeyframeClip, first: number, last: number, frameRate?: number, options?: SubclipOptions): KeyframeClip;
|
|
32
|
+
/**
|
|
33
|
+
* A clip of differences from a reference pose: translation and weights subtract it, scale divides by it (a zero
|
|
34
|
+
* reference axis gives 1) and rotation is `inverse(reference) * rotation`, the sums `@margoengine/animator` additive
|
|
35
|
+
* layers use. Every key keeps its time and interpolation, so the result is exact between keys too. Property tracks are
|
|
36
|
+
* left out: a difference means nothing to them. Play the result over a base pose with {@link applyAdditiveClip}.
|
|
37
|
+
*
|
|
38
|
+
* @example
|
|
39
|
+
* ```ts
|
|
40
|
+
* const nod = makeAdditive(headNod); // against the clip's first frame
|
|
41
|
+
* const lean = makeAdditive(leanClip, {clip: idle, time: 0.5}); // against a frame of another clip
|
|
42
|
+
* ```
|
|
43
|
+
*/
|
|
44
|
+
export declare function makeAdditive(clip: KeyframeClip, reference?: AdditiveReference): KeyframeClip;
|
|
45
|
+
/**
|
|
46
|
+
* Adds an additive clip from {@link makeAdditive} onto a skeleton's current pose at `time`, by `weight` (default 1). Pose
|
|
47
|
+
* the base first each frame: the additive adds to whatever is there, so applying it twice adds twice. Tracks naming no
|
|
48
|
+
* bone, and weights tracks, are skipped.
|
|
49
|
+
*/
|
|
50
|
+
export declare function applyAdditiveClip(clip: KeyframeClip, skeleton: Skeleton, time: number, weight?: number): void;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{a as e,i as t}from"./keyframes-YpidiYS4.js";import{interpolateQuaternions as n,multiplyQuaternions as r}from"@margoengine/math/quat";var i=e=>e.values.length/e.times.length,a=e=>e!==`linear`&&e!==`discrete`;function o(t,n,r,o){let{times:s,values:c,interpolations:l,tangents:u}=t,d=i(t),f=s.length-1,p=[],m=(r,i)=>p.push({time:r-n,value:Array.from(e(t,r).subarray(0,d)),interpolation:i}),h=(e,t=l[e])=>{let r={time:s[e]-n,value:Array.from(c.subarray(e*d,(e+1)*d)),interpolation:t};if(u){let t=e*d*2;r.inTangent=Array.from(u.subarray(t,t+d)),r.outTangent=Array.from(u.subarray(t+d,t+d*2))}p.push(r)},g=-1;for(;g<f&&s[g+1]<=n;)g++;let _=n;for(;_<r;){let e=g<f?s[g+1]:1/0,t=Math.min(e,r),n=g>=0&&s[g]===_,i=g>=0?l[g]:`linear`;if(g>=0&&g<f&&a(i)&&!(n&&e<=r)){n?h(g,`linear`):m(_,`linear`);let e=Math.max(1,Math.ceil((t-_)*o));for(let n=1;n<e;n++)m(_+(t-_)*n/e,`linear`)}else n?h(g):m(_,a(i)?`linear`:i);_=t,_===e&&g++}return g>=0&&s[g]===r?h(g):m(r,`linear`),p}function s(e,n,r,{name:i=e.name,fps:a=60}={}){if(!Number.isFinite(n)||!Number.isFinite(r)||n<0||r<=n||r>e.duration)throw RangeError(`Subclip range ${n} to ${r} is invalid; use 0 <= start < end <= ${e.duration}`);if(!Number.isFinite(a)||a<=0)throw RangeError(`Subclip fps must be a finite number > 0`);let s=e.tracks.map(e=>({target:e.target,path:e.path,keys:o(e,n,r,a),...e.blend?{blend:e.blend}:{}}));for(let t of e.properties??[])s.push({target:t.target,type:t.type,name:t.name,keys:o(t,n,r,a),...t.blend?{blend:t.blend}:{},...t.property===void 0?{get:()=>t.read(),set:e=>t.write(e)}:{property:t.property}});return t({name:i,tracks:s,markers:(e.markers??[]).filter(e=>e.time>=n&&e.time<=r).map(e=>({...e,time:e.time-n}))})}function c(e,t,n,r=30,i){if(!Number.isInteger(t)||!Number.isInteger(n)||!Number.isFinite(r)||r<=0)throw RangeError(`Subclip frames must be integers and the frame rate a finite number > 0`);return s(e,t/r,n/r,i)}function l(n,a={}){let{clip:o=n,time:s=0,name:c=n.name+` (additive)`}=a;if(!Number.isFinite(s)||s<0)throw RangeError(`Additive reference time must be finite and >= 0`);let l=n.tracks.map(t=>{let n=o.tracks.find(e=>e.target===t.target&&e.path===t.path);if(!n)throw RangeError(`Additive reference has no ${t.path} track for ${t.target}; use a reference clip that animates it`);let a=e(n,s),c=i(t),l=t.path===`rotation`?[-a[0],-a[1],-a[2],a[3]]:void 0;if(t.path===`weights`&&a.length!==c)throw RangeError(`Additive reference for ${t.target} has a different morph target count; use a reference clip of the same model`);let u=(e,n)=>l?Array.from(r(l,e)):Array.from(e,(e,r)=>t.path===`scale`?a[r]===0?+!n:e/a[r]:n?e:e-a[r]),d=Array.from(t.times,(e,n)=>{let r={time:e,value:u(t.values.subarray(n*c,(n+1)*c),!1),interpolation:t.interpolations[n]};if(t.tangents){let e=n*c*2;r.inTangent=u(t.tangents.subarray(e,e+c),!0),r.outTangent=u(t.tangents.subarray(e+c,e+c*2),!0)}return r});return{target:t.target,path:t.path,keys:d,...t.blend?{blend:t.blend}:{}}});return t({name:c,tracks:l,markers:n.markers??[]})}function u(t,i,a,o=1){if(!Number.isFinite(o)||o<0)throw RangeError(`Additive weight must be finite and >= 0`);for(let s of t.tracks){if(s.path===`weights`||!i.names.includes(s.target))continue;let t=i.index(s.target),c=i.getPose(t),l=e(s,a);if(s.path===`translation`)i.setPose(t,{translation:c.translation.map((e,t)=>e+l[t]*o)});else if(s.path===`scale`)i.setPose(t,{scale:c.scale.map((e,t)=>e*(1+(l[t]-1)*o))});else{let e=n([0,0,0,1],l,o,.9995);i.setPose(t,{rotation:Array.from(r(c.rotation,e))})}}}export{u as applyAdditiveClip,l as makeAdditive,s as subclip,c as subclipFrames};
|
package/dist/clone.d.ts
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import { PBRModel } from '@margoengine/gltf/pbr-model';
|
|
2
|
+
/**
|
|
3
|
+
* A second, independent copy of a glTF PBR model, with its own nodes (so its own
|
|
4
|
+
* skeleton) that an `Animation` from this package can play apart from the source (`Animation.attach(clone)`). The
|
|
5
|
+
* clone starts in the source's current local node transforms, visibility and morph weights, with its root unparented
|
|
6
|
+
* at the source root's local transform, and is registered with the engine when the source is (as `loadGLTF` does).
|
|
7
|
+
* It shares the source's parsed asset (document, buffers, accessors), decoded images and packed vertex arrays.
|
|
8
|
+
* gltf/pbr shares the GPU textures of shared images, and the GPU vertex and index buffers of shared arrays (and of
|
|
9
|
+
* baked static batches at the same pose), between the copies, freeing each with its last holder in any disposal order;
|
|
10
|
+
* an `Animation` shares the bind-pose vertices, morph deltas and skin influences the same way. Deformed output,
|
|
11
|
+
* weights, bones, uniforms and bind groups are per model. Materials come from the document, so edits made to the
|
|
12
|
+
* source's materials at runtime are not copied. Clone after a progressive load has finished. A copy costs no engine
|
|
13
|
+
* tick, so its world matrices publish with the next one: every frame and pick, and `model.bounds`, run it first.
|
|
14
|
+
*/
|
|
15
|
+
export declare function cloneModel(model: PBRModel): Promise<PBRModel>;
|
package/dist/cor.d.ts
ADDED
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
import { type SkinMeshPart, type SkinningMode } from './shader.js';
|
|
2
|
+
import { type SkinnedVertex } from './dqs.js';
|
|
3
|
+
/** Options of {@link rotationCentres}. */
|
|
4
|
+
export interface RotationCentreOptions {
|
|
5
|
+
/** Width of the weight similarity kernel (the paper's sigma). Default 0.1. */
|
|
6
|
+
sigma?: number;
|
|
7
|
+
/**
|
|
8
|
+
* Triangles whose weights agree to within `1 / steps` per bone are summed together before the vertices read them, so
|
|
9
|
+
* the work grows with the variety of weights, not the triangle count. Vertex weights are used exactly. Default 16.
|
|
10
|
+
*/
|
|
11
|
+
steps?: number;
|
|
12
|
+
}
|
|
13
|
+
/**
|
|
14
|
+
* Every vertex's centre of rotation (Le and Hodgins 2016), for all primitives of one skinned mesh in their bind pose:
|
|
15
|
+
* one `Float32Array` per part, four numbers per vertex, the centre then 1, or the vertex's own position then 0 where
|
|
16
|
+
* no triangle shares two of its bones (a vertex on one bone, whose skin is rigid wherever its centre is).
|
|
17
|
+
*
|
|
18
|
+
* @example
|
|
19
|
+
* ```ts
|
|
20
|
+
* import { rotationCentres } from '@margoengine/animation/cor';
|
|
21
|
+
* // Two triangles along x, the left one on bone 0, the right one half and half on bones 0 and 1.
|
|
22
|
+
* const [centres] = rotationCentres([{
|
|
23
|
+
* positions: [0, 0, 0, 1, 0, 0, 0, 1, 0, 1, 1, 0],
|
|
24
|
+
* triangles: [0, 1, 2, 1, 3, 2],
|
|
25
|
+
* joints: [0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0],
|
|
26
|
+
* weights: [1, 0, 0, 0, 0.5, 0.5, 0, 0, 0.5, 0.5, 0, 0, 0.5, 0.5, 0, 0],
|
|
27
|
+
* influences: 4,
|
|
28
|
+
* }]);
|
|
29
|
+
* console.log(centres.length); // 16: four numbers for each of the four vertices
|
|
30
|
+
* ```
|
|
31
|
+
*/
|
|
32
|
+
export declare function rotationCentres(parts: readonly SkinMeshPart[], options?: RotationCentreOptions): Float32Array[];
|
|
33
|
+
/**
|
|
34
|
+
* One vertex under bones encoded by `encodeDualQuaternions` (`@margoengine/animation/dqs`), about its centre of
|
|
35
|
+
* rotation `centre` (from {@link rotationCentres}): the shader's steps in double precision, for checks and CPU picking.
|
|
36
|
+
* `joints` and `weights` are parallel, weights summing to 1; the normal comes back unit length.
|
|
37
|
+
*/
|
|
38
|
+
export declare function skinCenterOfRotation(slots: Float32Array, joints: ArrayLike<number>, weights: ArrayLike<number>, position: ArrayLike<number>, normal?: ArrayLike<number>, centre?: ArrayLike<number>): SkinnedVertex;
|
|
39
|
+
/**
|
|
40
|
+
* The `skinning` option of `Animation` for skinning with optimized centres of rotation (Le and Hodgins 2016): no
|
|
41
|
+
* collapse at a bent or twisted joint and no bulge on the outside of a bend. Each skinned mesh's centres are computed
|
|
42
|
+
* once, from all of its primitives in the bind pose ({@link rotationCentres}); its `blend` gives the same pose on the
|
|
43
|
+
* CPU for synchronous raycasts. `@margoengine/humans` `addPerson` uses it by default.
|
|
44
|
+
*
|
|
45
|
+
* @example
|
|
46
|
+
* ```ts
|
|
47
|
+
* import { Animation } from '@margoengine/animation';
|
|
48
|
+
* import { centerOfRotationSkinning } from '@margoengine/animation/cor';
|
|
49
|
+
* const animation = Animation.attach(model, { skinning: centerOfRotationSkinning });
|
|
50
|
+
* ```
|
|
51
|
+
*/
|
|
52
|
+
export declare const centerOfRotationSkinning: SkinningMode;
|
package/dist/cor.js
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import{t as e}from"./shader-DuGkHFKx.js";import{encodeDualQuaternions as t}from"./dqs.js";var n=16;function r(e,t,n,r){n.length=r.length=0;let i=0;for(let a=0;a<e.influences;a++){let o=e.weights[t*e.influences+a];if(!(o>0))continue;let s=e.joints[t*e.influences+a],c=n.indexOf(s);c>=0?r[c]+=o:(n.push(s),r.push(o)),i+=o}for(let e=1;e<n.length;e++)for(let t=e;t>0&&n[t-1]>n[t];t--)[n[t-1],n[t]]=[n[t],n[t-1]],[r[t-1],r[t]]=[r[t],r[t-1]];for(let e=0;e<r.length;e++)r[e]/=i}function i(e,t={}){let n=t.sigma??.1,i=t.steps??16;if(!(n>0)||!Number.isFinite(n))throw RangeError(`rotationCentres sigma must be a positive number`);if(!(i>=1)||!Number.isInteger(i))throw RangeError(`rotationCentres steps must be a whole number >= 1`);for(let t of e){let e=t.positions.length/3;if(!Number.isInteger(e)||t.joints.length!==e*t.influences||t.weights.length!==e*t.influences)throw RangeError("rotationCentres parts need three positions and `influences` joints and weights per vertex");if(t.triangles&&t.triangles.length%3)throw RangeError(`rotationCentres triangles must come in threes`)}let a=n*n,o=/* @__PURE__ */ new Map,s=[],c=[],l=/* @__PURE__ */ new Map;for(let t of e){let e=t.triangles,n=t.positions,a=n.length/3;if(e)for(let u=0;u<e.length;u+=3){let d=e[u],f=e[u+1],p=e[u+2];if(d>=a||f>=a||p>=a)throw RangeError(`rotationCentres triangle corner out of range`);let m=n[f*3]-n[d*3],h=n[f*3+1]-n[d*3+1],g=n[f*3+2]-n[d*3+2],_=n[p*3]-n[d*3],v=n[p*3+1]-n[d*3+1],y=n[p*3+2]-n[d*3+2],b=.5*Math.hypot(h*y-g*v,g*_-m*y,m*v-h*_);if(!(b>0))continue;l.clear();for(let e of[d,f,p]){r(t,e,s,c);for(let e=0;e<s.length;e++)l.set(s[e],(l.get(s[e])??0)+c[e]/3)}if(l.size<2)continue;let x=[...l.keys()].sort((e,t)=>e-t),S=``;for(let e of x)S+=e+`:`+Math.round(l.get(e)*i)+`,`;let C=o.get(S);C||o.set(S,C={bones:x,weights:new Float64Array(x.length),area:0,x:0,y:0,z:0});for(let e=0;e<x.length;e++)C.weights[e]+=l.get(x[e])*b;C.area+=b,C.x+=b*(n[d*3]+n[f*3]+n[p*3])/3,C.y+=b*(n[d*3+1]+n[f*3+1]+n[p*3+1])/3,C.z+=b*(n[d*3+2]+n[f*3+2]+n[p*3+2])/3}}let u=[...o.values()],d=0;for(let e of u){for(let t=0;t<e.weights.length;t++)e.weights[t]/=e.area;d=Math.max(d,e.bones[e.bones.length-1])}for(let t of e)for(let e=0;e<t.joints.length;e++)d=Math.max(d,t.joints[e]);let f=d+1,p=/* @__PURE__ */ new Map;u.forEach((e,t)=>{let n=e.bones;for(let e=0;e<n.length;e++)for(let r=e+1;r<n.length;r++){let i=n[e]*f+n[r],a=p.get(i);a||p.set(i,a=[]),a.push(t)}});let m=new Int32Array(u.length).fill(-1),h=new Float64Array(f),g=/* @__PURE__ */ new Map,_=[],v=0;for(let t of e){let e=t.positions,n=e.length/3,i=new Float32Array(n*4);for(let o=0;o<n;o++){if(i[o*4]=e[o*3],i[o*4+1]=e[o*3+1],i[o*4+2]=e[o*3+2],r(t,o,s,c),s.length<2)continue;let n=``;for(let e=0;e<s.length;e++)n+=s[e]+`:`+Math.round(c[e]*4096)+`,`;let l=g.get(n);if(l===void 0){v++;for(let e=0;e<s.length;e++)h[s[e]]=c[e];let e=0,t=0,r=0,i=0;for(let n=0;n<s.length;n++)for(let o=n+1;o<s.length;o++)for(let c of p.get(s[n]*f+s[o])??[]){if(m[c]===v)continue;m[c]=v;let n=u[c],o=n.bones,s=n.weights,l=0;for(let e=0;e<o.length;e++){let t=h[o[e]];if(!t)continue;let n=s[e];for(let r=e+1;r<o.length;r++){let e=h[o[r]];if(!e)continue;let i=s[r],c=t*i-e*n;l+=t*e*n*i*Math.exp(-(c*c)/a)}}l&&(i+=l*n.area,e+=l*n.x,t+=l*n.y,r+=l*n.z)}for(let e=0;e<s.length;e++)h[s[e]]=0;l=i>0?Float64Array.of(e/i,t/i,r/i):null,g.set(n,l)}l&&(i[o*4]=l[0],i[o*4+1]=l[1],i[o*4+2]=l[2],i[o*4+3]=1)}_.push(i)}return _}var a=(e,t,n,r)=>{let i=e[1]*r-e[2]*n+e[3]*t,a=e[2]*t-e[0]*r+e[3]*n,o=e[0]*n-e[1]*t+e[3]*r;return[t+2*(e[1]*o-e[2]*a),n+2*(e[2]*i-e[0]*o),r+2*(e[0]*a-e[1]*i)]};function o(e,t,r,i,o=[0,0,1],s=i){if(t.length!==r.length||!t.length)throw RangeError(`Invalid influences; pass as many joints as weights, at least one`);let c=t[0],l=r[0];for(let e=1;e<t.length;e++)r[e]>l&&(l=r[e],c=t[e]);let u=c*n,d=[0,0,0,0],f=[0,0,0,0,0,0],p=[0,0,0],m=s[0],h=s[1],g=s[2];for(let i=0;i<t.length;i++){let o=t[i]*n,s=r[i],c=0;for(let t=0;t<4;t++)c+=e[o+t]*e[u+t];let l=c<0?-s:s;for(let t=0;t<4;t++)d[t]+=e[o+t]*l;for(let t=0;t<6;t++)f[t]+=e[o+8+t]*s;let _=e.subarray(o,o+4),v=e.subarray(o+4,o+8),y=a(_,e[o+8]*m+e[o+11]*h+e[o+12]*g,e[o+11]*m+e[o+9]*h+e[o+13]*g,e[o+12]*m+e[o+13]*h+e[o+10]*g);p[0]+=s*(y[0]+2*(_[3]*v[0]-v[3]*_[0]+_[1]*v[2]-_[2]*v[1])),p[1]+=s*(y[1]+2*(_[3]*v[1]-v[3]*_[1]+_[2]*v[0]-_[0]*v[2])),p[2]+=s*(y[2]+2*(_[3]*v[2]-v[3]*_[2]+_[0]*v[1]-_[1]*v[0]))}let _=Math.hypot(...d),v=d.map(e=>e/_),y=i[0]-m,b=i[1]-h,x=i[2]-g,S=a(v,f[0]*y+f[3]*b+f[4]*x,f[3]*y+f[1]*b+f[5]*x,f[4]*y+f[5]*b+f[2]*x),C=f[1]*f[2]-f[5]*f[5],w=f[4]*f[5]-f[3]*f[2],T=f[3]*f[5]-f[4]*f[1],E=f[0]*f[2]-f[4]*f[4],D=f[3]*f[4]-f[0]*f[5],O=f[0]*f[1]-f[3]*f[3],k=f[0]*C+f[3]*w+f[4]*T>=0?1:-1,A=k*(C*o[0]+w*o[1]+T*o[2]),j=k*(w*o[0]+E*o[1]+D*o[2]),M=k*(T*o[0]+D*o[1]+O*o[2]),N=A*A+j*j+M*M>0,P=a(v,N?A:0,N?j:1,N?M:0),F=Math.hypot(P[0],P[1],P[2])||1;return{position:[S[0]+p[0],S[1]+p[1],S[2]+p[2]],normal:[P[0]/F,P[1]/F,P[2]/F]}}var s=e=>{let t=[`x`,`y`,`z`,`w`].map(e=>[`joints.${e}`,`jointWeights.${e}`]);if(e)for(let e of[`x`,`y`,`z`,`w`])t.push([`jointsExtra.${e}`,`weightsExtra.${e}`]);return`var pivot=${t[0][0]};var heaviest=${t[0][1]};
|
|
2
|
+
${t.slice(1).map(([e,t])=>`if(${t}>heaviest){heaviest=${t};pivot=${e};}`).join(``)}
|
|
3
|
+
let near=boneMatrices[s.bones+pivot][0];let centre=vertexData.xyz;
|
|
4
|
+
var real=vec4f(0);var stretchA=vec4f(0);var stretchB=vec4f(0);var moved=vec3f(0);
|
|
5
|
+
${t.map(([e,t])=>`{let b=boneMatrices[s.bones+${e}];let k=select(${t},-${t},dot(b[0],near)<0);real+=b[0]*k;stretchA+=b[2]*${t};stretchB+=b[3]*${t};moved+=placed(b,centre)*${t};}`).join(`
|
|
6
|
+
`)}
|
|
7
|
+
let turn=real/length(real);
|
|
8
|
+
let stretch=mat3x3f(stretchA.x,stretchA.w,stretchB.x,stretchA.w,stretchA.y,stretchB.y,stretchB.x,stretchB.y,stretchA.z);
|
|
9
|
+
v.position=vec4f(rotated(turn,stretch*(v.position.xyz-centre))+moved,1);
|
|
10
|
+
let normalMatrix=mat3x3f(cross(stretch[1],stretch[2]),cross(stretch[2],stretch[0]),cross(stretch[0],stretch[1]));
|
|
11
|
+
let handedness=select(-1.0,1.0,dot(stretch[0],cross(stretch[1],stretch[2]))>=0.0);let bent=normalMatrix*v.normal.xyz*handedness;
|
|
12
|
+
v.normal=vec4f(rotated(turn,select(vec3f(0,1,0),bent,dot(bent,bent)>0.0)),0);
|
|
13
|
+
v.tangent=vec4f(rotated(turn,stretch*v.tangent.xyz),v.tangent.w*handedness);`},c=`fn rotated(q:vec4f,x:vec3f)->vec3f {return x+2*cross(q.xyz,cross(q.xyz,x)+q.w*x);}
|
|
14
|
+
fn placed(b:mat4x4f,p:vec3f)->vec3f {
|
|
15
|
+
let st=mat3x3f(b[2].x,b[2].w,b[3].x,b[2].w,b[2].y,b[3].y,b[3].x,b[3].y,b[2].z);
|
|
16
|
+
return rotated(b[0],st*p)+2*(b[0].w*b[1].xyz-b[1].w*b[0].xyz+cross(b[0].xyz,b[1].xyz));
|
|
17
|
+
}`,l={name:`center-of-rotation`,shader:t=>e(t,{functions:c,blend:s(t)},!0),encode:e=>{t(e)},blend:(e,t,n,r,i,a,s)=>o(e,t,n,r,i,s??r),vertexData:e=>i(e)};export{l as centerOfRotationSkinning,i as rotationCentres,o as skinCenterOfRotation};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
var e=/* @__PURE__ */ new WeakMap;export{e as t};
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @internal Models whose deformed vertices something besides the model's own draw reads (`DeformedPoints`), with the
|
|
3
|
+
* number of readers: `Animation` keeps deforming such a model while its nodes are hidden.
|
|
4
|
+
*/
|
|
5
|
+
export declare const deformReaders: WeakMap<object, number>;
|
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
/// <reference lib="esnext.disposable" preserve="true" />
|
|
2
|
+
import type { PBRModel } from '@margoengine/gltf/pbr';
|
|
3
|
+
import type { Engine, EnginePlugin, FrameGraph } from '@margoengine/core/extension';
|
|
4
|
+
import { type ColorInput } from '@margoengine/math/color';
|
|
5
|
+
/** Options for {@link DeformedPoints}; every one is also a live field of the same name. */
|
|
6
|
+
export interface DeformedPointsOptions {
|
|
7
|
+
/** Point diameter: CSS pixels, or world units when `sizeUnits` is 'world'. Finite, 0 or more. Default 4. */
|
|
8
|
+
size?: number;
|
|
9
|
+
/** 'pixels' keeps a constant screen size; 'world' shrinks with distance. Default 'pixels'. */
|
|
10
|
+
sizeUnits?: 'pixels' | 'world';
|
|
11
|
+
/** '#rrggbb', '#rgb' or 0xrrggbb are sRGB; an [r, g, b] array is linear RGB. Default white. */
|
|
12
|
+
color?: ColorInput;
|
|
13
|
+
/** Multiplies alpha, 0 to 1; below 1 the points blend over what is drawn and still write depth. Default 1. */
|
|
14
|
+
opacity?: number;
|
|
15
|
+
/** 'square', or 'round' (a disc cut from the square). Default 'square'. */
|
|
16
|
+
shape?: 'square' | 'round';
|
|
17
|
+
/** Multiplies `color` by each vertex's colour (glTF COLOR_0; white where the mesh has none). Default true. */
|
|
18
|
+
vertexColors?: boolean;
|
|
19
|
+
}
|
|
20
|
+
/**
|
|
21
|
+
* What the vertex stage adds to a point's clip position for a quad corner in [-1, 1]: `corner * [x, y]`, times the
|
|
22
|
+
* clip w when the third number is 1. `camera` is the view-projection matrix (column-major, `Camera.matrix`), `width`
|
|
23
|
+
* and `height` the view's pixels. Pixels: a point covers `size` pixels at any depth. World: `size` world units across,
|
|
24
|
+
* measured in the image plane, for any projection (the matrix's x and y rows without their share along the w row, so
|
|
25
|
+
* an orthographic or off-axis projection is sized like a centred perspective one).
|
|
26
|
+
* @throws RangeError for a size that is not finite and >= 0, an unknown unit or a view without pixels.
|
|
27
|
+
*/
|
|
28
|
+
export declare function pointScale(camera: ArrayLike<number>, size: number, sizeUnits: 'pixels' | 'world', width: number, height: number, out?: Float32Array<ArrayBuffer>): Float32Array;
|
|
29
|
+
/**
|
|
30
|
+
* The WGSL the points draw with. Each instance is one 80-byte vertex of the mesh (position at byte 0, colour at 64);
|
|
31
|
+
* the four strip vertices are the corners of its quad. Exposed for tooling and tests.
|
|
32
|
+
*/
|
|
33
|
+
export declare const deformedPointsShader = "\nstruct Frame {camera:mat4x4f,model:mat4x4f,color:vec4f,scale:vec4f,flags:vec4f}\n@group(0) @binding(0) var<uniform> f:Frame;\nstruct Out {@builtin(position) clip:vec4f,@location(0) color:vec4f,@location(1) corner:vec2f}\n@vertex fn vertex(@location(0) position:vec3f,@location(1) color:vec4f,@builtin(vertex_index) i:u32)->Out {\n let corner=vec2f(f32(i&1u),f32(i>>1u))*2.0-1.0;let c=f.camera*(f.model*vec4f(position,1.0));\n var o:Out;o.clip=vec4f(c.xy+corner*f.scale.xy*mix(1.0,c.w,f.scale.z),c.zw);o.color=f.color*mix(vec4f(1.0),color,f.flags.x);o.corner=corner;return o;\n}\n@fragment fn fragment(i:Out)->@location(0) vec4f {\n if(f.scale.w>0.5&&dot(i.corner,i.corner)>1.0){discard;}\n let x=clamp(i.color.rgb,vec3f(0.0),vec3f(1.0));\n return vec4f(select(select(x*12.92,1.055*pow(x,vec3f(1.0/2.4))-0.055,x>=vec3f(0.0031308)),i.color.rgb,f.flags.y>0.5),i.color.a);\n}\n";
|
|
34
|
+
/**
|
|
35
|
+
* Draws every vertex of a `gltf/pbr` model (or a `createMesh` mesh) as a point where the model's deformer last put
|
|
36
|
+
* it: `Animation` (skins and morph targets), `Skin`, `MorphWeightPlayer` or a geometry cache. A primitive with no
|
|
37
|
+
* deformer draws its own vertices at its node. Unlit, depth tested and depth writing, no shadows, picking or fog.
|
|
38
|
+
* The points show while `visible` is true whatever the model's own visibility: hide the model
|
|
39
|
+
* (`model.root.visible = false`) to see the points alone, and it keeps deforming for them.
|
|
40
|
+
* @example
|
|
41
|
+
* const points = DeformedPoints.attach(model, { size: 3, color: '#ffcc00' });
|
|
42
|
+
* model.root.visible = false;
|
|
43
|
+
*/
|
|
44
|
+
export declare class DeformedPoints implements EnginePlugin {
|
|
45
|
+
readonly model: PBRModel;
|
|
46
|
+
readonly name: string;
|
|
47
|
+
size: number;
|
|
48
|
+
sizeUnits: 'pixels' | 'world';
|
|
49
|
+
/** Linear RGB; assign with `set({ color })`. */
|
|
50
|
+
readonly color: Float32Array<ArrayBuffer>;
|
|
51
|
+
opacity: number;
|
|
52
|
+
shape: 'square' | 'round';
|
|
53
|
+
vertexColors: boolean;
|
|
54
|
+
/** False draws nothing (the model then deforms only while it shows itself). */
|
|
55
|
+
visible: boolean;
|
|
56
|
+
disposed: boolean;
|
|
57
|
+
private engine?;
|
|
58
|
+
private device?;
|
|
59
|
+
private pipeline?;
|
|
60
|
+
private key;
|
|
61
|
+
private frames?;
|
|
62
|
+
private groups;
|
|
63
|
+
/** Vertices of primitives no deformer writes, uploaded here. */
|
|
64
|
+
private readonly own;
|
|
65
|
+
private readonly values;
|
|
66
|
+
private readonly scale;
|
|
67
|
+
private reading;
|
|
68
|
+
private unsubscribe?;
|
|
69
|
+
/** Same as `model.root.engine.use(new DeformedPoints(model, options))`; returns the points. */
|
|
70
|
+
static attach(model: PBRModel, options?: DeformedPointsOptions): DeformedPoints;
|
|
71
|
+
/** @throws TypeError for anything but a model with primitives; RangeError for an option out of range. */
|
|
72
|
+
constructor(model: PBRModel, options?: DeformedPointsOptions);
|
|
73
|
+
/** Changes the given options; the others keep their values. Nothing changes when one is out of range. */
|
|
74
|
+
set({ size, sizeUnits, color, opacity, shape, vertexColors }: DeformedPointsOptions): this;
|
|
75
|
+
/** Points drawn: the model's vertices over all its primitives. */
|
|
76
|
+
get count(): number;
|
|
77
|
+
setup(engine: Engine): void;
|
|
78
|
+
private read;
|
|
79
|
+
registerPasses(graph: FrameGraph): void;
|
|
80
|
+
private draw;
|
|
81
|
+
private bind;
|
|
82
|
+
private release;
|
|
83
|
+
onDeviceRestored(): void;
|
|
84
|
+
/** Stops drawing and frees the GPU buffers; the model and its deformer are untouched. */
|
|
85
|
+
dispose(): void;
|
|
86
|
+
[Symbol.dispose]: () => void;
|
|
87
|
+
}
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
// @margo/core-built 1.0.0
|
|
2
|
+
import {coreRequirement as __margoCoreRequirement,assertCore as __margoAssertCore} from '@margoengine/core/extension';
|
|
3
|
+
|
|
4
|
+
import{t as e}from"./deform-readers-DmYAkvBK.js";import{t}from"./require-webgpu-Jrqt3Xy4.js";import{n,r,t as i}from"./hdr-format-cmvLFubB.js";import{MargoError as a}from"@margoengine/math/errors";import{parseColor as o}from"@margoengine/math/color";function s(e,t,n,r,i,a=/* @__PURE__ */ new Float32Array(3)){if(!(t>=0&&Number.isFinite(t))||n!==`pixels`&&n!==`world`||!(r>0&&i>0))throw RangeError(`Invalid point size; pass a finite size >= 0, sizeUnits 'pixels' or 'world' and a view of at least 1 pixel`);if(n===`pixels`)return a[0]=t/r,a[1]=t/i,a[2]=1,a;let o=e[3],s=e[7],c=e[11],l=o*o+s*s+c*c;for(let n=0;n<2;n++){let r=e[n],i=e[4+n],u=e[8+n],d=l>0?(r*o+i*s+u*c)/l:0;a[n]=t/2*Math.hypot(r-d*o,i-d*s,u-d*c)}return a[2]=0,a}var c=`
|
|
5
|
+
struct Frame {camera:mat4x4f,model:mat4x4f,color:vec4f,scale:vec4f,flags:vec4f}
|
|
6
|
+
@group(0) @binding(0) var<uniform> f:Frame;
|
|
7
|
+
struct Out {@builtin(position) clip:vec4f,@location(0) color:vec4f,@location(1) corner:vec2f}
|
|
8
|
+
@vertex fn vertex(@location(0) position:vec3f,@location(1) color:vec4f,@builtin(vertex_index) i:u32)->Out {
|
|
9
|
+
let corner=vec2f(f32(i&1u),f32(i>>1u))*2.0-1.0;let c=f.camera*(f.model*vec4f(position,1.0));
|
|
10
|
+
var o:Out;o.clip=vec4f(c.xy+corner*f.scale.xy*mix(1.0,c.w,f.scale.z),c.zw);o.color=f.color*mix(vec4f(1.0),color,f.flags.x);o.corner=corner;return o;
|
|
11
|
+
}
|
|
12
|
+
@fragment fn fragment(i:Out)->@location(0) vec4f {
|
|
13
|
+
if(f.scale.w>0.5&&dot(i.corner,i.corner)>1.0){discard;}
|
|
14
|
+
let x=clamp(i.color.rgb,vec3f(0.0),vec3f(1.0));
|
|
15
|
+
return vec4f(select(select(x*12.92,1.055*pow(x,vec3f(1.0/2.4))-0.055,x>=vec3f(0.0031308)),i.color.rgb,f.flags.y>0.5),i.color.a);
|
|
16
|
+
}
|
|
17
|
+
`,l=0,u=class u{coreRequirement=__margoCoreRequirement("1.0.0",import.meta.url);static attach(e,t){__margoAssertCore(e,__margoCoreRequirement("1.0.0",import.meta.url));let n=new u(e,t);return e.root.engine.use(n),n}constructor(e,t={}){if(this.model=e,this.name=`deformed-points:`+l++,this.size=4,this.sizeUnits=`pixels`,this.color=new Float32Array([1,1,1]),this.opacity=1,this.shape=`square`,this.vertexColors=!0,this.visible=!0,this.disposed=!1,this.key=``,this.groups=[],this.own=/* @__PURE__ */ new Map,this.values=/* @__PURE__ */ new Float32Array(44),this.scale=/* @__PURE__ */ new Float32Array(3),this.reading=!1,!Array.isArray(e?.primitives)||!e.root)throw TypeError(`DeformedPoints needs a gltf/pbr model; pass a loaded model or a createMesh mesh`);this.set(t)}set({size:e,sizeUnits:t,color:n,opacity:r,shape:i,vertexColors:a}){let s={size:e??this.size,sizeUnits:t??this.sizeUnits,opacity:r??this.opacity,shape:i??this.shape,vertexColors:a??this.vertexColors};return d(s),n!==void 0&&o(n,this.color),Object.assign(this,s),this}get count(){let e=0;for(let t of this.model.primitives)e+=t.vertices.length/20;return e}setup(e){if(this.disposed)throw new a(`disposed`,`DeformedPoints is disposed; create new points before attaching`);if(this.model.disposed)throw new a(`disposed`,`DeformedPoints model is disposed; attach the points to a live model`);t(e,`DeformedPoints`),this.engine=e,this.unsubscribe??=this.model.onDispose(()=>this.dispose()),this.read(!0)}read(t){if(this.reading===t)return;this.reading=t;let n=(e.get(this.model)??0)+(t?1:-1);n>0?e.set(this.model,n):e.delete(this.model)}registerPasses(e){e.add({name:this.name,order:1,execute:e=>{e.backend===`webgpu`&&this.draw(e)}})}draw(e){let t=this.engine,a=this.model.primitives;if(!t||!this.visible||this.model.disposed||!a.length)return;d(this);let o=e.device;this.device!==o&&(this.release(),this.device=o);let l=e.descriptor.multisample?.count??1,u=e.descriptor.depthStencil.format,f=this.opacity<1,p=e.format+l+u+f;if(this.key!==p){let t=o.createShaderModule({code:c});this.key=p,this.groups=[],this.pipeline=o.createRenderPipeline({layout:`auto`,vertex:{module:t,entryPoint:`vertex`,buffers:[{arrayStride:80,stepMode:`instance`,attributes:[{shaderLocation:0,offset:0,format:`float32x3`},{shaderLocation:1,offset:64,format:`float32x4`}]}]},fragment:{module:t,entryPoint:`fragment`,targets:[f?{format:e.format,blend:{color:{srcFactor:`src-alpha`,dstFactor:`one-minus-src-alpha`},alpha:{srcFactor:`one`,dstFactor:`one-minus-src-alpha`}}}:{format:e.format}]},primitive:{topology:`triangle-strip`},depthStencil:{format:u,depthWriteEnabled:!0,depthCompare:`greater-equal`},multisample:{count:l}})}(!this.frames||this.frames.size<a.length*256)&&(this.frames?.destroy(),this.frames=o.createBuffer({size:a.length*256,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST}),this.groups=[]);let m=t.canvas?.clientWidth,h=this.sizeUnits===`pixels`&&m?this.size*(e.width/m):this.size,[g,_]=r(e),v=s(e.camera.matrix,h,this.sizeUnits,g,_,this.scale),y=this.values;y.set(e.camera.matrix),y.set(this.color,32),y[35]=this.opacity,y.set(v,36),y[39]=+(this.shape===`round`),y[40]=+this.vertexColors,y[41]=+i(e.format);let b=e.encoder.beginRenderPass({colorAttachments:[{view:e.color,loadOp:`load`,storeOp:`store`}],depthStencilAttachment:{view:e.depth,depthLoadOp:`load`,depthStoreOp:`store`,stencilReadOnly:!0}});try{n(b,e),b.setPipeline(this.pipeline),a.forEach((e,n)=>{let r=e.vertices.length/20;r&&(y.set(e.node.matrix,16),o.queue.writeBuffer(this.frames,n*256,y),b.setBindGroup(0,this.groups[n]??=o.createBindGroup({layout:this.pipeline.getBindGroupLayout(0),entries:[{binding:0,resource:{buffer:this.frames,offset:n*256,size:176}}]})),e.deformed?b.setVertexBuffer(0,e.deformed,e.deformedOffset??0,r*80):b.setVertexBuffer(0,this.bind(o,e)),b.draw(4,r),t.stats.drawCalls++)})}finally{b.end()}}bind(e,t){let n=this.own.get(t);return n?.source!==t.vertices&&(n?.buffer.destroy(),n={source:t.vertices,buffer:e.createBuffer({size:t.vertices.byteLength,usage:GPUBufferUsage.VERTEX|GPUBufferUsage.COPY_DST})},e.queue.writeBuffer(n.buffer,0,t.vertices),this.own.set(t,n)),n.buffer}release(){this.frames?.destroy();for(let{buffer:e}of this.own.values())e.destroy();this.own.clear(),this.frames=this.pipeline=this.device=void 0,this.groups=[],this.key=``}onDeviceRestored(){this.release()}dispose(){this.disposed||(this.disposed=!0,this.read(!1),this.unsubscribe?.(),this.unsubscribe=void 0,this.engine?.sceneOf(this)?.removePlugin(this.name),this.release(),this.engine=void 0)}[Symbol.dispose??Symbol()](){this.dispose()}};function d({size:e,sizeUnits:t,opacity:n,shape:r,vertexColors:i}){if(!(e>=0&&Number.isFinite(e))||t!==`pixels`&&t!==`world`||!(n>=0&&n<=1)||r!==`square`&&r!==`round`)throw RangeError(`Invalid point options; use a finite size >= 0, sizeUnits 'pixels' or 'world', opacity in 0..1 and shape 'square' or 'round'`);if(typeof i!=`boolean`)throw TypeError(`DeformedPoints vertexColors must be true or false`)}export{u as DeformedPoints,c as deformedPointsShader,s as pointScale};
|
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
/** Step interpolation identifier, shared with familiar keyframe APIs. */
|
|
2
|
+
export declare const InterpolateDiscrete = 2300;
|
|
3
|
+
/** Categorical values are never numerically interpolated. */
|
|
4
|
+
export type DiscreteValue = boolean | string;
|
|
5
|
+
/** Optional property path or explicit synchronous accessors. Default path: track.name. */
|
|
6
|
+
export interface DiscreteBindingOptions<T extends DiscreteValue> {
|
|
7
|
+
property?: string;
|
|
8
|
+
get?: () => T;
|
|
9
|
+
set?: (value: T) => void;
|
|
10
|
+
}
|
|
11
|
+
/** One bound categorical channel, usable by createDiscreteClip and AnimationMixer. */
|
|
12
|
+
export interface BoundDiscreteTrack {
|
|
13
|
+
readonly target: object;
|
|
14
|
+
readonly property: string;
|
|
15
|
+
readonly duration: number;
|
|
16
|
+
sample(time: number): DiscreteValue;
|
|
17
|
+
read(): DiscreteValue;
|
|
18
|
+
write(value: DiscreteValue): void;
|
|
19
|
+
}
|
|
20
|
+
/** Bound boolean/string clip for the optional action mixer. */
|
|
21
|
+
export interface DiscreteClip {
|
|
22
|
+
readonly kind: 'discrete';
|
|
23
|
+
readonly name: string;
|
|
24
|
+
readonly duration: number;
|
|
25
|
+
readonly tracks: readonly BoundDiscreteTrack[];
|
|
26
|
+
}
|
|
27
|
+
/** JSON-compatible categorical track record. */
|
|
28
|
+
export interface DiscreteTrackData {
|
|
29
|
+
name: string;
|
|
30
|
+
type: 'bool' | 'string';
|
|
31
|
+
times: readonly number[];
|
|
32
|
+
values: readonly DiscreteValue[];
|
|
33
|
+
interpolation?: typeof InterpolateDiscrete;
|
|
34
|
+
}
|
|
35
|
+
declare abstract class StepTrack<T extends DiscreteValue> {
|
|
36
|
+
readonly name: string;
|
|
37
|
+
private readonly valueType;
|
|
38
|
+
/** Step interpolation is the only supported mode. */
|
|
39
|
+
readonly DefaultInterpolation = 2300;
|
|
40
|
+
/** Values use ordinary arrays so booleans and strings retain their types. */
|
|
41
|
+
readonly ValueBufferType: ArrayConstructor;
|
|
42
|
+
/** Double-precision key times preserve authored boundary positions. */
|
|
43
|
+
readonly TimeBufferType: Float64ArrayConstructor;
|
|
44
|
+
protected keyTimes: Float64Array;
|
|
45
|
+
protected keyValues: readonly T[];
|
|
46
|
+
/** Categorical value type. */
|
|
47
|
+
abstract readonly ValueTypeName: 'bool' | 'string';
|
|
48
|
+
constructor(name: string, times: ArrayLike<number>, values: readonly T[], valueType: 'boolean' | 'string');
|
|
49
|
+
/** Owned key times in seconds. Treat this view as read-only; use editing methods. */
|
|
50
|
+
get times(): Float64Array;
|
|
51
|
+
/** Frozen key values, copied from input. */
|
|
52
|
+
get values(): readonly T[];
|
|
53
|
+
/** One categorical value per key. */
|
|
54
|
+
getValueSize(): number;
|
|
55
|
+
/** Always InterpolateDiscrete. */
|
|
56
|
+
getInterpolation(): typeof InterpolateDiscrete;
|
|
57
|
+
/** Reject non-step interpolation rather than coercing categorical values. */
|
|
58
|
+
setInterpolation(mode: number): this;
|
|
59
|
+
/** Hold the last key at or before time, clamping outside the key range. Exact key times select that key. */
|
|
60
|
+
sample(time: number): T;
|
|
61
|
+
/** Familiar interpolant interface; evaluate reuses one output array. */
|
|
62
|
+
createInterpolant(result?: T[]): {
|
|
63
|
+
evaluate(time: number): T[];
|
|
64
|
+
};
|
|
65
|
+
/** Validate retained buffers after external inspection. */
|
|
66
|
+
validate(): boolean;
|
|
67
|
+
/** Shift all key times, rejecting precision collapse before changing them. */
|
|
68
|
+
shift(offset: number): this;
|
|
69
|
+
/**
|
|
70
|
+
* Scale time; a negative factor mirrors the track so it plays the original backwards. Zero is invalid. Under
|
|
71
|
+
* hold-last sampling the value held over (t[i], t[i+1]] moves to the key at -t[i+1], so values shift by one key:
|
|
72
|
+
* the original last value, held there for an instant only, is not kept.
|
|
73
|
+
*/
|
|
74
|
+
scale(factor: number): this;
|
|
75
|
+
/** Clip to inclusive bounds, inserting held boundary samples so no categorical state is lost. */
|
|
76
|
+
trim(start: number, end: number): this;
|
|
77
|
+
/** Remove redundant held keys, preserving the first and last key/duration. */
|
|
78
|
+
optimize(): this;
|
|
79
|
+
/** Serialize a track without executable accessors. */
|
|
80
|
+
toJSON(): DiscreteTrackData;
|
|
81
|
+
/** Bind a property once, or supply explicit get/set. Bind again after editing keys or replacing a containing object. */
|
|
82
|
+
bind(root: object, options?: DiscreteBindingOptions<T>): BoundDiscreteTrack;
|
|
83
|
+
}
|
|
84
|
+
/** Step-sampled visibility and other boolean flags. */
|
|
85
|
+
export declare class BooleanKeyframeTrack extends StepTrack<boolean> {
|
|
86
|
+
readonly ValueTypeName: 'bool';
|
|
87
|
+
constructor(name: string, times: ArrayLike<number>, values: readonly boolean[]);
|
|
88
|
+
/** Independent copy of this track and its key buffers. */
|
|
89
|
+
clone(): BooleanKeyframeTrack;
|
|
90
|
+
}
|
|
91
|
+
/** Step-sampled text, labels and other string properties. */
|
|
92
|
+
export declare class StringKeyframeTrack extends StepTrack<string> {
|
|
93
|
+
readonly ValueTypeName: 'string';
|
|
94
|
+
constructor(name: string, times: ArrayLike<number>, values: readonly string[]);
|
|
95
|
+
/** Independent copy of this track and its key buffers. */
|
|
96
|
+
clone(): StringKeyframeTrack;
|
|
97
|
+
}
|
|
98
|
+
/** Restore JSON data as a typed categorical track. */
|
|
99
|
+
export declare function parseDiscreteTrack(data: DiscreteTrackData): BooleanKeyframeTrack | StringKeyframeTrack;
|
|
100
|
+
/** Create a bound action clip. Highest effective action weight wins each categorical property; ties use the later action. */
|
|
101
|
+
export declare function createDiscreteClip(name: string, tracks: readonly BoundDiscreteTrack[]): DiscreteClip;
|
|
102
|
+
export {};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{n as e}from"./errors-t1ewumJS.js";var t=2300,n=t=>Object.assign(e(t,`arguments`),{code:`arguments`}),r=(e,t)=>{if(!Number.isFinite(e))throw n(`Invalid discrete ${t}; pass a finite number`);return e},i=e=>e.length>0&&Array.from(e).every((t,n)=>Number.isFinite(t)&&(n===0||t>e[n-1]));function a(e,t){if(!e||typeof e!=`object`||typeof t!=`string`||!t)throw n(`Invalid discrete binding; pass an object and a nonempty property path`);let r=/\.?([A-Za-z_$][\w$]*|\d+)|\[(?:(\d+)|"([^"\\]+)"|'([^'\\]+)')\]/gy,i=[];for(let e=0;e<t.length;){r.lastIndex=e;let a=r.exec(t);if(!a)throw n(`Invalid discrete property path; use dot names or quoted/numeric brackets`);let o=a[1]??a[2]??a[3]??a[4];if([`__proto__`,`prototype`,`constructor`].includes(o))throw n(`Unsafe discrete property path; choose an ordinary data property`);i.push(o),e=r.lastIndex}let a=e;for(let e of i.slice(0,-1)){let r=Reflect.get(a,e);if(!r||typeof r!=`object`)throw n(`Missing discrete path ${t}; initialize every containing object before binding`);a=r}return{target:a,property:i.at(-1)}}var o=class{constructor(e,r,a,o){if(this.name=e,this.valueType=o,this.DefaultInterpolation=t,this.ValueBufferType=Array,this.TimeBufferType=Float64Array,typeof e!=`string`||!e||!r||!Array.isArray(a)||r.length!==a.length||!i(r)||Array.from(a).some(e=>typeof e!==o))throw n(`Invalid ${o} keyframes; pass a name, strictly increasing finite times and one ${o} per time`);this.keyTimes=Float64Array.from(r),this.keyValues=Object.freeze([...a])}get times(){return this.keyTimes}get values(){return this.keyValues}getValueSize(){return 1}getInterpolation(){return t}setInterpolation(e){if(e!==2300)throw n(`Categorical tracks require InterpolateDiscrete; use a numeric track for interpolation`);return this}sample(e){r(e,`sample time`);let t=0,n=this.keyTimes.length-1;for(;t<n;){let r=Math.ceil((t+n)/2);this.keyTimes[r]<=e?t=r:n=r-1}return this.keyValues[t]}createInterpolant(e=[]){if(!Array.isArray(e))throw n(`Categorical interpolation needs a plain array; numeric buffers coerce boolean/string values`);return{evaluate:t=>(e[0]=this.sample(t),e)}}validate(){return i(this.keyTimes)&&this.keyTimes.length===this.keyValues.length&&this.keyValues.every(e=>typeof e===this.valueType)}shift(e){r(e,`offset`);let t=Float64Array.from(this.keyTimes,t=>t+e);if(!i(t))throw n(`Discrete shift loses time ordering; use a smaller finite offset`);return this.keyTimes=t,this}scale(e){if(r(e,`scale`),!e)throw n(`Discrete scale must be nonzero; use action timeScale to pause`);let t=Float64Array.from(this.keyTimes,t=>t*e+0);if(e<0&&t.reverse(),!i(t))throw n(`Discrete scale loses time ordering; use a finite factor that preserves distinct keys`);if(this.keyTimes=t,e<0){let e=this.keyValues,t=e.length;this.keyValues=Object.freeze(e.map((n,r)=>e[r<t-1?t-2-r:0]))}return this}trim(e,t){if(r(e,`trim start`),r(t,`trim end`),t<e)throw n(`Discrete trim end precedes start; pass start <= end`);let i=[e],a=[this.sample(e)];for(let n=0;n<this.keyTimes.length;n++)this.keyTimes[n]>e&&this.keyTimes[n]<t&&(i.push(this.keyTimes[n]),a.push(this.keyValues[n]));return t>e&&(i.push(t),a.push(this.sample(t))),this.keyTimes=Float64Array.from(i),this.keyValues=Object.freeze(a),this}optimize(){let e=[],t=[];for(let n=0;n<this.keyTimes.length;n++)(n===0||n===this.keyTimes.length-1||this.keyValues[n]!==this.keyValues[n-1])&&(e.push(this.keyTimes[n]),t.push(this.keyValues[n]));return this.keyTimes=Float64Array.from(e),this.keyValues=Object.freeze(t),this}toJSON(){return{name:this.name,type:this.ValueTypeName,times:Array.from(this.keyTimes),values:[...this.keyValues],interpolation:t}}bind(e,t={}){let r=t.property??this.name,i=t.get&&t.set?{target:e,property:r}:a(e,r);if(!i.target||typeof i.target!=`object`)throw n(`Discrete accessor binding needs an object identity; pass its owner`);let o=()=>{let e=t.get?t.get():Reflect.get(i.target,i.property);if(typeof e!==this.valueType)throw n(`Discrete ${r} has the wrong type; initialize a ${this.valueType} property or provide get/set`);return e};return o(),{...i,duration:Math.max(0,this.keyTimes.at(-1)),sample:e=>this.sample(e),read:o,write:e=>{if(typeof e!==this.valueType)throw n(`Discrete ${r} needs a ${this.valueType}; keep the binding value type`);if(t.set)t.set(e);else if(!Reflect.set(i.target,i.property,e))throw n(`Discrete ${r} is read-only; provide an explicit setter`)}}}},s=class e extends o{constructor(e,t,n){super(e,t,n,`boolean`),this.ValueTypeName=`bool`}clone(){return new e(this.name,this.times,this.values)}},c=class e extends o{constructor(e,t,n){super(e,t,n,`string`),this.ValueTypeName=`string`}clone(){return new e(this.name,this.times,this.values)}};function l(e){if(!e||e.type!==`bool`&&e.type!==`string`)throw n(`Unknown discrete track type; choose bool or string`);return(e.type===`bool`?new s(e.name,e.times,e.values):new c(e.name,e.times,e.values)).setInterpolation(e.interpolation??2300)}function u(e,t){if(typeof e!=`string`||!e||!Array.isArray(t)||!t.length)throw n(`Discrete clip needs a name and bound tracks; call track.bind(target) first`);let r=/* @__PURE__ */ new Map,i=0;for(let e of t){if(!e||typeof e.sample!=`function`||typeof e.read!=`function`||typeof e.write!=`function`||!e.target||typeof e.target!=`object`||typeof e.property!=`string`||!Number.isFinite(e.duration)||e.duration<0)throw n(`Invalid discrete clip channel; use track.bind(target)`);let t=e.read();if(typeof t!=`boolean`&&typeof t!=`string`)throw n(`Discrete clip channels need boolean or string originals; use a numeric clip for numbers`);let a=r.get(e.target);if(a||r.set(e.target,a=/* @__PURE__ */ new Set),a.has(e.property))throw n(`Duplicate discrete clip target; use one track per property`);a.add(e.property),i=Math.max(i,e.duration)}return Object.freeze({kind:`discrete`,name:e,duration:i,tracks:Object.freeze([...t])})}export{s as BooleanKeyframeTrack,t as InterpolateDiscrete,c as StringKeyframeTrack,u as createDiscreteClip,l as parseDiscreteTrack};
|
package/dist/dqs.d.ts
ADDED
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
import { type SkinningMode } from './shader.js';
|
|
2
|
+
/**
|
|
3
|
+
* Turns bone matrices (column major, 16 floats each, as a skin palette holds them) into 16-float dual quaternion slots:
|
|
4
|
+
* the rotation quaternion, its dual part, then the symmetric stretch (s00, s11, s22, s01, s02, s12, 0, 0). `out` may be
|
|
5
|
+
* `palette` itself. Every finite matrix encodes, singular and mirrored ones included; shear goes into the stretch.
|
|
6
|
+
*/
|
|
7
|
+
export declare function encodeDualQuaternions(palette: Float32Array, out?: Float32Array): Float32Array;
|
|
8
|
+
/**
|
|
9
|
+
* The `skinning` option of `Animation`: dual quaternion blending for every skinned primitive of that Animation.
|
|
10
|
+
*
|
|
11
|
+
* @example
|
|
12
|
+
* ```ts
|
|
13
|
+
* const animation = Animation.attach(model, { skinning: dualQuaternionSkinning });
|
|
14
|
+
* ```
|
|
15
|
+
*/
|
|
16
|
+
export declare const dualQuaternionSkinning: SkinningMode;
|
|
17
|
+
/**
|
|
18
|
+
* The `skinning` option for a skin that blends linear and dual quaternion skinning per vertex, as an FBX `Blend` skin
|
|
19
|
+
* does (Autodesk's FbxSkin::eBlend: each control point has its own share of dual quaternion). The share of each vertex
|
|
20
|
+
* comes from the node's `extras.fbxSkinning.blendWeights`, which `@margoengine/fbx/deformers` writes, one number in
|
|
21
|
+
* [0, 1] per vertex of the node's primitive (0 is linear, 1 is all dual quaternion). A node without it is all dual
|
|
22
|
+
* quaternion. Position, normal and tangent blend between the two skins with that share. Its `blend` gives the same pose
|
|
23
|
+
* on the CPU for synchronous raycasts.
|
|
24
|
+
*
|
|
25
|
+
* @example
|
|
26
|
+
* ```ts
|
|
27
|
+
* const animation = Animation.attach(model, { skinning: blendSkinning });
|
|
28
|
+
* ```
|
|
29
|
+
*/
|
|
30
|
+
export declare const blendSkinning: SkinningMode;
|
|
31
|
+
/** Where one vertex goes, the CPU twin of the shader. */
|
|
32
|
+
export interface SkinnedVertex {
|
|
33
|
+
position: [number, number, number];
|
|
34
|
+
normal: [number, number, number];
|
|
35
|
+
}
|
|
36
|
+
/**
|
|
37
|
+
* One vertex under encoded bones (`encodeDualQuaternions`), the same steps as the GPU in double precision, for checks
|
|
38
|
+
* and CPU picking. `joints` and `weights` are parallel, with weights summing to 1; the normal comes back unit length.
|
|
39
|
+
* `share` is the vertex's share of dual quaternion (default 1, all of it), the rest being the linear skin of the same
|
|
40
|
+
* bones, as `blendSkinning` draws it.
|
|
41
|
+
*/
|
|
42
|
+
export declare function skinDualQuaternion(slots: Float32Array, joints: ArrayLike<number>, weights: ArrayLike<number>, position: ArrayLike<number>, normal?: ArrayLike<number>, share?: number): SkinnedVertex;
|