@margoengine/worker 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.
package/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2026 Scott Campbell
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/NOTICE ADDED
@@ -0,0 +1,4 @@
1
+ Margo Engine
2
+ Copyright 2026 Scott Campbell
3
+
4
+ This product includes Margo Engine (https://margoengine.com) by Scott Campbell.
package/README.md CHANGED
@@ -1,3 +1,84 @@
1
- # Temporary Holding Version
2
-
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
1
+ # @margoengine/worker
2
+
3
+ Runs the engine inside a Web Worker on an `OffscreenCanvas`, so a heavy scene never blocks the page's main thread and a busy page never stalls the scene. The helper moves the canvas and keeps the worker told of the page's canvas: its size, position, pixel ratio and visibility, and the input events the worker listens for. Core needs no change and no option: `Engine.create`, `engine.pick`, the frame loop, control packages and the `@margoengine/webgl2-compat/preview` fallback run on the received canvas as they do on the page.
4
+
5
+ Two entries, one per side. `@margoengine/worker` goes in the page and `@margoengine/worker/canvas` in the worker, so neither side downloads the other's code.
6
+
7
+ ```ts
8
+ // page.ts
9
+ import { transferCanvas, workerCanvasSupported } from '@margoengine/worker';
10
+
11
+ const canvas = document.querySelector('canvas')!;
12
+ if (!workerCanvasSupported()) throw new Error('Run the scene on the page here');
13
+ const worker = new Worker(new URL('./scene-worker.js', import.meta.url), { type: 'module' });
14
+ const view = await transferCanvas(canvas, worker, { data: { level: 'plaza' } });
15
+
16
+ // Later: `view.dispose()` disposes the engine in the worker, then the worker is yours to end.
17
+ addEventListener('pagehide', () => {
18
+ view.dispose();
19
+ worker.terminate();
20
+ });
21
+ ```
22
+
23
+ ```ts
24
+ // scene-worker.ts
25
+ import { box, Engine, PbrMaterial } from '@margoengine/core';
26
+ import { OrbitControls } from '@margoengine/controls';
27
+ import { receiveCanvas } from '@margoengine/worker/canvas';
28
+
29
+ const received = await receiveCanvas();
30
+ const engine = await Engine.create(received.canvas);
31
+ received.attach(engine);
32
+ engine.createMesh().setGeometry(box()).setMaterial(new PbrMaterial({ color: '#84d6bd' }));
33
+ const controls = new OrbitControls(engine.camera, received.canvas);
34
+ engine.onFrame((_, delta) => controls.update(delta));
35
+ engine.start();
36
+ ```
37
+
38
+ ## Page side
39
+
40
+ `transferCanvas(canvas, worker, options)` resolves with a `WorkerCanvas` once the worker holds the canvas. Either side may start first.
41
+
42
+ | Option | Default | Meaning |
43
+ | --- | --- | --- |
44
+ | `data` | `undefined` | Anything structured clone accepts, read in the worker as `received.data`. |
45
+ | `transfer` | `[]` | Objects in `data` to transfer instead of copy. |
46
+ | `signal` | none | Aborts the wait. A canvas that had not moved yet stays usable. |
47
+ | `timeout` | `30000` | Milliseconds to wait for the worker to call `receiveCanvas`. |
48
+
49
+ It rejects with a `MargoError` whose `code` is `unsupported` (the browser cannot move a canvas), `state` (the canvas has a context or already moved), `failed` (the worker's script failed) or `timeout`.
50
+
51
+ `view.dispose()`, or `using`, stops forwarding, aborts `received.signal` and disposes an engine that used `received`. A canvas cannot come back from a worker, and the worker keeps running until you call `worker.terminate()`. `workerCanvasSupported()` says whether the browser can do this at all.
52
+
53
+ Your own `worker.postMessage` traffic is left alone: the link runs on a `MessageChannel` of its own after a short handshake whose messages carry the key `margo-worker-canvas`. Errors in the worker reach `worker.addEventListener('error', ...)`; the engine's default `onError` reports them there.
54
+
55
+ ## Worker side
56
+
57
+ `receiveCanvas({signal, timeout})` resolves with a `ReceivedCanvas`:
58
+
59
+ | Member | Meaning |
60
+ | --- | --- |
61
+ | `canvas` | The `OffscreenCanvas`, with `clientWidth`, `clientHeight`, `getBoundingClientRect`, `style` and the pointer capture methods of the page's canvas. Typed as an element, so it passes to `Engine.create` and to controls. |
62
+ | `data` | The page's `data` option. |
63
+ | `hidden` | True while the page is hidden. |
64
+ | `signal` | Aborts when the page disposes its end. |
65
+
66
+ `received.attach(engine)` makes the first frame after a background tab step 0, as on the page, and lets the page dispose the engine.
67
+
68
+ The page posts a size only when it differs from what the worker holds, so an unchanged resize costs no message; the frame loop runs in the worker and the page does no work per frame.
69
+
70
+ Because `clientWidth` follows the page and the page's `devicePixelRatio` and `margoLow` are copied to the worker, the engine picks the same drawing-buffer size as on the page, and `engine.pick` takes CSS pixels. With `exactSize` the worker owns `canvas.width` and `canvas.height`.
71
+
72
+ Input events arrive on `received.canvas`, as plain events with the values of the real ones (`clientX`, `pointerId`, `deltaY`, `key`, ...). The page only forwards a type once something in the worker listens for it. Pointer, mouse, wheel, click, context menu and focus events come from the canvas; key events come from the document, since an unfocused canvas gets none, and they land on `received.canvas`, which is where controls listen when an element has no document. A `style` written in the worker (`touchAction`, `cursor`) is set on the page's canvas.
73
+
74
+ ## What differs from the page
75
+
76
+ - `event.preventDefault()` in a worker comes too late to change anything. The page stops the default of `wheel` and `contextmenu` for you once the worker listens for them, and of nothing else, so keys keep their browser meaning.
77
+ - The page captures the pointer on every `pointerdown` the worker listens for, so a drag goes on outside the canvas. `setPointerCapture` in the worker only records it.
78
+ - Pointer lock, `document` and anything else from the DOM stay on the page. `PointerLockControls` needs the page.
79
+ - `mount` from `@margoengine/stage` builds its canvas in a page. In a worker create the engine and pass it to `new Stage(engine)`.
80
+ - Input reaches the worker one message later, and a worker stuck in a long task reads it when the task ends.
81
+
82
+ ## Browser support
83
+
84
+ The worker needs `OffscreenCanvas` and WebGPU (or WebGL2) in workers and `requestAnimationFrame` in workers. Proved on Chromium (`npm run test:gpu` in this package, real GPU); other browsers follow the same standards but have not been run. Keep a page path behind `workerCanvasSupported()` for browsers without them.
package/dist/auto.d.ts ADDED
@@ -0,0 +1,37 @@
1
+ export type { SceneContext, SceneInstance, SceneModule } from './scene-runtime.js';
2
+ /** Options for automatic worker/page scene selection. */
3
+ export interface AutoSceneOptions {
4
+ /** auto chooses a supported worker, then page fallback. page forces page; worker disables fallback. Default auto. */
5
+ mode?: 'auto' | 'worker' | 'page';
6
+ /** Required renderer capability in the worker probe. auto accepts WebGPU or WebGL2. Default auto. */
7
+ backend?: 'auto' | 'webgpu' | 'webgl2';
8
+ /** Passed to createScene on either thread. Default undefined. */
9
+ data?: unknown;
10
+ /** User data to move rather than copy on the worker path. Ignored on the page path. Default none. */
11
+ transfer?: Transferable[];
12
+ /** Startup/lifetime cancellation. Default none. */
13
+ signal?: AbortSignal;
14
+ /** Startup and worker cleanup deadline in milliseconds, above zero. Default 30000. */
15
+ timeout?: number;
16
+ /** Optional factory for a CSP-hosted copy of the bundled generic scene worker. Its worker is owned by this scene. */
17
+ worker?: () => Worker;
18
+ }
19
+ /** Running shared scene with its selected execution mode and lifetime owner. Use await using for cleanup. */
20
+ export declare class AutoScene {
21
+ /** The original canvas, retained on fallback because the worker is probed before transfer. */
22
+ readonly canvas: HTMLCanvasElement;
23
+ /** Selected thread. */
24
+ readonly mode: 'page' | 'worker';
25
+ /** Why auto selected the page, if a worker was attempted but unavailable. */
26
+ readonly fallbackReason: unknown;
27
+ private readonly cleanup;
28
+ [Symbol.dispose]: () => Promise<void>;
29
+ [Symbol.asyncDispose]: () => Promise<void>;
30
+ private closing?;
31
+ /** True once disposal starts. */
32
+ get disposed(): boolean;
33
+ /** Aborts scene lifetime, runs cleanup once, and terminates an owned worker even if cleanup fails. */
34
+ dispose(): Promise<void>;
35
+ }
36
+ /** Runs one scene module in a capable worker, otherwise on the page. Runtime scene failures are reported, never replayed. */
37
+ export declare function runScene(canvas: HTMLCanvasElement, moduleURL: URL, options?: AutoSceneOptions): Promise<AutoScene>;
package/dist/auto.js ADDED
@@ -0,0 +1,110 @@
1
+ import { n as e, t } from "./errors-CDgOgzCd.js";
2
+ import { transferCanvas as n, workerCanvasSupported as r } from "./index.js";
3
+ import { RpcClient as i } from "./rpc.js";
4
+ //#region src/scene-runtime.ts
5
+ var a = (e) => import(
6
+ /* @vite-ignore */
7
+ e
8
+ ), o = class {
9
+ constructor(e, t, n, r) {
10
+ this.canvas = e, this.mode = t, this.fallbackReason = n, this.cleanup = r;
11
+ }
12
+ get disposed() {
13
+ return !!this.closing;
14
+ }
15
+ dispose() {
16
+ return this.closing ??= this.cleanup();
17
+ }
18
+ [Symbol.dispose ?? Symbol()]() {
19
+ return this.dispose();
20
+ }
21
+ [Symbol.asyncDispose ?? Symbol()]() {
22
+ return this.dispose();
23
+ }
24
+ };
25
+ async function s(s, c, l = {}) {
26
+ let { mode: u = "auto", backend: d = "auto", timeout: f = 3e4, signal: p, data: m, transfer: h = [] } = l;
27
+ if (!(f > 0 && Number.isFinite(f))) throw e("Scene timeout must be finite and above zero", "worker");
28
+ if (![
29
+ "auto",
30
+ "page",
31
+ "worker"
32
+ ].includes(u) || ![
33
+ "auto",
34
+ "webgpu",
35
+ "webgl2"
36
+ ].includes(d)) throw t("state", "Choose auto, page or worker mode and a supported backend", "worker");
37
+ p?.throwIfAborted();
38
+ let g = new AbortController(), _ = new AbortController(), v = AbortSignal.any([
39
+ g.signal,
40
+ _.signal,
41
+ ...p ? [p] : []
42
+ ]), y = setTimeout(() => _.abort(t("timeout", "Scene startup deadline exceeded; check the scene module", "worker")), f), b, x, S, C, w, T = /* @__PURE__ */ new Set(), E = async () => {
43
+ try {
44
+ await C?.dispose();
45
+ } finally {
46
+ for (let e of T) e.dispose();
47
+ T.clear();
48
+ }
49
+ }, D = (e) => new Promise((t, n) => {
50
+ let r = () => n(v.reason);
51
+ v.addEventListener("abort", r, { once: !0 }), v.aborted && r(), e.then(t, n).finally(() => v.removeEventListener("abort", r));
52
+ });
53
+ try {
54
+ if (u !== "page") try {
55
+ if (!r()) throw t("unsupported", "Worker canvas unavailable; use page mode", "worker");
56
+ if (b = l.worker?.() ?? new Worker(new URL("./workers/scene.js?no-inline",
57
+ import.meta.url
58
+ ), { type: "module" }), x = new i(b), !await x.call("prepare", [c.href, d], {
59
+ signal: v,
60
+ timeout: f
61
+ })) throw t("unsupported", "Worker renderer or animation frames unavailable; use page mode", "worker");
62
+ } catch (e) {
63
+ if (x?.dispose(), b?.terminate(), x = void 0, b = void 0, v.throwIfAborted(), u === "worker") throw e;
64
+ w = e;
65
+ }
66
+ if (b && x) S = await n(s, b, {
67
+ data: m,
68
+ transfer: h,
69
+ signal: v,
70
+ timeout: f
71
+ }), await x.call("start", [], {
72
+ signal: v,
73
+ timeout: f
74
+ });
75
+ else {
76
+ let e = await D(a(c.href));
77
+ if (typeof e.createScene != "function") throw t("state", "Scene module must export createScene", "worker");
78
+ let n = Promise.resolve(e.createScene({
79
+ canvas: s,
80
+ data: m,
81
+ signal: AbortSignal.any([g.signal, ...p ? [p] : []]),
82
+ mode: "page",
83
+ attach: (e) => {
84
+ T.add(e);
85
+ }
86
+ }));
87
+ n.then(async (e) => {
88
+ v.aborted && await e.dispose();
89
+ }, () => {}), C = await D(n);
90
+ }
91
+ v.throwIfAborted(), clearTimeout(y);
92
+ let e = new o(s, b ? "worker" : "page", w, async () => {
93
+ p?.removeEventListener("abort", _), g.abort();
94
+ try {
95
+ x ? await x.call("dispose", [], { timeout: f }) : await E();
96
+ } finally {
97
+ S?.dispose(), x?.dispose(), b?.terminate();
98
+ }
99
+ }), _ = () => {
100
+ e.dispose().catch((e) => s.dispatchEvent(new ErrorEvent("error", { error: e })));
101
+ };
102
+ return p?.addEventListener("abort", _, { once: !0 }), e;
103
+ } catch (e) {
104
+ throw g.abort(), S?.dispose(), x?.dispose(), b?.terminate(), await E(), e;
105
+ } finally {
106
+ clearTimeout(y);
107
+ }
108
+ }
109
+ //#endregion
110
+ export { o as AutoScene, s as runScene };
@@ -0,0 +1,67 @@
1
+ import type { EngineKernel } from '@margoengine/core';
2
+ /** Options of {@link receiveCanvas}. */
3
+ export interface ReceiveCanvasOptions {
4
+ /** Aborts the wait for the page. Default none. */
5
+ signal?: AbortSignal;
6
+ /** Milliseconds to wait for the page to call `transferCanvas`, above 0. Default 30000. */
7
+ timeout?: number;
8
+ }
9
+ /** Pointer-lock request on either end of the canvas bridge. Browser user activation is still required. */
10
+ export interface WorkerPointerLockOptions {
11
+ /** Aborts the wait, not the browser's native permission request. Default none. */
12
+ signal?: AbortSignal;
13
+ /** Hard wait deadline in milliseconds, above zero. Default 10000. */
14
+ timeout?: number;
15
+ /** Requests raw mouse input; denial is reported rather than retried with adjusted input. Default false. */
16
+ unadjustedMovement?: boolean;
17
+ }
18
+ /**
19
+ * The worker's end of a canvas, from {@link receiveCanvas}. `received.attach(engine)` ties it to the engine: the first
20
+ * frame after the page comes back from a background tab steps 0, as on the page, and `dispose` on the page disposes
21
+ * the engine.
22
+ */
23
+ export declare class ReceivedCanvas {
24
+ /**
25
+ * The canvas, typed as an element because that is what it now serves as: pass it to `Engine.create` and to controls.
26
+ * `clientWidth` and `clientHeight` follow the page's canvas, so the engine sizes itself and takes CSS pixels in
27
+ * `pick` as it does on the page. Input events from the page arrive on it.
28
+ */
29
+ readonly canvas: HTMLCanvasElement;
30
+ /** The page's `data` option. */
31
+ readonly data: unknown;
32
+ private readonly port;
33
+ [Symbol.dispose]: () => void;
34
+ /** True while the page is hidden. */
35
+ hidden: boolean;
36
+ private readonly closing;
37
+ private readonly captured;
38
+ private readonly listened;
39
+ private readonly locks;
40
+ private nextLock;
41
+ private locked;
42
+ private engine?;
43
+ private resuming;
44
+ private rect;
45
+ /** Aborts when the page disposes its `WorkerCanvas`, or this is disposed. */
46
+ get signal(): AbortSignal;
47
+ /** True while this canvas owns the page's pointer lock, updated by native lock-change events. */
48
+ get pointerLocked(): boolean;
49
+ /** Asks the page to request lock. Invoke from forwarded trusted interaction; rejection reports activation/permission failure. */
50
+ requestPointerLock({ signal, timeout, unadjustedMovement, }?: WorkerPointerLockOptions): Promise<void>;
51
+ /** Asks the page to release this canvas's lock. The native change event updates pointerLocked. */
52
+ exitPointerLock(): void;
53
+ private send;
54
+ private resize;
55
+ private dispatch;
56
+ private setHidden;
57
+ private close;
58
+ /** Ties this canvas to `engine`: see the class. Disposing the engine then ends the link to the page. */
59
+ attach(engine: EngineKernel): this;
60
+ /** Ends the link to the page. The page's canvas keeps the last frame. */
61
+ dispose(): void;
62
+ }
63
+ /**
64
+ * In a worker: waits for the canvas the page passes to `transferCanvas`. Rejects with `timeout` when the page never
65
+ * sends one, or the signal's reason.
66
+ */
67
+ export declare function receiveCanvas({ signal, timeout }?: ReceiveCanvasOptions): Promise<ReceivedCanvas>;
package/dist/canvas.js ADDED
@@ -0,0 +1,157 @@
1
+ // @margo/core-built 0.1.0
2
+ import {coreRequirement as __margoCoreRequirement,assertCore as __margoAssertCore} from '@margoengine/core/extension';
3
+
4
+ import { n as e, t } from "./errors-CDgOgzCd.js";
5
+ //#region src/canvas.ts
6
+ var n = "margo-worker-canvas", r = () => globalThis, i = class {
7
+ constructor(e, t, n, r) {
8
+ this.canvas = e, this.data = t, this.port = n, this.hidden = !1, this.closing = new AbortController(), this.captured = /* @__PURE__ */ new Set(), this.listened = /* @__PURE__ */ new Set(), this.locks = /* @__PURE__ */ new Map(), this.nextLock = 0, this.locked = !1, this.resuming = !1, this.rect = {
9
+ width: 0,
10
+ height: 0,
11
+ left: 0,
12
+ top: 0
13
+ }, this.resize(r);
14
+ let i = e.addEventListener.bind(e), a = (e) => this.send(e), o = this.captured;
15
+ Object.defineProperties(e, {
16
+ clientWidth: { get: () => this.rect.width },
17
+ clientHeight: { get: () => this.rect.height },
18
+ style: { value: new Proxy({}, {
19
+ get: (e, t) => e[t] ?? "",
20
+ set(e, t, n) {
21
+ return e[t] = n, a({ style: [t.replace(/[A-Z]/g, (e) => `-${e.toLowerCase()}`), n] }), !0;
22
+ }
23
+ }) },
24
+ getBoundingClientRect: { value: () => {
25
+ let { left: e, top: t, width: n, height: r } = this.rect;
26
+ return {
27
+ left: e,
28
+ top: t,
29
+ width: n,
30
+ height: r,
31
+ x: e,
32
+ y: t,
33
+ right: e + n,
34
+ bottom: t + r
35
+ };
36
+ } },
37
+ setPointerCapture: { value: (e) => o.add(e) },
38
+ releasePointerCapture: { value: (e) => o.delete(e) },
39
+ hasPointerCapture: { value: (e) => o.has(e) },
40
+ requestPointerLock: { value: (e) => this.requestPointerLock(e) },
41
+ exitPointerLock: { value: () => this.exitPointerLock() },
42
+ pointerLockElement: { get: () => this.locked ? e : null },
43
+ addEventListener: { value: (e, ...t) => {
44
+ this.listened.has(e) || (this.listened.add(e), a({ listen: e })), i(e, ...t);
45
+ } }
46
+ }), n.onmessage = ({ data: t }) => {
47
+ t.type === "event" ? this.dispatch(t) : t.type === "size" ? this.resize(t) : t.type === "hidden" ? this.setHidden(t.hidden) : t.type === "close" ? this.close() : t.type === "pointerlock" ? (this.locked = t.locked, e.dispatchEvent(new Event("pointerlockchange"))) : t.type === "pointerlockerror" ? e.dispatchEvent(new Event("pointerlockerror")) : t.type === "lock-result" && this.locks.get(t.id)?.finish(t.error && Object.assign(Error(t.error.message), t.error));
48
+ };
49
+ }
50
+ get signal() {
51
+ return this.closing.signal;
52
+ }
53
+ get pointerLocked() {
54
+ return this.locked;
55
+ }
56
+ requestPointerLock({ signal: n, timeout: r = 1e4, unadjustedMovement: i = !1 } = {}) {
57
+ return new Promise((a, o) => {
58
+ let s = AbortSignal.any([this.signal, ...n ? [n] : []]);
59
+ if (s.throwIfAborted(), !(r > 0 && Number.isFinite(r))) throw e("Pointer lock timeout must be finite and above zero", "worker");
60
+ let c = ++this.nextLock, l = (e) => {
61
+ clearTimeout(d), s.removeEventListener("abort", u), this.locks.delete(c), e === void 0 ? a() : o(e);
62
+ }, u = () => {
63
+ this.send({
64
+ pointerLock: "cancel",
65
+ id: c
66
+ }), l(s.reason);
67
+ }, d = setTimeout(() => {
68
+ this.send({
69
+ pointerLock: "cancel",
70
+ id: c
71
+ }), l(t("timeout", "Pointer lock response deadline exceeded; check the page connection", "worker"));
72
+ }, r);
73
+ this.locks.set(c, { finish: l }), s.addEventListener("abort", u, { once: !0 });
74
+ try {
75
+ this.send({
76
+ pointerLock: "request",
77
+ id: c,
78
+ options: {
79
+ timeout: r,
80
+ unadjustedMovement: i
81
+ }
82
+ });
83
+ } catch (e) {
84
+ l(e);
85
+ }
86
+ });
87
+ }
88
+ exitPointerLock() {
89
+ this.send({ pointerLock: "exit" });
90
+ }
91
+ send(e) {
92
+ this.closing.signal.aborted || this.port.postMessage(e);
93
+ }
94
+ resize({ width: e, height: t, left: n, top: i, ratio: a, low: o }) {
95
+ this.rect = {
96
+ width: e,
97
+ height: t,
98
+ left: n,
99
+ top: i
100
+ };
101
+ let s = r();
102
+ a && (s.devicePixelRatio = a), o !== void 0 && (s.margoLow = o);
103
+ }
104
+ dispatch({ name: e, fields: t, left: n, top: r }) {
105
+ this.rect.left = n, this.rect.top = r, this.canvas.dispatchEvent(Object.assign(new Event(e, { cancelable: !0 }), t));
106
+ }
107
+ setHidden(e) {
108
+ let t = this.hidden && !e, n = this.engine;
109
+ if (this.hidden = e, !t || !n || this.resuming) return;
110
+ let r = n.maxDelta;
111
+ this.resuming = !0, n.maxDelta = 0;
112
+ let i = n.onFrame(() => {
113
+ i(), n.maxDelta = r, this.resuming = !1;
114
+ });
115
+ }
116
+ close() {
117
+ let e = this.engine;
118
+ this.dispose(), e && !e.disposed && e.dispose();
119
+ }
120
+ attach(e) {
121
+ return e.use({coreRequirement:/*@__PURE__*/__margoCoreRequirement("0.1.0",import.meta.url),
122
+ name: "worker-canvas",
123
+ setup() {},
124
+ dispose: () => this.dispose()
125
+ }), this.engine = e, this;
126
+ }
127
+ dispose() {
128
+ this.closing.signal.aborted || (this.send({ closed: !0 }), this.closing.abort(), this.locked && (this.locked = !1, this.canvas.dispatchEvent(new Event("pointerlockchange"))), this.engine = void 0, this.port.close());
129
+ }
130
+ [Symbol.dispose ?? Symbol()]() {
131
+ this.dispose();
132
+ }
133
+ };
134
+ function a({ signal: a, timeout: o = 3e4 } = {}) {
135
+ return new Promise((s, c) => {
136
+ if (!(o > 0 && o < Infinity)) throw e("receiveCanvas: timeout above 0", "worker");
137
+ a?.throwIfAborted();
138
+ let l = r(), u = () => {
139
+ clearTimeout(p), a?.removeEventListener("abort", d), l.removeEventListener("message", f);
140
+ }, d = () => {
141
+ u(), c(a.reason);
142
+ }, f = (e) => {
143
+ let t = e.data;
144
+ if (t?.[n] === "ask") l.postMessage({ [n]: "hello" });
145
+ else if (t?.[n] === "canvas") {
146
+ u();
147
+ let e = new i(t.canvas, t.data, t.port, t);
148
+ l.postMessage({ [n]: "received" }), s(e);
149
+ }
150
+ }, p = setTimeout(() => {
151
+ u(), c(t("timeout", "The page never called transferCanvas", "worker"));
152
+ }, o);
153
+ a?.addEventListener("abort", d), l.addEventListener("message", f), l.postMessage({ [n]: "hello" });
154
+ });
155
+ }
156
+ //#endregion
157
+ export { i as ReceivedCanvas, a as receiveCanvas };