@margoengine/quality 0.0.0-stage → 0.1.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.
@@ -0,0 +1,42 @@
1
+ import type { DemandSource } from './demand.js';
2
+ /** Motion-dependent picking policy and optional clock for deterministic tests. */
3
+ export interface AdaptiveEventOptions {
4
+ /** Minimum milliseconds between calls during motion. Infinity suppresses them until rest. Default 100. */
5
+ interval?: number;
6
+ /** Milliseconds without a control event before rest. Default 120. */
7
+ debounce?: number;
8
+ /** Control start/change/end sources. Default none; call regress or setMoving manually. */
9
+ sources?: readonly DemandSource[];
10
+ /** Cancels all returned promises and removes listeners. Default none. */
11
+ signal?: AbortSignal;
12
+ /** Monotonic milliseconds. Default performance.now. */
13
+ now?: () => number;
14
+ /** Schedule a timeout. Default global setTimeout. */
15
+ setTimer?: (callback: () => void, milliseconds: number) => unknown;
16
+ /** Cancel a timeout. Default global clearTimeout. */
17
+ clearTimer?: (timer: unknown) => void;
18
+ }
19
+ /** Serialized, latest-input picking; each run's promise receives the result of its coalesced call. */
20
+ export interface AdaptiveEventTask<A extends unknown[], R> {
21
+ /** Schedule picking with the latest arguments; queued calls coalesce. Errors reject every corresponding promise. */
22
+ run(...args: A): Promise<R>;
23
+ /** Mark movement and restart the inactivity window, including programmatic camera changes. */
24
+ regress(): void;
25
+ /** Set motion explicitly; false immediately flushes the latest queued input. */
26
+ setMoving(moving: boolean): void;
27
+ /** Force the latest input through, regardless of motion; an in-flight call still finishes first. */
28
+ flush(): void;
29
+ /** Whether motion is currently reducing event frequency. */
30
+ readonly moving: boolean;
31
+ /** Whether input is queued or a handler is in flight. */
32
+ readonly pending: boolean;
33
+ /** Cancel queued/in-flight results, unsubscribe and cancel timers. The underlying caller-owned task may finish. */
34
+ dispose(): void;
35
+ [Symbol.dispose](): void;
36
+ }
37
+ /**
38
+ * Throttle hover picks or raycasts during camera movement, restoring the final pointer at rest. Independent calls
39
+ * never overlap, including asynchronous GPU picks. Click/drag actions should call their handler directly.
40
+ * @throws RangeError for invalid interval or debounce; use nonnegative milliseconds (interval also accepts Infinity).
41
+ */
42
+ export declare function adaptiveEvents<A extends unknown[], R>(handler: (...args: A) => R | PromiseLike<R>, { interval, debounce, sources, signal, now, setTimer, clearTimer, }?: AdaptiveEventOptions): AdaptiveEventTask<A, R>;
package/dist/events.js ADDED
@@ -0,0 +1,88 @@
1
+ import { r as e, t } from "./errors-XvcwUnU4.js";
2
+ //#region src/events.ts
3
+ function n(n, { interval: r = 100, debounce: i = 120, sources: a = [], signal: o, now: s = () => performance.now(), setTimer: c = (e, t) => setTimeout(e, t), clearTimer: l = (e) => clearTimeout(e) } = {}) {
4
+ if (!(r >= 0) || r !== Infinity && r > 2147483647 || !(i >= 0) || i > 2147483647 || !Number.isFinite(i)) throw e("Invalid adaptive event timing; use nonnegative milliseconds", "arguments");
5
+ let u = !1, d = !1, f = -Infinity, p, m, h, g, _ = !1, v = () => {
6
+ h !== void 0 && l(h), h = void 0;
7
+ }, y = () => {
8
+ if (v(), u || m || !p) return;
9
+ let e = d && !_ ? r - (s() - f) : 0;
10
+ if (d && !_ && r === Infinity) return;
11
+ if (e > 0) {
12
+ h = c(() => {
13
+ h = void 0, y();
14
+ }, e);
15
+ return;
16
+ }
17
+ let t = m = p;
18
+ p = void 0, _ = !1, f = s();
19
+ let i = (e, n) => {
20
+ if (m === t) {
21
+ m = void 0;
22
+ for (let r of t.waiters) e ? r.resolve(n) : r.reject(n);
23
+ y();
24
+ }
25
+ };
26
+ try {
27
+ Promise.resolve(n(...t.args)).then((e) => i(!0, e), (e) => i(!1, e));
28
+ } catch (e) {
29
+ i(!1, e);
30
+ }
31
+ }, b = (e) => {
32
+ u || (g !== void 0 && l(g), g = void 0, d = e, y());
33
+ }, x = () => {
34
+ b(!0), u || (g = c(() => {
35
+ g = void 0, b(!1);
36
+ }, i));
37
+ }, S = [
38
+ "start",
39
+ "change",
40
+ "end"
41
+ ], C = () => o?.aborted ? o.reason : t("disposed", "Adaptive events disposed; create a new task", "disposed"), w = () => {
42
+ if (u) return;
43
+ u = !0, v(), g !== void 0 && l(g), g = void 0;
44
+ let e = C();
45
+ for (let t of [m, p]) for (let n of t?.waiters ?? []) n.reject(e);
46
+ m = p = void 0;
47
+ for (let e of a) for (let t of S) e.removeEventListener(t, x);
48
+ o?.removeEventListener("abort", w);
49
+ };
50
+ if (o?.aborted) u = !0;
51
+ else {
52
+ for (let e of a) for (let t of S) e.addEventListener(t, x);
53
+ o?.addEventListener("abort", w, { once: !0 });
54
+ }
55
+ return {
56
+ run(...e) {
57
+ if (u) return Promise.reject(C());
58
+ let t = new Promise((t, n) => {
59
+ p ? (p.args = e, p.waiters.push({
60
+ resolve: t,
61
+ reject: n
62
+ })) : p = {
63
+ args: e,
64
+ waiters: [{
65
+ resolve: t,
66
+ reject: n
67
+ }]
68
+ };
69
+ });
70
+ return y(), t;
71
+ },
72
+ regress: x,
73
+ setMoving: b,
74
+ flush() {
75
+ p && (_ = !0, y());
76
+ },
77
+ get moving() {
78
+ return d;
79
+ },
80
+ get pending() {
81
+ return !!(p || m);
82
+ },
83
+ dispose: w,
84
+ [Symbol.dispose]: w
85
+ };
86
+ }
87
+ //#endregion
88
+ export { n as adaptiveEvents };
@@ -0,0 +1,164 @@
1
+ import { type FrameTimers } from './resolution.js';
2
+ /** One thing the scaler can turn down, in `levels` steps from 0 (full quality). See {@link optionKnob}. */
3
+ export interface FeatureKnob {
4
+ /** Unique name, used in reports. */
5
+ name: string;
6
+ /** Number of levels, 2 or more. */
7
+ levels: number;
8
+ /** Sets level `level`, 0 to `levels - 1`. Runs on a change and, with 0, on dispose. */
9
+ apply(level: number): void;
10
+ /** How much a viewer notices a step: of two steps that save enough, the lower weight goes first. Above 0. Default 1. */
11
+ weight?: number;
12
+ }
13
+ /** Options of {@link FeatureScaler}. */
14
+ export interface FeatureScalerOptions {
15
+ /** Frame cost in milliseconds above which a feature goes down; under 70% of it one may come back. Default 12. */
16
+ budget?: number;
17
+ /** Samples averaged before each decision. Default 30. */
18
+ window?: number;
19
+ /** Samples ignored after a change, while it reaches the GPU. A shader change can compile in these. Default 8. */
20
+ settle?: number;
21
+ /** A step that saved less than this share of the frame is given back and left alone for a while. Default 0.03. */
22
+ minSaving?: number;
23
+ }
24
+ /** A change {@link FeatureScaler.push} made. */
25
+ export interface FeatureChange {
26
+ name: string;
27
+ level: number;
28
+ }
29
+ /** What one step of a knob measured. */
30
+ export interface FeatureCost {
31
+ name: string;
32
+ /** The level the step leaves. */
33
+ level: number;
34
+ /** Milliseconds per frame going one level down saves, undefined until tried. */
35
+ saved: number | undefined;
36
+ }
37
+ /**
38
+ * Lowers features by what they measure, not by resolution alone. Over budget it takes a step, watches what the frame
39
+ * cost did, and remembers the saving: a step that saved nothing is given back at once, and next time the step known
40
+ * to cover the shortfall with the least visible loss goes first. With room to spare, the most visible feature whose
41
+ * measured cost fits comes back. Free of timers and the DOM; feed it one frame cost per frame with
42
+ * {@link FeatureScaler.push}.
43
+ */
44
+ export declare class FeatureScaler {
45
+ /** Current budget in milliseconds; set it to change it, as `watchPower` does. */
46
+ budget: number;
47
+ private readonly knobs;
48
+ private readonly window;
49
+ private readonly settleFrames;
50
+ private readonly minSaving;
51
+ private sum;
52
+ private count;
53
+ private skip;
54
+ private calm;
55
+ private holdOff;
56
+ private sinceRise;
57
+ private trial?;
58
+ /**
59
+ * @throws RangeError when `budget` is not above 0, `window` is below 1, `settle` is negative, `minSaving` is not in
60
+ * [0, 1), or a knob has fewer than 2 levels, a weight not above 0 or a repeated name.
61
+ */
62
+ constructor(knobs: readonly FeatureKnob[], { budget, window, settle, minSaving }?: FeatureScalerOptions);
63
+ /** Each knob's current level by name; 0 is full quality. */
64
+ get levels(): Record<string, number>;
65
+ /** Every step of every knob with what it measured, cheapest knob level first. */
66
+ get costs(): FeatureCost[];
67
+ /** Forget the running window and any step on trial, after a change the scaler did not make (a new scene). Measured savings stay. */
68
+ restart(): void;
69
+ /**
70
+ * Record one frame's cost in milliseconds. Returns the change when this sample made one, after applying it.
71
+ * Non-finite or negative samples are ignored.
72
+ */
73
+ push(ms: number): FeatureChange | undefined;
74
+ private decide;
75
+ /** The step to take for a shortfall of `need` milliseconds, if any is left. */
76
+ private lower;
77
+ /** The most visible lowered knob whose measured cost fits under the budget, with a margin. */
78
+ private raise;
79
+ private move;
80
+ /** Puts every knob back at level 0. */
81
+ reset(): void;
82
+ }
83
+ /** Hooks of {@link watchFeatures}; timers default to the browser's own, so tests can inject them. */
84
+ export interface WatchFeaturesOptions extends FeatureScalerOptions, FrameTimers {
85
+ /** Told each change. */
86
+ onChange?: (change: FeatureChange) => void;
87
+ }
88
+ /** Stops {@link watchFeatures}. */
89
+ export interface FeatureWatch {
90
+ /** The scaler at work: `levels`, `costs`, `budget`. */
91
+ readonly scaler: FeatureScaler;
92
+ /** Stop measuring and put every feature back. Also runs on `using` disposal. */
93
+ dispose(): void;
94
+ [Symbol.dispose](): void;
95
+ }
96
+ /**
97
+ * While the scene runs, time each frame's GPU work and turn features down and up through a {@link FeatureScaler}.
98
+ *
99
+ * ```ts
100
+ * using features = watchFeatures(featureKnobs({shadows, ssao, camera: engine.camera}), {budget: 12});
101
+ * ```
102
+ * @throws RangeError for invalid options (see {@link FeatureScaler}).
103
+ */
104
+ export declare function watchFeatures(knobs: readonly FeatureKnob[], { request, queue, now, onChange, ...options }?: WatchFeaturesOptions): FeatureWatch;
105
+ /** A knob that writes `values[level]` to `target[key]`: `values[0]` is full quality. Use it for anything that reads an option live. */
106
+ export declare function optionKnob<T extends object, K extends keyof T>(name: string, target: T, key: K, values: readonly T[K][], weight?: number): FeatureKnob;
107
+ /** Effects and objects {@link featureKnobs} can turn down; pass what the app has. */
108
+ export interface FeatureTargets {
109
+ /** Post effects that can be switched off, cheapest to lose first (`Bloom`, `DOF` and the like): their `enabled` goes false. */
110
+ post?: readonly {
111
+ name: string;
112
+ enabled: boolean;
113
+ }[];
114
+ /** `SSAO`: samples halve twice, then it switches off. */
115
+ ssao?: {
116
+ enabled: boolean;
117
+ options: {
118
+ samples?: number;
119
+ };
120
+ };
121
+ /** `SSR`: steps halve twice, then it switches off. */
122
+ ssr?: {
123
+ enabled: boolean;
124
+ options: {
125
+ steps?: number;
126
+ };
127
+ };
128
+ /**
129
+ * `Shadows`: the filter goes soft, pcf, hard; a set `distance` falls to 70% and 50%; `resolution` halves twice;
130
+ * `cascades` falls one at a time to two.
131
+ */
132
+ shadows?: {
133
+ options: {
134
+ filter?: 'soft' | 'pcf' | 'hard' | object;
135
+ distance?: number;
136
+ resolution?: number | readonly [number, number];
137
+ cascades?: number;
138
+ bounds?: unknown;
139
+ frustum?: unknown;
140
+ };
141
+ };
142
+ /** `VolumetricFog`: the grid halves, then it switches off. */
143
+ volumetric?: {
144
+ options: {
145
+ enabled?: boolean;
146
+ grid?: readonly [number, number, number];
147
+ };
148
+ };
149
+ /** `LODSystem`: `bias` grows 1.5 and 2 times, so detail drops nearer the camera. */
150
+ lod?: {
151
+ bias: number;
152
+ };
153
+ /** Camera: `far` falls to 75% and 50%. What lies past it stops drawing, so pair it with fog. */
154
+ camera?: {
155
+ far: number;
156
+ near: number;
157
+ };
158
+ }
159
+ /**
160
+ * Knobs for the features an app passes, each starting from its current value, in the order they are tried before
161
+ * anything is measured: post effects, ambient occlusion, reflections, shadows, volumetric fog, level of detail, view
162
+ * distance. A feature already off gets no knob.
163
+ */
164
+ export declare function featureKnobs({ post, ssao, ssr, shadows, volumetric, lod, camera, }: FeatureTargets): FeatureKnob[];
@@ -0,0 +1,189 @@
1
+ import { n as e } from "./resolution-QY5Gc9gc.js";
2
+ //#region src/features.ts
3
+ var t = 120, n = class {
4
+ constructor(e, { budget: t = 12, window: n = 30, settle: r = 8, minSaving: i = .03 } = {}) {
5
+ if (this.sum = 0, this.count = 0, this.skip = 0, this.calm = 0, this.holdOff = 2, this.sinceRise = Infinity, !(Number.isFinite(t) && t > 0) || !Number.isInteger(n) || n < 1 || !Number.isInteger(r) || r < 0 || !(i >= 0 && i < 1)) throw RangeError("Invalid feature options; use budget > 0, an integer window >= 1, an integer settle >= 0 and minSaving in [0, 1)");
6
+ let a = /* @__PURE__ */ new Set();
7
+ this.knobs = e.map(({ name: e, levels: t, apply: n, weight: r = 1 }) => {
8
+ if (!e || a.has(e) || !Number.isInteger(t) || t < 2 || !(r > 0)) throw RangeError(`Invalid feature knob '${e}'; use a unique name, an integer levels >= 2 and a weight above 0`);
9
+ return a.add(e), {
10
+ name: e,
11
+ levels: t,
12
+ apply: n,
13
+ weight: r,
14
+ level: 0,
15
+ saved: [],
16
+ resting: []
17
+ };
18
+ }), this.budget = t, this.window = n, this.settleFrames = r, this.minSaving = i;
19
+ }
20
+ get levels() {
21
+ return Object.fromEntries(this.knobs.map((e) => [e.name, e.level]));
22
+ }
23
+ get costs() {
24
+ return this.knobs.flatMap(({ name: e, levels: t, saved: n }) => Array.from({ length: t - 1 }, (t, r) => ({
25
+ name: e,
26
+ level: r,
27
+ saved: n[r]
28
+ })));
29
+ }
30
+ restart() {
31
+ this.sum = this.count = 0, this.trial = void 0, this.skip = this.settleFrames;
32
+ }
33
+ push(e) {
34
+ if (!Number.isFinite(e) || e < 0) return;
35
+ if (this.skip > 0) {
36
+ this.skip--;
37
+ return;
38
+ }
39
+ if (this.sum += e, ++this.count < this.window) return;
40
+ let t = this.sum / this.count;
41
+ return this.sum = this.count = 0, this.decide(t);
42
+ }
43
+ decide(e) {
44
+ for (let e of this.knobs) e.resting.forEach((t, n) => {
45
+ t && (e.resting[n] = t - 1);
46
+ });
47
+ let n = this.trial;
48
+ if (this.trial = void 0, n) {
49
+ let { knob: r, step: i, before: a, down: o } = n, s = Math.max(0, o ? a - e : e - a), c = r.saved[i];
50
+ if (r.saved[i] = c === void 0 ? s : (c + s) / 2, o && s < a * this.minSaving) return r.resting[i] = t, this.move(r, i);
51
+ }
52
+ if (this.sinceRise++, e > this.budget) {
53
+ this.calm = 0;
54
+ let t = this.lower(e - this.budget * .95);
55
+ return t ? (this.sinceRise <= 3 && (this.holdOff = Math.min(32, this.holdOff * 2)), this.trial = {
56
+ knob: t,
57
+ step: t.level,
58
+ before: e,
59
+ down: !0
60
+ }, this.move(t, t.level + 1)) : void 0;
61
+ }
62
+ if (e < this.budget * .7) {
63
+ if (++this.calm < this.holdOff) return;
64
+ let t = this.raise(e);
65
+ return t ? (this.calm = 0, this.sinceRise = 0, this.trial = {
66
+ knob: t,
67
+ step: t.level - 1,
68
+ before: e,
69
+ down: !1
70
+ }, this.move(t, t.level - 1)) : void 0;
71
+ }
72
+ this.calm = Math.max(0, this.calm - 1);
73
+ }
74
+ lower(e) {
75
+ let t = this.knobs.filter((e) => e.level < e.levels - 1 && !e.resting[e.level]), n = (e) => e.saved[e.level];
76
+ return t.filter((t) => n(t) >= e).sort((e, t) => e.weight - t.weight || n(e) - n(t))[0] ?? t.find((e) => n(e) === void 0) ?? t.sort((e, t) => n(t) / t.weight - n(e) / e.weight)[0];
77
+ }
78
+ raise(e) {
79
+ return this.knobs.filter((t) => t.level > 0 && e + (t.saved[t.level - 1] ?? 0) <= this.budget * .9).sort((e, t) => t.weight - e.weight)[0];
80
+ }
81
+ move(e, t) {
82
+ return e.level = t, e.apply(t), this.skip = this.settleFrames, {
83
+ name: e.name,
84
+ level: t
85
+ };
86
+ }
87
+ reset() {
88
+ for (let e of this.knobs) e.level && this.move(e, 0);
89
+ this.trial = void 0;
90
+ }
91
+ };
92
+ function r(t, { request: r, queue: i, now: a, onChange: o, ...s } = {}) {
93
+ let c = new n(t, s), l = !1, u = e({
94
+ request: r,
95
+ queue: i,
96
+ now: a
97
+ }, (e) => {
98
+ if (l) return;
99
+ let t = c.push(e);
100
+ t && o?.(t);
101
+ }), d = () => {
102
+ l || (l = !0, u(), c.reset());
103
+ };
104
+ return {
105
+ scaler: c,
106
+ dispose: d,
107
+ [Symbol.dispose]: d
108
+ };
109
+ }
110
+ function i(e, t, n, r, i = 1) {
111
+ return {
112
+ name: e,
113
+ levels: r.length,
114
+ weight: i,
115
+ apply: (e) => void (t[n] = r[e])
116
+ };
117
+ }
118
+ var a = (e, t, n, r, i) => ({
119
+ name: e,
120
+ levels: 4,
121
+ weight: i,
122
+ apply(e) {
123
+ t.enabled = e < 3, e < 3 && (t.options[n] = Math.max(1, r / 2 ** e | 0));
124
+ }
125
+ });
126
+ function o({ post: e = [], ssao: t, ssr: n, shadows: r, volumetric: o, lod: s, camera: c }) {
127
+ let l = e.filter((e) => e.enabled).map((e) => i(e.name, e, "enabled", [!0, !1], 1));
128
+ if (t?.enabled && l.push(a("ssao", t, "samples", t.options.samples ?? 32, 1)), n?.enabled && l.push(a("ssr", n, "steps", n.options.steps ?? 64, 1)), r) {
129
+ let { options: e } = r, t = typeof e.filter == "object" ? "hard" : e.filter ?? "soft", n = [
130
+ "soft",
131
+ "pcf",
132
+ "hard"
133
+ ].slice([
134
+ "soft",
135
+ "pcf",
136
+ "hard"
137
+ ].indexOf(t));
138
+ if (n.length > 1 && l.push(i("shadow filter", e, "filter", n, 1.5)), e.distance !== void 0) {
139
+ let { distance: t } = e;
140
+ l.push(i("shadow distance", e, "distance", [
141
+ t,
142
+ t * .7,
143
+ t * .5
144
+ ], 1.5));
145
+ }
146
+ let { resolution: a = 2048, cascades: o = 4 } = e, s = (e) => {
147
+ let t = (t) => Math.max(16, t / e);
148
+ return typeof a == "number" ? t(a) : [t(a[0]), t(a[1])];
149
+ }, c = [
150
+ a,
151
+ s(2),
152
+ s(4)
153
+ ].filter((e, t, n) => !t || JSON.stringify(e) !== JSON.stringify(n[t - 1]));
154
+ if (c.length > 1 && l.push(i("shadow resolution", e, "resolution", c, 2)), !e.bounds && !e.frustum && o > 2) {
155
+ let t = Array.from({ length: o - 1 }, (e, t) => o - t);
156
+ l.push(i("shadow cascades", e, "cascades", t, 2));
157
+ }
158
+ }
159
+ if (o && o.options.enabled !== !1) {
160
+ let { options: e } = o, t = e.grid ?? [
161
+ 160,
162
+ 90,
163
+ 64
164
+ ], n = t.map((e) => Math.max(2, e >> 1));
165
+ l.push({
166
+ name: "volumetric fog",
167
+ levels: 3,
168
+ weight: 2,
169
+ apply(r) {
170
+ e.enabled = r < 2, r < 2 && (e.grid = r ? n : t);
171
+ }
172
+ });
173
+ }
174
+ if (s && l.push(i("level of detail", s, "bias", [
175
+ s.bias,
176
+ s.bias * 1.5,
177
+ s.bias * 2
178
+ ], 2)), c) {
179
+ let e = [
180
+ c.far,
181
+ c.far * .75,
182
+ c.far * .5
183
+ ].filter((e) => e > c.near);
184
+ e.length > 1 && l.push(i("view distance", c, "far", e, 3));
185
+ }
186
+ return l;
187
+ }
188
+ //#endregion
189
+ export { n as FeatureScaler, o as featureKnobs, i as optionKnob, r as watchFeatures };
@@ -0,0 +1,148 @@
1
+ import type { EngineKernel } from '@margoengine/core';
2
+ import type { DeviceLike, QueueLike } from './reading.js';
3
+ declare global {
4
+ var margoLow: number | undefined;
5
+ var margoPreset: QualityPreset | undefined;
6
+ }
7
+ /** The part of `GPUAdapter` the tier uses. */
8
+ export interface AdapterLike {
9
+ features: {
10
+ has(name: string): boolean;
11
+ };
12
+ requestDevice(descriptor?: {
13
+ requiredFeatures?: Iterable<string>;
14
+ }): unknown;
15
+ }
16
+ /** 'phone' is 1x at DPR 1; 'light' is 1x at a capped DPR; 'high' is core's 4x desktop path. */
17
+ export type QualityTier = 'phone' | 'light' | 'high';
18
+ /**
19
+ * Feature defaults for a tier. `applyQualityTier()` publishes the tier's preset as `globalThis.margoPreset`; each feature
20
+ * package reads its key when an effect is constructed and uses a value only where the app left that option undefined
21
+ * (explicit options always win). Packages never import this one; without it they keep their own defaults. Value names
22
+ * are the packages' option names.
23
+ */
24
+ export interface QualityPreset {
25
+ /** `Shadows` (@margoengine/shadows): texels per cascade (default 2048), edge filter (default 'soft', PCSS) and
26
+ * cascades (default 4). */
27
+ shadows?: {
28
+ resolution?: number;
29
+ filter?: 'soft' | 'pcf' | 'hard';
30
+ cascades?: number;
31
+ };
32
+ /** `Scatter` (@margoengine/scatter): LOD cross-fade width (default 2); 0 compiles out the fade's `discard`. */
33
+ scatter?: {
34
+ lodFade?: number;
35
+ };
36
+ /** `SSAO` (@margoengine/post/ssao): on/off (default on) and kernel samples, 1-32 (default 32). */
37
+ ssao?: {
38
+ enabled?: boolean;
39
+ samples?: number;
40
+ };
41
+ /** `SSR` (@margoengine/post/ssr): on/off (default on) and Hi-Z march steps (default 64). */
42
+ ssr?: {
43
+ enabled?: boolean;
44
+ steps?: number;
45
+ };
46
+ /** `VolumetricFog` (@margoengine/environment/volumetric): on/off (default on) and froxel grid (default [160, 90, 64]). */
47
+ volumetric?: {
48
+ enabled?: boolean;
49
+ grid?: readonly [number, number, number];
50
+ };
51
+ /** `LocalShadows` (@margoengine/clustered/shadows): shadowed lights (default 4) and layer size (default 512). */
52
+ localShadows?: {
53
+ maxLights?: number;
54
+ resolution?: number;
55
+ };
56
+ /** `VFX` (@margoengine/vfx): particle capacity (default 1,000,000). */
57
+ vfx?: {
58
+ capacity?: number;
59
+ };
60
+ }
61
+ /** The preset per tier. The full tier keeps package defaults; phones use light defaults with SSAO and volumetric fog
62
+ * off, two shadow cascades instead of four, and no scatter LOD fade (a fragment `discard` turns off early depth
63
+ * rejection on tile-based phone GPUs). */
64
+ export declare const QUALITY_PRESETS: Readonly<Record<QualityTier, QualityPreset>>;
65
+ /** This page's preset (calls `applyQualityTier()` first if nothing has). */
66
+ export declare const qualityPreset: () => QualityPreset;
67
+ /** Inputs of `applyQualityTier`; each defaults to the browser's own, so tests can inject them. */
68
+ export interface QualityOptions {
69
+ /** URL query to read `?quality=high|low` (forces a tier, never remembered) and `?scale=1..2` (light-tier DPR). */
70
+ search?: string;
71
+ /** Page the measured result belongs to, because it says what this page's scene costs. Default `location.pathname`. */
72
+ page?: string;
73
+ /** Persistent storage for the measured result; defaults to localStorage. */
74
+ storage?: {
75
+ getItem(key: string): string | null;
76
+ setItem(key: string, value: string): void;
77
+ };
78
+ /** This tab's storage, read for `LOWERED_KEY`; defaults to sessionStorage. */
79
+ session?: {
80
+ getItem(key: string): string | null;
81
+ };
82
+ /** User agent string; 'Mobi', 'Android' or 'iPhone' selects the phone tier. Default `navigator.userAgent`. */
83
+ userAgent?: string;
84
+ }
85
+ /** Below this many frames per second, a one-second window on the full tier counts as slow. */
86
+ export declare const SLOW_FPS = 55;
87
+ /** Light-tier GPU milliseconds per frame (90th percentile, timestamp queries: the time a frame's passes cover) below which
88
+ * this page's next load gets the full tier. Chosen from Plaza in real play at spawn, with the sun moving and shadows
89
+ * redrawing: an RTX A6000 on a busy machine read 3.2 to 7.25 ms from 720p to 4K, an Intel UHD (Alder Lake-N) 60 ms at 720p,
90
+ * and an Arc 140V 9 to 16.4 ms by the same queries, copies included, in `measure.mjs`. A limit for that scene, on those
91
+ * GPUs; other scenes read their own cost against it. */
92
+ export declare const FAST_GPU_MS = 8;
93
+ /** Set in sessionStorage by `watchPower` (`@margoengine/quality/power`): this tab's next load starts light, whatever was
94
+ * measured, because 4x multisampling cannot change while a page runs. */
95
+ export declare const LOWERED_KEY = "margoQualityLowered";
96
+ /** Choose this page's tier. Call once, before creating any engine: core reads `globalThis.margoLow` when it builds
97
+ * pipelines and sizes the canvas, and feature packages read `globalThis.margoPreset` (this tier's `QualityPreset`) when
98
+ * an effect is constructed. Desktops start light unless this browser already measured headroom for 4x, so a slow
99
+ * PC never shows a slow phase or a reload; `paceEngine` then holds light-tier engines to ~60 FPS. */
100
+ export declare function applyQualityTier({ search, page, storage, session, userAgent, }?: QualityOptions): QualityTier;
101
+ /** This page's tier (calls `applyQualityTier()` first if nothing has). */
102
+ export declare const currentTier: () => QualityTier;
103
+ /** An engine from `Engine.create` / `createStage` (EngineKernel) or the runtime `Engine` from core's extension API. */
104
+ export type Paced = EngineKernel | {
105
+ pace?: (time: number) => boolean;
106
+ };
107
+ /** Set `engine.pace` so the engine renders at an even rate no lower than `rate`, as near to it as the display allows: 60
108
+ * on 60/120/240 Hz, 72 on 144 Hz, 83 on 165 Hz, and every refresh of a 75, 90 or 100 Hz display. Each frame spans the most
109
+ * whole refreshes that still keep up with `rate`, so a display that is no multiple of it never falls below (every other
110
+ * refresh of 100 Hz would be 50 FPS). It counts refreshes rather than comparing times, so timestamp jitter cannot move it. */
111
+ export declare function capFrameRate(engine: Paced, rate?: number): void;
112
+ /** Apply the chosen tier's frame cap to an engine; call right after creating it. On the light tier a slow GPU on a
113
+ * 120 Hz panel otherwise swings between 120 and 40 FPS, so it is held to ~60 FPS; other tiers are left uncapped. */
114
+ export declare function paceEngine(engine: Paced): void;
115
+ /** Hooks of `watchQuality`; each defaults to the browser's own, so tests can inject them. */
116
+ export interface WatchOptions {
117
+ /** Frame scheduler, called with a time in milliseconds. Default `requestAnimationFrame`. */
118
+ request?: (callback: (time: number) => void) => unknown;
119
+ /** Queue whose `submit` is wrapped during the reading. Default `GPUQueue.prototype` when WebGPU exists. */
120
+ queue?: QueueLike;
121
+ /** Device whose `createCommandEncoder` is wrapped during the reading. Default `GPUDevice.prototype` when WebGPU exists. */
122
+ device?: Pick<DeviceLike, 'createCommandEncoder'>;
123
+ /** Told the light-tier reading when it ends: GPU milliseconds per frame (90th percentile), or undefined when there is
124
+ * none (no `timestamp-query`, too few frames). */
125
+ onReading?: (milliseconds: number | undefined) => void;
126
+ /** Remembers the result. Default writes it to the storage `applyQualityTier` used. */
127
+ store?: (value: 'high' | 'low') => void;
128
+ /** Called after remembering 'low' on the full tier. Default `location.reload`. */
129
+ reload?: () => void;
130
+ }
131
+ /** Call once the scene is running. On the light tier, reads the real GPU time of this page's frames by timestamp queries
132
+ * and remembers 'high' for this page's next load when it is under `FAST_GPU_MS`. The queries exist only during the
133
+ * reading (about 4 s at 60 FPS, 10 s at most); everything wrapped for it is then put back and its GPU objects destroyed.
134
+ * Without `timestamp-query` the page stays light and nothing is stored. A slow reading remembers nothing, so one bad
135
+ * session (a remote desktop, a busy machine, a slow first window) cannot hold a browser on the light tier for good: the
136
+ * next load measures again. On the full tier, five consecutive slow seconds remember that for good and reload once;
137
+ * `localStorage.removeItem('margoQuality:' + location.pathname)` measures again. Phones do nothing. */
138
+ export declare function watchQuality({ request, queue, device, onReading, store, reload, }?: WatchOptions): void;
139
+ /** An app that renders on demand (a paused scene, a stopped loop) shows an empty canvas after core restores a lost GPU
140
+ * device, until something renders again. Call once: `render` then runs on the next two animation frames after every
141
+ * restoration (effects that read the previous frame, such as water refraction and sky reflections, settle on the
142
+ * second). Returns a function that stops it. */
143
+ export declare function redrawAfterRestore(engine: EngineKernel, render: () => void, request?: (callback: () => void) => unknown): () => void;
144
+ export { frameDue, frameStatus } from './pacing.js';
145
+ /** 1 on phones and the light tier, 4 on the desktop full tier: the scene sample count core uses (call after applyQualityTier). */
146
+ export declare const sceneSamples: () => 1 | 4;
147
+ export { ResolutionScaler, watchResolution, type ResolutionOptions, type ResolutionWatch, type WatchResolutionOptions, } from './resolution.js';
148
+ export type { DeviceLike, QueueLike } from './reading.js';
package/dist/index.js ADDED
@@ -0,0 +1,3 @@
1
+ import { a as e, c as t, d as n, f as r, i, l as a, m as o, n as s, o as c, p as l, r as u, s as d, t as f, u as p } from "./src-CDJk96xr.js";
2
+ import { r as m, t as h } from "./resolution-QY5Gc9gc.js";
3
+ export { f as FAST_GPU_MS, s as LOWERED_KEY, u as QUALITY_PRESETS, h as ResolutionScaler, i as SLOW_FPS, e as applyQualityTier, c as capFrameRate, d as currentTier, l as frameDue, o as frameStatus, t as paceEngine, a as qualityPreset, p as redrawAfterRestore, n as sceneSamples, r as watchQuality, m as watchResolution };