@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.
package/README.md CHANGED
@@ -1,3 +1,621 @@
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/cameras
2
+
3
+ Orthographic projection and exactly vertical (top-down) views for the core camera, with matching culling and picking.
4
+
5
+ `WideAngle` and `WideAngleCube` detach from their owning scene when disposed and
6
+ preserve same-name effects in other scenes. Device restoration keeps them attached.
7
+ Use `scene.use()` to attach their PostStack to a secondary scene:
8
+
9
+ ```ts
10
+ import {Engine} from 'margoengine/core';
11
+ import {PostStack} from 'margoengine/post/stack';
12
+ import {CubeCamera} from 'margoengine/environment/cube-camera';
13
+ import {WideAngle} from 'margoengine/cameras/panini';
14
+ import {WideAngleCube} from 'margoengine/cameras/wide-cube';
15
+ const engine = await Engine.create(document.querySelector('canvas')!, {backend:'webgpu'});
16
+ const product = engine.createScene('product');
17
+ const cube = new CubeCamera({size:64});
18
+ product.use(cube);
19
+ const stack = new PostStack([new WideAngleCube({cube}), new WideAngle()]);
20
+ product.use(stack);
21
+ stack.dispose();
22
+ cube.dispose();
23
+ engine.dispose();
24
+ ```
25
+
26
+ Import `margoengine/cameras` from the `margoengine` package, or `@margoengine/cameras` from this package alone; the two are the same module. Neither is on npm yet: the [Install](../../README.md#install) section lists the two routes that work today (run in a clone, or install local tarballs).
27
+
28
+ Orthographic projection and exactly vertical (top-down and bottom-up) views for core's camera, for CAD, plans, maps
29
+ and isometric views. Culling, `engine.pick`, selection, bvh rays, TAA and every pass that reads `camera.matrix` see the
30
+ same view. It uses core's `camera.project` and `camera.up` hooks.
31
+
32
+ ```ts
33
+ import {Engine} from 'margoengine/core';
34
+ import {CameraProjection} from 'margoengine/cameras';
35
+ import {loadGLTF} from 'margoengine/gltf/pbr';
36
+ const canvas = document.querySelector('canvas')!;
37
+
38
+ const engine = await Engine.create(canvas, {camera: {position: [0, 40, 0], target: [0, 0, 0]}}); // straight down
39
+ const model = await loadGLTF(engine, '/model.glb');
40
+ const projection = CameraProjection.attach(engine); // orthographic, framed like the perspective view at the target
41
+
42
+ projection.mode = 'perspective'; // toggle at any time; vertical views keep working
43
+ projection.mode = 'orthographic';
44
+ projection.height = 12; // or fix the visible world height (resize widens with the aspect)
45
+ projection.zoom = 2;
46
+ projection.fit(model.bounds); // frame a box: [minX, minY, minZ, maxX, maxY, maxZ], animated
47
+ projection.mode = 'perspective';
48
+ projection.fit(model.bounds, {framing: 'box'}); // move in until the box's corners fill the frame
49
+ ```
50
+
51
+ - **Fitting**: `fit(bounds, {aspect, duration, padding})` takes the flat bounds array models carry (no slicing into
52
+ min/max). Orthographic: the view direction and distance stay, the box centre moves to the view centre and `zoom` is
53
+ set so the box's projected outline (not a bounding sphere) fills the view less `padding` (default 1.1), honouring
54
+ `height` or `left`/`right`/`top`/`bottom`. Perspective: core's `fitToBoundingBox`. `aspect` defaults to the engine
55
+ canvas, `duration` to 0.3 s; the engine advances the animation (after `attach(camera)` call `onPreUpdate(delta)`
56
+ yourself). Throws `Bounds exceed far` when the box does not fit the default depth range (`camera.far` deep).
57
+ `framing: 'box'` (perspective) keeps the view direction and field of view and moves the eye to the closest point from
58
+ which all eight corners sit in the padded frame, so a car side-on fills 48 % of a 16:9 frame where the bounding
59
+ sphere gave 13 %. The box is centred on screen on both axes: the tighter one touches the padded frame on both
60
+ sides, the looser one has equal margins in pixels even when the box's near and far corners sit at different depths
61
+ (a plate seen from above). The default, `'sphere'`, stays core's framing.
62
+ - **`fitBox(view, bounds, {aspect, padding})`** is that framing as a pure function: it returns `{position, target,
63
+ distance, nearest}` for a `{position, target, fov, up?}` view, to set on any camera or to plan a shot without one:
64
+
65
+ ```ts
66
+ import {fitBox} from 'margoengine/cameras';
67
+
68
+ const fit = fitBox({position: [0, 1, 10], target: [0, 0.7, 0], fov: 40}, [-2.3, 0, -1, 2.3, 1.5, 1], {aspect: 16 / 9});
69
+ console.log(fit.position, fit.target, fit.nearest); // nearest: the closest corner's depth, to check against camera.near
70
+ ```
71
+
72
+ - **Parameters**: `left`, `right`, `top`, `bottom` (all four replace `height` and
73
+ the canvas aspect, so update them on resize), `zoom` (divides the frustum about its centre), `near`, `far` (eye-space, may be negative).
74
+ Without `height` or bounds the visible height is `2 · distance · tan(fov / 2)`: the perspective framing at the target,
75
+ so `fitToBoundingBox`, the stage's `CADCameraControls` and `@margoengine/controls` dolly become ortho zoom and pan tracks
76
+ the cursor exactly. Without `near`/`far` the depth range is `camera.far` deep and centred on the target (Blender's
77
+ convention), so zooming in never clips a model at the eye.
78
+ - **Fixed size.** With an explicit `height` or all four bounds, `projection.fixedOrthographic` (also readable on the
79
+ attached camera) is true: dolly changes only the distance, so `@margoengine/controls` zoom-to-cursor adds no pan.
80
+ - **Depth** is reversed-Z on WebGPU (near 1, far 0) like core, and -1..1 on WebGL. Orthographic depth is linear.
81
+ - **Vertical views**: pole detection follows the camera's current world-up vector,
82
+ including a custom world up, rather than assuming the world Y axis. At a pole,
83
+ screen up comes from projection.up (default [0,0,-1]); it must be finite and
84
+ nonparallel to the view axis. Away from the pole, camera.up returns world up.
85
+ Assigning camera.up changes world up while the projection is attached. The
86
+ camera position stays exact; passes that rebuild the view read the same camera.up.
87
+ With world up [0,0,1] and a view down Z, supply projection.up [0,1,0] instead of
88
+ the default. Invalid world/screen up throws RangeError when evaluated.
89
+ - **Culling** is exact and stays on: core derives the culling planes from the matrix the `project` hook builds. No
90
+ `culling: false` and no extra cost.
91
+ - **Detecting it**: `camera.matrix` is orthographic when entries 3, 7 and 11 are zero.
92
+ - `attach(camera)` drives a camera without an engine; `dispose()` (or `engine.removePlugin('cameras')`) restores core's
93
+ `project` (unset) and a plain `up` field. Attaching to a camera whose `project` is already set throws.
94
+
95
+ Errors name their fix. Argument problems throw `RangeError` or `TypeError` (for example `Invalid fit; pass min <= max, aspect > 0, duration >= 0 and padding >= 1, all finite`). Branch on `error.code` for the rest: `attached` (a projection or camera already in use) and `state` (a `FloatingOrigin` used before `engine.use(origin)`).
96
+
97
+ Orthographic-aware (they read `camera.matrix`): SSAO, points, labels, clustered, DOF, splats and lines' world-space
98
+ widths. Shadow cascades are fitted to the perspective frustum, which covers
99
+ the default ortho view; a fixed small `height` far from the target wastes shadow resolution. Cascades stay texel-locked under orthographic pan and
100
+ zoom, with no visible shimmer: an ortho zoom leaves the shadow matrices unchanged, and a slow pan changes about 0.6 of
101
+ 14k shadow-edge pixels per frame, against 194 for a 0.01° light turn (Intel Arc 140V laptop iGPU, Edge 155;
102
+ `examples/package-benchmarks/shadow-shimmer.mjs`, [shadow-shimmer.json](../../examples/package-benchmarks/results/shadow-shimmer.json)). Specular uses the camera
103
+ position, not a parallel view direction.
104
+
105
+ ## Large coordinates: `@margoengine/cameras/origin`
106
+
107
+ Core and its transform kernel are float32, so a part 1 km from the world origin already shakes by ~0.7 px at
108
+ millimetre zoom, at 100 km by tens of pixels, and at Earth-radius scale it falls apart. `FloatingOrigin` keeps float64
109
+ world positions for root meshes on the CPU and hands core coordinates relative to an origin near the camera, moving
110
+ that origin (one full transform update of the placed roots) when the camera drifts too far. Measured: under 0.05 px
111
+ of jitter at any distance up to 6,000 km ([docs/large-coordinates.md](../../docs/large-coordinates.md)). 0 core bytes.
112
+
113
+ ```ts
114
+ import {FloatingOrigin} from 'margoengine/cameras/origin';
115
+ import {Raycaster} from 'margoengine/bvh';
116
+ import {Engine} from 'margoengine/core';
117
+ import {boxGeometry} from 'margoengine/geometry';
118
+ import {Material, createMesh} from 'margoengine/materials';
119
+ const x = 0;
120
+ const y = 0;
121
+ const engine = await Engine.create(document.querySelector('canvas')!);
122
+
123
+ const material = new Material({color: '#8d99a6', doubleSided: true});
124
+ const flange = createMesh(engine, boxGeometry(0.4, 0.4, 0.05), material).root;
125
+ const origin = FloatingOrigin.attach(engine); // default ratio 1000
126
+ origin.place(flange, [2_880_000.12, 3_600_000.65, 3_840_000.31]); // float64 world metres; root meshes or model.root
127
+ origin.lookAt([2_880_000.15, 3_600_000.68, 3_840_000.35], [2_880_000.12, 3_600_000.65, 3_840_000.31]);
128
+ origin.worldPosition(flange); // float64 back
129
+ const hit = new Raycaster().setFromEngine(engine, x, y).intersectEngine(engine)[0];
130
+ origin.toWorld(hit.point); // pick point in float64 world coordinates
131
+ const worldPlane: [number, number, number, number] = [0, 0, 1, -3_840_000.31];
132
+ material.clippingPlanes = [origin.toLocalPlane(worldPlane)];
133
+ origin.onRebase(() => { material.clippingPlanes = [origin.toLocalPlane(worldPlane)]; });
134
+ ```
135
+
136
+ - **Local coordinates.** While attached, the camera, controls (`OrbitControls`, `CADCameraControls`, any that read
137
+ `camera.position`/`target`), `engine.pick`, bvh hits, `mesh.matrix`, gltf/pbr node matrices, section planes and
138
+ measurements all work in local coordinates (world − `origin`). Convert at the boundary with `toWorld`, `toLocal` and
139
+ `toLocalPlane`; `cameraPosition`/`cameraTarget` read the camera in world coordinates. Distances and angles between
140
+ local points need no conversion.
141
+ - **Rebase rule.** Before each frame, when the camera is farther from the origin than `ratio` × its distance to
142
+ `camera.target` (default 1000: 50 m at 50 mm zoom), the origin moves to the camera. Placed roots and the camera
143
+ shift together; a running `fitToBoundingBox` animation is shifted too. Children follow their roots. `rebase(point)`
144
+ forces one; `onRebase((shift, origin) => ...)` lets you shift data you hold in local coordinates (saved views,
145
+ OrbitControls `saveState`, section planes, an orthographic `CameraProjection.fit` in flight).
146
+ - **Moving placed parts.** `place(mesh, world)` again, or move it through `mesh.position` (drag and transform gizmos,
147
+ physics): the next rebase or `worldPosition` reads the new local position back.
148
+ - **Cost.** A rebase rewrites every placed root and makes the kernel recompute all of them and core re-upload their
149
+ instances once (see the doc for 10k/50k timings); it is rare, since the camera must move ratio × view distance.
150
+ - **Limits.** Only root positions are float64. Geometry vertices and child (node) translations that are themselves
151
+ kilometres from their root are float32 when loaded: re-centre such assets (or load each far part as its own root).
152
+ `dispose()` leaves the scene in local coordinates.
153
+ - **Terrain.** Pass the origin to a clipmap terrain as `floatingOrigin` (`Terrain.attach(engine, {..., floatingOrigin:
154
+ origin})`) and its rings, layer textures, virtual texture, prints and streaming follow every rebase, the same picture
155
+ at 1e7 m as at zero; `PlanetTerrain` takes it as `origin`. See the terrain README, "Far from the origin".
156
+
157
+ ## Render layers: `@margoengine/cameras/layers`
158
+
159
+ Every mesh has a 32-bit layer mask (default 1, layer 0) and every camera or engine view draws only the meshes whose
160
+ mask shares a bit with its own. Core does the filtering while it collects instances, so nothing is hidden and
161
+ `mesh.visible` stays yours.
162
+
163
+ ```ts
164
+ import {ALL_LAYERS, layerMask, setCameraLayers, setRenderLayers, withLayers} from 'margoengine/cameras/layers';
165
+ import {Reflector} from 'margoengine/environment/reflector';
166
+ import {loadGLTF} from 'margoengine/gltf/pbr';
167
+ import {Camera, Engine} from 'margoengine/core';
168
+ const top = new Camera({position: [0, 20, 0], target: [0, 0, 0]});
169
+ const engine = await Engine.create(document.querySelector('canvas')!);
170
+
171
+ const helpers = await loadGLTF(engine, '/helpers.glb');
172
+ const mirror = Reflector.attach(engine, {width: 4, height: 3});
173
+ setRenderLayers(helpers.root, layerMask(1)); // a model by its root: children without a mask follow it
174
+ setCameraLayers(engine.camera, layerMask(0)); // the engine camera now skips the helpers
175
+ engine.views = [
176
+ {camera: engine.camera, viewport: [0, 0, 0.5, 1]},
177
+ {camera: top, viewport: [0.5, 0, 0.5, 1], layers: ALL_LAYERS}, // this view shows the helpers too
178
+ ];
179
+ mirror.layers = layerMask(0); // Reflector, Refractor and CubeCamera take a mask too
180
+ ```
181
+
182
+ - **Masks**: `setRenderLayers(mesh, mask)` / `getRenderLayers(mesh)`; a mesh without its own mask takes its nearest
183
+ ancestor's, else 1. `layerMask(...layers)` builds a mask from layer indices 0-31; `ALL_LAYERS` is every bit.
184
+ `@margoengine/bvh` raycasts read the same masks (a mesh's own; a model primitive's node, else its root), so one
185
+ `setRenderLayers` call filters both. `useLayerSource(fn)` makes drawing read masks from `fn` instead;
186
+ `useLayerSource(null)` goes back. The masks live in one registry on `globalThis`, shared by every copy of this
187
+ module and read by core and `@margoengine/environment`'s captures.
188
+ - **Cameras and views**: `setCameraLayers(camera, mask)` / `getCameraLayers(camera)` (default every layer). The engine
189
+ frame, `engine.render({camera})` and every view through that camera use its mask; a view's own `layers` wins.
190
+ - **Scenes**: to show one set of meshes at a time, put each set on its own layer and switch the camera's mask (or the
191
+ view's `layers`). Separate meshes, lighting and plugins are core scenes: `engine.createScene()`.
192
+ - **withLayers(engine, mask, run, exclude?)** hides the meshes outside `mask` and the `exclude` meshes for one callback
193
+ (restored also when it throws): for a capture that must also leave out given meshes.
194
+ - **Limits**: masks with a layer source are re-read every frame; set masks are applied on the next frame. Raycasts keep
195
+ bvh's own `raycaster.layers`. Unit tests: `test/layers.test.js` (real core on a mock GPU); real-GPU layer checks run
196
+ in `scripts/env-mirror-gpu-check.js`.
197
+
198
+ ## View offset: tiles, walls and jitter
199
+
200
+ `setViewOffset` renders one rectangle of a larger image. The frustum is built for the full image and the view shows only
201
+ the rectangle, in both modes, with any `zoom`, `height` or bounds. 0 core bytes.
202
+
203
+ ```ts
204
+ import {CameraProjection, tileOffsets} from 'margoengine/cameras';
205
+ import {Engine} from 'margoengine/core';
206
+ const canvas = document.querySelector('canvas')!;
207
+ const engine = await Engine.create(canvas);
208
+
209
+ const projection = CameraProjection.attach(engine, {mode: 'perspective'});
210
+ // A 8192 x 4608 screenshot from 2048 x 1152 tiles: size the canvas to a tile, then render each rectangle.
211
+ const picture = new OffscreenCanvas(8192, 4608).getContext('2d')!;
212
+ for (const t of tileOffsets(8192, 4608, 2048, 1152)) {
213
+ projection.setViewOffset(t.fullWidth, t.fullHeight, t.x, t.y, t.width, t.height);
214
+ engine.render();
215
+ picture.drawImage(canvas, t.x, t.y); // into the big image at (t.x, t.y)
216
+ }
217
+ projection.clearViewOffset();
218
+ ```
219
+
220
+ - **Rectangle**: `setViewOffset(fullWidth, fullHeight, x, y, width, height)` in pixels of the full image, origin top
221
+ left. `x` and `y` may be fractions or negative: a quarter-pixel step per frame is jittered rendering. `viewOffset` is
222
+ also an option and a property.
223
+ - **Walls**: give each monitor its rectangle of the combined desktop (`fullWidth` the sum of widths).
224
+ - **Tiles**: `tileOffsets(fullWidth, fullHeight, tileWidth, tileHeight = tileWidth)` lists the rectangles row by row;
225
+ edge tiles are smaller. Size the canvas to the tile; the aspect of the full image is used for the frustum.
226
+ - **Same view everywhere**: culling, `engine.pick`, and passes that read `camera.matrix` see the tile. `fit` still
227
+ frames the canvas.
228
+ - **Limit**: passes that read neighbouring pixels (bloom, SSAO, DOF, TAA history) see only the tile, so seams can
229
+ show; render tiles with overlap and crop. See [limits](../../docs/limits.md).
230
+
231
+ ## Focal length and film gauge
232
+
233
+ Set the view the way photographers and Blender users do: a lens in millimetres on a sensor size, not a field of view.
234
+
235
+ ```ts
236
+ import {CameraProjection, fovToLens, lensToFov} from 'margoengine/cameras';
237
+ import {Engine} from 'margoengine/core';
238
+ const engine = await Engine.create(document.querySelector('canvas')!);
239
+
240
+ const projection = CameraProjection.attach(engine, {mode: 'perspective', focalLength: 50}); // 50 mm on a 36 mm sensor
241
+ projection.focalLength = 85; // portrait lens; camera.fov follows each frame
242
+ projection.filmGauge = 24; // sensor size in mm along sensorFit
243
+ projection.sensorFit = 'vertical'; // 'auto' (default: the longer image side), 'horizontal' or 'vertical'
244
+ lensToFov(35, 16 / 9); // vertical field of view in degrees for a 35 mm lens at 16:9
245
+ fovToLens(40, 16 / 9, {filmGauge: 36}); // the focal length that gives a 40 degree vertical field of view
246
+ ```
247
+
248
+ - **Maths**: the field of view along the sensor axis is `2·atan(filmGauge / (2·focalLength))`, converted to the vertical
249
+ axis by the image aspect. 50 mm on 36 mm is 39.6 degrees across the sensor's long side.
250
+ - **Sync**: with a `focalLength` set, the projection uses the lens in both modes (the default orthographic height too)
251
+ and writes the vertical field of view to `camera.fov` every frame (`applyLens(aspect)` does it on demand), so
252
+ shadows, controls and `fit` agree with it. Without one, `camera.fov` rules as before. With a view offset the lens
253
+ is applied at the full image's aspect.
254
+ - **Errors**: `Invalid projection lens; ...` for a focal length, gauge or aspect that is not above 0 or an unknown
255
+ `sensorFit`.
256
+
257
+ ## Off-axis and oblique projection: `@margoengine/cameras/offaxis`
258
+
259
+ Head-tracked displays, CAVE walls and portals need a frustum that is not centred on the view axis. 0 core bytes.
260
+
261
+ ```ts
262
+ import {ObliqueNearPlane, OffAxisProjection, offAxisFrustum, type Screen} from 'margoengine/cameras/offaxis';
263
+ import {Engine} from 'margoengine/core';
264
+ const engine = await Engine.create(document.querySelector('canvas')!);
265
+
266
+ // A 1.2 x 0.7 m monitor standing on the desk at the origin, facing +z; corners counter clockwise from the viewer.
267
+ const screen: Screen = {lowerLeft: [-0.6, 0, 0], lowerRight: [0.6, 0, 0], upperLeft: [-0.6, 0.7, 0]};
268
+ const window = OffAxisProjection.attach(engine, screen, [0, 0.4, 0.8]);
269
+ // The viewer's head in world metres, here from the pointer; the screen stays a window onto the scene.
270
+ addEventListener('pointermove', (event) => window.setEye([event.clientX / innerWidth - 0.5, 0.4, 0.8]));
271
+
272
+ offAxisFrustum(screen, [0, 0.4, 0.8], 0.1); // {left, right, bottom, top, xAxis, yAxis, normal, distance}
273
+
274
+ // Portals and mirrors: clip everything in front of a plane with no extra clip plane.
275
+ window.dispose();
276
+ const oblique = new ObliqueNearPlane([0, 0, -1, 0.5]).attach(engine.camera); // keeps z <= 0.5
277
+ oblique.plane = [0, -1, 0, 2]; // change it every frame; undefined clips nothing
278
+ ```
279
+
280
+ - **Off-axis**: `OffAxisProjection(screen, eye)` aims the camera straight into the screen from the eye and builds the
281
+ asymmetric frustum from the three corners, so a point on the screen plane shows at the same place for any eye
282
+ position, and anything behind it moves with parallax. The canvas aspect is ignored; size the canvas like the screen.
283
+ Give each wall of a CAVE its own camera, view and `OffAxisProjection`. The eye must be in front of the screen;
284
+ `camera.near` should not exceed the eye's distance to the screen or the screen's near corners are clipped.
285
+ - **Oblique**: `ObliqueNearPlane` replaces the near plane of the camera's projection with a plane in world space
286
+ (`[nx, ny, nz, d]`, points with `n·p + d >= 0` are kept). It works with core's perspective camera, `CameraProjection`
287
+ (orthographic too) and `OffAxisProjection`, on both depth conventions, and culling sees the same plane. Attach it
288
+ last and `dispose()` it first. The camera must be on the clipped side; the oblique plane trades depth precision for the
289
+ extra slant, so keep it away from edge-on views of the camera.
290
+ - `obliqueProjection(matrix, planeInEyeSpace, webgpu)` does the matrix part on its own.
291
+
292
+ ## Physical exposure: `@margoengine/cameras/physical`
293
+
294
+ Aperture, shutter time and ISO set the exposure, the depth of field and the motion blur together, as on a real camera. 0 core bytes.
295
+
296
+ ```ts
297
+ import {DOF} from 'margoengine/dof';
298
+ import {PostStack} from 'margoengine/post';
299
+ import {MotionBlur} from 'margoengine/post/motion-blur';
300
+ import {TAA} from 'margoengine/taa';
301
+ import {Tonemap} from 'margoengine/tonemap';
302
+ import {PhysicalCamera} from 'margoengine/cameras/physical';
303
+ import {Engine} from 'margoengine/core';
304
+ const engine = await Engine.create(document.querySelector('canvas')!);
305
+
306
+ const dof = new DOF(), tonemap = new Tonemap();
307
+ const taa = TAA.attach(engine, {depth: () => stack.depthTexture});
308
+ const motionBlur = new MotionBlur({velocity: () => taa.velocity});
309
+ const stack = PostStack.attach(engine, [dof, motionBlur, tonemap]);
310
+ const camera = new PhysicalCamera({focalLength: 85, aperture: 1.8, shutter: 1 / 120, iso: 200, focusDistance: 3});
311
+ camera.apply({dof, motionBlur, exposure: tonemap, camera: engine.camera, aspect: 16 / 9});
312
+ camera.aperture = 5.6; // stops down: darker, deeper focus
313
+ camera.apply({dof, motionBlur, exposure: tonemap});
314
+ camera.exposure; // stops against the reference: -1 at f/5.6, 1/120 s, ISO 200
315
+ camera.depthOfField(); // {hyperfocal, near, far} in metres, far is Infinity past the hyperfocal distance
316
+ camera.blurDiameter(10); // mm of blur on the sensor for a point 10 m away
317
+ engine.start(); // TAA wraps the shared HDR stack; blur uses its velocity
318
+ ```
319
+
320
+ - **Exposure**: `ev100 = log2(N² / t) − log2(ISO / 100)` for f-number N, shutter time t seconds. `exposure` is
321
+ `referenceEV − ev100` in stops: a stop wider aperture, a doubled shutter time and a doubled ISO each add one. The
322
+ engine's light is not calibrated in photometric units, so the reference decides what looks right: by default the
323
+ defaults of `DOF` and `MotionBlur` (f/2.8, 1/120 s, ISO 100) are 0 stops and an unchanged scene looks as before. Set
324
+ `referenceEV` to the setting that should look as the scene was lit.
325
+ - **Depth of field**: `apply` gives `DOF` the focus distance, the focal length (millimetres to metres) and the f-number.
326
+ `depthOfField(coc)` and `blurDiameter(distance)` are the thin-lens formulas, with a circle of confusion of
327
+ `filmGauge / 1500` unless you pass one.
328
+ - **Motion blur**: `shutterFraction` is the exposure time as a share of the frame interval at `frameRate`, at most 1;
329
+ `MotionBlur.shutter` takes it, and `shutterAngle` is the same as a rotary shutter's angle.
330
+ - **Lens**: `apply({camera, aspect})` sets `camera.fov` from the focal length and film gauge; `apply({projection})` sets
331
+ a `CameraProjection`'s `focalLength` and `filmGauge`.
332
+ - **Targets**: `apply` writes only the targets you pass. `exposure` takes anything with an `exposure` option in stops
333
+ (`Tonemap`, `Bloom`, `PostStack`), whose own ranges apply. Errors: `Invalid physical camera; ...` for a value that is
334
+ not finite and above 0, or a focus distance inside the focal length.
335
+
336
+ ## Wide-angle projections: `@margoengine/cameras/panini`
337
+
338
+ A plain perspective stretches the edges of a wide view. `WideAngle` draws the scene rectilinear at a wide field of view
339
+ and resamples it as a Panini or a fisheye picture, in a `PostStack`. WebGPU, perspective cameras. 0 core bytes.
340
+
341
+ ```ts
342
+ import {PostStack} from 'margoengine/post';
343
+ import {WideAngle} from 'margoengine/cameras/panini';
344
+ import {Engine} from 'margoengine/core';
345
+ const px = 0;
346
+ const py = 0;
347
+ const canvas = document.querySelector('canvas')!;
348
+ const engine = await Engine.create(canvas);
349
+
350
+ engine.camera.fov = 100; // the rectilinear picture the stage resamples
351
+ const wide = new WideAngle({mode: 'panini', distance: 1}); // 'panini' | 'equidistant' | 'equisolid' | 'stereographic' | 'orthographic'
352
+ PostStack.attach(engine, [wide]); // after the display effect: [new Tonemap(), wide]
353
+ // or: const wide = await WideAngle.attach(engine, {mode: 'panini'}); joins the scene's stack, or makes one (needs @margoengine/post)
354
+ wide.options.distance = 0.6; // read every frame, like mode and crop
355
+ wide.enabled = false; // the plain picture
356
+
357
+ // Where a click on the projected picture lands on the source picture, for engine.pick or overlays:
358
+ const map = wide.map(engine.camera.fov, canvas.width / canvas.height);
359
+ const [x, y] = map.toSource(2 * px / canvas.width - 1, 1 - 2 * py / canvas.height)!; // normalised, y up; null outside
360
+ map.toOutput(x, y); // and back
361
+ ```
362
+
363
+ - **Panini** keeps vertical lines vertical and straight lines through the centre straight, and compresses the sides
364
+ of a wide view toward the centre. `distance` 0 is the plain picture, 1 the classic Panini, larger values bend toward
365
+ a cylinder. Projection after Sharpless, Postle and German (2010).
366
+ - **Fisheye** modes follow r = f·g(θ): equidistant θ, equisolid 2 sin(θ/2), stereographic 2 tan(θ/2), orthographic
367
+ sin θ. The source is one rectilinear picture, so a fisheye reaches only as far as that picture does: under 180
368
+ degrees across, in practice 120 to 150. For 180 degrees and past it, use `WideAngleCube` below.
369
+ - **Crop**: the output plane is zoomed in just enough that no pixel falls outside the source (`crop`, default true);
370
+ `map.zoom` says by how much. With `crop: false` the uncovered corners are black.
371
+ - **Camera**: it reads `engine.camera.fov` and the frame's shape each frame, so a lens set with `focalLength` works.
372
+ Draw the source at the field of view you want to see across.
373
+ - **Errors**: `Invalid wide angle mode; ...`, `Invalid wide angle distance; ...`, `Invalid wide angle view; ...`;
374
+ MargoError `state` outside a PostStack, `unsupported` on WebGL2, `attached` and `disposed`.
375
+
376
+ ## Past 180 degrees: `@margoengine/cameras/wide-cube`
377
+
378
+ `WideAngleCube` reads a cube captured at the camera, so a fisheye or a Panini sees the whole sphere: `fov` is degrees across
379
+ the width, up to 360 for equidistant and equisolid. WebGPU. Needs `@margoengine/post` and `@margoengine/environment`.
380
+
381
+ ```ts
382
+ import {WideAngleCube} from 'margoengine/cameras/wide-cube';
383
+ import {Engine} from 'margoengine/core';
384
+ const canvas = document.querySelector('canvas')!;
385
+ const engine = await Engine.create(canvas);
386
+
387
+ const wide = await WideAngleCube.attach(engine, {mode: 'equidistant', fov: 220, size: 512});
388
+ wide.options.fov = 280; // read every frame, like mode, distance and circle
389
+ wide.facesPerFrame = 2; // spread the capture over three frames
390
+ engine.start(); // captures before each frame; with engine.render(), call wide.capture() first
391
+
392
+ // The direction shown at a pointer position, in camera space (forward is [0, 0, -1]):
393
+ const ray = wide.map(canvas.width / canvas.height).toDirection(0.5, 0); // null outside the picture
394
+ wide.dispose(); // the effect, its stack and its cube
395
+ ```
396
+
397
+ - **Cost**: six scene draws a frame at `facesPerFrame` 6, on top of the main draw, which the stage replaces. `size`
398
+ (default 512) sets the sharpness: a face of 512 is about 5.7 texels a degree.
399
+ - **Reach**: equidistant and equisolid up to 360, stereographic below 360, orthographic 180, Panini below 360 at `distance`
400
+ 1 (`distance` 0 stops below 180, larger values also stop short, because the projection folds back). A `fov` past that throws.
401
+ - **Circle**: `circle` (default true) leaves black past half of `fov`; false fills the corners as far as the law reaches.
402
+ - **Light**: the cube holds linear light and this is an HDR stage, so tone mapping comes after it, and a display effect
403
+ goes after it in your own stack: `const cube = CubeCamera.attach(engine, {size: 512}); PostStack.attach(engine, [new WideAngleCube({cube}), new Tonemap()]);`
404
+ `WideAngleCube.attach(engine, options)` on a scene that already has a PostStack adds the stage after its last HDR effect.
405
+ Faces run the scene passes only, so HDR effects ahead of this stage do not reach the picture. The camera's `fov` is not used.
406
+ - **Errors**: `Invalid wide angle fov ...` and the `WideAngle` errors; MargoError `state` outside a PostStack, with no cube,
407
+ or for `capture()` before attaching; `unsupported` on WebGL2, `attached` and `disposed`.
408
+
409
+ Apache-2.0. Optional, tree-shakable package; `/origin` and `/layers` are separate entries; core peer: ^1.0.0.
410
+
411
+ Build and unit tests: npm test --workspace @margoengine/cameras
412
+
413
+ ## Spherical capture: optional /panorama
414
+
415
+ capturePanorama(engine, options) returns one complete 360 by 180 degree
416
+ equirectangular image. It requires WebGPU or the full WebGL2 compatibility layer;
417
+ the native WebGL2 preview does not supply this WebGPU texture/readback API. Without
418
+ a cube option it lazily imports the optional environment/cube-camera entry, creates
419
+ a temporary CubeCamera at position (default engine.camera.position), captures all
420
+ six faces and disposes it, including on failure. Install that optional peer when
421
+ using this route. The main camera, canvas dimensions and scene state are preserved.
422
+
423
+ size is the temporary cube's power-of-two face edge (8..2048, default 256). width
424
+ defaults to 4*size, must be an even integer >=2, and height is width/2. The device's
425
+ maxTextureDimension2D and maxBufferSize also apply, including 256-byte row padding
426
+ in the readback buffer. Large captures allocate six cube faces, an output texture
427
+ and a readback buffer; choose a size appropriate to the device.
428
+
429
+ With cube, pass a caller-owned linear-light GPUTextureView and optional update(faces).
430
+ The view must be a compatible cube on the engine device. An update method is called
431
+ with 6 and must return 6; omit it for an already baked cube. The caller keeps cube
432
+ ownership. The image runs top-to-bottom, +Y at the top and -Z at the center. yaw
433
+ defaults 0 radians; positive yaw turns the center toward +X. panoramaDirection(u,v,yaw)
434
+ exposes the same mapping, with wrapping u and v in [0,1].
435
+
436
+ format defaults srgb: Uint8ClampedArray RGBA8 display pixels, with exposure (default
437
+ 0 stops) applied before the sRGB transfer and clipping. linear returns Float32Array
438
+ RGBA32F in linear light, without exposure or display clipping. It does not restore
439
+ HDR range absent from the supplied cube. panoramaPNG(image, signal?) encodes an srgb
440
+ image as a PNG Blob and rejects linear data. Both operations accept AbortSignal;
441
+ abort rejects with its reason, ends the wait and releases owned temporary resources.
442
+ Borrowed cubes remain live. An abort cannot undo GPU work already submitted.
443
+
444
+ ```ts
445
+ import {Engine, box, PbrMaterial} from '@margoengine/core';
446
+ import {capturePanorama, panoramaPNG, panoramaDirection} from '@margoengine/cameras/panorama';
447
+ const canvas = document.body.appendChild(document.createElement('canvas'));
448
+ const engine = await Engine.create(canvas, {backend: 'webgpu'});
449
+ engine.createMesh().setGeometry(box()).setMaterial(new PbrMaterial()).setPosition([0, 0, -3]);
450
+ const controller = new AbortController();
451
+ const image = await capturePanorama(engine, {size: 64, width: 256, signal: controller.signal});
452
+ if (image.width !== 256 || image.height !== 128) throw new Error('Unexpected panorama dimensions');
453
+ const png = await panoramaPNG(image, controller.signal);
454
+ console.log(png.size, panoramaDirection(0.5, 0.5)); // Center looks along -Z.
455
+ const reason = new Error('Capture cancelled by the application');
456
+ const cancelled = await capturePanorama(engine, {signal: AbortSignal.abort(reason)})
457
+ .then(() => false, error => error === reason);
458
+ if (!cancelled) throw new Error('Capture did not preserve the abort reason');
459
+ engine.dispose(); canvas.remove();
460
+ ```
461
+
462
+ A reusable cube keeps its ownership across both display and linear captures:
463
+
464
+ ```ts
465
+ import {Engine} from '@margoengine/core';
466
+ import {CubeCamera} from '@margoengine/environment/cube-camera';
467
+ import {capturePanorama} from '@margoengine/cameras/panorama';
468
+ const canvas = document.body.appendChild(document.createElement('canvas'));
469
+ const engine = await Engine.create(canvas, {backend: 'webgpu'});
470
+ const cube = CubeCamera.attach(engine, {size: 64});
471
+ const linear = await capturePanorama(engine, {cube, width: 256, format: 'linear', yaw: Math.PI / 2});
472
+ console.log(linear.data instanceof Float32Array, linear.data.length);
473
+ cube.dispose(); engine.dispose(); canvas.remove();
474
+ ```
475
+
476
+ ## Non-XR stereo: optional /stereo
477
+
478
+ StereoRig derives two parallel off-axis cameras from a source Camera without
479
+ changing its pose or projection. eyeSeparation defaults to 0.064 world units
480
+ (normally metres) and must be finite/nonnegative. focusDistance defaults to the
481
+ camera-to-target distance and must be positive, with Infinity allowed. It is the
482
+ zero-parallax distance, not camera convergence by toe-in. With an orthographic
483
+ source the projection has no binocular depth disparity. Call rig.update(source,
484
+ aspect) after source changes; aspect may be a function read after canvas resize.
485
+ rig.left and rig.right are reusable camera objects, not separately owned devices.
486
+
487
+ StereoOutput owns the rig, two RGBA8 eye textures, uniforms and packing pipeline.
488
+ Construct it with an engine and call render(deltaSeconds) from the application's
489
+ frame loop. Do not also call engine.start or engine.render for that same frame.
490
+ Scene/plugin animation advances once for the eye pair; scene rendering runs twice.
491
+ The default camera/scene are engine.camera/engine.scene; layers defaults to the
492
+ source camera's layer mask. Explicit camera, scene and layers override those choices.
493
+
494
+ mode defaults side-by-side; top-bottom, anaglyph and parallax-barrier are also
495
+ available. The packed modes give each eye half the corresponding canvas dimension
496
+ (rounded up); other modes use full-size eye images. Anaglyph uses the documented
497
+ Dubois red/cyan matrix in linear light with per-eye clipping; glasses and display
498
+ color affect its perceived result. parallax-barrier interleaves physical drawing-
499
+ buffer columns by default, or rows with barrierAxis. barrierPhase 0 (default) or 1
500
+ sets left-eye stripe parity. swapEyes defaults false. These are non-XR display
501
+ layouts; the application supplies any display alignment or viewing hardware.
502
+
503
+ Options are mutable and validated on render. Eye targets rebuild after canvas size,
504
+ packing size, device or output format changes. StereoOutput requires WebGPU or the
505
+ full compatibility layer, and does not attach a clock/plugin or dispose the engine.
506
+ dispose() releases its eye textures/uniforms and is idempotent; subsequent render
507
+ throws a coded disposed error. Do not reuse a disposed output.
508
+
509
+ ```ts
510
+ import {Engine, box, PbrMaterial} from '@margoengine/core';
511
+ import {StereoOutput, StereoRig} from '@margoengine/cameras/stereo';
512
+ const canvas = document.body.appendChild(document.createElement('canvas'));
513
+ canvas.width = 640; canvas.height = 320;
514
+ const engine = await Engine.create(canvas, {backend: 'webgpu'});
515
+ engine.createMesh().setGeometry(box()).setMaterial(new PbrMaterial());
516
+ const rig = new StereoRig({eyeSeparation: 0.064, focusDistance: 4});
517
+ rig.update(engine.camera, canvas.width / canvas.height / 2);
518
+ console.log(rig.left.position, rig.right.position);
519
+ const output = new StereoOutput(engine, {mode: 'side-by-side', eyeSeparation: 0.064, focusDistance: 4});
520
+ // The application owns this frame loop. Delta is seconds, measured by that loop.
521
+ const frame = (delta: number) => output.render(delta);
522
+ for (const mode of ['side-by-side', 'top-bottom', 'anaglyph', 'parallax-barrier'] as const) {
523
+ output.options.mode = mode;
524
+ frame(1 / 60);
525
+ }
526
+ output.options.mode = 'parallax-barrier';
527
+ output.options.barrierAxis = 'rows';
528
+ output.options.barrierPhase = 1;
529
+ output.options.swapEyes = true;
530
+ frame(1 / 60);
531
+ output.dispose(); engine.dispose(); canvas.remove();
532
+ ```
533
+
534
+ ## Pyramid hologram: optional /hologram
535
+
536
+ A see-through pyramid stood on a flat screen (a "Pepper's ghost" display) shows a floating object when the screen
537
+ draws four views of it in a cross: the front view in the bottom slot, the back view in the top slot and the side
538
+ views in the left and right slots. Each face is a half-mirror over its wedge of the screen, so its reflection is
539
+ mirrored and a point farther from the centre appears higher.
540
+
541
+ HologramRig derives four cameras from a source Camera: front at the source position, then back, right and left a
542
+ quarter turn apart about camera.up, all looking at the source target from the same height. distance (world units)
543
+ defaults to the source camera's distance to its target. The source pose and projection are not changed; views are
544
+ square, and an orthographic source stays orthographic.
545
+
546
+ HologramOutput owns the rig, four RGBA8 view textures and the layout pass. Construct it with an engine and call
547
+ render(deltaSeconds) from the application's frame loop instead of engine.render. Animation and plugins advance once
548
+ for the four views. Options (all mutable, validated on render):
549
+
550
+ | Option | Default | Meaning |
551
+ | --- | --- | --- |
552
+ | camera | engine.camera | Source camera; its target is the centre, its side the front |
553
+ | scene | engine.scene | Scene drawn in all four views |
554
+ | layers | the source camera's mask | Layer mask for all four views |
555
+ | distance | source distance to target | Camera distance from the target, > 0 |
556
+ | gap | 0.2 | Side of the empty centre square, a fraction of the canvas's smaller side, in [0, 1) |
557
+ | views | HOLOGRAM_VIEWS | Per side `{rotation: 0 \| 90 \| 180 \| 270, mirror: boolean}`; missing fields keep the default |
558
+ | background | '#000000' | Clear colour of each view, or false to keep the scene's background |
559
+
560
+ Each view is (1 - gap) / 2 of the smaller canvas side. Below gap 1/3 neighbouring slots meet along the diagonals and
561
+ each view is cut to its own wedge, the shape a pyramid face covers. Everything outside the slots is black, which a
562
+ face does not reflect. HOLOGRAM_VIEWS mirrors every view and turns its top away from the centre (front 180, back 0,
563
+ left 90, right 270 degrees counter-clockwise), which suits a pyramid standing on the screen; for a screen held above
564
+ the pyramid, turn each view by 180 degrees. dispose() releases the textures and is idempotent; render after it
565
+ throws a coded disposed error. WebGPU or the full WebGL2 compatibility layer.
566
+
567
+ ```ts
568
+ import {Engine, box, PbrMaterial} from '@margoengine/core';
569
+ import {HologramOutput, HologramRig} from '@margoengine/cameras/hologram';
570
+ const canvas = document.body.appendChild(document.createElement('canvas'));
571
+ canvas.width = 480; canvas.height = 480;
572
+ const engine = await Engine.create(canvas, {backend: 'webgpu', camera: {position: [0, 1, 4], target: [0, 0, 0]}});
573
+ engine.createMesh().setGeometry(box()).setMaterial(new PbrMaterial({color: '#4af'}));
574
+ const rig = new HologramRig({distance: 5});
575
+ rig.update(engine.camera);
576
+ console.log(rig.front.position, rig.right.position);
577
+ using output = new HologramOutput(engine, {gap: 0.25, distance: 5});
578
+ output.render(1 / 60);
579
+ // Show the front view upright and unmirrored, for a check without the pyramid.
580
+ output.options.views = {front: {rotation: 0, mirror: false}};
581
+ output.render(1 / 60);
582
+ engine.dispose(); canvas.remove();
583
+ ```
584
+
585
+ Sources (public descriptions only): J. H. Pepper, "The True History of the Ghost; and All About Metempsychosis",
586
+ 1890 (the half-mirror illusion, with H. Dircks); patent WO2017196399A1, "Hologram pyramid", 2017,
587
+ https://patents.google.com/patent/WO2017196399A1/en (four views of one object around a centre square, one per face);
588
+ University of Arizona Wyant College of Optical Sciences, "POPtics Pepper's Pyramid",
589
+ https://wp.optics.arizona.edu/oscoutreach/poptics-peppers-pyramid/ (four faces so the image is seen from all sides).
590
+
591
+ - npm run test:browser:hologram --workspace @margoengine/cameras checks the four views against each camera drawn
592
+ alone, every slot's turn and mirror, the wedge cut, gap, distance, one update per frame, resize, device restore
593
+ and disposal. Add -- --compat for the WebGL2 compatibility layer.
594
+
595
+ ## Attachment ownership and validation
596
+
597
+ CameraProjection.attach(engine) registers the projection with the engine, while
598
+ new CameraProjection(options).attach(camera) only owns that camera's projection/up
599
+ hooks. The latter needs caller updates for fitting. dispose restores the camera's
600
+ plain world-up field and removes its owned project/fixedOrthographic hooks. It does
601
+ not destroy a camera or engine. Disposing the owning engine removes its registered
602
+ plugins. FloatingOrigin.dispose clears root tracking and listeners without undoing rebased
603
+ coordinates. onRebase returns an unsubscribe function for shorter subscriptions.
604
+ WideAngle/WideAngleCube keep their owning scene registration and borrowed cube
605
+ ownership as shown at the start of this README. Use Symbol.dispose/using for
606
+ lifetimes scoped to a block where the target runtime supports explicit disposal.
607
+
608
+ Run from the repository root after npm run build:packages:
609
+
610
+ - npm run test:gpu --workspace @margoengine/cameras checks projection, picking,
611
+ view-offset and wide-angle rendering on a real adapter.
612
+ - npm run test:browser:panorama --workspace @margoengine/cameras checks spherical
613
+ orientation, PNG pixels, float output, borrowed cubes, limits, abort and cleanup.
614
+ - npm run test:browser:stereo --workspace @margoengine/cameras checks geometry,
615
+ packing/stripe parity, layers, resize, disposal and device restoration.
616
+ Repeat these three commands with -- --compat for the full WebGL2 compatibility
617
+ layer; they use the same scenes and assertions.
618
+
619
+ These correctness fixtures make no speed or cross-device quality claim. Works with
620
+ the [J6 public CAD-format viewer](../../docs/integration-engineering.md), including
621
+ its orthographic camera and navigation-profile attachment/restoration checks.
@@ -0,0 +1,7 @@
1
+ //#region ../shared/errors.js
2
+ var e = (e, t) => Object.assign(Error(t), {
3
+ name: "MargoError",
4
+ code: e
5
+ }), t = (e, t) => `${e}; see https://margoengine.com/errors#${t}`, n = (e, n) => RangeError(t(e, n));
6
+ //#endregion
7
+ export { n, e as t };