@margoengine/cinematic 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/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2026 Scott Campbell
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/NOTICE ADDED
@@ -0,0 +1,4 @@
1
+ Margo Engine
2
+ Copyright 2026 Scott Campbell
3
+
4
+ This product includes Margo Engine (https://margoengine.com) by Scott Campbell.
package/README.md CHANGED
@@ -1,3 +1,321 @@
1
- # Temporary Holding Version
1
+ # @margoengine/cinematic
2
+
3
+ Virtual cameras with priorities and blends, framing, dolly tracks, group framing, camera noise, confiners and focus tracking, on top of damped follow, look-at and shake.
4
+
5
+ `Cinematic` and `CameraBrain` detach from the scene where their actual plugin
6
+ instance was registered. Direct disposal, removing the owning plugin or scene,
7
+ and engine disposal all release the registration. Repeated disposal preserves
8
+ same-name replacements. Both plugins can attach to another scene after disposal;
9
+ later cleanup follows that new registration.
10
+
11
+ Import `margoengine/cinematic` from the `margoengine` package, or `@margoengine/cinematic` 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).
12
+
13
+ `rig.setOrbitOffset(yaw, pitch, distance, height = 0)` writes the retained camera
14
+ offset in place from orbit angles (no new vector is created). The sandbox uses this
15
+ public method after its shared locomotion step.
16
+
17
+ A virtual camera with analytically integrated critically damped follow and look-at springs plus additive screen shake.
18
+
19
+ ```ts
20
+ import {Cinematic} from 'margoengine/cinematic';
21
+ import {Engine} from 'margoengine/core';
22
+ import {boxGeometry} from 'margoengine/geometry';
23
+ import {PbrMaterial, createMesh} from 'margoengine/materials';
24
+ const engine = await Engine.create(document.querySelector('canvas')!);
25
+ const player = createMesh(engine, boxGeometry(0.5, 1.8, 0.5), new PbrMaterial()).root;
26
+ const rig = Cinematic.attach(engine, {offset: [0,3,6], damping: 6});
27
+ rig.follow(player);
28
+ rig.shake(0.2, 0.4);
29
+ ```
30
+
31
+ follow accepts a live mesh from the attached engine or a world-position tuple. Mesh targets use world transforms. Shake amplitude is in world units and duration is seconds; it does not alter the settled spring position. The frame plugin owns camera position/target while attached, so disable competing camera controls. dispose detaches it.
32
+
33
+ Film time: `rig.advanceTime(delta)` is one frame of the rig with no draw (springs, shake, `rig.time`), so `seek` from
34
+ `@margoengine/cutscene/seek` starts a film scene where a continuous run's follow and shake are. A `CameraNoise` stage
35
+ moves its clock with `noise.advanceTime(delta)`; pass it to `seek` as an `extra` clock when no attached `CameraBrain`
36
+ runs it as a stage (the brain's own clock steps its stages).
37
+
38
+ Scope the rig with `using` (it calls `dispose()` and returns the camera to your controls):
39
+
40
+ ```ts
41
+ import {Cinematic} from 'margoengine/cinematic';
42
+ import {Engine} from 'margoengine/core';
43
+ import {Physics} from 'margoengine/physics';
44
+ const engine = await Engine.create(document.querySelector('canvas')!);
45
+ await Physics.load();
46
+ const physics = Physics.attach(engine);
47
+ {
48
+ using rig = Cinematic.attach(engine, {offset: [0, 3, 6]});
49
+ rig.follow([0, 1.6, 0]);
50
+ rig.update(1 / 60);
51
+ }
52
+ ```
53
+
54
+ Errors name their fix: a bad argument throws `RangeError` or `TypeError` (for example `Invalid camera delta; pass a finite delta of 0 or more seconds`), and attaching a rig twice throws `MargoError` with code `attached`.
55
+
56
+ Set `ground: (x,z) => height` to keep the camera arm above a CPU heightfield.
57
+ `clearance` defaults to 0.65 world units. The rig checks both its desired arm and
58
+ the resulting damped/shaken camera, without changing your requested `offset`.
59
+ For a below-target orbit, it raises the rendered aim point by as much as the ground
60
+ lifted the camera, so terrain clearance preserves upward look instead of forcing the
61
+ view back down; shake and spring lag never move the aim point.
62
+ Six samples along each arm suit broad terrain; narrow ridges and buildings need
63
+ collision geometry. Heights must be finite. Ground handling is disabled by default.
64
+
65
+ Walls and ceilings: set `collide: (origin, direction, distance) => hitDistance | null`. Each frame
66
+ the rig asks for the first obstacle along the arm from the look-at point to the (damped, shaken,
67
+ ground-lifted) camera; on a hit the camera moves in at once to `clearance` short of it, and once the
68
+ arm is clear it eases back out at the follow damping. The spring state and your `offset` are
69
+ unchanged. The arrays passed in are reused each frame. Any scene query fits, for example a sphere
70
+ cast against the physics world (so the near plane does not clip into the wall):
71
+
72
+ ```ts
73
+ const rig = Cinematic.attach(engine, {offset: [0, 3, 6], clearance: 0.3,
74
+ collide: (o, d, max) => physics.shapeCast({shape: 'sphere', radius: 0.2}, [o[0], o[1], o[2]], [0, 0, 0, 1], [d[0], d[1], d[2]], {maxDistance: max, excludeDynamic: true})?.distance});
75
+ ```
76
+
77
+ or `@margoengine/bvh`'s Raycaster (`firstHitOnly`, `far = max`) over the level. Exclude the followed
78
+ character from the query, and start it above the floor if the look-at point sits on it (the arm
79
+ starts at the target, usually the character's feet).
80
+
81
+ ## Camera priorities and blends
82
+
83
+ `@margoengine/cinematic/brain` runs many virtual cameras and shows one. Every enabled `VirtualCamera` keeps moving; the `CameraBrain` puts the highest `priority` on screen and blends when that changes. Raise a priority to take the shot:
84
+
85
+ ```ts
86
+ import {CameraBrain} from 'margoengine/cinematic/brain';
87
+ import {Engine} from 'margoengine/core';
88
+ const engine = await Engine.create(document.querySelector('canvas')!);
89
+ const brain = CameraBrain.attach(engine, {
90
+ blend: {duration: 1.5},
91
+ rules: [{from: 'wide', to: 'boss', duration: 0}],
92
+ });
93
+ brain.add({name: 'wide', priority: 10, position: [0, 8, 20], target: [0, 1, 0], fov: 50});
94
+ const boss = brain.add({name: 'boss', priority: 0, position: [3, 2, 6], target: [0, 2, 0], fov: 35});
95
+ brain.on('change', ({from, to}) => console.log(from?.name, 'to', to.name));
96
+ boss.priority = 20; // The next frame cuts to it, by the rule. Set it back and it blends out over 1.5 s.
97
+ ```
98
+
99
+ | Option | Default | Meaning |
100
+ | --- | --- | --- |
101
+ | `blend` | `{duration: 1}` | Used when no rule matches. `duration` in seconds, 0 is a cut; `ease` takes and gives 0..1 (any tween easing), default smoothstep; `style` `'direct'` moves straight across, `'orbit'` swings around the subject. |
102
+ | `rules` | none | `{from, to, ...blend}` with camera names or `'*'`. The exact pair wins, then `from` to `'*'`, `'*'` to `to`, `'*'` to `'*'`. |
103
+ | `camera` | `engine.camera` | The camera written. |
104
+ | `aspect` | the canvas's | Width / height, read by stages. |
105
+ | `name` | `'cinematic-brain'` | Plugin name, so each view of a split screen can have a brain. |
106
+
107
+ On a tie the camera on screen stays; with none on screen the one added last wins. A switch in the middle of a blend starts from what is on screen, and every camera in a blend keeps moving. `brain.cut()` ends a blend now. `camera.enabled = false` takes a camera out of the running and stops its work; its stages start fresh when it comes back.
108
+
109
+ A camera starts each frame from its `base` pose and runs its `stages` in order; `brain.stages` run after them on the blended pose. A stage is a function `(pose, delta, context) => void` or an object with `update` and `reset`. `rigStage` makes a `Cinematic` rig a stage, so the spring follow of this package drives a virtual camera. Do not attach that rig to the engine:
110
+
111
+ ```ts
112
+ import {Cinematic} from 'margoengine/cinematic';
113
+ import {CameraBrain, rigStage} from 'margoengine/cinematic/brain';
114
+ const brain = new CameraBrain();
115
+ const rig = new Cinematic({offset: [0, 3, 6]});
116
+ rig.follow([0, 1, 0]);
117
+ brain.add({name: 'follow', stages: [rigStage(rig)]});
118
+ console.log(brain.update(1 / 60).position);
119
+ ```
120
+
121
+ Film time: `brain.advanceTime(delta)` is one update with no listener call (the cameras and their stages, the blend, `brain.stages` and the camera write), so `seek` from `@margoengine/cutscene/seek` starts a film scene where a continuous run's blend, camera moves and focus pulls are. A live `update` sends its `change` and `blended` events after its step, so a listener reads that frame's pose; the steps a seek replays send none.
122
+
123
+ ```ts
124
+ import {CameraBrain} from 'margoengine/cinematic/brain';
125
+ const brain = new CameraBrain({camera: {position: [0, 0, 0], target: [0, 0, 0], up: [0, 1, 0], fov: 60}});
126
+ brain.add({name: 'wide', position: [0, 4, 12]});
127
+ for (let step = 0; step < 600; step++) brain.advanceTime(1 / 60);
128
+ console.log(brain.live?.name, brain.pose.position);
129
+ ```
130
+
131
+ Cutscenes have their own timed cameras in `@margoengine/cutscene/shots`; the brain is for play, where what happens decides the shot.
132
+
133
+ ## Framing composer
134
+
135
+ `FramingComposer` keeps a subject on a chosen spot of the screen the way a camera operator does: small moves leave the picture still, bigger ones are caught up with, and the subject never leaves the frame. It is a stage, so it goes after whatever places the camera. It only turns the camera:
136
+
137
+ ```ts
138
+ import {CameraBrain} from 'margoengine/cinematic/brain';
139
+ import {FramingComposer} from 'margoengine/cinematic/composer';
140
+ import {Engine} from 'margoengine/core';
141
+ import {boxGeometry} from 'margoengine/geometry';
142
+ import {PbrMaterial, createMesh} from 'margoengine/materials';
143
+ const engine = await Engine.create(document.querySelector('canvas')!);
144
+ const player = createMesh(engine, boxGeometry(0.5, 1.8, 0.5), new PbrMaterial()).root;
145
+ const brain = CameraBrain.attach(engine);
146
+ brain.add({
147
+ position: [0, 4, 12],
148
+ stages: [new FramingComposer(player, {screen: [0.4, 0.6], deadZone: [0.15, 0.1], lookahead: 0.4})],
149
+ });
150
+ ```
151
+
152
+ The target is a mesh, a world point or a function giving one. Sizes are shares of the screen, and `screen` counts from the top left.
153
+
154
+ | Option | Default | Meaning |
155
+ | --- | --- | --- |
156
+ | `screen` | `[0.5, 0.5]` | Where the subject sits. `[1 / 3, 0.5]` is the rule of thirds. |
157
+ | `deadZone` | `[0.1, 0.1]` | Full width and height of the box around `screen` where the camera does not move. |
158
+ | `softZone` | `[0.8, 0.8]` | The box the subject never leaves. Between the two the camera catches up. |
159
+ | `damping` | `4` | Catch-up rate in 1/seconds, or `[horizontal, vertical]`. Higher is stiffer. Any frame rate gives the same motion. |
160
+ | `lookahead` | `0` | Seconds to aim ahead of the subject along its velocity. |
161
+ | `lookaheadSmoothing` | `6` | How fast the measured velocity follows, in 1/seconds. Lower is calmer. |
162
+ | `lookaheadVertical` | `true` | Turn it off for a platformer, so a jump does not nod the camera. |
163
+
164
+ `composer.onScreen` says where the subject is, and `composer.reset()` snaps it back to `screen`, as after a teleport. The camera's `reset()` does the same for all its stages.
165
+
166
+ ## Dolly tracks
167
+
168
+ `DollyTrack` puts the camera on a rail: any `Spline` from `@margoengine/splines`. Give it a target and the cart goes to the point of the track nearest that target, so the camera keeps pace with the subject without keyframes. It is a stage and goes first; aim afterwards with `FramingComposer`, or let `lookAlong` look down the track.
169
+
170
+ ```ts
171
+ import {CameraBrain} from 'margoengine/cinematic/brain';
172
+ import {FramingComposer} from 'margoengine/cinematic/composer';
173
+ import {DollyTrack} from 'margoengine/cinematic/dolly';
174
+ import {Engine} from 'margoengine/core';
175
+ import {boxGeometry} from 'margoengine/geometry';
176
+ import {PbrMaterial, createMesh} from 'margoengine/materials';
177
+ import {Spline} from 'margoengine/splines';
178
+ const engine = await Engine.create(document.querySelector('canvas')!);
179
+ const runner = createMesh(engine, boxGeometry(0.5, 1.8, 0.5), new PbrMaterial()).root;
180
+ const rail = new Spline([[-20, 3, 8], [0, 4, 10], [20, 3, 8]]);
181
+ const brain = CameraBrain.attach(engine);
182
+ brain.add({stages: [new DollyTrack(rail, {target: runner, lead: 2}), new FramingComposer(runner)]});
183
+ ```
184
+
185
+ | Option | Default | Meaning |
186
+ | --- | --- | --- |
187
+ | `target` | none | A mesh, point or function. Without one the cart stays at `position`; write `dolly.position` to move it. |
188
+ | `position` | `0`, or nearest to `target` | Start, in world units along the track. |
189
+ | `lead` | `0` | Stay this far ahead of the nearest point; below 0 is behind. |
190
+ | `damping` | `4` | Catch-up rate in 1/seconds. |
191
+ | `window` | whole track | Search only this far either side of the cart. Set it when the track passes close to itself. |
192
+ | `lookAlong` | `false` | Look down the track. |
193
+
194
+ A closed track wraps and the cart takes the short way round; an open one stops at its ends. `dolly.reset()` puts the cart back on the subject at once. The tests use generated curves as a stand-in for a track from a real level.
195
+
196
+ ## Group framing
197
+
198
+ `GroupFraming` keeps several subjects in one shot. It aims at their centre and moves or zooms until all of them fit. The angle of the shot comes from the pose, so set that with the camera's `position` and `target`, or an earlier stage:
199
+
200
+ ```ts
201
+ import {CameraBrain} from 'margoengine/cinematic/brain';
202
+ import {GroupFraming} from 'margoengine/cinematic/group';
203
+ import {Engine} from 'margoengine/core';
204
+ import {boxGeometry} from 'margoengine/geometry';
205
+ import {PbrMaterial, createMesh} from 'margoengine/materials';
206
+ const engine = await Engine.create(document.querySelector('canvas')!);
207
+ const player = (x: number) => {
208
+ const mesh = createMesh(engine, boxGeometry(0.5, 1.8, 0.5), new PbrMaterial()).root;
209
+ mesh.setPosition([x, 0, 0]);
210
+ return mesh;
211
+ };
212
+ const brain = CameraBrain.attach(engine);
213
+ const group = new GroupFraming(
214
+ [{target: player(-4), radius: 1}, {target: player(4), radius: 1, weight: 2}],
215
+ {mode: 'both', maxDistance: 40},
216
+ );
217
+ brain.add({position: [0, 8, 14], target: [0, 1, 0], fov: 45, stages: [group]});
218
+ ```
219
+
220
+ | Option | Default | Meaning |
221
+ | --- | --- | --- |
222
+ | `mode` | `'dolly'` | `'dolly'` moves along the view; `'zoom'` stands still and changes the field of view; `'both'` moves, then zooms for what the distance limits left. |
223
+ | `padding` | `0.1` | Share of the screen kept clear at each side. |
224
+ | `minDistance`, `maxDistance` | `1`, `Infinity` | How near and far the camera goes from the centre. |
225
+ | `minFov`, `maxFov` | `10`, `100` | Limits of the zoom, in degrees. |
226
+ | `damping` | `4` | How fast the shot follows, in 1/seconds. |
227
+
228
+ A member is a mesh, a point, a function or `{target, radius, weight}`. `radius` is a sphere that stays in view; `weight` pulls the centre, and 0 leaves the member out. `group.members` can change at any time. `group.fits` is false when the limits stop the shot, and `group.center` can feed a `FramingComposer`: `new FramingComposer(() => group.center)`.
229
+
230
+ ## Noise profiles
231
+
232
+ `CameraNoise` makes a camera feel held, carried or driven. A profile is plain data, so it can live in a JSON file: bands of smooth noise on each axis, each with a `frequency` in hertz, the middle of its power, and an `amplitude` that is the most it can add. It is a stage and goes after the stages that aim:
233
+
234
+ ```ts
235
+ import {CameraBrain} from 'margoengine/cinematic/brain';
236
+ import {CameraNoise, handheld, type NoiseProfile} from 'margoengine/cinematic/noise';
237
+ const brain = new CameraBrain();
238
+ const shaky = new CameraNoise(handheld, {gain: 1.5, seed: 7});
239
+ brain.add({name: 'documentary', position: [0, 2, 6], target: [0, 1, 0], stages: [shaky]});
240
+
241
+ const boat: NoiseProfile = {
242
+ position: {y: [{frequency: 0.2, amplitude: 0.3}]},
243
+ rotation: {roll: [{frequency: 0.15, amplitude: 0.05}], pitch: [{frequency: 0.2, amplitude: 0.02}]},
244
+ };
245
+ brain.add({name: 'deck', position: [0, 3, 6], target: [0, 2, 0], stages: [new CameraNoise(boat)]});
246
+ console.log(brain.update(1 / 60).position);
247
+ ```
248
+
249
+ | Export | What it is |
250
+ | --- | --- |
251
+ | `handheld` | Slow sway of the arms and a little hand tremor near 8 Hz. |
252
+ | `walking` | The step up and down near 2 Hz, the sway of each leg at half that. |
253
+ | `vehicle` | Body bounce near 1 to 2 Hz and the buzz of the wheels near 12 Hz. |
254
+
255
+ | Option | Default | Meaning |
256
+ | --- | --- | --- |
257
+ | `gain` | `1` | Scales every amplitude. Change it at any time, or tween it to fade the noise. |
258
+ | `speed` | `1` | Scales every frequency. Tie it to a vehicle's speed. |
259
+ | `seed` | `0` | The same seed gives the same motion. |
260
+
261
+ `position` moves along the camera's own axes in world units; `rotation` is `pitch`, `yaw` and `roll` in radians. The motion is a function of time, so it does not change with the frame rate; set `noise.time` to replay a moment. The amplitudes of the presets were chosen by eye and their frequencies follow published ranges, so treat them as starting points. Keep a band below half the frame rate. For one short hit, use `Cinematic.shake`.
262
+
263
+ ## Confiner volumes
264
+
265
+ `CameraConfiner` keeps the camera inside a box or an area of the level, however it got out. The camera keeps looking at the same point. Put it last on a camera, after noise, or in `brain.stages`, where it holds blends between cameras too:
266
+
267
+ ```ts
268
+ import {CameraBrain} from 'margoengine/cinematic/brain';
269
+ import {CameraConfiner} from 'margoengine/cinematic/confine';
270
+ const brain = new CameraBrain();
271
+ brain.stages.push(new CameraConfiner({min: [-50, 0.5, -50], max: [50, 30, 50]}, {margin: 1}));
272
+ const room = new CameraConfiner(
273
+ {area: [[0, 0], [30, 0], [30, 30], [20, 30], [20, 10], [10, 10], [10, 30], [0, 30]], bottom: 1, top: 6},
274
+ {margin: 0.5},
275
+ );
276
+ const camera = brain.add({position: [15, 3, 25], target: [15, 2, 0], stages: [room]});
277
+ console.log(camera.update(1 / 60).position, room.clamped);
278
+ ```
279
+
280
+ | Shape | Meaning |
281
+ | --- | --- |
282
+ | `{min, max}` | A box, aligned to the world axes. |
283
+ | `{area, bottom, top}` | An outline of `[x, z]` points on the ground, convex or not, either way round, with optional height limits. |
284
+
285
+ `margin` (default 0) is the space kept from every wall. `confiner.clamped` says whether the last update moved the camera and `confiner.correction` how far. For walls between the camera and its subject use the `collide` option of `Cinematic`.
286
+
287
+ ## Focus tracking
288
+
289
+ `FocusTracker` is a focus puller and a zoom operator. It sets the pose's focus from a followed subject, measured along the view as a lens does, and with `size` it also sets the field of view that holds the subject at one size on screen. `focusOutput` goes in `brain.stages` and hands the focus to the lens, so a blend racks focus from one camera to the next:
290
+
291
+ ```ts
292
+ import {PhysicalCamera} from 'margoengine/cameras/physical';
293
+ import {CameraBrain} from 'margoengine/cinematic/brain';
294
+ import {FocusTracker, focusOutput} from 'margoengine/cinematic/lens';
295
+ const brain = new CameraBrain();
296
+ const physical = new PhysicalCamera({focalLength: 85, aperture: 1.8});
297
+ brain.stages.push(focusOutput({physical}));
298
+ const hero = [0, 1.6, 0] as const;
299
+ brain.add({position: [0, 1.6, 6], target: [0, 1.6, 0], stages: [new FocusTracker(hero, {size: 1.8, screenHeight: 0.6})]});
300
+ brain.update(1 / 60);
301
+ console.log(physical.focusDistance, brain.pose.fov);
302
+ ```
303
+
304
+ Pass `dof` as well to drive a `DOF` effect from `@margoengine/dof`.
305
+
306
+ | Option | Default | Meaning |
307
+ | --- | --- | --- |
308
+ | `focusDamping` | `6` | How fast focus follows, in 1/seconds. Lower is a slow rack. |
309
+ | `focusOffset` | `0` | Added to the distance, to focus on a face rather than the feet. |
310
+ | `minFocus` | `0.1` | Nearest focus. Keep it beyond the focal length. |
311
+ | `size` | none | Height of the subject in world units. Turns on the field of view. |
312
+ | `screenHeight` | `0.5` | Share of the screen height the subject fills. |
313
+ | `fovDamping` | `4` | How fast the field of view follows. |
314
+ | `minFov`, `maxFov` | `10`, `100` | Limits, in degrees. |
315
+
316
+ Keep `minFocus` above the lens's focal length: `DOF` refuses a focus at or inside it. Focus comes from the point you give it. To focus on whatever a pixel shows, use `Autofocus` from `@margoengine/dof/autofocus`.
317
+
318
+ Apache-2.0. Optional, tree-shakable package; core peer: ^0.1.0 || ^1.0.0.
319
+
320
+ Build and unit tests: npm test --workspace @margoengine/cinematic
2
321
 
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.