@margoengine/cameras 0.0.0-stage → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/origin.js ADDED
@@ -0,0 +1,147 @@
1
+ // @margo/core-built 1.0.0
2
+ import {coreRequirement as __margoCoreRequirement,assertCore as __margoAssertCore} from '@margoengine/core/extension';
3
+ const t=(engine,version="1.0.0",source=import.meta.url)=>__margoRuntime(engine,version,source);
4
+ import { t as e } from "./errors-Cp7bu2gW.js";
5
+ import { engineRuntime as __margoRuntime, meshRuntime as n } from "@margoengine/core/extension";
6
+ //#region src/origin.ts
7
+ var r = class r {coreRequirement=__margoCoreRequirement("1.0.0",import.meta.url);
8
+ static attach(e, t) {__margoAssertCore(e,__margoCoreRequirement("1.0.0",import.meta.url));
9
+ let n = new r(t);
10
+ return e.use(n), n;
11
+ }
12
+ constructor({ ratio: e = 1e3 } = {}) {
13
+ if (this.name = "floating-origin", this.ratio = 1e3, this.rebases = 0, this.value = [
14
+ 0,
15
+ 0,
16
+ 0
17
+ ], this.roots = /* @__PURE__ */ new Map(), this.listeners = /* @__PURE__ */ new Set(), !(e > 0)) throw RangeError("Invalid ratio; pass a number above 0");
18
+ this.ratio = e;
19
+ }
20
+ setup(e) {
21
+ this.engine = t(e);
22
+ }
23
+ get origin() {
24
+ return [...this.value];
25
+ }
26
+ get camera() {
27
+ if (!this.engine) throw e("state", "FloatingOrigin is not attached; call engine.use(origin) first");
28
+ return this.engine.camera;
29
+ }
30
+ place(e, t) {
31
+ let r = n(e);
32
+ if (r.check(), r.engine !== this.engine) throw TypeError("Foreign mesh; place meshes created by the engine this origin is attached to");
33
+ if (r.engine.store.parents[r.id] !== -1) throw TypeError("place() takes root meshes; place the root of the hierarchy, not a child");
34
+ let a = i(t, "Invalid world position"), o = this.roots.get(r) ?? /* @__PURE__ */ new Float64Array(6);
35
+ o.set(a), this.roots.set(r, o), this.write(r, o);
36
+ }
37
+ forget(e) {
38
+ this.roots.delete(n(e));
39
+ }
40
+ worldPosition(e) {
41
+ let t = n(e), r = this.roots.get(t);
42
+ if (r) return this.sync(t, r), [
43
+ r[0],
44
+ r[1],
45
+ r[2]
46
+ ];
47
+ }
48
+ toWorld(e) {
49
+ let t = this.value;
50
+ return [
51
+ e[0] + t[0],
52
+ e[1] + t[1],
53
+ e[2] + t[2]
54
+ ];
55
+ }
56
+ toLocal(e) {
57
+ let t = this.value;
58
+ return [
59
+ e[0] - t[0],
60
+ e[1] - t[1],
61
+ e[2] - t[2]
62
+ ];
63
+ }
64
+ toLocalPlane(e) {
65
+ let t = this.value;
66
+ return [
67
+ e[0],
68
+ e[1],
69
+ e[2],
70
+ e[3] + e[0] * t[0] + e[1] * t[1] + e[2] * t[2]
71
+ ];
72
+ }
73
+ lookAt(e, t) {
74
+ let n = i(e, "Invalid camera"), r = i(t, "Invalid camera"), a = this.camera;
75
+ a.cancelFit(), a.position = this.toLocal(n), a.target = this.toLocal(r), this.check();
76
+ }
77
+ get cameraPosition() {
78
+ return this.toWorld(this.camera.position);
79
+ }
80
+ get cameraTarget() {
81
+ return this.toWorld(this.camera.target);
82
+ }
83
+ onRebase(e) {
84
+ return this.listeners.add(e), () => {
85
+ this.listeners.delete(e);
86
+ };
87
+ }
88
+ rebase(e = this.cameraPosition) {
89
+ let t = i(e, "Invalid origin"), n = this.value, r = [
90
+ t[0] - n[0],
91
+ t[1] - n[1],
92
+ t[2] - n[2]
93
+ ], a = this.camera;
94
+ this.value = t;
95
+ let o = (e) => [
96
+ e[0] - r[0],
97
+ e[1] - r[1],
98
+ e[2] - r[2]
99
+ ];
100
+ a.position = o(a.position), a.target = o(a.target);
101
+ let s = Object.values(a).find((e) => e && typeof e == "object" && "fromTarget" in e);
102
+ if (s) for (let e of [
103
+ "position",
104
+ "target",
105
+ "from",
106
+ "fromTarget"
107
+ ]) s[e] = o(s[e]);
108
+ for (let [e, t] of this.roots) e.engine.meshes.get(e.id) === e ? (this.sync(e, t, n), this.write(e, t)) : this.roots.delete(e);
109
+ this.rebases++;
110
+ for (let e of this.listeners) e(r, this.origin);
111
+ }
112
+ onPreUpdate() {
113
+ this.engine && this.check();
114
+ }
115
+ dispose() {
116
+ this.engine = void 0, this.roots.clear(), this.listeners.clear();
117
+ }
118
+ [Symbol.dispose ?? Symbol()]() {
119
+ this.dispose();
120
+ }
121
+ check() {
122
+ let e = this.camera, t = e.position, n = e.target;
123
+ Math.hypot(t[0], t[1], t[2]) > this.ratio * Math.hypot(t[0] - n[0], t[1] - n[1], t[2] - n[2]) && this.rebase();
124
+ }
125
+ write(e, t) {
126
+ let n = e.engine.store.transforms, r = this.value;
127
+ n.x[e.id] = t[3] = Math.fround(t[0] - r[0]), n.y[e.id] = t[4] = Math.fround(t[1] - r[1]), n.z[e.id] = t[5] = Math.fround(t[2] - r[2]);
128
+ }
129
+ sync(e, t, n = this.value) {
130
+ let r = e.engine.store.transforms, i = r.x[e.id], a = r.y[e.id], o = r.z[e.id];
131
+ (i !== t[3] || a !== t[4] || o !== t[5]) && (t[0] = i + n[0], t[1] = a + n[1], t[2] = o + n[2], t[3] = i, t[4] = a, t[5] = o);
132
+ }
133
+ };
134
+ function i(e, t) {
135
+ if (!e || e.length !== 3 || ![
136
+ 0,
137
+ 1,
138
+ 2
139
+ ].every((t) => typeof e[t] == "number" && Number.isFinite(e[t]))) throw RangeError(t);
140
+ return [
141
+ e[0],
142
+ e[1],
143
+ e[2]
144
+ ];
145
+ }
146
+ //#endregion
147
+ export { r as FloatingOrigin };
@@ -0,0 +1,90 @@
1
+ /// <reference lib="esnext.disposable" preserve="true" />
2
+ import type { EngineKernel } from '@margoengine/core';
3
+ import type { Engine, EnginePlugin } from '@margoengine/core/extension';
4
+ import { type WideAngleMode } from './wide-laws.js';
5
+ export type { WideAngleMode } from './wide-laws.js';
6
+ /** Options of {@link WideAngleMap} and {@link WideAngle}. */
7
+ export interface WideAngleOptions {
8
+ /** Default 'panini'. The fisheye modes are r = θ (equidistant), 2 sin(θ/2) (equisolid), 2 tan(θ/2) (stereographic) and sin θ (orthographic). */
9
+ mode?: WideAngleMode;
10
+ /** Panini compression d: 0 is the plain rectilinear picture, 1 the classic Panini, larger bends verticals toward a cylinder. 0 or more, default 1. */
11
+ distance?: number;
12
+ /** Zoom in just enough that no output pixel falls outside the source picture. Default true; false leaves black where the source ends. */
13
+ crop?: boolean;
14
+ /** False passes the picture through. Default true. Also `effect.enabled`. */
15
+ enabled?: boolean;
16
+ }
17
+ /**
18
+ * The mapping between the wide picture a camera draws (rectilinear, `fov` degrees vertical) and the projected output,
19
+ * both as normalised device coordinates (x right and y up, -1 to 1). The same maths runs in the shader; use it to turn a
20
+ * pointer position on the output into a position on the source for `engine.pick`, or to place overlays.
21
+ */
22
+ export declare class WideAngleMap {
23
+ readonly mode: WideAngleMode;
24
+ readonly distance: number;
25
+ /** Tangent of the half angle across and up the source picture. */
26
+ readonly tx: number;
27
+ readonly ty: number;
28
+ /** Half extent of the output plane before `zoom`, across and up. */
29
+ readonly halfWidth: number;
30
+ readonly halfHeight: number;
31
+ /** Factor the output plane is shrunk by so it stays inside the source (1 when `crop` is false or nothing is outside). */
32
+ readonly zoom: number;
33
+ constructor(fov: number, aspect: number, { mode, distance, crop }?: WideAngleOptions);
34
+ /** Source position (normalised, x right and y up) shown at output position (`u`, `v`), or null where the output shows nothing. */
35
+ toSource(u: number, v: number): [number, number] | null;
36
+ /** Output position of the source position (`x`, `y`), or null when it falls outside the output. */
37
+ toOutput(x: number, y: number): [number, number] | null;
38
+ private sourceOf;
39
+ private fitZoom;
40
+ }
41
+ /**
42
+ * Panini and fisheye projection as a stage of `PostStack`, after the display effect: draw the scene with a wide
43
+ * perspective camera (for example `camera.fov = 100`) and this resamples it. It reads `engine.camera.fov` and the
44
+ * frame's shape each frame, so a camera with a lens (`CameraProjection.focalLength`) works unchanged. Perspective
45
+ * cameras only. The source is one rectilinear picture, so a fisheye reaches only as far as that picture does (under
46
+ * 180 degrees across), and the corners are cropped unless `crop` is false. `WideAngleCube` in
47
+ * `@margoengine/cameras/wide-cube` reads a cube capture and reaches past that.
48
+ * @throws RangeError for an unknown `mode`, a negative `distance` or a field of view outside 0 to 180; MargoError
49
+ * `'state'` outside a PostStack, `'unsupported'` on a WebGL engine, `'attached'` when joined twice, `'disposed'`
50
+ * after `dispose()`.
51
+ */
52
+ export declare class WideAngle implements EnginePlugin {
53
+ readonly options: WideAngleOptions;
54
+ readonly name = "wide-angle";
55
+ private engine?;
56
+ private stack?;
57
+ private stacked;
58
+ private disposed;
59
+ private uniform?;
60
+ private sampler?;
61
+ private pipeline?;
62
+ private key;
63
+ private group?;
64
+ private input?;
65
+ private mapKey;
66
+ private lastMap?;
67
+ private readonly values;
68
+ private readonly attachment;
69
+ private readonly descriptor;
70
+ constructor(options?: WideAngleOptions);
71
+ /**
72
+ * Adds a new WideAngle to the scene's PostStack after its last LDR effect, or to a new PostStack when the scene has
73
+ * none (needs `@margoengine/post`). Disposing it takes it out, and a stack made for it goes with it.
74
+ */
75
+ static attach(engine: EngineKernel, options?: WideAngleOptions): Promise<WideAngle>;
76
+ /** Whether the picture is projected (mirrors `options.enabled`). */
77
+ get enabled(): boolean;
78
+ set enabled(value: boolean);
79
+ /** The mapping for a camera of `fov` degrees (vertical) and a view of `aspect`, with these options. */
80
+ map(fov: number, aspect: number): WideAngleMap;
81
+ private joinStack;
82
+ setup(engine: Engine): void;
83
+ onDeviceRestored(engine: Engine): void;
84
+ /** Removes the effect and releases its GPU resources. Safe to call twice. */
85
+ dispose(): void;
86
+ [Symbol.dispose]: () => void;
87
+ private draw;
88
+ private pipelineFor;
89
+ private release;
90
+ }
package/dist/panini.js ADDED
@@ -0,0 +1,184 @@
1
+ // @margo/core-built 1.0.0
2
+ import {coreRequirement as __margoCoreRequirement,assertCore as __margoAssertCore} from '@margoengine/core/extension';
3
+
4
+ import { t as e } from "./errors-Cp7bu2gW.js";
5
+ import { r as t, t as n } from "./view-rect-p0kR0Q6B.js";
6
+ import { n as r, r as i, t as a } from "./gpu-BRxrrZK3.js";
7
+ import { n as o, r as s, t as c } from "./wide-laws-Dj0410P1.js";
8
+ //#region ../shared/effect-lifecycle.js
9
+ function l(e, t) {
10
+ e.release(), e.engine = void 0, e.setup(t);
11
+ }
12
+ function u(e) {
13
+ if (e.disposed) return !1;
14
+ e.disposed = !0;
15
+ let t = e.engine;
16
+ return e.engine = void 0, t?.sceneOf(e)?.removePlugin(e.name), e.release(), !0;
17
+ }
18
+ //#endregion
19
+ //#region src/panini.ts
20
+ var d = 1e-9, f = class {
21
+ constructor(e, t, { mode: n = "panini", distance: r = 1, crop: i = !0 } = {}) {
22
+ if (!(n in s)) throw RangeError("Invalid wide angle mode; use 'panini', 'equidistant', 'equisolid', 'stereographic' or 'orthographic'");
23
+ if (!(r >= 0 && r < Infinity)) throw RangeError("Invalid wide angle distance; use a finite number from 0");
24
+ if (!(t > 0 && t < Infinity) || !(e > 0 && e < 180)) throw RangeError("Invalid wide angle view; use a field of view between 0 and 180 degrees and an aspect above 0");
25
+ this.mode = n, this.distance = r, this.ty = Math.tan(e * Math.PI / 360), this.tx = this.ty * t;
26
+ let a = Math.atan(this.tx);
27
+ this.halfWidth = n === "panini" ? (r + 1) * Math.sin(a) / (r + Math.cos(a)) : c[n](a), this.halfHeight = this.halfWidth / t, this.zoom = 1, i && (this.zoom = this.fitZoom());
28
+ }
29
+ toSource(e, t) {
30
+ return this.sourceOf(e, t, this.zoom);
31
+ }
32
+ toOutput(e, t) {
33
+ let n = e * this.tx, r = t * this.ty, i, a;
34
+ if (this.mode === "panini") {
35
+ let e = this.distance, t = Math.atan(n), o = Math.cos(t), s = (e + 1) / (e + o);
36
+ i = s * Math.sin(t), a = s * r * o;
37
+ } else {
38
+ let e = Math.hypot(n, r), t = e ? c[this.mode](Math.atan(e)) / e : 0;
39
+ i = n * t, a = r * t;
40
+ }
41
+ let o = i / (this.halfWidth * this.zoom), s = a / (this.halfHeight * this.zoom);
42
+ return Math.abs(o) <= 1.000000001 && Math.abs(s) <= 1.000000001 ? [o, s] : null;
43
+ }
44
+ sourceOf(e, t, n) {
45
+ let r = e * this.halfWidth * n, i = t * this.halfHeight * n, a, s;
46
+ if (this.mode === "panini") {
47
+ let e = this.distance, t = r / (e + 1), n = Math.atan(t) + Math.asin(Math.max(-1, Math.min(1, t * e / Math.sqrt(1 + t * t)))), o = Math.cos(n);
48
+ if (!(o > d)) return null;
49
+ a = Math.tan(n), s = i / ((e + 1) / (e + o) * o);
50
+ } else {
51
+ let e = Math.hypot(r, i), t = o[this.mode](e);
52
+ if (t === null || !(t < Math.PI / 2 - d)) return null;
53
+ let n = e ? Math.tan(t) / e : 0;
54
+ a = r * n, s = i * n;
55
+ }
56
+ let c = a / this.tx, l = s / this.ty;
57
+ return Math.abs(c) <= 1.000000001 && Math.abs(l) <= 1.000000001 ? [c, l] : null;
58
+ }
59
+ fitZoom() {
60
+ let e = (e) => {
61
+ for (let t = 0; t <= 64; t++) {
62
+ let n = t / 64 * 2 - 1;
63
+ for (let [t, r] of [
64
+ [n, 1],
65
+ [n, -1],
66
+ [1, n],
67
+ [-1, n]
68
+ ]) if (!this.sourceOf(t, r, e)) return !1;
69
+ }
70
+ return !0;
71
+ };
72
+ if (e(1)) return 1;
73
+ let t = 0, n = 1;
74
+ for (let r = 0; r < 40; r++) {
75
+ let r = (t + n) / 2;
76
+ e(r) ? t = r : n = r;
77
+ }
78
+ return t;
79
+ }
80
+ }, p = `${a}
81
+ struct Wide {a:vec4f,b:vec4f}
82
+ @group(0) @binding(0) var<uniform> w:Wide;
83
+ @group(0) @binding(1) var frame:texture_2d<f32>;
84
+ @group(0) @binding(2) var smp:sampler;
85
+ const HALF_PI=1.5707963267948966;
86
+
87
+
88
+ @fragment fn fragment(v:Vertex)->@location(0) vec4f {
89
+ let mode=i32(w.a.x);
90
+ if (mode<0) {return textureSampleLevel(frame,smp,v.uv,0);}
91
+ let d=w.a.y;
92
+ let p=(v.uv*2-1)*vec2f(1,-1)*w.b.xy;
93
+ var s=vec2f(0);
94
+ if (mode==0) {
95
+ let xp=p.x/(d+1);
96
+ let phi=atan(xp)+asin(clamp(xp*d/sqrt(1+xp*xp),-1,1));
97
+ let c=cos(phi);
98
+ if (c<=1e-9) {return vec4f(0,0,0,1);}
99
+ s=vec2f(tan(phi),p.y/(((d+1)/(d+c))*c));
100
+ } else {
101
+ let r=length(p);
102
+ var theta=r;
103
+ if (mode==2) {if (r>2) {return vec4f(0,0,0,1);} theta=2*asin(r/2);}
104
+ else if (mode==3) {theta=2*atan(r/2);}
105
+ else if (mode==4) {if (r>1) {return vec4f(0,0,0,1);} theta=asin(r);}
106
+ if (theta>=HALF_PI-1e-9) {return vec4f(0,0,0,1);}
107
+ if (r>0) {s=p*(tan(theta)/r);}
108
+ }
109
+ let q=s/w.b.zw;
110
+ if (abs(q.x)>1.0000001||abs(q.y)>1.0000001) {return vec4f(0,0,0,1);}
111
+ return textureSampleLevel(frame,smp,vec2f(q.x*0.5+0.5,0.5-q.y*0.5),0);
112
+ }`, m = class a {coreRequirement=__margoCoreRequirement("1.0.0",import.meta.url);
113
+ constructor(e = {}) {
114
+ this.options = e, this.name = "wide-angle", this.stacked = !1, this.disposed = !1, this.key = "", this.mapKey = "", this.values = /* @__PURE__ */ new Float32Array(8), this.attachment = {
115
+ view: void 0,
116
+ loadOp: "clear",
117
+ storeOp: "store"
118
+ }, this.descriptor = { colorAttachments: [this.attachment] }, this.map(60, 1);
119
+ }
120
+ static async attach(e, t = {}) {__margoAssertCore(e,__margoCoreRequirement("1.0.0",import.meta.url));
121
+ let { PostStack: n } = await import("@margoengine/post"), r = new a(t);
122
+ return r.stack = n.join(e, r), r;
123
+ }
124
+ get enabled() {
125
+ return this.options.enabled ?? !0;
126
+ }
127
+ set enabled(e) {
128
+ if (typeof e != "boolean") throw TypeError("WideAngle enabled must be a boolean; pass true or false");
129
+ this.options.enabled = e;
130
+ }
131
+ map(e, t) {
132
+ let n = this.options, r = `${e}:${t}:${n.mode}:${n.distance}:${n.crop}`;
133
+ return (r !== this.mapKey || !this.lastMap) && (this.lastMap = new f(e, t, n), this.mapKey = r), this.lastMap;
134
+ }
135
+ joinStack(t) {
136
+ if (this.engine || this.stacked || this.disposed) throw e("attached", "WideAngle is already attached; create a new WideAngle");
137
+ return this.stacked = !0, {
138
+ kind: "ldr",
139
+ render: (e, t, n) => this.draw(e, t, n)
140
+ };
141
+ }
142
+ setup(t) {
143
+ if (this.disposed) throw e("disposed", "WideAngle is disposed; create a new WideAngle");
144
+ if (!this.stacked) throw e("state", "WideAngle runs inside a PostStack; add it to PostStack.join(engine, effect)");
145
+ if (!t.gpu) throw e("unsupported", "WideAngle requires WebGPU; it does not run on the WebGL2 fallback");
146
+ this.engine = t, this.uniform = t.gpu.createBuffer({
147
+ size: 32,
148
+ usage: GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST
149
+ }), this.sampler = t.gpu.createSampler({
150
+ magFilter: "linear",
151
+ minFilter: "linear"
152
+ });
153
+ }
154
+ onDeviceRestored(e) {
155
+ l(this, e);
156
+ }
157
+ dispose() {
158
+ u(this) && (this.stack?.removeEffect(this), this.stack = void 0);
159
+ }
160
+ [Symbol.dispose ?? Symbol()]() {
161
+ this.dispose();
162
+ }
163
+ draw(e, i, a) {
164
+ let o = e.device, c = this.engine, l = this.map(c.camera.fov, e.width / e.height), u = this.values;
165
+ u[0] = this.enabled ? s[l.mode] : -1, u[1] = l.distance, u[4] = l.halfWidth * l.zoom, u[5] = l.halfHeight * l.zoom, u[6] = l.tx, u[7] = l.ty, o.queue.writeBuffer(this.uniform, 0, u);
166
+ let d = this.pipelineFor(o, a);
167
+ this.input !== i && (this.input = i, this.group = r(o, d, [
168
+ { buffer: this.uniform },
169
+ i,
170
+ this.sampler
171
+ ])), this.attachment.view = a.view, this.attachment.loadOp = t(e, "clear");
172
+ let f = e.encoder.beginRenderPass(this.descriptor);
173
+ f.setPipeline(d), f.setBindGroup(0, this.group), n(f, e), f.draw(3), f.end();
174
+ }
175
+ pipelineFor(e, t) {
176
+ let n = t.multisample?.count ?? 1;
177
+ return this.key !== `${t.format}/${n}` && (this.key = `${t.format}/${n}`, this.pipeline = i(e, p, t.format, { multisample: t.multisample }), this.input = void 0), this.pipeline;
178
+ }
179
+ release() {
180
+ this.uniform?.destroy(), this.uniform = this.sampler = this.pipeline = this.group = this.input = void 0, this.key = "";
181
+ }
182
+ };
183
+ //#endregion
184
+ export { m as WideAngle, f as WideAngleMap };
@@ -0,0 +1,46 @@
1
+ import type { EngineKernel } from '@margoengine/core';
2
+ import { type Vec3 } from '@margoengine/core/extension';
3
+ /** A standard WebGPU cube source, such as an attached CubeCamera. The caller retains ownership. */
4
+ export interface PanoramaCube {
5
+ /** Linear-light cube view. */
6
+ readonly view: GPUTextureView;
7
+ /** Refresh all six faces; return the number drawn. Omit for an already baked cube. */
8
+ update?(faces?: number): number;
9
+ }
10
+ /** Options for a single, complete 360 by 180 degree capture. */
11
+ export interface PanoramaOptions {
12
+ /** Use a caller-owned cube instead of making a temporary CubeCamera. */
13
+ cube?: PanoramaCube;
14
+ /** Temporary cube face edge, a power of two from 8 to 2048. Default 256. */
15
+ size?: number;
16
+ /** Capture point. Default the engine camera position. */
17
+ position?: Vec3;
18
+ /** Image width, an even positive integer. Height is width / 2. Default 4 * size. */
19
+ width?: number;
20
+ /** Longitude of the image centre, in radians. Zero looks along -Z; positive turns toward +X. Default 0. */
21
+ yaw?: number;
22
+ /** 'srgb' is RGBA8 for viewers and PNG; 'linear' is unclipped RGBA32F for baking. Default 'srgb'. */
23
+ format?: 'srgb' | 'linear';
24
+ /** Exposure in stops before the sRGB transfer function; ignored for linear output. Default 0. */
25
+ exposure?: number;
26
+ /** Abort the operation, including GPU readback and PNG encoding waits. */
27
+ signal?: AbortSignal;
28
+ }
29
+ /** Top-to-bottom equirectangular pixels, with north (+Y) at the top and -Z at the centre. */
30
+ export type PanoramaImage = {
31
+ width: number;
32
+ height: number;
33
+ format: 'srgb';
34
+ data: Uint8ClampedArray;
35
+ } | {
36
+ width: number;
37
+ height: number;
38
+ format: 'linear';
39
+ data: Float32Array;
40
+ };
41
+ /** Map normalised equirectangular coordinates to a world direction (u wraps, v is top to bottom). */
42
+ export declare function panoramaDirection(u: number, v: number, yaw?: number): Vec3;
43
+ /** Capture six scene faces and resample the whole sphere. No camera, canvas size or scene state is changed. */
44
+ export declare function capturePanorama(engine: EngineKernel, options?: PanoramaOptions): Promise<PanoramaImage>;
45
+ /** Encode viewer-ready sRGB pixels as a PNG Blob. Capture with format 'srgb' (the default) first. */
46
+ export declare function panoramaPNG(image: PanoramaImage, signal?: AbortSignal): Promise<Blob>;
@@ -0,0 +1,128 @@
1
+ // @margo/core-built 1.0.0
2
+ import {coreRequirement as __margoCoreRequirement,assertCore as __margoAssertCore} from '@margoengine/core/extension';
3
+ const r=(engine,version="1.0.0",source=import.meta.url)=>__margoRuntime(engine,version,source);
4
+ import { n as e, r as t, t as n } from "./gpu-BRxrrZK3.js";
5
+ import { engineRuntime as __margoRuntime } from "@margoengine/core/extension";
6
+ import { MargoError as i } from "@margoengine/math/errors";
7
+ //#region src/panorama.ts
8
+ function a(e, t, n = 0) {
9
+ if (![
10
+ e,
11
+ t,
12
+ n
13
+ ].every(Number.isFinite) || t < 0 || t > 1) throw RangeError("Invalid panorama coordinates; pass finite u, yaw and v in 0..1");
14
+ let r = (e - .5) * 2 * Math.PI + n, i = (.5 - t) * Math.PI, a = Math.cos(i);
15
+ return [
16
+ a * Math.sin(r),
17
+ Math.sin(i),
18
+ -a * Math.cos(r)
19
+ ];
20
+ }
21
+ var o = `
22
+ ${n}
23
+ @group(0) @binding(0) var cube:texture_cube<f32>;
24
+ @group(0) @binding(1) var linearSampler:sampler;
25
+ @group(0) @binding(2) var<uniform> settings:vec4f;
26
+ fn srgb(c:vec3f)->vec3f {
27
+ let x=max(c,vec3f(0));
28
+ return select(1.055*pow(x,vec3f(1.0/2.4))-0.055,12.92*x,x<=vec3f(0.0031308));
29
+ }
30
+ @fragment fn fragment(i:Vertex)->@location(0) vec4f {
31
+ let longitude=(i.uv.x-0.5)*6.28318530718+settings.x;
32
+ let latitude=(0.5-i.uv.y)*3.14159265359;
33
+ let d=vec3f(cos(latitude)*sin(longitude),sin(latitude),-cos(latitude)*cos(longitude));
34
+ let c=textureSampleLevel(cube,linearSampler,d,0.0);
35
+ return vec4f(select(c.rgb,srgb(c.rgb*exp2(settings.y)),settings.z>0.5),c.a);
36
+ }`;
37
+ async function s(e, t) {
38
+ if (!t) return e;
39
+ let n, r = new Promise((r, i) => {
40
+ e.then(r, i), n = () => i(t.reason), t.addEventListener("abort", n, { once: !0 }), t.aborted && n();
41
+ });
42
+ try {
43
+ return await r;
44
+ } finally {
45
+ t.removeEventListener("abort", n);
46
+ }
47
+ }
48
+ async function c(n, a = {}) {
49
+ let { signal: c, yaw: l = 0, exposure: u = 0, format: d = "srgb", size: f = 256 } = a;
50
+ c?.throwIfAborted();
51
+ let p = a.width ?? f * 4, m = p / 2;
52
+ if (!Number.isInteger(p) || p < 2 || p % 2 || ![l, u].every(Number.isFinite)) throw RangeError("Invalid panorama size or orientation; pass an even width >= 2 and finite yaw and exposure");
53
+ if (d !== "linear" && d !== "srgb") throw TypeError("Invalid panorama format; pass srgb or linear");
54
+ let h = r(n).gpu;
55
+ if (n.backend !== "webgpu" || !h) throw new i("unsupported", "Panorama capture needs WebGPU or the WebGL2 compatibility layer");
56
+ if (p > h.limits.maxTextureDimension2D) throw RangeError("Panorama exceeds the device texture limit; reduce width");
57
+ let g = p * (d === "linear" ? 16 : 4), _ = Math.ceil(g / 256) * 256, v = _ * m;
58
+ if (v > h.limits.maxBufferSize) throw RangeError("Panorama exceeds the device buffer limit; reduce width");
59
+ let y, b, x, S;
60
+ try {
61
+ let r = a.cube;
62
+ if (!r) {
63
+ let { CubeCamera: e } = await s(import("@margoengine/environment/cube-camera"), c), t = e.attach(n, {
64
+ size: f,
65
+ position: a.position ?? n.camera.position
66
+ });
67
+ r = t, y = t;
68
+ }
69
+ if (c?.throwIfAborted(), r.update && r.update(6) !== 6) throw new i("state", "Panorama did not capture all six faces; capture after device restoration");
70
+ let C = d === "linear" ? "rgba32float" : "rgba8unorm", w = t(h, o, C);
71
+ x = h.createBuffer({
72
+ size: 16,
73
+ usage: GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST
74
+ }), h.queue.writeBuffer(x, 0, new Float32Array([
75
+ l,
76
+ u,
77
+ +(d === "srgb"),
78
+ 0
79
+ ])), b = h.createTexture({
80
+ size: [p, m],
81
+ format: C,
82
+ usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.COPY_SRC
83
+ }), S = h.createBuffer({
84
+ size: v,
85
+ usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ
86
+ });
87
+ let T = e(h, w, [
88
+ r.view,
89
+ h.createSampler({
90
+ minFilter: "linear",
91
+ magFilter: "linear"
92
+ }),
93
+ { buffer: x }
94
+ ]), E = h.createCommandEncoder(), D = E.beginRenderPass({ colorAttachments: [{
95
+ view: b.createView(),
96
+ loadOp: "clear",
97
+ storeOp: "store"
98
+ }] });
99
+ D.setPipeline(w), D.setBindGroup(0, T), D.draw(3), D.end(), E.copyTextureToBuffer({ texture: b }, {
100
+ buffer: S,
101
+ bytesPerRow: _
102
+ }, [p, m]), h.queue.submit([E.finish()]), await s(S.mapAsync(GPUMapMode.READ), c);
103
+ let O = new Uint8Array(S.getMappedRange()), k = new Uint8Array(g * m);
104
+ for (let e = 0; e < m; e++) k.set(O.subarray(e * _, e * _ + g), e * g);
105
+ return d === "linear" ? {
106
+ width: p,
107
+ height: m,
108
+ format: d,
109
+ data: new Float32Array(k.buffer)
110
+ } : {
111
+ width: p,
112
+ height: m,
113
+ format: d,
114
+ data: new Uint8ClampedArray(k.buffer)
115
+ };
116
+ } finally {
117
+ S?.unmap(), S?.destroy(), b?.destroy(), x?.destroy(), y?.dispose();
118
+ }
119
+ }
120
+ async function l(e, t) {
121
+ if (t?.throwIfAborted(), e.format !== "srgb") throw TypeError("PNG needs sRGB pixels; capture with format srgb");
122
+ if (!Number.isInteger(e.width) || e.width < 2 || e.width % 2 || e.height !== e.width / 2 || e.data.length !== e.width * e.height * 4) throw RangeError("Invalid panorama pixels; pass a complete 2:1 RGBA8 image");
123
+ let n = new OffscreenCanvas(e.width, e.height), r = n.getContext("2d");
124
+ if (!r) throw new i("unsupported", "PNG needs a 2D canvas; enable canvas support");
125
+ return r.putImageData(new ImageData(new Uint8ClampedArray(e.data), e.width, e.height), 0, 0), s(n.convertToBlob({ type: "image/png" }), t);
126
+ }
127
+ //#endregion
128
+ export { c as capturePanorama, a as panoramaDirection, l as panoramaPNG };