@margoengine/gltf 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.
Files changed (138) hide show
  1. package/LICENSE +201 -0
  2. package/NOTICE +4 -0
  3. package/README.md +1753 -2
  4. package/dist/accessor-CU_1uSZ1.js +1 -0
  5. package/dist/accessor-DuqjpuxI.js +1 -0
  6. package/dist/accessor.d.ts +12 -0
  7. package/dist/asset-DN3ocEdY.js +4 -0
  8. package/dist/asset-entry.d.ts +1 -0
  9. package/dist/asset-entry.js +1 -0
  10. package/dist/asset.d.ts +395 -0
  11. package/dist/audio.d.ts +47 -0
  12. package/dist/audio.js +1 -0
  13. package/dist/auto.d.ts +29 -0
  14. package/dist/auto.js +1 -0
  15. package/dist/base-textures.d.ts +20 -0
  16. package/dist/coalesce.d.ts +29 -0
  17. package/dist/compression-CUOCmjmE.js +1 -0
  18. package/dist/compression.d.ts +21 -0
  19. package/dist/coordinates.d.ts +1 -0
  20. package/dist/coordinates.js +1 -0
  21. package/dist/dds.d.ts +7 -0
  22. package/dist/dds.js +1 -0
  23. package/dist/decoder-default-CxLH8Vz0.js +1 -0
  24. package/dist/decoder-default.d.ts +5 -0
  25. package/dist/default-materials.d.ts +10 -0
  26. package/dist/default-transmission.d.ts +13 -0
  27. package/dist/draco-state.d.ts +7 -0
  28. package/dist/draw-batch.d.ts +83 -0
  29. package/dist/draw-memo.d.ts +136 -0
  30. package/dist/extended.d.ts +12 -0
  31. package/dist/extended.js +1 -0
  32. package/dist/gltf.worker.d.ts +1 -0
  33. package/dist/group.d.ts +18 -0
  34. package/dist/image-limit-DvFSfR5T.js +1 -0
  35. package/dist/image-limit.d.ts +6 -0
  36. package/dist/index.d.ts +95 -0
  37. package/dist/index.js +1 -0
  38. package/dist/instanced-shader-C9ZMazvo.js +5 -0
  39. package/dist/instanced-shader.d.ts +14 -0
  40. package/dist/instancing.d.ts +9 -0
  41. package/dist/instancing.js +1 -0
  42. package/dist/interactivity-graph.d.ts +193 -0
  43. package/dist/interactivity-model.d.ts +94 -0
  44. package/dist/interactivity-ops.d.ts +20 -0
  45. package/dist/interactivity.d.ts +33 -0
  46. package/dist/interactivity.js +1 -0
  47. package/dist/lights.d.ts +98 -0
  48. package/dist/lights.js +1 -0
  49. package/dist/limits-_LZ441oV.js +1 -0
  50. package/dist/material-draw-state-GKiHDb0p.js +1 -0
  51. package/dist/material-draw-state.d.ts +7 -0
  52. package/dist/material-draw.d.ts +18 -0
  53. package/dist/material-draw.js +1 -0
  54. package/dist/material-extension.d.ts +96 -0
  55. package/dist/mesh-source-DvU8YvMc.js +1 -0
  56. package/dist/meshopt.d.ts +9 -0
  57. package/dist/meshopt.js +1 -0
  58. package/dist/metadata.d.ts +114 -0
  59. package/dist/metadata.js +1 -0
  60. package/dist/mipmaps-38NmjDc3.js +21 -0
  61. package/dist/model-C77ATxi1.js +25 -0
  62. package/dist/model-entry.d.ts +2 -0
  63. package/dist/model-entry.js +1 -0
  64. package/dist/model.d.ts +1088 -0
  65. package/dist/native-glass-D85twud0.js +19 -0
  66. package/dist/node-image-decode.d.ts +6 -0
  67. package/dist/node-matrix-R9BipGnp.js +1 -0
  68. package/dist/node-matrix.d.ts +16 -0
  69. package/dist/occlusion.d.ts +8 -0
  70. package/dist/pack-DdxRO8k6.js +1 -0
  71. package/dist/pack.d.ts +27 -0
  72. package/dist/parts.d.ts +54 -0
  73. package/dist/pbr-instancing.d.ts +83 -0
  74. package/dist/pbr-instancing.js +1 -0
  75. package/dist/pbr.d.ts +13 -0
  76. package/dist/pbr.js +1 -0
  77. package/dist/physics.d.ts +148 -0
  78. package/dist/physics.js +1 -0
  79. package/dist/prepare.d.ts +26 -0
  80. package/dist/prepare.js +1 -0
  81. package/dist/progressive-lod.d.ts +13 -0
  82. package/dist/progressive.d.ts +62 -0
  83. package/dist/progressive.js +4 -0
  84. package/dist/progressive.worker.d.ts +1 -0
  85. package/dist/quantized.d.ts +8 -0
  86. package/dist/quantized.js +1 -0
  87. package/dist/render-state.d.ts +18 -0
  88. package/dist/replica.d.ts +37 -0
  89. package/dist/report.d.ts +128 -0
  90. package/dist/report.js +1 -0
  91. package/dist/scene-data.d.ts +61 -0
  92. package/dist/scene-data.js +1 -0
  93. package/dist/scene-scope-CZDEkd24.js +4 -0
  94. package/dist/scene.d.ts +61 -0
  95. package/dist/scene.js +4 -0
  96. package/dist/shader-C29RtPAw.js +409 -0
  97. package/dist/shader.d.ts +246 -0
  98. package/dist/shared/caster.d.ts +159 -0
  99. package/dist/shared/gltf.d.ts +257 -0
  100. package/dist/shared/iridescence.d.ts +2 -0
  101. package/dist/shared/prepared-geometry.d.ts +8 -0
  102. package/dist/side-shader.d.ts +1 -0
  103. package/dist/soft-mesh.d.ts +132 -0
  104. package/dist/soft-mesh.js +4 -0
  105. package/dist/spec-gloss.d.ts +21 -0
  106. package/dist/spec-gloss.js +18 -0
  107. package/dist/splat-state.d.ts +7 -0
  108. package/dist/splats.d.ts +18 -0
  109. package/dist/splats.js +1 -0
  110. package/dist/src-Btvz5f6i.js +4 -0
  111. package/dist/stream-CrfNNCRd.js +1 -0
  112. package/dist/stream.d.ts +104 -0
  113. package/dist/stroke-width-B2cnYGgn.js +1 -0
  114. package/dist/stroke-width.d.ts +18 -0
  115. package/dist/strokes.d.ts +12 -0
  116. package/dist/strokes.js +1 -0
  117. package/dist/texture-coordinates-XFsEMdU6.js +2 -0
  118. package/dist/texture-coordinates.d.ts +26 -0
  119. package/dist/texture-stream-Cu_XpyVO.js +4 -0
  120. package/dist/texture-stream.d.ts +88 -0
  121. package/dist/textured.d.ts +34 -0
  122. package/dist/textured.js +5 -0
  123. package/dist/transmission.d.ts +81 -0
  124. package/dist/transmission.js +66 -0
  125. package/dist/uniform-arena.d.ts +78 -0
  126. package/dist/version-B6NE5cJf.js +1 -0
  127. package/dist/version.d.ts +8 -0
  128. package/dist/vertex-inputs.d.ts +53 -0
  129. package/dist/view-uniform.d.ts +13 -0
  130. package/dist/visibility-C_Oqz9Sr.js +1 -0
  131. package/dist/warning-UqjZyyqW.js +89 -0
  132. package/dist/warning.d.ts +24 -0
  133. package/dist/worker-CY1TQnYX.js +1 -0
  134. package/dist/worker.d.ts +21 -0
  135. package/dist/worker.js +4 -0
  136. package/dist/workers/gltf.js +322 -0
  137. package/dist/workers/progressive.js +1 -0
  138. package/package.json +232 -4
@@ -0,0 +1,193 @@
1
+ import { type GraphValue } from './interactivity-ops.js';
2
+ import { type ObjectModel } from './interactivity-model.js';
3
+ type Json = Record<string, any>;
4
+ type Sampler = (channel: {
5
+ times: Float32Array;
6
+ values: Float32Array;
7
+ width: number;
8
+ interpolation: any;
9
+ }, time: number) => number[];
10
+ /** Why a file's interactivity does not run: `extension` for the whole object, otherwise the selected graph. */
11
+ export declare class GraphRejected extends Error {
12
+ readonly extension: boolean;
13
+ constructor(message: string, extension: boolean);
14
+ }
15
+ /** The type-default value of a signature. */
16
+ export declare function typeDefault(type: string): GraphValue;
17
+ interface Param {
18
+ id: string;
19
+ ref: boolean;
20
+ at: number;
21
+ }
22
+ /** A JSON Pointer Template: path segments, with the parameters at their places. */
23
+ export interface PointerTemplate {
24
+ segments: string[];
25
+ params: Param[];
26
+ }
27
+ /** Parses a pointer template as the specification lays out; undefined for bad syntax. */
28
+ export declare function parseTemplate(text: unknown): PointerTemplate | undefined;
29
+ /** Bezier easing of `variable/interpolate` and `pointer/interpolate`: the y of the curve where its x is `t`. */
30
+ export declare function ease(p1: number[], p2: number[], t: number): number;
31
+ interface Source {
32
+ node?: Live;
33
+ socket?: string;
34
+ constant?: GraphValue;
35
+ type: string;
36
+ }
37
+ /** A node of a running graph. */
38
+ interface Live {
39
+ index: number;
40
+ op: string;
41
+ noop: boolean;
42
+ inputs: Record<string, Source>;
43
+ outputs: Record<string, string>;
44
+ flows: Record<string, {
45
+ node: number;
46
+ socket: string;
47
+ }>;
48
+ /** What the configuration settled. */
49
+ config: Json;
50
+ /** Output values held between activations. */
51
+ state: Json;
52
+ memo?: Record<string, GraphValue>;
53
+ memoEpoch: number;
54
+ /** Input flow sockets, when not just `in`. */
55
+ entries?: string[];
56
+ }
57
+ interface EventDef {
58
+ id?: string;
59
+ values: Record<string, {
60
+ type: string;
61
+ value: GraphValue;
62
+ }>;
63
+ }
64
+ interface Compiled {
65
+ nodes: Live[];
66
+ variables: {
67
+ type: string;
68
+ value: GraphValue;
69
+ name?: string;
70
+ }[];
71
+ events: EventDef[];
72
+ }
73
+ /** Options of a {@link BehaviorGraph}. */
74
+ export interface BehaviorGraphOptions {
75
+ /** Receives `debug/log` output. Default: dropped. */
76
+ log?: (message: string, severity: number) => void;
77
+ /**
78
+ * Flow activations one call may run before the graph stops for good, so a graph that never ends cannot hang the page.
79
+ * Default 1,000,000.
80
+ */
81
+ maxActivations?: number;
82
+ /** Custom events run in one tick; the rest wait for the next. Default 10,000. */
83
+ maxEventsPerTick?: number;
84
+ /** Samples an animation channel. Without it `animation/start` activates `err`. */
85
+ sample?: Sampler;
86
+ /** Runs `rigid_body/*` operations; absent, they do nothing. */
87
+ physics?: GraphPhysics;
88
+ }
89
+ /** The rigid body operations a host can run for a graph. */
90
+ export interface GraphPhysics {
91
+ applyImpulse(nodeIndex: number, linear: number[], angular: number[]): void;
92
+ applyPointImpulse(nodeIndex: number, impulse: number[], position: number[]): void;
93
+ rayCast(start: number[], end: number[], filter: number): {
94
+ nodeIndex: number;
95
+ fraction: number;
96
+ normal: number[];
97
+ } | undefined;
98
+ }
99
+ /** One selection, as `select` takes it. */
100
+ export interface SelectInfo {
101
+ controllerIndex?: number;
102
+ /** Where the ray met the node, in global space. */
103
+ point?: readonly number[];
104
+ /** Where the ray started, in global space. */
105
+ origin?: readonly number[];
106
+ }
107
+ type Listener = (values: Record<string, GraphValue>) => void;
108
+ /** The default graph of a file's KHR_interactivity, or why it does not run. */
109
+ export declare function compileInteractivity(doc: Json, model: ObjectModel, extensions: string[]): Compiled | undefined;
110
+ /**
111
+ * A running behaviour graph. `start` activates `event/onStart`; `tick` moves the clock, and with it delays, interpolations,
112
+ * animations and `event/onTick`. Custom events go in through `send` and out through `on`.
113
+ */
114
+ export declare class BehaviorGraph {
115
+ /** Set when the graph stopped for good, with the reason. */
116
+ halted?: string;
117
+ /** Seconds since `start`. */
118
+ time: number;
119
+ private readonly nodes;
120
+ private readonly variableList;
121
+ private readonly events;
122
+ private readonly model;
123
+ private readonly options;
124
+ private readonly listeners;
125
+ private readonly queue;
126
+ private delays;
127
+ private variableMoves;
128
+ private pointerMoves;
129
+ private playing;
130
+ private readonly refsMade;
131
+ private readonly hovered;
132
+ private epoch;
133
+ private budget;
134
+ private serial;
135
+ private ticked;
136
+ private lastTick;
137
+ private started;
138
+ private running;
139
+ private readonly peers;
140
+ constructor(compiled: Compiled, model: ObjectModel, options?: BehaviorGraphOptions);
141
+ /** Whether the graph has a working node of `op`, such as `event/onSelect`. */
142
+ handles(op: string): boolean;
143
+ /** The value of a variable by index or name. */
144
+ variable(which: number | string): GraphValue;
145
+ /** Calls `listener` when the graph sends the custom event `id`; returns a remover. */
146
+ on(id: string, listener: Listener): () => void;
147
+ /** Sends the custom event `id` into the graph. Values left out take their initial values. */
148
+ send(id: string, values?: Record<string, GraphValue>): boolean;
149
+ /**
150
+ * Forwards this graph's public custom events, those with an id not starting with `_`, to `other` and back, for two files
151
+ * loaded together. Returns a remover.
152
+ */
153
+ link(other: BehaviorGraph): () => void;
154
+ private slice;
155
+ private static readonly spent;
156
+ private occurrence;
157
+ private readonly occurrences;
158
+ /** Runs `targets` in JSON order as one occurrence of an event. */
159
+ private dispatch;
160
+ private of;
161
+ /** Activates `event/onStart`. */
162
+ start(): void;
163
+ /** Moves the clock by `seconds`, then runs what came due and `event/onTick`. The first tick is at time zero. */
164
+ tick(seconds: number): void;
165
+ private drain;
166
+ private runDelays;
167
+ private removeDelay;
168
+ private mixed;
169
+ private runMoves;
170
+ private applyAnimation;
171
+ private finish;
172
+ private runAnimations;
173
+ private input;
174
+ private output;
175
+ private compute;
176
+ /** Resolves a pointer, the graph's own delay and event references included. */
177
+ private lookup;
178
+ /** The effective pointer of a node, or undefined for a negative index or a null reference. */
179
+ private effective;
180
+ private fire;
181
+ private activate;
182
+ private flow;
183
+ private motion;
184
+ private gate;
185
+ private control;
186
+ /** Runs `event/onSelect` for a selection on `nodeIndex`, lowest node first; false when the node is not selectable. */
187
+ select(nodeIndex: number, info?: SelectInfo): boolean;
188
+ /** Moves the hover of a controller to `nodeIndex`, or off everything with undefined. */
189
+ hover(nodeIndex: number | undefined, controllerIndex?: number): void;
190
+ /** Runs a physics trigger event of `op` for the trigger at `nodeIndex`. */
191
+ trigger(op: 'event/rigid_body_triggerEntered' | 'event/rigid_body_triggerExited', nodeIndex: number, colliderNodeIndex: number, motionNodeIndex: number): void;
192
+ }
193
+ export {};
@@ -0,0 +1,94 @@
1
+ import type { GraphRef, GraphValue } from './interactivity-ops.js';
2
+ type Json = Record<string, any>;
3
+ /** One property of the object model. */
4
+ export interface ModelProperty {
5
+ type: string;
6
+ get(): GraphValue;
7
+ /** Absent on a read-only property. */
8
+ set?(value: GraphValue): void;
9
+ }
10
+ /** The camera the viewer shows, for `/extensions/KHR_interactivity/activeCamera`. Any part may be left out. */
11
+ export interface ActiveCamera {
12
+ position?: readonly number[];
13
+ rotation?: readonly number[];
14
+ perspective?: {
15
+ aspectRatio: number;
16
+ yfov: number;
17
+ znear: number;
18
+ zfar: number;
19
+ };
20
+ orthographic?: {
21
+ xmag: number;
22
+ ymag: number;
23
+ znear: number;
24
+ zfar: number;
25
+ };
26
+ }
27
+ /** One animation channel, flattened to the pointer it writes. */
28
+ export interface ModelChannel {
29
+ pointer: string;
30
+ times: Float32Array;
31
+ values: Float32Array;
32
+ width: number;
33
+ interpolation: 'STEP' | 'LINEAR' | 'CUBICSPLINE';
34
+ }
35
+ /** What `/animations/{}/extensions/KHR_interactivity` reports for one animation. */
36
+ export interface AnimationState {
37
+ channels: ModelChannel[];
38
+ minTime: number;
39
+ maxTime: number;
40
+ isPlaying: boolean;
41
+ playhead: number;
42
+ virtualPlayhead: number;
43
+ }
44
+ /** What the object model asks of its surroundings. */
45
+ export interface ModelHost {
46
+ accessor(index: number, type: string): Float32Array;
47
+ live?(pointer: string, value: GraphValue): void;
48
+ camera?(): ActiveCamera | undefined;
49
+ /** glTF extensions this runtime supports. */
50
+ supports(extension: string): boolean;
51
+ }
52
+ export declare const INT_MAX = 2147483647;
53
+ /** The most simultaneous delays, animations and interpolations of each kind; the graph sees them under `limits`. */
54
+ export declare const ACTIVE_LIMIT = 65536;
55
+ /** The object model of one asset. */
56
+ export declare class ObjectModel {
57
+ readonly animations: AnimationState[];
58
+ private readonly doc;
59
+ private readonly host;
60
+ private readonly written;
61
+ private readonly refs;
62
+ private readonly parents;
63
+ private readonly nodes;
64
+ constructor(doc: Json, host: ModelHost);
65
+ /** The one reference of `path`: references of the same object are the same value. */
66
+ ref(path: string): GraphRef;
67
+ /** The reference a static pointer names, or null. */
68
+ resolveRef(pointer: string): GraphRef | null;
69
+ private animation;
70
+ private channelPointer;
71
+ /** Writes what an animation produced; `/nodes/{}/weights` takes the whole array, which no graph can do. */
72
+ animate(pointer: string, value: number[]): void;
73
+ /** The property `pointer` resolves to, or undefined. */
74
+ property(pointer: string): ModelProperty | undefined;
75
+ private count;
76
+ private refTo;
77
+ private stored;
78
+ private fixed;
79
+ private activeCamera;
80
+ private objects;
81
+ private member;
82
+ private node;
83
+ private local;
84
+ private global;
85
+ /** Whether `flag` is on for `node` and every node above it. */
86
+ inherited(node: number, flag: string): boolean;
87
+ /** The parent of `node`, or -1. */
88
+ parent(node: number): number;
89
+ get nodeCount(): number;
90
+ private material;
91
+ private mesh;
92
+ private animationProperty;
93
+ }
94
+ export {};
@@ -0,0 +1,20 @@
1
+ /** An opaque reference of a behaviour graph: a glTF object, a delay or an event, named by its JSON pointer. */
2
+ export interface GraphRef {
3
+ readonly path: string;
4
+ }
5
+ /** A value on a socket: `bool`, `int` and `float` as themselves, vectors and column-major matrices as arrays. */
6
+ export type GraphValue = boolean | number | number[] | GraphRef | null;
7
+ type Outs = Record<string, string>;
8
+ /** A stateless operation: `resolve` maps input types to output types, or undefined for an overload it lacks. */
9
+ export interface PureOp {
10
+ inputs: string[];
11
+ resolve(types: string[]): Outs | undefined;
12
+ /** The `value` output, or a record of all outputs when `multi`. */
13
+ run(values: any[], types: string[]): any;
14
+ multi?: boolean;
15
+ }
16
+ export declare const ops: Map<string, PureOp>;
17
+ export declare const quatMul: (a: number[], b: number[]) => number[];
18
+ /** Spherical interpolation of unit quaternions, `c` unclamped. */
19
+ export declare function quatSlerp(a: number[], b: number[], c: number): number[];
20
+ export {};
@@ -0,0 +1,33 @@
1
+ import { BehaviorGraph, type BehaviorGraphOptions, type GraphPhysics, type SelectInfo } from './interactivity-graph.js';
2
+ import { type ActiveCamera } from './interactivity-model.js';
3
+ import type { GraphRef, GraphValue } from './interactivity-ops.js';
4
+ import type { GLTFAsset } from './pbr.js';
5
+ export { BehaviorGraph };
6
+ export type { ActiveCamera, BehaviorGraphOptions, GraphPhysics, GraphRef, GraphValue, SelectInfo };
7
+ /** Options of {@link loadBehaviorGraph}. */
8
+ export interface LoadBehaviorGraphOptions extends BehaviorGraphOptions {
9
+ /** Receives each written property, to reach something rendered. */
10
+ live?: (pointer: string, value: GraphValue) => void;
11
+ /** The camera the viewer shows; absent, `activeCamera` reads as NaN. */
12
+ camera?: () => ActiveCamera | undefined;
13
+ /** Extensions to report as supported, beyond the ones this entry knows. Default none. */
14
+ supported?: readonly string[];
15
+ }
16
+ /** The behaviour graph of a file, or why it has none. */
17
+ export interface LoadedBehaviorGraph {
18
+ /** The running graph; undefined when the file has none or it was rejected. */
19
+ graph?: BehaviorGraph;
20
+ /** Why the file's graph must not run, when it was rejected. */
21
+ rejected?: string;
22
+ }
23
+ /**
24
+ * Reads the selected behaviour graph of an asset without an engine: time moves only through `graph.tick`. A graph the
25
+ * specification rejects does not throw, as the file stays a valid model: it comes back as `rejected`. `sample` plays
26
+ * animations: `sampleChannel` of `@margoengine/animation/interactivity`, which also runs a graph on a rendered model.
27
+ *
28
+ * @example
29
+ * const {graph, rejected} = loadBehaviorGraph(asset);
30
+ * graph?.on('checkout', ({variant}) => console.log(variant));
31
+ * graph?.tick(1 / 60);
32
+ */
33
+ export declare function loadBehaviorGraph(asset: GLTFAsset, options?: LoadBehaviorGraphOptions): LoadedBehaviorGraph;
@@ -0,0 +1 @@
1
+ import{rotationToQuaternion as e}from"@margoengine/math/quat";import{composeMatrix as t,multiplyMatrices as n}from"@margoengine/math/mat4";var r=[`float`,`float2`,`float3`,`float4`],i=r.slice(1),a=[`float2x2`,`float3x3`,`float4x4`],o=[...r,...a],s=1e-9,c=(e,t)=>n=>e.includes(n[0])&&n.every(e=>e===n[0])?{value:t??n[0]}:void 0,l=(e,t)=>n=>n.join(` `)===e?typeof t==`string`?{value:t}:t:void 0,u=e=>t=>Array.isArray(t[0])?t[0].map((n,r)=>e(...t.map(e=>e[r]))):e(...t),d=/* @__PURE__ */ new Map,f=(e,t,n,r,i)=>d.set(e,{inputs:t?t.split(` `):[],resolve:n,run:r,multi:i}),p=(e,t,n,r,i)=>{let a=u(r);f(e,t,c(i?[...n,`int`]:n),(e,t)=>t[0]===`int`?i(...e):a(e))};for(let[e,t]of[[`E`,Math.E],[`Pi`,Math.PI],[`Tau`,2*Math.PI],[`Inf`,1/0],[`NaN`,NaN]])f(`math/${e}`,``,()=>({value:`float`}),()=>t);var ee=(e,t,n)=>Math.min(Math.max(e,Math.min(t,n)),Math.max(t,n)),te=e=>Math.min(Math.max(e,0),1);p(`math/abs`,`a`,o,Math.abs,e=>Math.abs(e)|0),p(`math/sign`,`a`,o,Math.sign,Math.sign),p(`math/trunc`,`a`,o,Math.trunc),p(`math/floor`,`a`,o,Math.floor),p(`math/ceil`,`a`,o,Math.ceil),p(`math/round`,`a`,o,e=>e<0?-Math.round(-e):Math.round(e)),p(`math/fract`,`a`,o,e=>e-Math.floor(e)),p(`math/neg`,`a`,o,e=>-e,e=>-e|0),p(`math/add`,`a b`,o,(e,t)=>e+t,(e,t)=>e+t|0),p(`math/sub`,`a b`,o,(e,t)=>e-t,(e,t)=>e-t|0),p(`math/mul`,`a b`,o,(e,t)=>e*t,Math.imul),p(`math/div`,`a b`,o,(e,t)=>e/t,(e,t)=>t?e/t|0:0),p(`math/rem`,`a b`,o,(e,t)=>e%t,(e,t)=>t?e%t|0:0),p(`math/min`,`a b`,o,Math.min,Math.min),p(`math/max`,`a b`,o,Math.max,Math.max),p(`math/clamp`,`a b c`,o,ee,ee),p(`math/saturate`,`a`,o,te),p(`math/mix`,`a b c`,o,(e,t,n)=>(1-n)*e+n*t),p(`math/smoothStep`,`a b c`,r,(e,t,n)=>{let r=te((n-Math.min(e,t))/Math.abs(t-e));return r*r*(3-2*r)});for(let[e,t]of Object.entries({rad:e=>e*Math.PI/180,deg:e=>e*180/Math.PI,sin:Math.sin,cos:Math.cos,tan:Math.tan,asin:Math.asin,acos:Math.acos,atan:Math.atan,sinh:Math.sinh,cosh:Math.cosh,tanh:Math.tanh,asinh:Math.asinh,acosh:Math.acosh,atanh:Math.atanh,exp:Math.exp,log:Math.log,log2:Math.log2,log10:Math.log10,sqrt:Math.sqrt,cbrt:Math.cbrt}))p(`math/${e}`,`a`,r,t);p(`math/atan2`,`a b`,r,Math.atan2),p(`math/pow`,`a b`,r,Math.pow);var ne=(e,t)=>Array.isArray(e)?e.every((e,n)=>e===t[n]):e===t;f(`math/eq`,`a b`,c([...o,`int`,`bool`],`bool`),([e,t])=>ne(e,t));var m=(e,t)=>f(`math/${e}`,`a b`,c([`float`,`int`],`bool`),([e,n])=>t(e,n));m(`lt`,(e,t)=>e<t),m(`le`,(e,t)=>e<=t),m(`gt`,(e,t)=>e>t),m(`ge`,(e,t)=>e>=t),f(`math/isNaN`,`a`,l(`float`,`bool`),([e])=>Number.isNaN(e)),f(`math/isInf`,`a`,l(`float`,`bool`),([e])=>e===1/0||e===-1/0),f(`math/select`,`condition a b`,e=>e[0]===`bool`&&e[1]===e[2]?{value:e[1]}:void 0,([e,t,n])=>e?t:n);var h=(e,t)=>e.reduce((e,n,r)=>e+n*t[r],0),g=(e,t)=>[e[1]*t[2]-e[2]*t[1],e[2]*t[0]-e[0]*t[2],e[0]*t[1]-e[1]*t[0]],_=(e,t)=>e.map(e=>e*t),v=e=>_(e,1/Math.hypot(...e)),y=(e,t,n)=>e.map((e,r)=>(1-n)*e+n*t[r]),b=e=>v(g(e,Math.abs(e[0])<Math.abs(e[1])?[1,0,0]:[0,1,0])),x=(e,t)=>{let n=t.slice(0,3),r=g(n,e),i=g(n,r);return e.map((e,n)=>e+2*(i[n]+t[3]*r[n]))},re=(e,t)=>[e[3]*t[0]+e[0]*t[3]+e[1]*t[2]-e[2]*t[1],e[3]*t[1]+e[1]*t[3]+e[2]*t[0]-e[0]*t[2],e[3]*t[2]+e[2]*t[3]+e[0]*t[1]-e[1]*t[0],e[3]*t[3]-e[0]*t[0]-e[1]*t[1]-e[2]*t[2]];function ie(e,t,n){let r=h(e,t),i=t;if(r<0&&(r=-r,i=_(t,-1)),r>.999999999)return e.map((e,t)=>e*(1-n)+i[t]*n);let a=Math.acos(r),o=Math.sin(a*(1-n))/Math.sin(a),s=Math.sin(a*n)/Math.sin(a);return e.map((e,t)=>e*o+i[t]*s)}var ae=([e,t,n])=>{let r=Math.hypot(...e),i=Math.hypot(...t);if(r<s||i<s)return y(e,t,n);let a=_(e,1/r),o=_(t,1/i),c=(1-n)*r+n*i;if(e.length===2){let e=Math.acos(Math.min(1,Math.max(-1,h(a,o))));a[0]*o[1]-a[1]*o[0]<0&&(e=-e);let t=Math.cos(n*e),r=Math.sin(n*e);return[(a[0]*t-a[1]*r)*c,(a[0]*r+a[1]*t)*c]}let l=h(a,o);if(l>.999999999)return y(e,t,n);let u=l<-.999999999?b(a):v(g(a,o)),d=n*Math.acos(Math.min(1,Math.max(-1,l)))/2;return _(x(a,[..._(u,Math.sin(d)),Math.cos(d)]),c)};f(`math/length`,`a`,c(i,`float`),([e])=>Math.hypot(...e)),f(`math/normalize`,`a`,e=>i.includes(e[0])?{value:e[0],isValid:`bool`}:void 0,([e])=>{let t=Math.hypot(...e),n=t>0&&t<1/0;return{value:n?_(e,1/t):e.map(()=>0),isValid:n}},!0),f(`math/dot`,`a b`,c(i,`float`),([e,t])=>h(e,t)),f(`math/cross`,`a b`,c([`float3`],`float3`),([e,t])=>g(e,t)),f(`math/rotate2D`,`a angle`,l(`float2 float`,`float2`),([e,t])=>{let n=Math.cos(t),r=Math.sin(t);return[e[0]*n-e[1]*r,e[0]*r+e[1]*n]}),f(`math/rotate3D`,`a rotation`,l(`float3 float4`,`float3`),([e,t])=>x(e,t)),f(`math/transform`,`a b`,e=>i.includes(e[0])&&e[1]===`${e[0]}x${e[0].slice(-1)}`?{value:e[0]}:void 0,([e,t])=>e.map((n,r)=>e.reduce((n,i,a)=>n+t[a*e.length+r]*i,0))),f(`math/slerp`,`a b c`,e=>e[0]===e[1]&&(e[0]===`float2`||e[0]===`float3`)&&e[2]===`float`?{value:e[0]}:void 0,e=>ae(e));var S=e=>Math.sqrt(e.length);function C(e){let t=S(e);if(t===1)return e[0];let n=0;for(let r=0;r<t;r++)n+=(r%2?-1:1)*e[r]*C(oe(e,t,0,r));return n}var oe=(e,t,n,r)=>e.filter((e,i)=>Math.floor(i/t)!==n&&i%t!==r);f(`math/transpose`,`a`,c(a),([e])=>{let t=S(e);return e.map((n,r)=>e[r%t*t+Math.floor(r/t)])}),f(`math/determinant`,`a`,c(a,`float`),([e])=>C(e)),f(`math/inverse`,`a`,e=>a.includes(e[0])?{value:e[0],isValid:`bool`}:void 0,([e])=>{let t=C(e),n=S(e);return!Number.isFinite(t)||t===0?{value:e.map(()=>0),isValid:!1}:{value:e.map((r,i)=>{let a=Math.floor(i/n),o=i%n;return((a+o)%2?-1:1)*C(oe(e,n,o,a))/t}),isValid:!0}},!0),f(`math/matMul`,`a b`,c(a),([e,t])=>{let n=S(e);return e.map((r,i)=>{let a=0;for(let r=0;r<n;r++)a+=e[r*n+i%n]*t[Math.floor(i/n)*n+r];return a})}),f(`math/matCompose`,`translation rotation scale`,l(`float3 float4 float3`,`float4x4`),([e,n,r])=>Array.from(t(e,n,r,/* @__PURE__ */ new Float64Array(16))));function se(t){let n=t.slice(12,15),[r,i,a]=[0,4,8].map(e=>Math.hypot(t[e],t[e+1],t[e+2]));return[r,i,a].every(e=>Number.isFinite(e)&&e!==0)?(C([t[0],t[1],t[2],t[4],t[5],t[6],t[8],t[9],t[10]])<0&&(r=-r),{translation:n,rotation:e(t,[0,0,0,0],r,i,a),scale:[r,i,a]}):{translation:n,rotation:[0,0,0,1],scale:[r,i,a]}}f(`math/matDecompose`,`a`,e=>e[0]===`float4x4`?{translation:`float3`,rotation:`float4`,scale:`float3`}:void 0,([e])=>se(e),!0),f(`math/quatConjugate`,`a`,l(`float4`,`float4`),([e])=>[-e[0],-e[1],-e[2],e[3]]),f(`math/quatMul`,`a b`,l(`float4 float4`,`float4`),([e,t])=>re(e,t)),f(`math/quatAngleBetween`,`a b`,l(`float4 float4`,`float`),([e,t])=>2*Math.acos(h(e,t))),f(`math/quatFromAxisAngle`,`axis angle`,l(`float3 float`,`float4`),([e,t])=>[..._(e,Math.sin(.5*t)),Math.cos(.5*t)]),f(`math/quatToAxisAngle`,`a`,l(`float4`,{axis:`float3`,angle:`float`}),([e])=>Math.abs(Math.abs(e[3])-1)<s?{axis:[1,0,0],angle:0}:{axis:_(e.slice(0,3),1/Math.sqrt(1-e[3]*e[3])),angle:2*Math.acos(e[3])},!0),f(`math/quatFromDirections`,`a b`,l(`float3 float3`,`float4`),([e,t])=>{let n=h(e,t);return n>.999999999?[0,0,0,1]:n<-.999999999?[...b(e),0]:[..._(v(g(e,t)),Math.sqrt(.5-.5*n)),Math.sqrt(.5+.5*n)]}),f(`math/quatFromUpForward`,`up forward`,l(`float3 float3`,`float4`),([t,n])=>{let r=g(t,n),i=Math.hypot(...r)<s?b(n):v(r),a=g(n,i);return e([...i,0,...a,0,...n],[0,0,0,0])}),f(`math/quatSlerp`,`a b c`,l(`float4 float4 float`,`float4`),([e,t,n])=>ie(e,t,n));var ce=`abcdefghijklmnop`;for(let[e,t,n]of[[`2`,`float2`,2],[`3`,`float3`,3],[`4`,`float4`,4],[`2x2`,`float2x2`,4],[`3x3`,`float3x3`,9],[`4x4`,`float4x4`,16]]){let r=[...ce.slice(0,n)].join(` `);f(`math/combine${e}`,r,l(Array(n).fill(`float`).join(` `),t),e=>e.slice());let i=Object.fromEntries(Array.from({length:n},(e,t)=>[String(t),`float`]));f(`math/extract${e}`,`a`,l(t,i),([e])=>({...e}),!0)}var w=(e,t,n)=>f(`math/${e}`,`a b`,c([`int`,`bool`]),([e,r],i)=>i[0]===`int`?t(e,r):n(e,r));f(`math/not`,`a`,c([`int`,`bool`]),([e],t)=>t[0]===`int`?~e:!e),w(`and`,(e,t)=>e&t,(e,t)=>e&&t),w(`or`,(e,t)=>e|t,(e,t)=>e||t),w(`xor`,(e,t)=>e^t,(e,t)=>e!==t);var T=(e,t,n)=>f(`math/${e}`,t,c([`int`]),e=>n(...e));T(`asr`,`a b`,(e,t)=>e>>t),T(`lsl`,`a b`,(e,t)=>e<<t),T(`clz`,`a`,Math.clz32),T(`ctz`,`a`,e=>e?31-Math.clz32(e&-e):32),T(`popcnt`,`a`,e=>{let t=0;for(let n=e;n;n&=n-1)t++;return t});var E=(e,t,n,r)=>e[0]*t+e[1]*n+e[2]*r,le=`float float float`;f(`math/rgbToOkLCh`,`r g b`,l(le,{l:`float`,c:`float`,h:`float`}),([e,t,n])=>{let r=Math.cbrt(E([.4122214708,.5363325363,.0514459929],e,t,n)),i=Math.cbrt(E([.2119034982,.6806995451,.1073969566],e,t,n)),a=Math.cbrt(E([.0883024619,.2817188376,.6299787005],e,t,n)),o=E([1.9779984951,-2.428592205,.4505937099],r,i,a),s=E([.0259040371,.7827717662,-.808675766],r,i,a);return{l:E([.2104542553,.793617785,-.0040720468],r,i,a),c:Math.sqrt(o*o+s*s),h:Math.atan2(s,o)}},!0),f(`math/rgbFromOkLCh`,`l c h`,l(le,{r:`float`,g:`float`,b:`float`}),([e,t,n])=>{let r=t*Math.cos(n),i=t*Math.sin(n),a=E([1,.3963377774,.2158037573],e,r,i)**3,o=E([1,-.1055613458,-.0638541728],e,r,i)**3,s=E([1,-.0894841775,-1.291485548],e,r,i)**3;return{r:E([4.0767416621,-3.3077115913,.2309699292],a,o,s),g:E([-1.2684380046,2.6097574011,-.3413193965],a,o,s),b:E([-.0041960863,-.7034186147,1.707614701],a,o,s)}},!0),f(`ref/eq`,`a b`,l(`ref ref`,`bool`),([e,t])=>e===t);var D=(e,t,n,r)=>f(`type/${e}`,`a`,l(t,n),([e])=>r(e));D(`boolToInt`,`bool`,`int`,e=>+!!e),D(`boolToFloat`,`bool`,`float`,e=>+!!e),D(`intToBool`,`int`,`bool`,e=>e!==0),D(`intToFloat`,`int`,`float`,e=>e+0),D(`floatToBool`,`float`,`bool`,e=>!!e),D(`floatToInt`,`float`,`int`,e=>e|0);var ue=65536,de=e=>Array(e).fill(NaN),fe=/\/(0|[1-9]\d*)(?=\/|$|\.length$)/g,O=`extensions/KHR_materials_clearcoat/`,k=`extensions/KHR_materials_iridescence/`,A=`extensions/KHR_materials_sheen/`,j=`extensions/KHR_materials_specular/`,M=`extensions/KHR_materials_volume/`,N=`extensions/KHR_materials_anisotropy/`,P=`pbrMetallicRoughness/`,pe={alphaCutoff:[`float`,.5],emissiveFactor:[`float3`,[0,0,0]],"normalTexture/scale":[`float`,1],"occlusionTexture/strength":[`float`,1],[`${P}baseColorFactor`]:[`float4`,[1,1,1,1]],[`${P}metallicFactor`]:[`float`,1],[`${P}roughnessFactor`]:[`float`,1],[`${N}anisotropyRotation`]:[`float`,0],[`${N}anisotropyStrength`]:[`float`,0],[`${O}clearcoatFactor`]:[`float`,0],[`${O}clearcoatRoughnessFactor`]:[`float`,0],[`${O}clearcoatNormalTexture/scale`]:[`float`,1],"extensions/KHR_materials_dispersion/dispersion":[`float`,0],"extensions/KHR_materials_emissive_strength/emissiveStrength":[`float`,1],"extensions/KHR_materials_ior/ior":[`float`,1.5],[`${k}iridescenceFactor`]:[`float`,0],[`${k}iridescenceIor`]:[`float`,1.3],[`${k}iridescenceThicknessMinimum`]:[`float`,100],[`${k}iridescenceThicknessMaximum`]:[`float`,400],[`${A}sheenColorFactor`]:[`float3`,[0,0,0]],[`${A}sheenRoughnessFactor`]:[`float`,0],[`${j}specularFactor`]:[`float`,1],[`${j}specularColorFactor`]:[`float3`,[1,1,1]],"extensions/KHR_materials_transmission/transmissionFactor":[`float`,0],[`${M}thicknessFactor`]:[`float`,0],[`${M}attenuationDistance`]:[`float`,1/0],[`${M}attenuationColor`]:[`float3`,[1,1,1]]},me=/* @__PURE__ */ new Set([`emissiveTexture`,`normalTexture`,`occlusionTexture`,`${P}baseColorTexture`,`${P}metallicRoughnessTexture`,`${N}anisotropyTexture`,`${O}clearcoatTexture`,`${O}clearcoatRoughnessTexture`,`${O}clearcoatNormalTexture`,`${k}iridescenceTexture`,`${k}iridescenceThicknessTexture`,`${A}sheenColorTexture`,`${A}sheenRoughnessTexture`,`${j}specularTexture`,`${j}specularColorTexture`,`extensions/KHR_materials_transmission/transmissionTexture`,`${M}thicknessTexture`]),he={offset:[`float2`,[0,0]],rotation:[`float`,0],scale:[`float2`,[1,1]]},ge={color:[`float3`,[1,1,1]],intensity:[`float`,1],range:[`float`,1/0],"spot/innerConeAngle":[`float`,0],"spot/outerConeAngle":[`float`,Math.PI/4]},F={perspective:[`aspectRatio`,`yfov`,`zfar`,`znear`],orthographic:[`xmag`,`ymag`,`zfar`,`znear`]},I=(e,t)=>t.split(`/`).reduce((e,t)=>e&&typeof e==`object`?e[t]:void 0,e),_e=class{constructor(e,t){this.written=/* @__PURE__ */ new Map,this.refs=/* @__PURE__ */ new Map,this.doc=e,this.host=t,this.nodes=e.nodes??[],this.parents=new Int32Array(this.nodes.length).fill(-1),this.nodes.forEach((e,t)=>{for(let n of e.children??[])this.parents[n]=t}),this.animations=(e.animations??[]).map(e=>this.animation(e))}ref(e){let t=this.refs.get(e);return t||this.refs.set(e,t={path:e}),t}resolveRef(e){let t=this.property(e);return t?.type===`ref`?t.get():null}animation(e){let t=[],n={channels:t,minTime:NaN,maxTime:NaN,isPlaying:!1,playhead:0,virtualPlayhead:0},r=1/0,i=-1/0;for(let a of e.channels??[]){let o=e.samplers?.[a.sampler],s=this.doc.accessors?.[o?.input],c=this.channelPointer(a.target);if(!s||!c)return{...n,playhead:NaN,virtualPlayhead:NaN};r=Math.min(r,s.min?.[0]??1/0),i=Math.max(i,s.max?.[0]??-1/0);let l=this.host.accessor(o.input,`SCALAR`),u=o.interpolation??`LINEAR`,d=this.doc.accessors?.[o.output],f=this.host.accessor(o.output,d?.type),p=f.length/(u===`CUBICSPLINE`?3:1);t.push({pointer:c,times:l,values:f,width:p/l.length,interpolation:u})}return t.length?{...n,minTime:r,maxTime:i}:{...n,playhead:NaN,virtualPlayhead:NaN}}channelPointer(e){return e?.path===`pointer`?e.extensions?.KHR_animation_pointer?.pointer:e&&Number.isInteger(e.node)?`/nodes/${e.node}/${e.path}`:void 0}animate(e,t){if(e.endsWith(`/weights`))t.forEach((t,n)=>this.property(`${e}/${n}`)?.set?.(t));else{let n=this.property(e);n?.type===`bool`?n.set?.(t[0]!==0):n?.set?.(n.type===`float`?t[0]:t)}}property(e){let t=[],n=e.replace(fe,(e,n)=>(t.push(+n),`/#`));return this.fixed(n,t,e)??this.objects(n,t,e)}count(e){return{type:`int`,get:()=>e?.length??0}}refTo(e){return e===void 0?void 0:{type:`ref`,get:()=>this.ref(e)}}stored(e,t,n,r=!0){return{type:t,get:()=>this.written.has(e)?this.written.get(e):n(),...r?{set:t=>{this.written.set(e,t),this.host.live?.(e,t)}}:{}}}fixed(e,t,n){let r=this.doc,i={"/animations.length":r.animations,"/cameras.length":r.cameras,"/materials.length":r.materials,"/meshes.length":r.meshes,"/nodes.length":r.nodes,"/scenes.length":r.scenes,"/skins.length":r.skins,"/extensions/KHR_lights_punctual/lights.length":r.extensions?.KHR_lights_punctual?.lights};if(e in i)return this.count(i[e]);if(e===`/scene`)return this.refTo(r.scene===void 0?void 0:`/scenes/${r.scene}`);let a={"/animations/#":r.animations,"/cameras/#":r.cameras,"/materials/#":r.materials,"/meshes/#":r.meshes,"/nodes/#":r.nodes,"/scenes/#":r.scenes,"/skins/#":r.skins,"/extensions/KHR_lights_punctual/lights/#":r.extensions?.KHR_lights_punctual?.lights};if(e in a)return a[e]?.[t[0]]===void 0?void 0:this.refTo(n);if(!e.startsWith(`/extensions/KHR_interactivity/`))return;let o=e.slice(30);if(o===`asset/majorVersion`)return{type:`int`,get:()=>2};if(o===`asset/minorVersion`)return{type:`int`,get:()=>0};let s=/^asset\/extensions\/([^/]+)\/enabled$/.exec(o);return s?(r.extensionsUsed??[]).includes(s[1])&&this.host.supports(s[1])?{type:`bool`,get:()=>!0}:void 0:/^limits\/maxActive(Animations|Delays|PropertyInterpolations|VariableInterpolations)$/.test(o)?{type:`int`,get:()=>ue}:this.activeCamera(o)}activeCamera(e){let t=()=>this.host.camera?.();if(e===`activeCamera/position`)return{type:`float3`,get:()=>t()?.position?[...t().position]:de(3)};if(e===`activeCamera/rotation`)return{type:`float4`,get:()=>t()?.rotation?[...t().rotation]:de(4)};let n=/^activeCamera\/(perspective|orthographic)\/(\w+)$/.exec(e);if(n&&F[n[1]].includes(n[2]))return{type:`float`,get:()=>t()?.[n[1]]?.[n[2]]??NaN}}objects(e,t,n){let[,r]=e.split(`/`);if(r===`nodes`)return this.node(e,t,n);if(r===`materials`)return this.material(e,t,n);if(r===`meshes`)return this.mesh(e,t);if(r===`animations`)return this.animationProperty(e,t);if(r===`cameras`){let r=this.doc.cameras?.[t[0]],i=/^\/cameras\/#\/(perspective|orthographic)\/(\w+)$/.exec(e);if(!r||!i||!F[i[1]].includes(i[2])||!r[i[1]])return;let a=r[i[1]][i[2]];return this.stored(n,`float`,()=>a??(i[2]===`zfar`?1/0:NaN))}if(r===`scenes`){let n=this.doc.scenes?.[t[0]];return n?e===`/scenes/#/nodes.length`?this.count(n.nodes):e===`/scenes/#/nodes/#`?this.member(n.nodes,t[1]):void 0:void 0}if(r===`skins`){let n=this.doc.skins?.[t[0]];return n?e===`/skins/#/joints.length`?this.count(n.joints):e===`/skins/#/joints/#`?this.member(n.joints,t[1]):e===`/skins/#/skeleton`?this.refTo(n.skeleton===void 0?void 0:`/nodes/${n.skeleton}`):void 0:void 0}let i=/^\/extensions\/KHR_physics_rigid_bodies\/physicsJoints\/#\/drives\/#\/(maxForce|positionTarget|velocityTarget|stiffness|damping)$/.exec(e);if(i){let e=this.doc.extensions?.KHR_physics_rigid_bodies?.physicsJoints?.[t[0]]?.drives?.[t[1]];return e?this.stored(n,`float`,()=>e[i[1]]??(i[1]===`maxForce`?1/0:0)):void 0}let a=/^\/extensions\/KHR_lights_punctual\/lights\/#\/(.+)$/.exec(e);if(a){let e=this.doc.extensions?.KHR_lights_punctual?.lights?.[t[0]],r=ge[a[1]];return!e||!r||a[1].startsWith(`spot/`)&&e.type!==`spot`?void 0:this.stored(n,r[0],()=>I(e,a[1])??r[1])}}member(e,t){return e?.[t]===void 0?void 0:this.refTo(`/nodes/${e[t]}`)}node(e,t,n){let r=t[0],i=this.nodes[r];if(!i)return;let a=e.slice(9),o=this.doc.meshes?.[i.mesh],s=o?.primitives?.[0]?.targets?.length??0;switch(a){case`translation`:return this.stored(n,`float3`,()=>i.matrix?i.matrix.slice(12,15):(i.translation??[0,0,0]).slice());case`rotation`:return i.matrix?void 0:this.stored(n,`float4`,()=>(i.rotation??[0,0,0,1]).slice());case`scale`:return i.matrix?void 0:this.stored(n,`float3`,()=>(i.scale??[1,1,1]).slice());case`matrix`:return{type:`float4x4`,get:()=>Array.from(this.local(r))};case`globalMatrix`:return{type:`float4x4`,get:()=>Array.from(this.global(r))};case`parent`:return this.refTo(this.parents[r]<0?void 0:`/nodes/${this.parents[r]}`);case`camera`:return this.refTo(i.camera===void 0?void 0:`/cameras/${i.camera}`);case`mesh`:return this.refTo(i.mesh===void 0?void 0:`/meshes/${i.mesh}`);case`skin`:return this.refTo(i.skin===void 0?void 0:`/skins/${i.skin}`);case`children.length`:return this.count(i.children);case`children/#`:return this.member(i.children,t[1]);case`weights.length`:return o?{type:`int`,get:()=>s}:void 0;case`weights/#`:return t[1]>=s?void 0:this.stored(n,`float`,()=>i.weights?.[t[1]]??o.weights?.[t[1]]??0);case`extensions/KHR_lights_punctual/light`:{let e=i.extensions?.KHR_lights_punctual?.light;return this.refTo(e===void 0?void 0:`/extensions/KHR_lights_punctual/lights/${e}`)}}let c=/^extensions\/KHR_physics_rigid_bodies\/motion\/(linearVelocity|angularVelocity|gravityFactor)$/.exec(a);if(c){let e=i.extensions?.KHR_physics_rigid_bodies?.motion;return e?c[1]===`gravityFactor`?this.stored(n,`float`,()=>e.gravityFactor??1):this.stored(n,`float3`,()=>(e[c[1]]??[0,0,0]).slice()):void 0}if(/^extensions\/KHR_node_(visibility\/visible|selectability\/selectable|hoverability\/hoverable)$/.exec(a))return this.stored(n,`bool`,()=>I(i,a)??!0)}local(e){let n=this.nodes[e],r=t=>this.property(`/nodes/${e}/${t}`)?.get();if(n.matrix){let e=Float64Array.from(n.matrix);return e.set(r(`translation`),12),e}return t(r(`translation`),r(`rotation`),r(`scale`),/* @__PURE__ */ new Float64Array(16))}global(e){let t=this.local(e);return this.parents[e]<0?t:n(this.global(this.parents[e]),t,/* @__PURE__ */ new Float64Array(16))}inherited(e,t){for(let n=e;n>=0;n=this.parents[n])if(this.property(`/nodes/${n}/extensions/KHR_node_${t}`)?.get()===!1)return!1;return!0}parent(e){return this.parents[e]??-1}get nodeCount(){return this.nodes.length}material(e,t,n){let r=this.doc.materials?.[t[0]];if(!r)return;let i=e.slice(13);if(i===`doubleSided`)return{type:`bool`,get:()=>!!r.doubleSided};let a=/^(.+)\/extensions\/KHR_texture_transform\/(offset|rotation|scale)$/.exec(i);if(a){if(!me.has(a[1])||!I(r,a[1]))return;let[e,t]=he[a[2]];return this.stored(n,e,()=>{let e=I(r,`${a[1]}/extensions/KHR_texture_transform/${a[2]}`)??t;return Array.isArray(e)?e.slice():e})}let o=pe[i];if(!o)return;let s=/^extensions\/[^/]+/.exec(i)?.[0]??/^(normal|occlusion)Texture/.exec(i)?.[0];if(!s||I(r,s))return this.stored(n,o[0],()=>{let e=I(r,i)??o[1];return Array.isArray(e)?e.slice():e})}mesh(e,t){let n=this.doc.meshes?.[t[0]];if(n){if(e===`/meshes/#/primitives.length`)return this.count(n.primitives);if(e===`/meshes/#/primitives/#`)return n.primitives?.[t[1]]?this.refTo(`/meshes/${t[0]}/primitives/${t[1]}`):void 0;if(e===`/meshes/#/primitives/#/material`){let e=n.primitives?.[t[1]];return e?this.refTo(e.material===void 0?void 0:`/materials/${e.material}`):void 0}}}animationProperty(e,t){let n=this.animations[t[0]],r=/^\/animations\/#\/extensions\/KHR_interactivity\/(isPlaying|minTime|maxTime|playhead|virtualPlayhead)$/.exec(e)?.[1];if(n&&r)return{type:r===`isPlaying`?`bool`:`float`,get:()=>n[r]}}},L=class extends Error{constructor(e,t){super(e),this.extension=t,this.name=`GraphRejected`}},R=(e,t)=>{if(!e)throw new L(`${t}; fix the KHR_interactivity object`,!0)},z=e=>{throw new L(`${e}; fix the behaviour graph`,!1)},B={bool:1,float:1,float2:2,float3:3,float4:4,float2x2:4,float3x3:9,float4x4:16,int:1,ref:1},ve=/* @__PURE__ */ new Set([...Object.keys(B),`custom`]),V=e=>!!e&&typeof e==`object`&&!Array.isArray(e),H=e=>Number.isInteger(e)&&e>=0&&e<2147483648,U=e=>typeof e==`number`&&e===(e|0),W=e=>Array.isArray(e)&&e.length>0,G=e=>V(e)&&Object.keys(e).length>0,ye=e=>typeof e==`string`&&/^(\/([^~]|~[01])*)*$/.test(e);function K(e){return e===`bool`?!1:e===`int`?0:e===`ref`||e===`custom`?null:e===`float`?NaN:Array(B[e]).fill(NaN)}var be=e=>e.replaceAll(`~1`,`/`).replaceAll(`~0`,`~`);function xe(e){if(!ye(e))return;let t=e.split(`/`),n=[];for(let e=0;e<t.length;e++){let r=t[e];if(r===`[`||r===`{`)return;let i=r[0],a=i===`[`?`]`:`}`;if((i===`[`||i===`{`)&&r[1]!==i){let t=r.slice(1,-1);if(!r.endsWith(a)||!t||/[[\]{}]/.test(t))return;let o=be(t);if(n.some(e=>e.id===o))return;n.push({id:o,ref:i===`{`,at:e})}else if((r.match(/\[+|\]+|\{+|\}+/g)??[]).some(e=>e.length%2))return}return{segments:t,params:n}}var Se=e=>e.replaceAll(`[[`,`[`).replaceAll(`]]`,`]`).replaceAll(`{{`,`{`).replaceAll(`}}`,`}`);function Ce(e){let t=[],n=0,r=0;for(let i=0;i<e.length;i++){let a=e[i];if(a===`{`){if(n>1)return;n=+!n}else if(a===`}`){if(n===1)return;n===2&&t.push({from:r,to:i,id:e.slice(r+1,i)}),n=n===0?3:0}else if(n===1)r=i-1,n=2;else if(n===3)return}return n?void 0:t}function we(e,t,n){let r=(e,t,n)=>(3*e-3*t+1)*n**3+(-6*e+3*t)*n*n+3*e*n,i=0,a=1,o=n;for(let s=0;s<60;s++){let s=r(e[0],t[0],o);if(Math.abs(s-n)<1e-12)break;s<n?i=o:a=o,o=(i+a)/2}return r(e[1],t[1],o)}var Te={KHR_node_selectability:{"event/onSelect":{outputs:{selectedNode:`ref`,controllerIndex:`int`,selectionPoint:`float3`,selectionRayOrigin:`float3`,event:`ref`}}},KHR_node_hoverability:{"event/onHoverIn":{outputs:{hoveredNode:`ref`,controllerIndex:`int`,event:`ref`}},"event/onHoverOut":{outputs:{hoveredNode:`ref`,controllerIndex:`int`,event:`ref`}}},KHR_physics_rigid_bodies:{"rigid_body/applyImpulse":{inputs:{nodeIndex:`int`,linearImpulse:`float3`,angularImpulse:`float3`},flows:[`in`],implied:!0},"rigid_body/applyPointImpulse":{inputs:{nodeIndex:`int`,impulse:`float3`,position:`float3`},flows:[`in`],implied:!0},"rigid_body/rayCast":{inputs:{rayStart:`float3`,rayEnd:`float3`,collisionFilterIndex:`int`},outputs:{hitNodeIndex:`int`,hitFraction:`float`,hitNormal:`float3`},flows:[`in`],implied:!0},"event/rigid_body_triggerEntered":{outputs:{colliderNodeIndex:`int`,motionNodeIndex:`int`},implied:!0},"event/rigid_body_triggerExited":{outputs:{colliderNodeIndex:`int`,motionNodeIndex:`int`},implied:!0}}},Ee={"flow/sequence":{},"flow/branch":{inputs:{condition:`bool`}},"flow/switch":{inputs:{selection:`int`}},"flow/while":{inputs:{condition:`bool`}},"flow/for":{inputs:{startIndex:`int`,endIndex:`int`},outputs:{index:`int`}},"flow/doN":{inputs:{n:`int`},outputs:{currentCount:`int`},entries:[`in`,`reset`]},"flow/multiGate":{outputs:{lastIndex:`int`},entries:[`in`,`reset`]},"flow/waitAll":{outputs:{remainingInputs:`int`}},"flow/throttle":{inputs:{duration:`float`},outputs:{lastRemainingTime:`float`},entries:[`in`,`reset`]},"flow/setDelay":{inputs:{duration:`float`},outputs:{lastDelay:`ref`},entries:[`in`,`cancel`]},"flow/cancelDelay":{inputs:{delay:`ref`}},"variable/get":{},"variable/set":{},"variable/interpolate":{inputs:{duration:`float`,p1:`float2`,p2:`float2`}},"pointer/get":{},"pointer/set":{},"pointer/interpolate":{inputs:{duration:`float`,p1:`float2`,p2:`float2`}},"animation/start":{inputs:{animation:`ref`,startTime:`float`,endTime:`float`,speed:`float`}},"animation/stop":{inputs:{animation:`ref`}},"animation/stopAt":{inputs:{animation:`ref`,stopTime:`float`}},"event/onStart":{outputs:{event:`ref`}},"event/onTick":{outputs:{timeSinceStart:`float`,timeSinceLastTick:`float`,event:`ref`}},"event/stopPropagation":{inputs:{stopImmediate:`bool`,event:`ref`}},"event/receive":{},"event/send":{},"debug/log":{},"math/switch":{},"math/random":{outputs:{value:`float`}},"math/quatFromAngles":{inputs:{x:`float`,y:`float`,z:`float`},outputs:{value:`float4`}}},De=Object.freeze({});function q(e,t,n){if(R(W(e),`An inline value is not a non-empty array`),t===`custom`)return null;let r=e;r.length!==B[t]&&z(`A ${t} value has ${r.length} elements`);let[i]=r;return t===`bool`?typeof i==`boolean`?i:z(`A bool value is not a boolean`):t===`int`?U(i)?i|0:z(`An int value is not a 32-bit integer`):t===`ref`?ye(i)?n.resolveRef(i):z(`A ref value is not a JSON pointer`):(r.every(e=>typeof e==`number`)||z(`A ${t} value holds something other than numbers`),t===`float`?i:r.slice())}function Oe(e,t,n){R(V(e),`A graph is not an object`);let r=e,i=[],a=e=>(R(H(e),`A type index is not an index`),e<i.length?i[e]:z(`Type ${e} does not exist`));if(`types`in r){R(W(r.types),`types is empty`);for(let e of r.types)R(V(e)&&typeof e.signature==`string`,`A type has no signature`),ve.has(e.signature)||z(`Unknown type signature ${e.signature}`),e.signature!==`custom`&&i.includes(e.signature)&&z(`Type ${e.signature} is repeated`),i.push(e.signature)}let o=[];if(`variables`in r){R(`types`in r,`variables need types`),R(W(r.variables),`variables is empty`);for(let e of r.variables){R(V(e),`A variable is not an object`);let n=a(e.type);`name`in e&&R(typeof e.name==`string`,`A variable name is not a string`),o.push({type:n,value:`value`in e?q(e.value,n,t):K(n),name:e.name})}}let s=[];if(`events`in r){R(W(r.events),`events is empty`);let e=/* @__PURE__ */ new Set;for(let n of r.events){R(V(n),`An event is not an object`),`id`in n&&(R(typeof n.id==`string`,`An event id is not a string`),e.has(n.id)&&z(`Event id ${n.id} is repeated`),e.add(n.id)),`name`in n&&R(typeof n.name==`string`,`An event name is not a string`);let r={};if(`values`in n){R(G(n.values),`An event has empty values`);for(let[e,i]of Object.entries(n.values)){R(e!==`event`,`An event value is called event`),R(V(i),`An event value is not an object`);let n=a(i.type);r[e]={type:n,value:`value`in i?q(i.value,n,t):K(n)}}}s.push({id:n.id,values:r})}}let c=[];if(`declarations`in r){R(W(r.declarations),`declarations is empty`);let e=/* @__PURE__ */ new Set;for(let t of r.declarations){R(V(t)&&typeof t.op==`string`,`A declaration has no op`);let i=e=>{if(e in t)return R(G(t[e]),`${e} is empty`),R(`types`in r,`${e} needs types`),Object.fromEntries(Object.entries(t[e]).map(([e,t])=>(R(V(t),`A declared socket is not an object`),[e,a(t.type)])))};`extension`in t?R(typeof t.extension==`string`,`A declaration extension is not a string`):(!d.has(t.op)&&!Ee[t.op]&&z(`Unknown operation ${t.op}`),(`inputValueSockets`in t||`outputValueSockets`in t)&&z(`${t.op} declares sockets of its own`));let o=i(`inputValueSockets`),s=i(`outputValueSockets`),l=JSON.stringify([t.op,t.extension,Object.entries(t.inputValueSockets??{}).map(([e,t])=>[e,t.type]).sort()]);e.has(l)&&z(`Declarations of ${t.op} are equal`),e.add(l);let u=n.includes(t.extension)?Te[t.extension]?.[t.op]:void 0,f=(e,t)=>!e&&u?.implied||JSON.stringify(Object.entries(e??{}).sort())===JSON.stringify(Object.entries(t??{}).sort());c.push({op:t.op,extension:t.extension,inputs:u?.implied&&!o?u.inputs:o,outputs:u?.implied&&!s?u.outputs:s,supported:`extension`in t?!!u&&f(o,u.inputs)&&f(s,u.outputs):!0})}}let l=[];return`nodes`in r&&(R(`declarations`in r,`nodes need declarations`),R(W(r.nodes),`nodes is empty`),r.nodes.forEach((e,n)=>{R(V(e)&&H(e.declaration),`A node has no declaration`);let u=e;u.declaration>=c.length&&z(`Declaration ${u.declaration} does not exist`);let d=c[u.declaration];if(`configuration`in u){R(G(u.configuration),`A node has an empty configuration`);for(let e of Object.values(u.configuration))R(V(e)&&W(e.value),`A configuration has no value`)}let f={};if(`values`in u){R(G(u.values),`A node has empty values`);for(let[e,r]of Object.entries(u.values))if(R(V(r),`An input value is not an object`),`node`in r){R(!(`value`in r)&&H(r.node),`An input names no node`),r.node>=n&&z(`An input refers to a later node`);let t=`socket`in r?r.socket:`value`;R(typeof t==`string`,`An input socket is not a string`);let i=l[r.node].outputs[t];i||z(`Node ${r.node} has no output ${t}`),`type`in r&&a(r.type)!==i&&z(`An input does not match the type of output ${t}`),f[e]={node:l[r.node],socket:t,type:i}}else{let n=a(r.type);f[e]={type:n,constant:`value`in r?q(r.value,n,t):K(n)}}}let p={};if(`flows`in u){R(G(u.flows),`A node has empty flows`);for(let[e,t]of Object.entries(u.flows))R(V(t)&&H(t.node),`A flow names no node`),(t.node<=n||t.node>=r.nodes.length)&&z(`A flow goes back or past the end`),`socket`in t&&R(typeof t.socket==`string`,`A flow socket is not a string`),p[e]={node:t.node,socket:t.socket??`in`}}l.push(ke(n,d,u,f,p,{types:i,variables:o,events:s,typeOf:a}))})),`name`in r&&R(typeof r.name==`string`,`A graph name is not a string`),{nodes:l,variables:o,events:s}}var J=(e,t,n,r)=>{let i=e[t];i||z(`${r} has no input ${t}`),n&&i.type!==n&&z(`${r} input ${t} is ${i.type}, not ${n}`)},Y=(e,t)=>{let n=e.configuration?.[t]?.value;return n?.length===1&&U(n[0])?n[0]:void 0},X=(e,t)=>{let n=e.configuration?.[t]?.value;return n?.length===1&&typeof n[0]==`boolean`?n[0]:void 0},Z=(e,t)=>{let n=e.configuration?.[t]?.value;return n?.length===1&&typeof n[0]==`string`?n[0]:void 0},Q=e=>{let t=e.configuration?.cases?.value;return Array.isArray(t)&&t.every(U)?[...new Set(t)]:[]};function ke(e,t,n,r,i,a){let o={index:e,op:t.op,noop:!1,inputs:r,outputs:{},flows:i,config:De,state:{},memoEpoch:-1};if(t.extension!==void 0){for(let[e,n]of Object.entries(t.inputs??{}))J(r,e,n,t.op);if(o.outputs=t.outputs??{},!t.supported)o.noop=!0;else{let e=Y(n,`nodeIndex`);o.config={nodeIndex:e!==void 0&&e>=0?e:void 0};for(let[e,t]of Object.entries(o.outputs))o.state[e]=e===`controllerIndex`?-1:K(t)}return o}let s=d.get(t.op);if(s){let e=s.inputs.map(e=>(J(r,e,void 0,t.op),r[e].type)),n=s.resolve(e);return n||z(`${t.op} does not take ${e.join(`, `)}`),o.outputs=n,o}let c=Ee[t.op];for(let[e,n]of Object.entries(c.inputs??{}))J(r,e,n,t.op);o.outputs={...c.outputs},o.entries=c.entries;let l=e=>e!==void 0&&e>=0&&e<a.variables.length?e:z(`${t.op} names no variable`),u=()=>{let e=Y(n,`event`);return e!==void 0&&e>=0&&e<a.events.length?e:z(`${t.op} names no custom event`)},f=e=>{let i=xe(Z(n,`pointer`));i||z(`${t.op} has no valid pointer`);let s=Y(n,`type`);(s===void 0||s<0||s>=a.types.length)&&z(`${t.op} has no valid type`);for(let n of i.params)e.includes(n.id)&&z(`${t.op} pointer uses the parameter ${n.id}`),J(r,n.id,n.ref?`ref`:`int`,t.op);return o.config={template:i,type:a.types[s]},a.types[s]};switch(t.op){case`flow/sequence`:case`flow/multiGate`:{o.config={order:Object.keys(i).sort(),isRandom:!1,isLoop:!1};let e=X(n,`isRandom`),t=X(n,`isLoop`);e!==void 0&&t!==void 0&&Object.assign(o.config,{isRandom:e,isLoop:t}),o.state={lastIndex:-1,used:Array(o.config.order.length).fill(!1)};break}case`flow/switch`:o.config={cases:Q(n)};break;case`math/switch`:{J(r,`selection`,`int`,t.op),J(r,`default`,void 0,t.op);let e=Q(n);for(let n of e)J(r,String(n),r.default.type,t.op);o.config={cases:e},o.outputs={value:r.default.type};break}case`math/quatFromAngles`:{let e=Z(n,`order`);o.config={order:e&&/^(xyz|xzy|yxz|yzx|zxy|zyx)$/.test(e)?e:`yxz`};break}case`flow/for`:o.state={index:Y(n,`initialIndex`)??0};break;case`flow/doN`:o.state={currentCount:0};break;case`flow/waitAll`:{let e=Y(n,`inputFlows`),t=e!==void 0&&e>=0&&e<=64?e:0;o.config={inputFlows:t},o.entries=[...Array.from({length:t},(e,t)=>String(t)),`reset`],o.state={remainingInputs:t,seen:Array(t).fill(!1)};break}case`flow/throttle`:o.state={lastRemainingTime:NaN,stamp:0};break;case`flow/setDelay`:o.state={lastDelay:null,pending:[]};break;case`variable/get`:{let e=l(Y(n,`variable`));o.config={variable:e},o.outputs={value:a.variables[e].type};break}case`variable/set`:{let e=n.configuration?.variables?.value;W(e)||z(`variable/set has no variables`);let i=[...new Set(e)];for(let e of i)H(e)||z(`variable/set names no variable`),J(r,String(l(e)),a.variables[e].type,t.op);o.config={variables:i};break}case`variable/interpolate`:{let e=l(Y(n,`variable`)),i=a.variables[e].type,s=X(n,`useSlerp`);(i===`bool`||i===`int`||i===`ref`||i===`custom`)&&z(`variable/interpolate cannot move a ${i}`),(s===void 0||s&&i!==`float4`)&&z(`variable/interpolate has no valid useSlerp`),J(r,`value`,i,t.op),o.config={variable:e,useSlerp:s};break}case`pointer/get`:o.outputs={value:f([]),isValid:`bool`};break;case`pointer/set`:J(r,`value`,f([`value`]),t.op);break;case`pointer/interpolate`:{let e=f([`value`,`duration`,`p1`,`p2`]);(e===`bool`||e===`int`||e===`ref`||e===`custom`)&&z(`pointer/interpolate cannot move a ${e}`),J(r,`value`,e,t.op);break}case`event/receive`:{let e=u();o.config={event:e},o.outputs={event:`ref`};for(let[t,n]of Object.entries(a.events[e].values))o.outputs[t]=n.type,o.state[t]=n.value;o.state.event=null;break}case`event/send`:{let e=u();o.config={event:e};for(let[n,i]of Object.entries(a.events[e].values))J(r,n,i.type,t.op);break}case`event/onStart`:o.state={event:null};break;case`event/onTick`:o.state={timeSinceStart:NaN,timeSinceLastTick:NaN,event:null};break;case`debug/log`:{let e=Y(n,`severity`),i=Z(n,`message`),a=i===void 0?void 0:Ce(i),s=e!==void 0&&a;o.config={severity:s?e:0,message:s?i:``,params:s?a:[]};for(let e of o.config.params)J(r,e.id,void 0,t.op);break}}return o}function Ae(e,t,n){let r=e.extensions?.KHR_interactivity;if(r===void 0)return;R(V(r)&&W(r.graphs),`graphs is empty or missing`);let i,a,o=`graph`in r?r.graph:0;if(R(H(o),`graph is not an index`),o>=r.graphs.length)throw new L(`graph names no graph; fix the KHR_interactivity object`,!0);if(r.graphs.forEach((e,r)=>{try{let a=Oe(e,t,n);r===o&&(i=a)}catch(e){if(!(e instanceof L)||e.extension)throw e;r===o&&(a=e)}}),a)throw a;return i}var $=class e{constructor(e,t,n={}){this.time=0,this.listeners=/* @__PURE__ */ new Map,this.queue=[],this.delays=[],this.variableMoves=[],this.pointerMoves=[],this.playing=[],this.refsMade=/* @__PURE__ */ new Set,this.hovered=/* @__PURE__ */ new Map,this.epoch=0,this.budget=0,this.serial=0,this.ticked=!1,this.lastTick=0,this.started=!1,this.running=!1,this.peers=/* @__PURE__ */ new Set,this.occurrences=/* @__PURE__ */ new Map,this.nodes=e.nodes,this.variableList=e.variables,this.events=e.events,this.model=t,this.options=n}handles(e){return this.of(e).length>0}variable(e){let t=typeof e==`number`?this.variableList[e]:this.variableList.find(t=>t.name===e);return t?t.value:null}on(e,t){let n=this.listeners.get(e);return n||this.listeners.set(e,n=/* @__PURE__ */ new Set),n.add(t),()=>n.delete(t)}send(e,t={}){let n=this.events.findIndex(t=>t.id===e);return n<0?!1:(this.queue.push({event:n,values:t}),this.slice(()=>this.drain()),!0)}link(e){return this.peers.add(e),e.peers.add(this),()=>{this.peers.delete(e),e.peers.delete(this)}}slice(t){if(!(this.halted||this.running)){this.running=!0,this.budget=this.options.maxActivations??1e6;try{t()}catch(t){if(t!==e.spent)throw t;this.halted=`The graph ran past its activation limit in one step; raise maxActivations or end its loop`}finally{this.running=!1}}}static{this.spent=Symbol(`spent`)}occurrence(){let e=this.model.ref(`/extensions/KHR_interactivity/events/${this.serial++}`);return this.refsMade.add(e),{ref:e,stopped:!1,immediate:!1}}dispatch(e,t,n){this.occurrences.set(t.ref,t);for(let r of e)n?.(r),r.state.event=t.ref;for(let n of e){if(t.immediate)break;this.fire(n,`out`)}}of(e){return this.nodes.filter(t=>t.op===e&&!t.noop)}start(){this.started||(this.started=!0,this.slice(()=>{this.dispatch(this.of(`event/onStart`),this.occurrence()),this.drain()}))}tick(e){this.started||this.start();let t=!this.ticked;this.ticked=!0,t||(this.time+=e),this.slice(()=>{this.epoch++,this.runAnimations(),this.runDelays(),this.runMoves();let e=this.time,n=t?NaN:this.time-this.lastTick;this.lastTick=this.time,this.dispatch(this.of(`event/onTick`),this.occurrence(),t=>{t.state.timeSinceStart=e,t.state.timeSinceLastTick=n}),this.drain(this.options.maxEventsPerTick??1e4)})}drain(e=1/0){let t=0;for(;this.queue.length&&t++<e;){let{event:e,values:t}=this.queue.shift(),n=this.events[e],r=this.of(`event/receive`).filter(t=>t.config.event===e);this.dispatch(r,this.occurrence(),e=>{for(let[r,i]of Object.entries(n.values))e.state[r]=r in t?t[r]:i.value})}}runDelays(){let e=this.delays.filter(e=>e.at<=this.time).sort((e,t)=>e.at-t.at||e.serial-t.serial);for(let t of e)this.delays.includes(t)&&(this.removeDelay(t.ref),this.fire(t.node,`done`))}removeDelay(e){let t=this.delays.find(t=>t.ref===e);t&&(this.delays=this.delays.filter(e=>e!==t),t.node.state.pending=t.node.state.pending.filter(t=>t!==e))}mixed(e,t){let n=we(e.p1,e.p2,t),{from:r,to:i}=e;return typeof r==`number`?(1-n)*r+n*i:e.slerp?ie(r,i,n):r.map((e,t)=>(1-n)*e+n*i[t])}runMoves(){for(let e of this.variableMoves.slice()){if(!this.variableMoves.includes(e))continue;let t=(this.time-e.start)/e.duration;t<=0||(Number.isNaN(t)||t>=1?(this.variableList[e.variable].value=e.to,this.variableMoves=this.variableMoves.filter(t=>t!==e),this.fire(e.node,`done`)):this.variableList[e.variable].value=this.mixed(e,t))}for(let e of this.pointerMoves.slice()){if(!this.pointerMoves.includes(e))continue;let t=(this.time-e.start)/e.duration,n=this.model.property(e.pointer);t<=0||(Number.isNaN(t)||t>=1?(n?.set?.(e.to),this.pointerMoves=this.pointerMoves.filter(t=>t!==e),this.fire(e.node,`done`)):n?.set?.(this.mixed(e,t)))}}applyAnimation(e,t){let n=this.model.animations[e],r=n.maxTime,i=0;r!==0&&(i=t-(t>0?Math.ceil((t-r)/r):Math.floor(t/r))*r),n.playhead=i,n.virtualPlayhead=t;for(let e of n.channels)this.model.animate(e.pointer,this.options.sample(e,i))}finish(e,t,n){this.applyAnimation(e.index,t),this.playing=this.playing.filter(t=>t!==e),this.model.animations[e.index].isPlaying=!1,n&&this.fire(n,`done`)}runAnimations(){for(let e of this.playing.slice()){if(!this.playing.includes(e))continue;let{start:t,end:n,stop:r,speed:i}=e;if(t===n){this.finish(e,t,e.endDone);continue}let a=t<n,o=(this.time-e.created)*i,s=t+(a?o:-o);(a?s>=r&&r>=t&&r<n:s<=r&&r<=t&&r>n)?this.finish(e,r,e.stopDone):(a?s>=n:s<=n)?this.finish(e,n,e.endDone):this.applyAnimation(e.index,s)}}input(e,t){let n=e.inputs[t];return n.node?this.output(n.node,n.socket):n.constant}output(e,t){if(e.noop)return K(e.outputs[t]);let n=d.get(e.op);return n||e.op===`math/switch`||e.op===`pointer/get`||e.op===`variable/get`||e.op===`math/random`||e.op===`math/quatFromAngles`?((e.memoEpoch!==this.epoch||!e.memo)&&(e.memoEpoch=this.epoch,e.memo=this.compute(e,n)),e.memo[t]):e.state[t]}compute(e,t){if(t){let n=t.inputs.map(t=>this.input(e,t)),r=t.run(n,t.inputs.map(t=>e.inputs[t].type));return t.multi?r:{value:r}}switch(e.op){case`math/random`:return{value:Math.random()};case`math/quatFromAngles`:{let t=[0,0,0,1];for(let n of e.config.order){let r=this.input(e,n)/2,i=[0,0,0,Math.cos(r)];i[`xyz`.indexOf(n)]=Math.sin(r),t=re(t,i)}return{value:t}}case`variable/get`:return{value:this.variableList[e.config.variable].value};case`math/switch`:{let t=this.input(e,`selection`);return{value:this.input(e,e.config.cases.includes(t)?String(t):`default`)}}}let n=this.effective(e),r=e.config.type,i=n===void 0?void 0:this.lookup(n);return i?.type===r?{value:i.get(),isValid:!0}:{value:K(r),isValid:!1}}lookup(e){let t=/^\/extensions\/KHR_interactivity\/(delays|events)\/\d+$/.exec(e);if(!t)return this.model.property(e);let n=this.model.ref(e);return(t[1]===`delays`?this.delays.some(e=>e.ref===n):this.refsMade.has(n))?{type:`ref`,get:()=>n,set:void 0}:void 0}effective(e){let t=e.config.template,n=t.segments.map(Se);for(let{id:r,ref:i,at:a}of t.params){let t=this.input(e,r);if(i){if(t===null)return;let e=t.path,r=e.lastIndexOf(`/`);n[a]=e.slice(0,r)===n.slice(0,a).join(`/`)?e.slice(r+1):`-`}else{if(t<0)return;n[a]=String(t)}}return n.join(`/`)}fire(e,t){let n=e.flows[t];n&&this.activate(this.nodes[n.node],n.socket)}activate(t,n){if(--this.budget<0)throw e.spent;if(this.epoch++,!t.noop&&(t.entries??[`in`]).includes(n)){if(t.op===`flow/sequence`)for(let e of t.config.order)this.fire(t,e);else this.flow(t,n)}}flow(t,n){let r=t.state,i=e=>this.input(t,e);switch(t.op){case`flow/branch`:return this.fire(t,i(`condition`)?`true`:`false`);case`flow/switch`:{let e=i(`selection`);return this.fire(t,t.config.cases.includes(e)?String(e):`default`)}case`flow/while`:for(;i(`condition`);){if(this.fire(t,`loopBody`),--this.budget<0)throw e.spent;this.epoch++}return this.fire(t,`completed`);case`flow/for`:for(r.index=i(`startIndex`);r.index<i(`endIndex`);){if(this.fire(t,`loopBody`),r.index=r.index+1|0,--this.budget<0)throw e.spent;this.epoch++}return this.fire(t,`completed`);case`flow/doN`:if(n===`reset`){r.currentCount=0;return}r.currentCount<i(`n`)&&(r.currentCount++,this.fire(t,`out`));return;case`flow/multiGate`:return this.gate(t,n);case`flow/waitAll`:if(n===`reset`){r.remainingInputs=t.config.inputFlows,r.seen.fill(!1);return}return r.seen[+n]||(r.seen[+n]=!0,r.remainingInputs--),this.fire(t,r.remainingInputs?`out`:`completed`);case`flow/throttle`:{if(n===`reset`){r.lastRemainingTime=NaN;return}let e=i(`duration`);if(!Number.isFinite(e)||e<0)return this.fire(t,`err`);if(!Number.isNaN(r.lastRemainingTime)){let t=this.time-r.stamp;if(e>t){r.lastRemainingTime=e-t;return}}return r.stamp=this.time,r.lastRemainingTime=0,this.fire(t,`out`)}case`flow/setDelay`:{if(n===`cancel`){r.lastDelay=null;for(let e of r.pending.slice())this.removeDelay(e);return}let e=i(`duration`);if(!Number.isFinite(e)||e<0||this.delays.length>=65536)return this.fire(t,`err`);let a=this.serial++,o=this.model.ref(`/extensions/KHR_interactivity/delays/${a}`);return r.lastDelay=o,r.pending.push(o),this.delays.push({ref:o,node:t,at:this.time+e,serial:a}),this.fire(t,`out`)}case`flow/cancelDelay`:{let e=i(`delay`);return e&&this.removeDelay(e),this.fire(t,`out`)}case`variable/set`:{let e=t.config.variables.map(e=>i(String(e)));return t.config.variables.forEach((t,n)=>{this.variableMoves=this.variableMoves.filter(e=>e.variable!==t),this.variableList[t].value=e[n]}),this.fire(t,`out`)}case`variable/interpolate`:{let{variable:e,useSlerp:n}=t.config,r=this.motion(t);return!r||this.variableMoves.length>=65536?this.fire(t,`err`):(this.variableMoves=this.variableMoves.filter(t=>t.variable!==e),this.variableMoves.push({...r,variable:e,from:this.variableList[e].value,slerp:n,node:t}),this.fire(t,`out`))}case`pointer/set`:{let e=i(`value`),n=this.effective(t),r=n===void 0?void 0:this.lookup(n);return r?.type!==t.config.type||!r?.set?this.fire(t,`err`):(this.pointerMoves=this.pointerMoves.filter(e=>e.pointer!==n),r.set(e),this.fire(t,`out`))}case`pointer/interpolate`:{let e=this.effective(t),n=e===void 0?void 0:this.lookup(e),r=this.motion(t);return n?.type!==t.config.type||!n?.set||!r||this.pointerMoves.length>=65536?this.fire(t,`err`):(this.pointerMoves=this.pointerMoves.filter(t=>t.pointer!==e),this.pointerMoves.push({...r,pointer:e,from:n.get(),slerp:n.type===`float4`&&e.endsWith(`/rotation`),node:t}),this.fire(t,`out`))}case`animation/start`:case`animation/stop`:case`animation/stopAt`:return this.control(t);case`event/stopPropagation`:{let e=this.occurrences.get(i(`event`)),n=i(`stopImmediate`);return e&&(e.stopped=!0,n&&(e.immediate=!0)),this.fire(t,`out`)}case`event/send`:{let e=this.events[t.config.event],n=Object.fromEntries(Object.keys(e.values).map(e=>[e,i(e)]));if(this.queue.push({event:t.config.event,values:n}),e.id!==void 0){for(let t of[...this.listeners.get(e.id)??[]])t(n);if(!e.id.startsWith(`_`))for(let t of this.peers)t.send(e.id,n)}return this.fire(t,`out`)}case`debug/log`:{let e=t.config.message;for(let{from:n,to:r,id:a}of[...t.config.params].reverse())e=e.slice(0,n)+je(i(a)).replaceAll(`{`,`{{`).replaceAll(`}`,`}}`)+e.slice(r+1);return this.options.log?.(e.replaceAll(`{{`,`{`).replaceAll(`}}`,`}`),t.config.severity),this.fire(t,`out`)}case`rigid_body/applyImpulse`:return this.options.physics?.applyImpulse(i(`nodeIndex`),i(`linearImpulse`),i(`angularImpulse`));case`rigid_body/applyPointImpulse`:return this.options.physics?.applyPointImpulse(i(`nodeIndex`),i(`impulse`),i(`position`));case`rigid_body/rayCast`:{let e=this.options.physics?.rayCast(i(`rayStart`),i(`rayEnd`),i(`collisionFilterIndex`));return e?(Object.assign(r,{hitNodeIndex:e.nodeIndex,hitFraction:e.fraction,hitNormal:e.normal}),this.fire(t,`hit`)):this.fire(t,`miss`)}}}motion(e){let t=this.input(e,`duration`),n=this.input(e,`p1`),r=this.input(e,`p2`),i=this.input(e,`value`);if(!(!Number.isFinite(t)||t<0)&&!(![...n,...r].every(Number.isFinite)||n[0]<0||n[0]>1||r[0]<0||r[0]>1))return{start:this.time,duration:t,to:i,p1:n,p2:r}}gate(e,t){let n=e.state,{order:r,isRandom:i,isLoop:a}=e.config;if(t===`reset`){n.lastIndex=-1,n.used.fill(!1);return}let o=r.flatMap((e,t)=>n.used[t]?[]:[t]),s=o.length?i?o[Math.floor(Math.random()*o.length)]:o[0]:-1;if(s<0){if(!a||!r.length)return;n.used.fill(!1),s=i?Math.floor(Math.random()*r.length):0}n.used[s]=!0,n.lastIndex=s,this.fire(e,r[s])}control(e){let t=this.input(e,`animation`),n=/^\/animations\/(\d+)$/.exec(t?.path??``)?.[1],r=n===void 0?void 0:this.model.animations[+n];if(!r)return this.fire(e,`err`);let i=+n,a=this.playing.find(e=>e.index===i);if(e.op===`animation/stop`)return a&&(this.playing=this.playing.filter(e=>e!==a),r.isPlaying=!1),this.fire(e,`out`);if(e.op===`animation/stopAt`){let t=this.input(e,`stopTime`);return Number.isNaN(t)?this.fire(e,`err`):(a&&(a.stop=t,a.stopDone=e),this.fire(e,`out`))}let o=this.input(e,`startTime`),s=this.input(e,`endTime`),c=this.input(e,`speed`);if(Number.isNaN(o)||Number.isNaN(s)||!Number.isFinite(o)||!Number.isFinite(c)||c<=0||!this.options.sample||!r.channels.length||!a&&this.playing.length>=65536)return this.fire(e,`err`);this.playing=this.playing.filter(e=>e!==a),this.playing.push({index:i,start:o,end:s,stop:s,speed:c,created:this.time,endDone:e}),r.isPlaying=!0,this.fire(e,`out`)}select(e,t={}){if(!this.model.inherited(e,`selectability/selectable`))return!1;let n=this.occurrence(),r=this.of(`event/onSelect`);return this.slice(()=>{for(let i=e;i>=0&&!n.stopped;i=this.model.parent(i))this.dispatch(r.filter(e=>e.config.nodeIndex===i),n,n=>Object.assign(n.state,{selectedNode:this.model.ref(`/nodes/${e}`),controllerIndex:t.controllerIndex??0,selectionPoint:t.point?[...t.point]:[NaN,NaN,NaN],selectionRayOrigin:t.origin?[...t.origin]:[NaN,NaN,NaN]}));this.drain()}),!0}hover(e,t=0){let n=e!==void 0&&this.model.inherited(e,`hoverability/hoverable`)?e:-1,r=this.hovered.get(t)??-1;if(n===r)return;this.hovered.set(t,n);let i=e=>{let t=[];for(let n=e;n>=0;n=this.model.parent(n))t.push(n);return t},a=i(r),o=i(n),s=(e,n,r)=>{let i=this.occurrence(),a=this.of(e);for(let e of n){if(i.stopped)break;this.dispatch(a.filter(t=>t.config.nodeIndex===e),i,e=>Object.assign(e.state,{hoveredNode:this.model.ref(`/nodes/${r}`),controllerIndex:t}))}};this.slice(()=>{s(`event/onHoverOut`,a.filter(e=>!o.includes(e)),r),s(`event/onHoverIn`,o.filter(e=>!a.includes(e)),n),this.drain()})}trigger(e,t,n,r){this.slice(()=>{this.dispatch(this.of(e).filter(e=>e.config.nodeIndex===t),this.occurrence(),e=>Object.assign(e.state,{colliderNodeIndex:n,motionNodeIndex:r})),this.drain()})}},je=e=>e===null?`null`:typeof e==`object`&&!Array.isArray(e)?e.path:Array.isArray(e)?`[${e.join(`, `)}]`:String(e),Me=[`KHR_interactivity`,`KHR_node_selectability`,`KHR_node_hoverability`,`KHR_node_visibility`,`KHR_physics_rigid_bodies`],Ne=/^KHR_(materials_(anisotropy|clearcoat|dispersion|emissive_strength|ior|iridescence|sheen|specular|transmission|unlit|variants|volume|volume_scatter)|texture_transform|lights_punctual|animation_pointer|mesh_quantization)$/;function Pe(e,t={}){let n=e.doc;if(n.extensions?.KHR_interactivity===void 0)return{};let r=[...Me,...t.supported??[]],i=new _e(n,{accessor:(t,n)=>e.accessor(t,n),live:t.live,camera:t.camera,supports:e=>r.includes(e)||Ne.test(e)});try{let e=Ae(n,i,r);return e?{graph:new $(e,i,t)}:{}}catch(e){if(e instanceof L)return{rejected:e.message};throw e}}export{$ as BehaviorGraph,Pe as loadBehaviorGraph};
@@ -0,0 +1,98 @@
1
+ // @ts-ignore optional peer: its types apply when it is installed
2
+ import type { Clustered, PointLight } from '@margoengine/clustered';
3
+ // @ts-ignore optional peer: its types apply when it is installed
4
+ import type { IESLights, IESProfile } from '@margoengine/clustered/ies';
5
+ // @ts-ignore optional peer: its types apply when it is installed
6
+ import type { CubeFaces, Environment, EnvironmentBackground, EnvironmentLighting } from '@margoengine/environment';
7
+ import type { PBRModel } from './pbr.js';
8
+ type Vec3 = [number, number, number];
9
+ type Quaternion = readonly [number, number, number, number];
10
+ /** Where a light's files come from. */
11
+ export interface GLTFLightFileOptions {
12
+ /** Base of relative `uri`s; default where `loadGLTF` read the file from. */
13
+ baseURL?: string | URL;
14
+ /** Default `globalThis.fetch`. */
15
+ fetch?: typeof globalThis.fetch;
16
+ signal?: AbortSignal;
17
+ }
18
+ /** One node's EXT_lights_ies light. */
19
+ export interface GLTFIESLight {
20
+ name: string;
21
+ /** The profile, on the type C grid `parseIES` gives every file. */
22
+ profile: IESProfile;
23
+ /** Index of the node in the glTF file. */
24
+ nodeIndex: number;
25
+ /** Candela scale, default 1. */
26
+ multiplier: number;
27
+ /** Linear RGB tint, each channel from 0 to 1. */
28
+ color: Vec3;
29
+ }
30
+ /** A scene's EXT_lights_image_based light. */
31
+ export interface GLTFImageLight {
32
+ name: string;
33
+ /** Brightness multiplier, default 1. */
34
+ intensity: number;
35
+ /** The rotation of the environment, as the file states it; `faces` have it applied. */
36
+ rotation: Quaternion;
37
+ /** Mip 0 of the specular cube in linear light, for `Environment.create`. */
38
+ faces: CubeFaces;
39
+ /** The file's nine SH rows of three, as data: the extension does not say how they are scaled (see the README). */
40
+ irradianceCoefficients: readonly (readonly number[])[];
41
+ }
42
+ /** Options of `applyGLTFLightExtensions`. */
43
+ export interface GLTFLightExtensionOptions extends GLTFLightFileOptions {
44
+ /** Clustered lights to use; default one attached here, which `dispose()` removes. */
45
+ clustered?: Clustered;
46
+ /** Scales every IES light's candela, as `applyGLTFLights` does. Default 1. */
47
+ exposure?: number;
48
+ /** Draw the image-based light's cube behind the scene. Default false. */
49
+ background?: boolean;
50
+ /** The scene whose image-based light to use; default the file's `scene`, else 0. */
51
+ scene?: number;
52
+ }
53
+ /** What `applyGLTFLightExtensions` made. `dispose()` removes all of it. */
54
+ export interface GLTFLightExtensions {
55
+ readonly iesLights: readonly GLTFIESLight[];
56
+ readonly imageLight?: GLTFImageLight;
57
+ readonly clustered?: Clustered;
58
+ readonly ies?: IESLights;
59
+ readonly environment?: Environment;
60
+ readonly lighting?: EnvironmentLighting;
61
+ readonly background?: EnvironmentBackground;
62
+ dispose(): void;
63
+ [Symbol.dispose](): void;
64
+ }
65
+ /**
66
+ * The EXT_lights_ies lights on the model's nodes, in node order. Their files are read once each; a type A profile
67
+ * is refused by `parseIES`, as the extension allows. `applyGLTFLightExtensions` places them.
68
+ */
69
+ export declare function gltfIESLights(model: PBRModel, options?: GLTFLightFileOptions): Promise<GLTFIESLight[]>;
70
+ /**
71
+ * `profile` as a light aimed straight down with no turn sees it (`IESLights`' frame for a point light, whose axes are
72
+ * -Y, +X and -Z): a point light has no direction of its own, and a spot's cone stops at a hemisphere, which would cut
73
+ * an uplight. `basis` holds the node's unit X, Y and Z in world space; the extension aims the light down -Z with the
74
+ * horizontal angle 0 along +X and 90 along +Y. Same 1 by 5 degree grid `IESLights` reads.
75
+ */
76
+ export declare function orientIES(profile: IESProfile, candelaOf: (profile: IESProfile, theta: number, phi: number) => number, basis: readonly [Vec3, Vec3, Vec3]): IESProfile;
77
+ /** `cube` with its environment turned by `q`: what lay along d now lies along q d. A cube rotates only about +Y in `Environment`, a quaternion any way. */
78
+ export declare function rotateCube(cube: CubeFaces, _arg0: Quaternion): CubeFaces;
79
+ /** The scene's EXT_lights_image_based light, or undefined when it has none. */
80
+ export declare function gltfImageLight(model: PBRModel, options?: GLTFLightFileOptions & {
81
+ scene?: number;
82
+ }): Promise<GLTFImageLight | undefined>;
83
+ /**
84
+ * The point lights and aimed profiles for `lights`, each placed by its node's world matrix (`matrixOf`). Lights that
85
+ * use the same profile and point the same way share one aimed profile (IESLights holds 16); the cache is keyed by the
86
+ * parsed profile itself, so two unnamed profiles of one format stay apart.
87
+ */
88
+ export declare function placeIESLights(lights: readonly GLTFIESLight[], matrixOf: (nodeIndex: number) => ArrayLike<number>, candelaOf: (profile: IESProfile, theta: number, phi: number) => number, exposure?: number): {
89
+ fixtures: PointLight[];
90
+ profiles: IESProfile[];
91
+ };
92
+ /**
93
+ * Lights `model` with the file's EXT_lights_ies fixtures, placed where their nodes are now, and its scene's
94
+ * EXT_lights_image_based environment. Keeps the model's KHR_lights_punctual point and spot lights in the same list.
95
+ * A file with neither makes nothing and loads neither package.
96
+ */
97
+ export declare function applyGLTFLightExtensions(model: PBRModel, options?: GLTFLightExtensionOptions): Promise<GLTFLightExtensions>;
98
+ export {};
package/dist/lights.js ADDED
@@ -0,0 +1 @@
1
+ import{margoError as e}from"@margoengine/core/extension";import{decodePNG as t}from"@margoengine/decoders/png";var n=e=>/* @__PURE__ */ TypeError(`Invalid glTF ${e}; the file is not valid, re-export it and check it with the glTF Validator`),r=(t,n)=>t.catch(t=>{throw e(`unsupported`,`glTF light extensions need ${n} (${t instanceof Error?t.message:t}): install it to use @margoengine/gltf/lights`)});async function i(t,r,{baseURL:i=t.asset.baseURL,fetch:a=globalThis.fetch,signal:o}){if(r.bufferView!==void 0){let e=t.asset.doc.bufferViews?.[r.bufferView],i=e&&t.asset.buffers[e.buffer];if(!e||!i)throw n(`light bufferView`);return i.subarray(e.byteOffset??0,(e.byteOffset??0)+e.byteLength)}if(typeof r.uri!=`string`)throw n(`light file: it needs a uri or a bufferView`);if(!r.uri.startsWith(`data:`)&&i===void 0&&!/^[a-z]+:/i.test(r.uri))throw e(`state`,`glTF light file ${r.uri} is relative and the model has no base URL; pass baseURL`);let s=await a(new URL(r.uri,i),{signal:o});if(!s.ok)throw e(`failed`,`glTF light file ${r.uri} answered ${s.status}; check that it is there`);return new Uint8Array(await s.arrayBuffer())}async function a(e,t={}){let a=e.asset.doc,o=a.extensions?.EXT_lights_ies?.lights,s=a.nodes??[];if(!s.some(e=>e?.extensions?.EXT_lights_ies))return[];if(!Array.isArray(o))throw n(`EXT_lights_ies: it has no lights`);let{parseIES:c}=await r(import(`@margoengine/clustered/ies`),`@margoengine/clustered`),l=/* @__PURE__ */ new Map,u=[];for(let r=0;r<s.length;r++){let a=s[r]?.extensions?.EXT_lights_ies;if(!a||!e.nodes[r])continue;let d=a.light;if(d===void 0)throw n(`EXT_lights_ies light index`);let f=o[d],p=a.multiplier??1,m=a.color??[1,1,1];if(!f)throw n(`EXT_lights_ies light index`);if(typeof p!=`number`||!Number.isFinite(p)||p<0)throw n(`EXT_lights_ies multiplier`);if(!Array.isArray(m)||m.length!==3||m.some(e=>typeof e!=`number`||!Number.isFinite(e)))throw n(`EXT_lights_ies color`);if(f.bufferView!==void 0&&f.mimeType!==`application/x-ies-lm-63`)throw n(`EXT_lights_ies mimeType`);let h=l.get(d);h||l.set(d,h=i(e,f,t).then(e=>c(new TextDecoder().decode(e)))),u.push({name:f.name??``,profile:await h,nodeIndex:r,multiplier:p,color:m.map(e=>Math.min(1,Math.max(0,e)))})}return u}function o([e,t,n,r],i){let a=2*(t*i[2]-n*i[1]),o=2*(n*i[0]-e*i[2]),s=2*(e*i[1]-t*i[0]);return[i[0]+r*a+t*s-n*o,i[1]+r*o+n*a-e*s,i[2]+r*s+e*o-t*a]}var s=1,c=5;function l(e,t,n){let r=180/Math.PI,i=Array.from({length:181},(e,t)=>t*s),a=Array.from({length:73},(e,t)=>t*c),o=(e,t)=>e[0]*t[0]+e[1]*t[1]+e[2]*t[2],l=a.map(a=>i.map(i=>{let s=i/r,c=a/r,l=[Math.sin(s)*Math.cos(c),-Math.cos(s),-Math.sin(s)*Math.sin(c)],u=o(l,n[0]),d=o(l,n[1]),f=o(l,n[2]);return t(e,Math.acos(Math.min(1,Math.max(-1,-f)))*r,Math.atan2(d,u)*r)}));return{...e,vertical:i,horizontal:a,candela:l,peak:Math.max(...l.map(e=>Math.max(...e)))}}var u=e=>e<=.04045?e/12.92:((e+.055)/1.055)**2.4;async function d(e,n){if(n===`image/png`||e[0]===137&&e[1]===80)return t(e);let r=await createImageBitmap(new Blob([e],{type:n??`image/jpeg`}),{colorSpaceConversion:`none`}),i=new OffscreenCanvas(r.width,r.height),a=i.getContext(`2d`);return a.drawImage(r,0,0),r.close(),{width:i.width,height:i.height,data:new Uint8Array(a.getImageData(0,0,i.width,i.height).data.buffer)}}function f({width:e,data:t}){let n=new Float32Array(e*e*4);for(let r=0;r<e;r++)for(let i=0;i<e;i++){let a=((e-1-r)*e+i)*4,o=(r*e+i)*4,s=Math.max(t[a+3],1);for(let e=0;e<3;e++)n[o+e]=u(t[a+e]/s);n[o+3]=1}return n}var p=(e,t,n)=>[[1,-n,-t],[-1,-n,t],[t,1,n],[t,-1,-n],[t,-n,1],[-t,-n,-1]][e];function m({size:e,faces:t},n,r,i){let[a,o,s]=n.map(Math.abs),c=a>=o&&a>=s?n[0]>0?0:1:o>=s?n[1]>0?2:3:n[2]>0?4:5,l=Math.max(a,o,s),[u,d]=[[-n[2],-n[1]],[n[2],-n[1]],[n[0],n[2]],[n[0],-n[2]],[n[0],-n[1]],[-n[0],-n[1]]][c],f=Math.min(e-1,Math.max(0,(u/l+1)*e/2-.5)),p=Math.min(e-1,Math.max(0,(d/l+1)*e/2-.5)),m=Math.floor(f),h=Math.floor(p),g=Math.min(e-1,m+1),_=Math.min(e-1,h+1),v=f-m,y=p-h,b=t[c];for(let t=0;t<4;t++){let n=b[(h*e+m)*4+t]*(1-v)+b[(h*e+g)*4+t]*v,a=b[(_*e+m)*4+t]*(1-v)+b[(_*e+g)*4+t]*v;r[i+t]=n*(1-y)+a*y}}function h(e,[t,n,r,i]){if(t===0&&n===0&&r===0)return e;let a=[-t,-n,-r,i],{size:s}=e;return{size:s,faces:e.faces.map((t,n)=>{let r=new Float32Array(s*s*4);for(let t=0;t<s;t++)for(let i=0;i<s;i++)m(e,o(a,p(n,(i+.5)/s*2-1,(t+.5)/s*2-1)),r,(t*s+i)*4);return r})}}async function g(e,t={}){let r=e.asset.doc,a=(r.scenes?.[t.scene??r.scene??0])?.extensions?.EXT_lights_image_based?.light;if(a===void 0)return;let o=r.extensions?.EXT_lights_image_based?.lights?.[a];if(!o)throw n(`EXT_lights_image_based light index`);let{specularImages:s,specularImageSize:c,irradianceCoefficients:l,intensity:u=1}=o,p=o.rotation??[0,0,0,1];if(!Array.isArray(s)||!Array.isArray(s[0])||s[0].length!==6||!Number.isInteger(c)||c<1||c&c-1)throw n(`EXT_lights_image_based specular images`);if(!Array.isArray(l)||l.length!==9)throw n(`EXT_lights_image_based irradiance coefficients`);if(!Array.isArray(p)||p.length!==4||Math.abs(Math.hypot(...p)-1)>.001)throw n(`EXT_lights_image_based rotation`);if(typeof u!=`number`||!Number.isFinite(u)||u<0)throw n(`EXT_lights_image_based intensity`);let m=[p[0],p[1],p[2],p[3]],g=await Promise.all(s[0].map(async a=>{let o=r.images?.[a];if(!o)throw n(`EXT_lights_image_based image index`);let s=await d(await i(e,o,t),o.mimeType);if(s.width!==c||s.height!==c)throw n(`EXT_lights_image_based image: it must be specularImageSize square`);return f(s)}));return{name:o.name??``,intensity:u,rotation:m,faces:h({size:c,faces:g},m),irradianceCoefficients:l}}function _(e,t,n,r=1){let i=/* @__PURE__ */ new Map,a=[],o=[];for(let s of e){let e=t(s.nodeIndex),c=t=>{let n=Math.hypot(e[t],e[t+1],e[t+2])||1;return[e[t]/n,e[t+1]/n,e[t+2]/n]},u=[c(0),c(4),c(8)],d=u.flat().map(e=>e.toFixed(3)).join(),f=i.get(s.profile);f||i.set(s.profile,f=/* @__PURE__ */ new Map);let p=f.get(d);p||f.set(d,p=l(s.profile,n,u));let m=p.peak*s.multiplier*r;a.push({position:[e[12],e[13],e[14]],range:Math.sqrt(m*256)||1,color:s.color,intensity:m,decay:2}),o.push(p)}return{fixtures:a,profiles:o}}async function v(e,t={}){let{exposure:n=1,background:i=!1}=t;if(!Number.isFinite(n)||n<0)throw RangeError(`applyGLTFLightExtensions: exposure must be a finite number of 0 or more; pass a number such as 1`);let o=e.engine,[s,c]=await Promise.all([a(e,t),g(e,t)]),l=[],u={},d=()=>{for(let e of l.splice(0).reverse())e()};try{if(s.length){let[{Clustered:i},{IESLights:a,iesCandela:c}]=await Promise.all([r(import(`@margoengine/clustered`),`@margoengine/clustered`),r(import(`@margoengine/clustered/ies`),`@margoengine/clustered`)]),d=t.clustered??i.attach(o);t.clustered||l.push(()=>d.dispose());let f=a.attach(o,{lights:d});l.push(()=>f.dispose()),o.store.tick(!1);let p=e.clusteredLights(),{fixtures:m,profiles:h}=_(s,t=>e.nodes[t].matrix,c,n);d.setLights([...p,...m]),f.setProfiles([...p.map(()=>null),...h]),l.push(d.add(e)),Object.assign(u,{clustered:d,ies:f})}if(c){let{Environment:t,EnvironmentBackground:n,EnvironmentLighting:a}=await r(import(`@margoengine/environment`),`@margoengine/environment`),s=await t.attach(o,c.faces,{intensity:c.intensity}),d=a.attach(o,s);if(l.push(()=>s.dispose()),l.push(()=>d.dispose()),d.add(e),Object.assign(u,{environment:s,lighting:d}),i){let e=n.attach(o,s);l.push(()=>e.dispose()),u.background=e}}}catch(e){throw d(),e}return{iesLights:s,imageLight:c,...u,dispose:d,[Symbol.dispose]:d}}export{v as applyGLTFLightExtensions,a as gltfIESLights,g as gltfImageLight,l as orientIES,_ as placeIESLights,h as rotateCube};
@@ -0,0 +1 @@
1
+ function e(e,t=1e5){if(!Number.isSafeInteger(t)||t<1||t>8388608)throw RangeError(`${e} must be an integer from 1 to 8388608`);return t}function t(e,t,n,r){if(t>n)throw RangeError(`${e} (${t} > ${n}; raise the ${r} option)`)}export{e as n,t};
@@ -0,0 +1 @@
1
+ import{typeError as e}from"@margoengine/core/extension";var t=/* @__PURE__ */ new WeakMap,n=/* @__PURE__ */ new WeakSet;function r(e){return n.delete(e)?void 0:t.get(e)}function i(t,r,i,a){let o=r({model:t,context:i[0],mode:i[1],phase:i[4]??`all`,draw(){n.add(t);try{a()}finally{n.delete(t)}}});if(o&&typeof o.then==`function`)throw e(`Material draw adapters must complete synchronously; do not return a promise`,`material`)}function a(e,n){let r=t.get(e);r?t.set(n,r):t.delete(n)}export{i,a as n,t as r,r as t};
@@ -0,0 +1,7 @@
1
+ import type { PBRModel } from './model.js';
2
+ import type { MaterialDrawAdapter } from './material-draw.js';
3
+ /** One explicit adapter per source model; replicas inherit the current owner each draw. */
4
+ export declare const materialDrawAdapters: WeakMap<PBRModel, MaterialDrawAdapter>;
5
+ export declare function currentMaterialDraw(model: PBRModel): MaterialDrawAdapter | undefined;
6
+ export declare function runMaterialDraw(model: PBRModel, adapter: MaterialDrawAdapter, parameters: Parameters<PBRModel['draw']>, draw: () => void): void;
7
+ export declare function inheritMaterialDraw(source: PBRModel, replica: PBRModel): void;
@@ -0,0 +1,18 @@
1
+ import type { PBRModel } from './model.js';
2
+ /** A synchronous draw on the source model or an isolated device renderer. */
3
+ export interface MaterialDrawCall {
4
+ readonly model: PBRModel;
5
+ readonly context: Parameters<PBRModel['draw']>[0];
6
+ readonly mode: Parameters<PBRModel['draw']>[1];
7
+ readonly phase: 'all' | 'opaque' | 'blend';
8
+ /** Draw the current material records with the original context, pass and phase. */
9
+ draw(): void;
10
+ }
11
+ /** Temporarily select materials, call draw for each layer, then restore the records before returning. */
12
+ export type MaterialDrawAdapter = (call: MaterialDrawCall) => void;
13
+ /**
14
+ * Install one synchronous material-layer adapter. It also reaches existing and future isolated renderers.
15
+ * The returned remover is idempotent; disposing the source removes the adapter automatically.
16
+ * No adapter is installed by importing this entry.
17
+ */
18
+ export declare function setMaterialDraw(model: PBRModel, adapter: MaterialDrawAdapter): () => void;
@@ -0,0 +1 @@
1
+ import{r as e}from"./material-draw-state-GKiHDb0p.js";import{fault as t}from"@margoengine/core/extension";function n(n,r){if(n.disposed)throw t(`disposed`,`Material drawing needs a live model; load the model again`);if(typeof r!=`function`)throw TypeError(`Material draw adapter must be a synchronous function; see https://margoengine.com/errors#material`);if(e.has(n))throw t(`attached`,`A material draw adapter is already installed; remove it before installing another`,`material`);let i,a=()=>{e.get(n)===r&&e.delete(n),i?.(),i=void 0};e.set(n,r);try{i=n.onDispose(a)}catch(e){throw a(),e}return a}export{n as setMaterialDraw};