@margoengine/cameras 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,34 @@
1
+ import type { Vec3 } from '@margoengine/core/extension';
2
+ /** The view {@link fitBox} keeps: its direction (`target - position`), vertical field of view and screen up. */
3
+ export interface BoxFitView {
4
+ position: ArrayLike<number>;
5
+ target: ArrayLike<number>;
6
+ /** Vertical field of view in degrees, as core's `Camera.fov`. */
7
+ fov: number;
8
+ /** Screen up, not parallel to the view. Default [0, 1, 0], as core's `Camera.up`. */
9
+ up?: ArrayLike<number>;
10
+ }
11
+ /** Options of {@link fitBox}. */
12
+ export interface BoxFitOptions {
13
+ /** Width / height of the frame. Default 1. */
14
+ aspect?: number;
15
+ /** At least 1: the box fills 1 / padding of the frame's width or height, whichever binds. Default 1.1. */
16
+ padding?: number;
17
+ }
18
+ /** Where {@link fitBox} puts the camera. */
19
+ export interface BoxFit {
20
+ position: Vec3;
21
+ /** On the view axis, level with the box's centre. */
22
+ target: Vec3;
23
+ /** From `position` to `target`. */
24
+ distance: number;
25
+ /** The nearest corner's depth along the view, so a caller can check it against `camera.near`. */
26
+ nearest: number;
27
+ }
28
+ /**
29
+ * The closest camera position, along the view's own direction, from which all eight corners of `bounds`
30
+ * (`[minX, minY, minZ, maxX, maxY, maxZ]`, as `model.bounds`) sit inside the frame shrunk by `padding`, centred. Pure:
31
+ * apply it with `camera.position = fit.position; camera.target = fit.target`, or use
32
+ * `CameraProjection.fit(bounds, { framing: 'box' })` to animate it.
33
+ */
34
+ export declare function fitBox(view: BoxFitView, bounds: ArrayLike<number>, { aspect, padding }?: BoxFitOptions): BoxFit;
@@ -0,0 +1,31 @@
1
+ (globalThis[Symbol.for("margoengine.frame-resources")] ??= { devices: /* @__PURE__ */ new WeakMap() }).devices;
2
+ //#endregion
3
+ //#region ../shared/gpu.js
4
+ var e = "\nstruct Vertex { @builtin(position) position:vec4f,@location(0) uv:vec2f }\n@vertex fn vertex(@builtin(vertex_index) index:u32)->Vertex {\n let p=array<vec2f,3>(vec2f(-1,-1),vec2f(3,-1),vec2f(-1,3))[index];\n return Vertex(vec4f(p,0,1),vec2f(p.x*0.5+0.5,0.5-p.y*0.5));\n}";
5
+ function t(e, t, n) {
6
+ return e.createBindGroup({
7
+ layout: t.getBindGroupLayout(0),
8
+ entries: n.map((e, t) => ({
9
+ binding: t,
10
+ resource: e
11
+ }))
12
+ });
13
+ }
14
+ function n(e, t, n, r = {}) {
15
+ let i = e.createShaderModule({ code: t });
16
+ return e.createRenderPipeline({
17
+ layout: "auto",
18
+ vertex: {
19
+ module: i,
20
+ entryPoint: "vertex"
21
+ },
22
+ fragment: {
23
+ module: i,
24
+ entryPoint: "fragment",
25
+ targets: [{ format: n }]
26
+ },
27
+ ...r
28
+ });
29
+ }
30
+ //#endregion
31
+ export { t as n, n as r, e as t };
@@ -0,0 +1,75 @@
1
+ /// <reference lib="esnext.disposable" preserve="true" />
2
+ import type { EngineKernel } from '@margoengine/core';
3
+ import { Camera, type RenderView } from '@margoengine/core/extension';
4
+ /** A side of the target. front sits in the bottom slot, back in the top, left and right in their own slots. */
5
+ export type HologramSide = 'front' | 'back' | 'left' | 'right';
6
+ /** How one view is laid on the screen. */
7
+ export interface HologramViewOrientation {
8
+ /** Counter-clockwise turn of the picture in degrees: 0 keeps its top up, 90 turns its top to the left. */
9
+ rotation?: 0 | 90 | 180 | 270;
10
+ /** Mirror the picture left to right before the turn, as a pyramid face's reflection needs. */
11
+ mirror?: boolean;
12
+ }
13
+ /** Default orientations: every view mirrored, its top pointing away from the screen centre (screen-down pyramid). */
14
+ export declare const HOLOGRAM_VIEWS: Readonly<Record<HologramSide, Readonly<Required<HologramViewOrientation>>>>;
15
+ /** Camera geometry of the four views. Distances use world units (normally metres). */
16
+ export interface HologramRigOptions {
17
+ /** Distance from the target to each camera, > 0. Default the source camera's distance to its target. */
18
+ distance?: number;
19
+ }
20
+ /** Four cameras around the source camera's target, a quarter turn apart about its up axis. */
21
+ export declare class HologramRig {
22
+ /** Looks at the target from the source camera's side. */
23
+ readonly front: Camera;
24
+ /** Looks from the opposite side. */
25
+ readonly back: Camera;
26
+ /** Looks from the source camera's left. */
27
+ readonly left: Camera;
28
+ /** Looks from the source camera's right. */
29
+ readonly right: Camera;
30
+ /** Mutable geometry; validated on update. */
31
+ readonly options: HologramRigOptions;
32
+ constructor(options?: HologramRigOptions);
33
+ /** Place the four cameras from a source camera. Its pose and projection are not changed; views are square. */
34
+ update(source: Camera): void;
35
+ }
36
+ /** Four-view output settings. Update them before render. */
37
+ export interface HologramOutputOptions extends HologramRigOptions {
38
+ /** Source camera: its target is the centre and its side is the front. Default engine.camera. */
39
+ camera?: Camera;
40
+ /** Scene to render. Default engine.scene. */
41
+ scene?: RenderView['scene'];
42
+ /** Layer mask for all four views. Default the source camera's mask. */
43
+ layers?: number;
44
+ /**
45
+ * Side of the empty centre square, as a fraction of the canvas's smaller side, in [0, 1). Default 0.2. Each view is
46
+ * (1 - gap) / 2 across; below 1/3 the views meet along the diagonals and each is cut to its wedge, like a face.
47
+ */
48
+ gap?: number;
49
+ /** Per-side orientation; missing fields keep {@link HOLOGRAM_VIEWS}. */
50
+ views?: Partial<Record<HologramSide, HologramViewOrientation>>;
51
+ /** Clear colour of each view, `#rgb` or `#rrggbb`, or false for the scene's background. Default '#000000'. */
52
+ background?: string | false;
53
+ }
54
+ /** Replaces the application's engine.render call: four square scene views and one layout pass onto the canvas. */
55
+ export declare class HologramOutput {
56
+ private readonly engine;
57
+ /** Creates four-view output for the application's frame loop. Same as the constructor. */
58
+ static attach(engine: EngineKernel, options?: HologramOutputOptions): HologramOutput;
59
+ /** Mutable settings, validated on render. */
60
+ readonly options: HologramOutputOptions;
61
+ /** The four cameras, also usable for picking or custom layouts. */
62
+ readonly rig: HologramRig;
63
+ private state?;
64
+ private disposed;
65
+ constructor(engine: EngineKernel, options?: HologramOutputOptions);
66
+ /** The resolved orientation of every side, after validation. */
67
+ orientations(): Record<HologramSide, Required<HologramViewOrientation>>;
68
+ /** Render once; animation and plugin updates happen once for the four views. Use from your frame loop. */
69
+ render(delta?: number): void;
70
+ private ensure;
71
+ private release;
72
+ /** Release the four view textures and uniforms. Safe to call more than once. */
73
+ dispose(): void;
74
+ [Symbol.dispose]: () => void;
75
+ }
@@ -0,0 +1,208 @@
1
+ // @margo/core-built 0.1.0
2
+ import {coreRequirement as __margoCoreRequirement,assertCore as __margoAssertCore} from '@margoengine/core/extension';
3
+ const a=(engine,version="0.1.0",source=import.meta.url)=>__margoRuntime(engine,version,source);
4
+ import { n as e } from "./layers-CkdgcqTK.js";
5
+ import { n as t, r as n, t as r } from "./gpu-BRxrrZK3.js";
6
+ import { Camera as i, engineRuntime as __margoRuntime } from "@margoengine/core/extension";
7
+ import { MargoError as o } from "@margoengine/math/errors";
8
+ import { hexColor as s } from "@margoengine/math/color";
9
+ //#region src/hologram.ts
10
+ var c = "; see https://margoengine.com/errors#camera-hologram", l = Object.freeze({
11
+ front: Object.freeze({
12
+ rotation: 180,
13
+ mirror: !0
14
+ }),
15
+ back: Object.freeze({
16
+ rotation: 0,
17
+ mirror: !0
18
+ }),
19
+ left: Object.freeze({
20
+ rotation: 90,
21
+ mirror: !0
22
+ }),
23
+ right: Object.freeze({
24
+ rotation: 270,
25
+ mirror: !0
26
+ })
27
+ }), u = [
28
+ "front",
29
+ "back",
30
+ "left",
31
+ "right"
32
+ ], d = class {
33
+ constructor(e = {}) {
34
+ this.front = new i(), this.back = new i(), this.left = new i(), this.right = new i(), this.options = { ...e };
35
+ }
36
+ update(e) {
37
+ e.update(1, !0);
38
+ let t = e.position, n = e.target, r = e.up, i = Math.hypot(...r), a = r.map((e) => e / i), s = [
39
+ t[0] - n[0],
40
+ t[1] - n[1],
41
+ t[2] - n[2]
42
+ ], l = s[0] * a[0] + s[1] * a[1] + s[2] * a[2], d = s.map((e, t) => e - l * a[t]), f = Math.hypot(...d), p = this.options.distance ?? Math.hypot(...s);
43
+ if (!(f > 1e-9 * Math.hypot(...s))) throw new o("state", "Hologram source camera looks along its up axis; tilt it or change camera.up" + c);
44
+ if (!Number.isFinite(p) || p <= 0) throw RangeError("Invalid hologram distance; pass a finite distance > 0" + c);
45
+ let m = d.map((e) => e / f), h = [
46
+ a[1] * m[2] - a[2] * m[1],
47
+ a[2] * m[0] - a[0] * m[2],
48
+ a[0] * m[1] - a[1] * m[0]
49
+ ], g = p / Math.hypot(...s), _ = l * g, v = f * g, y = {
50
+ front: m,
51
+ back: m.map((e) => -e),
52
+ right: h,
53
+ left: h.map((e) => -e)
54
+ };
55
+ for (let t of u) {
56
+ let i = this[t], o = y[t];
57
+ i.position = n.map((e, t) => e + o[t] * v + a[t] * _), i.target = [
58
+ n[0],
59
+ n[1],
60
+ n[2]
61
+ ], i.up = r, i.fov = e.fov, i.near = e.near, i.far = e.far, i.project = e.project && ((t, n, r) => e.project(t, 1, r));
62
+ }
63
+ }
64
+ }, f = `${r}
65
+ @group(0) @binding(0) var front:texture_2d<f32>;
66
+ @group(0) @binding(1) var back:texture_2d<f32>;
67
+ @group(0) @binding(2) var left:texture_2d<f32>;
68
+ @group(0) @binding(3) var right:texture_2d<f32>;
69
+ @group(0) @binding(4) var linearSampler:sampler;
70
+ @group(0) @binding(5) var<uniform> settings:array<vec4f,4>;
71
+ @fragment fn fragment(i:Vertex)->@location(0) vec4f {
72
+ let size=settings[0].xy;let g=settings[0].z;let v=settings[0].w;
73
+ let d=(i.position.xy-size*0.5)/min(size.x,size.y);
74
+ var side=0u;var s=vec2f(0);
75
+ if(abs(d.y)>=abs(d.x)){
76
+ if(d.y>0.0){side=0u;s=vec2f(d.x+v*0.5,d.y-g*0.5)/v;}else{side=1u;s=vec2f(d.x+v*0.5,d.y+g*0.5+v)/v;}
77
+ } else {
78
+ if(d.x<0.0){side=2u;s=vec2f(d.x+g*0.5+v,d.y+v*0.5)/v;}else{side=3u;s=vec2f(d.x-g*0.5,d.y+v*0.5)/v;}
79
+ }
80
+ if(any(s<vec2f(0))||any(s>vec2f(1))){return vec4f(0,0,0,1);}
81
+ var c=s-0.5;
82
+ for(var k=0u;k<u32(settings[1][side]+0.5);k++){c=vec2f(-c.y,c.x);}
83
+ if(settings[2][side]>0.5){c.x=-c.x;}
84
+ let q=clamp(c+0.5,vec2f(settings[3].x),vec2f(1.0-settings[3].x));
85
+ let a=textureSampleLevel(front,linearSampler,q,0.0);let b=textureSampleLevel(back,linearSampler,q,0.0);
86
+ let l=textureSampleLevel(left,linearSampler,q,0.0);let r=textureSampleLevel(right,linearSampler,q,0.0);
87
+ if(side==0u){return a;} if(side==1u){return b;} if(side==2u){return l;} return r;
88
+ }`, p = class r {
89
+ static attach(e, t = {}) {__margoAssertCore(e,__margoCoreRequirement("0.1.0",import.meta.url));
90
+ return new r(e, t);
91
+ }
92
+ constructor(e, t = {}) {
93
+ this.engine = e, this.disposed = !1, this.options = { ...t }, this.rig = new d(this.options);
94
+ }
95
+ orientations() {
96
+ let e = this.options.views ?? {}, t = {};
97
+ for (let t of Object.keys(e)) if (!u.includes(t)) throw TypeError(`Unknown hologram side ${t}; use front, back, left or right; see https://margoengine.com/errors#camera-hologram`);
98
+ for (let n of u) {
99
+ let { rotation: r = l[n].rotation, mirror: i = l[n].mirror } = e[n] ?? {};
100
+ if (![
101
+ 0,
102
+ 90,
103
+ 180,
104
+ 270
105
+ ].includes(r) || typeof i != "boolean") throw TypeError("Invalid hologram view orientation; use rotation 0, 90, 180 or 270 and boolean mirror" + c);
106
+ t[n] = {
107
+ rotation: r,
108
+ mirror: i
109
+ };
110
+ }
111
+ return t;
112
+ }
113
+ render(t = 0) {
114
+ if (this.disposed) throw new o("disposed", "Hologram output is disposed; create another HologramOutput" + c);
115
+ if (!Number.isFinite(t) || t < 0) throw RangeError("Invalid hologram delta; pass finite seconds >= 0" + c);
116
+ let { gap: n = .2, background: r = "#000000" } = this.options;
117
+ if (!Number.isFinite(n) || n < 0 || n >= 1) throw RangeError("Invalid hologram gap; pass a fraction in [0, 1)" + c);
118
+ if (r !== !1 && (String(r).length > 7 || !s(String(r)))) throw TypeError("Invalid hologram background; pass #rgb, #rrggbb or false" + c);
119
+ let i = this.orientations(), l = this.engine, d = a(l), f = d.gpu;
120
+ if (l.backend !== "webgpu" || !f) throw new o("unsupported", "Hologram output needs WebGPU or the WebGL2 compatibility layer" + c);
121
+ let p = l.canvas, m = (1 - n) / 2, h = Math.max(1, Math.ceil(m * Math.min(p.width, p.height))), g = this.ensure(f, h, d.renderTarget.format), _ = this.options.camera ?? l.camera;
122
+ _.advance(t), this.rig.options.distance = this.options.distance, this.rig.update(_);
123
+ let v = this.options.scene, y = this.options.layers ?? e(_), b = r === !1 ? void 0 : { color: r };
124
+ l.render({
125
+ delta: t,
126
+ views: u.map((e, t) => ({
127
+ id: "hologram:" + e,
128
+ camera: this.rig[e],
129
+ viewport: [
130
+ 0,
131
+ 0,
132
+ 1,
133
+ 1
134
+ ],
135
+ target: { color: g.textures[t] },
136
+ scene: v,
137
+ layers: y,
138
+ clear: b
139
+ }))
140
+ });
141
+ let x = p.getContext("webgpu");
142
+ if (!x) throw new o("state", "Hologram output needs the engine canvas context; create a WebGPU engine first" + c);
143
+ f.queue.writeBuffer(g.uniform, 0, new Float32Array([
144
+ p.width,
145
+ p.height,
146
+ n,
147
+ m,
148
+ ...u.map((e) => i[e].rotation / 90),
149
+ ...u.map((e) => +!!i[e].mirror),
150
+ .5 / h,
151
+ 0,
152
+ 0,
153
+ 0
154
+ ]));
155
+ let S = f.createCommandEncoder(), C = S.beginRenderPass({ colorAttachments: [{
156
+ view: x.getCurrentTexture().createView(),
157
+ loadOp: "clear",
158
+ storeOp: "store"
159
+ }] });
160
+ C.setPipeline(g.pipeline), C.setBindGroup(0, g.bindings), C.draw(3), C.end(), f.queue.submit([S.finish()]);
161
+ }
162
+ ensure(e, r, i) {
163
+ if (this.state?.device === e && this.state.side === r && this.state.format === i) return this.state;
164
+ this.release();
165
+ let a = [], o;
166
+ try {
167
+ for (let t = 0; t < 4; t++) a.push(e.createTexture({
168
+ size: [r, r],
169
+ format: "rgba8unorm",
170
+ usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.TEXTURE_BINDING
171
+ }));
172
+ o = e.createBuffer({
173
+ size: 64,
174
+ usage: GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST
175
+ });
176
+ let s = n(e, f, i), c = t(e, s, [
177
+ ...a.map((e) => e.createView()),
178
+ e.createSampler({
179
+ magFilter: "linear",
180
+ minFilter: "linear"
181
+ }),
182
+ { buffer: o }
183
+ ]);
184
+ return this.state = {
185
+ device: e,
186
+ side: r,
187
+ format: i,
188
+ textures: a,
189
+ uniform: o,
190
+ pipeline: s,
191
+ bindings: c
192
+ };
193
+ } catch (e) {
194
+ throw a.forEach((e) => e.destroy()), o?.destroy(), e;
195
+ }
196
+ }
197
+ release() {
198
+ this.state?.textures.forEach((e) => e.destroy()), this.state?.uniform.destroy(), this.state = void 0;
199
+ }
200
+ dispose() {
201
+ this.disposed = !0, this.release();
202
+ }
203
+ [Symbol.dispose ?? Symbol()]() {
204
+ this.dispose();
205
+ }
206
+ };
207
+ //#endregion
208
+ export { l as HOLOGRAM_VIEWS, p as HologramOutput, d as HologramRig };
@@ -0,0 +1,150 @@
1
+ /// <reference lib="esnext.disposable" preserve="true" />
2
+ import type { EngineKernel } from '@margoengine/core';
3
+ import type { Camera, Engine, EnginePlugin, Vec3 } from '@margoengine/core/extension';
4
+ export { fitBox, type BoxFit, type BoxFitOptions, type BoxFitView } from './fit-box.js';
5
+ /** Options of `CameraProjection`: orthographic or perspective framing, frustum bounds, zoom and clip range. */
6
+ export interface ProjectionOptions {
7
+ /** 'orthographic' (default) or 'perspective'; both accept exactly vertical views. */
8
+ mode?: 'orthographic' | 'perspective';
9
+ /** Visible world height at zoom 1. Default: the perspective height at the target, 2·distance·tan(fov/2), so dolly controls zoom. */
10
+ height?: number;
11
+ /** Orthographic frustum bounds in view units. When all four are set they replace height and the canvas aspect. */
12
+ left?: number;
13
+ right?: number;
14
+ top?: number;
15
+ bottom?: number;
16
+ /** Zoom factor: divides the frustum about its centre. */
17
+ zoom?: number;
18
+ /** Eye-space clip distances, may be negative. Default: camera.far deep, centred on the target. */
19
+ near?: number;
20
+ far?: number;
21
+ /** Screen up when the view is parallel to camera world up; must not be parallel to that view. Default [0,0,-1]. */
22
+ up?: Vec3;
23
+ /** Render only a sub-rectangle of a larger frustum; see `ViewOffset`. Default: none, the whole frustum. */
24
+ viewOffset?: ViewOffset;
25
+ /** Lens focal length in millimetres. Replaces `camera.fov` with the field of view of this lens on `filmGauge`. Default: none, `camera.fov` rules. */
26
+ focalLength?: number;
27
+ /** Sensor size in millimetres along the fitted axis (see `sensorFit`). Default 36, a full-frame sensor's width. */
28
+ filmGauge?: number;
29
+ /** Which image axis `filmGauge` spans: 'horizontal', 'vertical', or 'auto' (the longer side, Blender's default). */
30
+ sensorFit?: SensorFit;
31
+ }
32
+ /** The image axis a sensor size spans. */
33
+ export type SensorFit = 'horizontal' | 'vertical' | 'auto';
34
+ /** Options of `lensToFov` and `fovToLens`. */
35
+ export interface LensOptions {
36
+ /** Sensor size in millimetres along the fitted axis. Default 36. */
37
+ filmGauge?: number;
38
+ /** Default 'auto': `filmGauge` spans the longer image side. */
39
+ sensorFit?: SensorFit;
40
+ }
41
+ /**
42
+ * Vertical field of view in degrees of a lens of `focalLength` mm for an image of `aspect` (width / height) on a sensor
43
+ * `filmGauge` mm along `sensorFit`: 2·atan(sensor / 2f) on that axis, converted to the vertical axis.
44
+ * A 50 mm lens on a 36 mm wide sensor is 39.6° horizontally and 26.99° vertically at 3:2.
45
+ */
46
+ export declare function lensToFov(focalLength: number, aspect: number, { filmGauge, sensorFit }?: LensOptions): number;
47
+ /** The focal length in millimetres that gives vertical field of view `fov` degrees; the inverse of `lensToFov`. */
48
+ export declare function fovToLens(fov: number, aspect: number, { filmGauge, sensorFit }?: LensOptions): number;
49
+ /**
50
+ * A sub-rectangle of a larger image, in pixels of that image with the origin at its top left. The frustum is built
51
+ * for the full image (aspect `fullWidth / fullHeight`) and the view shows only the rectangle, so the canvas or render
52
+ * target should be `width` by `height`. `x` and `y` may be fractions (jittered rendering) or negative.
53
+ */
54
+ export interface ViewOffset {
55
+ fullWidth: number;
56
+ fullHeight: number;
57
+ x: number;
58
+ y: number;
59
+ width: number;
60
+ height: number;
61
+ }
62
+ /** Splits a `fullWidth` by `fullHeight` image into `tileWidth` by `tileHeight` offsets, row by row from the top left; edge tiles are smaller. */
63
+ export declare function tileOffsets(fullWidth: number, fullHeight: number, tileWidth: number, tileHeight?: number): ViewOffset[];
64
+ /** Options of `CameraProjection.fit`: the view's aspect, the animation time and the margin around the box. */
65
+ export interface FitOptions {
66
+ /** Width / height of the view. Default: the engine canvas (`setup`), else 1. */
67
+ aspect?: number;
68
+ /** Seconds; 0 jumps. Default 0.3, like core's `fitToBoundingBox`. */
69
+ duration?: number;
70
+ /** At least 1. Default 1.1. */
71
+ padding?: number;
72
+ /**
73
+ * Perspective only: 'sphere' (default) frames the box's bounding sphere, as core's `fitToBoundingBox`; 'box' moves
74
+ * the camera, along its own view, to the closest point from which all eight corners sit in the padded frame (see
75
+ * {@link fitBox}), so a wide, flat or tall model fills the frame. Orthographic fits always use the box's outline.
76
+ */
77
+ framing?: 'sphere' | 'box';
78
+ }
79
+ /**
80
+ * Orthographic projection and exactly vertical views for core's Camera, through its `project` and `up` hooks, so the
81
+ * matrix, culling planes, `engine.pick`, every pass and every `camera.matrix` reader get the same view.
82
+ */
83
+ export declare class CameraProjection implements EnginePlugin, ProjectionOptions {
84
+ readonly name = "cameras";
85
+ mode: 'orthographic' | 'perspective';
86
+ height?: number;
87
+ left?: number;
88
+ right?: number;
89
+ top?: number;
90
+ bottom?: number;
91
+ zoom: number;
92
+ near?: number;
93
+ far?: number;
94
+ up: Vec3;
95
+ viewOffset?: ViewOffset;
96
+ focalLength?: number;
97
+ filmGauge: number;
98
+ sensorFit: SensorFit;
99
+ private camera?;
100
+ private worldUp;
101
+ private canvas?;
102
+ /** The engine this projection was attached to as a plugin, so dispose() can detach it from its scene. */
103
+ private host?;
104
+ private animation?;
105
+ /** Same as `engine.use(new CameraProjection(...))`; returns the CameraProjection. */
106
+ static attach(engine: EngineKernel, options?: ProjectionOptions): CameraProjection;
107
+ constructor(options?: ProjectionOptions);
108
+ setup(engine: Pick<Engine, 'camera'> & {
109
+ canvas?: {
110
+ width: number;
111
+ height: number;
112
+ };
113
+ sceneOf?: EngineKernel['sceneOf'];
114
+ }): void;
115
+ /**
116
+ * Frames a box given as `[minX, minY, minZ, maxX, maxY, maxZ]` (`model.bounds`). Perspective: core's
117
+ * `fitToBoundingBox`. Orthographic: keeps the view direction and distance, centres the box and sets `zoom` so the
118
+ * box's projected outline fits (tighter than a bounding sphere). Animated by the engine (`onPreUpdate`).
119
+ */
120
+ fit(bounds: ArrayLike<number>, { aspect, duration, padding, framing, }?: FitOptions): void;
121
+ /** Advances an orthographic `fit`; the engine calls it each frame. Call it yourself after `attach(camera)`. */
122
+ onPreUpdate(delta: number): void;
123
+ /**
124
+ * Renders the `width` by `height` rectangle at (`x`, `y`) of a `fullWidth` by `fullHeight` image (see `ViewOffset`).
125
+ * Works in both modes and with any `zoom`, `height` or bounds; `fit` still frames the whole canvas.
126
+ */
127
+ setViewOffset(fullWidth: number, fullHeight: number, x: number, y: number, width: number, height: number): void;
128
+ /**
129
+ * With a `focalLength`, writes the lens's vertical field of view for `aspect` to `camera.fov`, so passes and controls
130
+ * that read `camera.fov` agree with the projection, and returns it; else returns `camera.fov`. The engine does this
131
+ * each frame (`onPreUpdate`); call it yourself without an engine.
132
+ */
133
+ applyLens(aspect: number): number;
134
+ /** Goes back to the whole frustum. */
135
+ clearViewOffset(): void;
136
+ /** Use without an engine, e.g. on a second Camera. */
137
+ attach(camera: Camera): void;
138
+ /** Gives the camera back its own projection and up, and detaches from the engine's scene it was attached to. */
139
+ dispose(): void;
140
+ [Symbol.dispose]: () => void;
141
+ /**
142
+ * True when the orthographic view size is fixed (`height` or all four bounds set), so moving the camera along its
143
+ * view direction does not change what is visible. Also exposed on the attached camera for controls.
144
+ */
145
+ get fixedOrthographic(): boolean;
146
+ private screenUp;
147
+ private vfov;
148
+ private project;
149
+ private build;
150
+ }
package/dist/index.js ADDED
@@ -0,0 +1 @@
1
+ export { t as CameraProjection, a as fitBox, n as fovToLens, r as lensToFov, i as tileOffsets } from "./src-_OQ7cR69.js";
@@ -0,0 +1,59 @@
1
+ import { i as e, n as t } from "./view-rect-p0kR0Q6B.js";
2
+ //#region ../shared/layers.js
3
+ var n = Symbol.for("margoengine.layers");
4
+ function r() {
5
+ return globalThis[n] ??= {
6
+ masks: /* @__PURE__ */ new WeakMap(),
7
+ cameras: /* @__PURE__ */ new WeakMap(),
8
+ source: null,
9
+ used: !1,
10
+ maskOf(e) {
11
+ if (this.source) return this.source(e) >>> 0;
12
+ if (!this.used) return 1;
13
+ let t = e;
14
+ for (let e = 0; t && e < 64; e++) {
15
+ let e = this.masks.get(t);
16
+ if (e !== void 0) return e;
17
+ let n = t.engine.store.parents[t.id];
18
+ t = n >= 0 ? t.engine.meshes.get(n) : void 0;
19
+ }
20
+ return 1;
21
+ }
22
+ };
23
+ }
24
+ function i(e, n) {
25
+ let i = r();
26
+ i.masks.set(e, t(n, "Render layer mask")), i.used = !0, e.engine && (e.engine.collected = -1);
27
+ }
28
+ //#endregion
29
+ //#region src/layers.ts
30
+ var a = 4294967295, o = r();
31
+ function s(...e) {
32
+ let t = 0;
33
+ for (let n of e) {
34
+ if (!Number.isInteger(n) || n < 0 || n > 31) throw RangeError(`Layer ${n} is outside 0..31; pass a layer index from 0 to 31`);
35
+ t |= 1 << n;
36
+ }
37
+ return t >>> 0;
38
+ }
39
+ function c(e, t) {
40
+ i(e, t);
41
+ }
42
+ function l(e) {
43
+ return o.maskOf(e);
44
+ }
45
+ function u(e) {
46
+ if (e !== null && typeof e != "function") throw TypeError("Layer source must be a function (mesh) => mask or null; pass such a function or null");
47
+ o.source = e;
48
+ }
49
+ function d(e, n) {
50
+ o.cameras.set(e, t(n, "Camera layer mask"));
51
+ }
52
+ function f(e) {
53
+ return o.cameras.get(e) ?? 4294967295;
54
+ }
55
+ function p(n, r, i, a) {
56
+ return e(n, t(r, "Layer mask"), a, i);
57
+ }
58
+ //#endregion
59
+ export { d as a, p as c, s as i, f as n, c as o, l as r, u as s, a as t };
@@ -0,0 +1,36 @@
1
+ import type { EngineKernel, Mesh } from '@margoengine/core';
2
+ import type { Camera } from '@margoengine/core/extension';
3
+ /** Every layer: the mask that filters nothing. */
4
+ export declare const ALL_LAYERS = 4294967295;
5
+ /** Mask with the given layers (0-31) enabled: `layerMask(0, 2)` is 0b101. */
6
+ export declare function layerMask(...layers: number[]): number;
7
+ /**
8
+ * Sets the layer mask of `mesh` (32-bit, default 1 = layer 0), the one mask drawing and @margoengine/bvh raycasts read.
9
+ * For drawing, its descendants without a mask of their own follow it, so `setRenderLayers(model.root, mask)` layers a
10
+ * whole model; a Raycaster tests a mesh's own mask (a model primitive: its node's, else `model.root`'s).
11
+ * @throws RangeError for a mask that is not an integer from 0 to 0xffffffff.
12
+ */
13
+ export declare function setRenderLayers(mesh: Mesh, mask: number): void;
14
+ /** Render layer mask of `mesh`: its own, else its nearest ancestor's, else 1; or the `useLayerSource` reader's value. */
15
+ export declare function getRenderLayers(mesh: Mesh): number;
16
+ /**
17
+ * Reads every mesh mask for drawing through `source` instead of `setRenderLayers`, or restores the default with null.
18
+ * @throws TypeError when `source` is neither a function nor null.
19
+ */
20
+ export declare function useLayerSource(source: ((mesh: Mesh) => number) | null): void;
21
+ /**
22
+ * Sets the layer mask a camera draws (default every layer): the engine draws its frame, `render({camera})` and every
23
+ * view through that camera with it, unless a view sets its own `layers`.
24
+ * @throws RangeError for a mask that is not an integer from 0 to 0xffffffff.
25
+ */
26
+ export declare function setCameraLayers(camera: Camera, mask: number): void;
27
+ /** Layer mask `camera` draws: the one set with `setCameraLayers`, else every layer. */
28
+ export declare function getCameraLayers(camera: Camera): number;
29
+ /**
30
+ * Runs `run` with only the meshes in `mask` (and not in `exclude`) visible, then makes the hidden ones visible again,
31
+ * also when `run` throws: for a capture that also leaves out given meshes (a mirror leaving out itself). To filter
32
+ * what a view draws by layers alone, give the view `layers` or its camera `setCameraLayers` instead; that hides
33
+ * nothing. A hidden parent hides its children.
34
+ * @throws RangeError for a mask that is not an integer from 0 to 0xffffffff.
35
+ */
36
+ export declare function withLayers<T>(engine: EngineKernel, mask: number, run: () => T, exclude?: Iterable<Mesh>): T;
package/dist/layers.js ADDED
@@ -0,0 +1 @@
1
+ export { t as ALL_LAYERS, n as getCameraLayers, r as getRenderLayers, i as layerMask, a as setCameraLayers, o as setRenderLayers, s as useLayerSource, c as withLayers } from "./layers-CkdgcqTK.js";