@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.
@@ -0,0 +1,97 @@
1
+ //#region src/confine.ts
2
+ var e = class {
3
+ constructor(e, t = {}) {
4
+ this.clamped = !1, this.correction = 0, this.low = new Float64Array([
5
+ -Infinity,
6
+ -Infinity,
7
+ -Infinity
8
+ ]), this.high = new Float64Array([
9
+ Infinity,
10
+ Infinity,
11
+ Infinity
12
+ ]), this.orientation = 1, this.near = /* @__PURE__ */ new Float64Array(4), this.edge = -1;
13
+ let { margin: n = 0 } = t;
14
+ if (typeof e != "object" || !e) throw RangeError("Invalid confiner shape; pass a box {min, max} or an area {area}");
15
+ if (!(n >= 0 && n < Infinity)) throw RangeError("Invalid confiner margin; pass 0 or more");
16
+ if (this.margin = n, "area" in e) {
17
+ let { area: t, bottom: r = -Infinity, top: i = Infinity } = e;
18
+ if (!Array.isArray(t) || t.length < 3) throw RangeError("Invalid confiner area; pass at least 3 [x, z] points");
19
+ let a = new Float64Array(t.length * 2);
20
+ t.forEach((e, t) => {
21
+ let n = e?.[0], r = e?.[1];
22
+ if (!(Number.isFinite(n) && Number.isFinite(r))) throw RangeError("Invalid confiner area; pass at least 3 [x, z] points, all finite");
23
+ a[t * 2] = n, a[t * 2 + 1] = r;
24
+ });
25
+ let o = 0;
26
+ for (let e = 0, n = t.length; e < n; e++) {
27
+ let t = (e + 1) % n;
28
+ o += a[e * 2] * a[t * 2 + 1] - a[t * 2] * a[e * 2 + 1];
29
+ }
30
+ if (!o) throw RangeError("Invalid confiner area; pass an outline with some area");
31
+ this.outline = a, this.orientation = Math.sign(o), this.low[1] = r + n, this.high[1] = i - n;
32
+ } else {
33
+ let { min: t, max: r } = e;
34
+ for (let e = 0; e < 3; e++) {
35
+ if (!(Number.isFinite(t?.[e]) && Number.isFinite(r?.[e]))) throw RangeError("Invalid confiner box; pass finite min and max corners");
36
+ this.low[e] = t[e] + n, this.high[e] = r[e] - n;
37
+ }
38
+ }
39
+ for (let e = 0; e < 3; e++) if (!(this.low[e] <= this.high[e])) throw RangeError("Invalid confiner bounds; each low side must be below its high side, margins included");
40
+ }
41
+ nearest(e, t) {
42
+ let n = this.outline, r = this.near, i = n.length / 2, a = Infinity;
43
+ for (let o = 0; o < i; o++) {
44
+ let s = (o + 1) % i, c = n[o * 2], l = n[o * 2 + 1], u = n[s * 2] - c, d = n[s * 2 + 1] - l, f = u * u + d * d, p = f ? Math.min(1, Math.max(0, ((e - c) * u + (t - l) * d) / f)) : 0, m = c + u * p, h = l + d * p, g = Math.hypot(e - m, t - h);
45
+ if (g < a && f) {
46
+ a = g, this.edge = o;
47
+ let e = Math.sqrt(f) * this.orientation;
48
+ r[0] = m, r[1] = h, r[2] = -d / e, r[3] = u / e;
49
+ }
50
+ }
51
+ return a;
52
+ }
53
+ meet(e, t) {
54
+ let n = this.outline, r = n.length / 2, i = (e) => {
55
+ let t = (e + 1) % r, i = n[t * 2] - n[e * 2], a = n[t * 2 + 1] - n[e * 2 + 1], o = Math.hypot(i, a) * this.orientation, s = -a / o, c = i / o;
56
+ return [
57
+ s,
58
+ c,
59
+ s * n[e * 2] + c * n[e * 2 + 1] + this.margin
60
+ ];
61
+ }, [a, o, s] = i(e), [c, l, u] = i(t), d = a * l - o * c;
62
+ return Math.abs(d) < 1e-9 ? !1 : (this.near[0] = (s * l - u * o) / d, this.near[1] = (a * u - c * s) / d, !0);
63
+ }
64
+ inside(e, t) {
65
+ let n = this.outline, r = n.length / 2, i = !1;
66
+ for (let a = 0, o = r - 1; a < r; o = a++) {
67
+ let r = n[a * 2 + 1], s = n[o * 2 + 1];
68
+ r > t != s > t && e < n[a * 2] + (t - r) / (s - r) * (n[o * 2] - n[a * 2]) && (i = !i);
69
+ }
70
+ return i;
71
+ }
72
+ holdArea(e) {
73
+ let t = this.near, n = this.margin, r = n * .999999999, i = e[0], a = e[2], o = -1, s = -1;
74
+ for (let c = 0; c < 8; c++) {
75
+ let c = this.inside(i, a), l = this.nearest(i, a);
76
+ if (c && l >= r) {
77
+ e[0] = i, e[2] = a;
78
+ return;
79
+ }
80
+ let u = this.edge, d = u === s && u !== o && this.meet(u, o);
81
+ if (s = o, o = u, d) {
82
+ i = t[0], a = t[1];
83
+ continue;
84
+ }
85
+ let f = l > 1e-12 ? (c ? 1 : -1) / l : 0, p = f ? (i - t[0]) * f : t[2], m = f ? (a - t[1]) * f : t[3];
86
+ i = t[0] + p * n, a = t[1] + m * n;
87
+ }
88
+ this.inside(i, a) || (this.nearest(i, a), i = t[0], a = t[1]), e[0] = i, e[2] = a;
89
+ }
90
+ update(e) {
91
+ let { position: t } = e, n = t[0], r = t[1], i = t[2];
92
+ for (let e = 0; e < 3; e++) t[e] = Math.min(this.high[e], Math.max(this.low[e], t[e]));
93
+ this.outline && this.holdArea(t), this.correction = Math.hypot(t[0] - n, t[1] - r, t[2] - i), this.clamped = this.correction > 0;
94
+ }
95
+ };
96
+ //#endregion
97
+ export { e as CameraConfiner };
@@ -0,0 +1,59 @@
1
+ import type { Spline } from '@margoengine/splines';
2
+ import type { CameraPose } from './brain.js';
3
+ import { type CameraTarget } from './target.js';
4
+ export type { CameraTarget } from './target.js';
5
+ /** Settings of a {@link DollyTrack}. Distances are world units along the track. */
6
+ export interface DollyTrackOptions {
7
+ /** What the cart keeps pace with. Without one the cart stays at `position`, for you to move. Default none. */
8
+ target?: CameraTarget;
9
+ /** Where the cart starts, in world units from the start of the track. Default 0, or the nearest point to `target`. */
10
+ position?: number;
11
+ /** Stay this far ahead of the nearest point (behind when below 0). Finite. Default 0. */
12
+ lead?: number;
13
+ /** How fast the cart catches up, in 1/seconds, above 0. Default 4. */
14
+ damping?: number;
15
+ /**
16
+ * Search only this far either side of the cart, above 0. Set it on a track that passes close to itself, so the cart
17
+ * follows the subject along the rail instead of jumping across. Default the whole track.
18
+ */
19
+ window?: number;
20
+ /** Look down the track instead of at the pose's target. Default false. */
21
+ lookAlong?: boolean;
22
+ }
23
+ /**
24
+ * A stage that puts the camera on a spline track. Put it first, before the stages that aim. With a `target` the cart
25
+ * follows that target's progress along the track; on a closed track it takes the short way round.
26
+ */
27
+ export declare class DollyTrack {
28
+ readonly track: Spline;
29
+ /** What the cart keeps pace with; change it at any time. */
30
+ target?: CameraTarget;
31
+ /** Where the cart is, in world units from the start of the track. Write it to move the cart by hand. */
32
+ position: number;
33
+ /** Stay this far ahead of the nearest point; change it at any time. */
34
+ lead: number;
35
+ private readonly length;
36
+ private readonly damping;
37
+ private readonly window;
38
+ private readonly lookAlong;
39
+ private readonly start;
40
+ private readonly subject;
41
+ private readonly point;
42
+ private readonly ahead;
43
+ private readonly closest;
44
+ private started;
45
+ /** @throws RangeError for a value outside what {@link DollyTrackOptions} allows, or a track of no length. */
46
+ constructor(track: Spline, options?: DollyTrackOptions);
47
+ /** Length of the track in world units. */
48
+ get trackLength(): number;
49
+ /** Wraps a distance onto a closed track and stops it at the ends of an open one. */
50
+ private fit;
51
+ private gap;
52
+ private squared;
53
+ /** The nearest point of the track within `window` of the cart: the best of even samples, refined by golden section. */
54
+ private nearby;
55
+ /** Forgets the cart's place: the next update starts it where the subject is, or where it was built to start. */
56
+ reset(): void;
57
+ /** Stage hook. @throws RangeError for a bad target or a `position` that is not finite. */
58
+ update(pose: CameraPose, delta: number): void;
59
+ }
package/dist/dolly.js ADDED
@@ -0,0 +1,64 @@
1
+ import { t as e } from "./target-CZNe0IXh.js";
2
+ import { closestPointOnSpline as t } from "@margoengine/splines/closest";
3
+ //#region src/dolly.ts
4
+ var n = 32, r = 40, i = (Math.sqrt(5) - 1) / 2, a = class {
5
+ constructor(e, t = {}) {
6
+ this.track = e, this.subject = /* @__PURE__ */ new Float64Array(3), this.point = /* @__PURE__ */ new Float64Array(3), this.ahead = /* @__PURE__ */ new Float64Array(3), this.closest = {
7
+ t: 0,
8
+ arc: 0,
9
+ point: /* @__PURE__ */ new Float64Array(3),
10
+ distance: 0
11
+ }, this.started = !1;
12
+ let { target: n, position: r, lead: i = 0, damping: a = 4, window: o = Infinity, lookAlong: s = !1 } = t;
13
+ if (this.length = e.length, !(this.length > 0)) throw RangeError("Invalid dolly track; pass a spline of some length");
14
+ if (r !== void 0 && !Number.isFinite(r)) throw RangeError("Invalid dolly position; pass a finite distance along the track");
15
+ if (!Number.isFinite(i)) throw RangeError("Invalid dolly lead; pass a finite distance");
16
+ if (!(a > 0 && a < Infinity)) throw RangeError("Invalid dolly damping; pass a rate above 0");
17
+ if (!(o > 0)) throw RangeError("Invalid dolly window; pass a distance above 0");
18
+ this.target = n, this.start = this.fit(r ?? 0), this.position = this.start, this.lead = i, this.damping = a, this.window = o, this.lookAlong = s, this.started = r !== void 0;
19
+ }
20
+ get trackLength() {
21
+ return this.length;
22
+ }
23
+ fit(e) {
24
+ return this.track.closed ? (e % this.length + this.length) % this.length : Math.min(this.length, Math.max(0, e));
25
+ }
26
+ gap(e, t) {
27
+ let n = t - e;
28
+ return this.track.closed && (n %= this.length, n > this.length / 2 ? n -= this.length : n < -this.length / 2 && (n += this.length)), n;
29
+ }
30
+ squared(e) {
31
+ let t = this.point, n = this.subject;
32
+ return this.track.atDistance(this.fit(e), t), (t[0] - n[0]) ** 2 + (t[1] - n[1]) ** 2 + (t[2] - n[2]) ** 2;
33
+ }
34
+ nearby() {
35
+ let e = this.window, t = this.track.closed, a = t ? this.position - e : Math.max(0, this.position - e), o = t ? this.position + e : Math.min(this.length, this.position + e), s = (o - a) / n, c = a, l = Infinity;
36
+ for (let e = 0; e <= n; e++) {
37
+ let t = a + s * e, n = this.squared(t);
38
+ n < l && (l = n, c = t);
39
+ }
40
+ let u = Math.max(t ? -Infinity : a, c - s), d = Math.min(t ? Infinity : o, c + s), f = d - i * (d - u), p = u + i * (d - u), m = this.squared(f), h = this.squared(p);
41
+ for (let e = 0; e < r; e++) m < h ? (d = p, p = f, h = m, f = d - i * (d - u), m = this.squared(f)) : (u = f, f = p, m = h, p = u + i * (d - u), h = this.squared(p));
42
+ let g = (u + d) / 2;
43
+ return l < this.squared(g) ? c : g;
44
+ }
45
+ reset() {
46
+ this.position = this.start, this.started = !1;
47
+ }
48
+ update(n, r) {
49
+ if (!Number.isFinite(this.position) || !Number.isFinite(this.lead)) throw RangeError("Invalid dolly position; pass a finite distance along the track");
50
+ if (this.target !== void 0) {
51
+ e(this.target, this.subject);
52
+ let n = !this.started || this.window >= this.length, i = this.fit((n ? t(this.track, this.subject, {}, this.closest).arc : this.nearby()) + this.lead);
53
+ this.position = this.started ? this.fit(this.position + this.gap(this.position, i) * (1 - Math.exp(-this.damping * r))) : i, this.started = !0;
54
+ } else this.position = this.fit(this.position);
55
+ let i = this.point, a = this.ahead;
56
+ if (this.track.atDistance(this.position, i), n.position[0] = i[0], n.position[1] = i[1], n.position[2] = i[2], this.lookAlong) {
57
+ let e = Math.min(this.length / 1e3, .01), t = !this.track.closed && this.position + e > this.length ? -1 : 1;
58
+ this.track.atDistance(this.fit(this.position + t * e), a);
59
+ for (let r = 0; r < 3; r++) n.target[r] = i[r] + (a[r] - i[r]) * t * (1 / e);
60
+ }
61
+ }
62
+ };
63
+ //#endregion
64
+ export { a as DollyTrack };
@@ -0,0 +1,72 @@
1
+ import type { CameraPose, StageContext } from './brain.js';
2
+ import { type CameraTarget } from './target.js';
3
+ export type { CameraTarget } from './target.js';
4
+ /** One subject of a group. */
5
+ export interface GroupMember {
6
+ target: CameraTarget;
7
+ /** Radius of a sphere around the point that must stay in view, in world units, 0 or more. Default 0. */
8
+ radius?: number;
9
+ /** Pull on the centre of the shot, 0 or more; 0 leaves the member out of the shot altogether. Default 1. */
10
+ weight?: number;
11
+ }
12
+ /** Settings of a {@link GroupFraming}. */
13
+ export interface GroupFramingOptions {
14
+ /**
15
+ * `'dolly'` (default) moves the camera along its view. `'zoom'` keeps the camera where it stands, aims at the group and
16
+ * changes the field of view. `'both'` moves within its limits, then zooms for the rest.
17
+ */
18
+ mode?: 'dolly' | 'zoom' | 'both';
19
+ /** Share of the screen kept clear at each side, 0 or more and below 0.5. Default 0.1. */
20
+ padding?: number;
21
+ /** Nearest the camera comes to the centre of the group, above 0. Default 1. */
22
+ minDistance?: number;
23
+ /** Farthest it goes, at least `minDistance`; may be Infinity. Default Infinity. */
24
+ maxDistance?: number;
25
+ /** Narrowest field of view in degrees. Default 10. */
26
+ minFov?: number;
27
+ /** Widest field of view in degrees, at least `minFov`, below 180. Default 100. */
28
+ maxFov?: number;
29
+ /** How fast the shot follows, in 1/seconds, above 0. Default 4. */
30
+ damping?: number;
31
+ }
32
+ /**
33
+ * A stage that keeps several subjects in view. It aims at their weighted centre and moves or zooms until all of them
34
+ * fit. The view direction comes from the pose, so the stage goes after whatever sets the angle of the shot.
35
+ */
36
+ export declare class GroupFraming {
37
+ /** The subjects. Add, remove and edit them at any time. */
38
+ readonly members: GroupMember[];
39
+ /** The centre of the shot after the last update, smoothed, in world units. */
40
+ readonly center: Float64Array<ArrayBuffer>;
41
+ /** False when the limits stopped the shot from holding every member at the last update. */
42
+ fits: boolean;
43
+ private readonly mode;
44
+ private readonly padding;
45
+ private readonly minDistance;
46
+ private readonly maxDistance;
47
+ private readonly minFov;
48
+ private readonly maxFov;
49
+ private readonly damping;
50
+ private readonly point;
51
+ private readonly goal;
52
+ private readonly back;
53
+ private readonly right;
54
+ private readonly top;
55
+ private distance;
56
+ private fov;
57
+ private started;
58
+ /** @throws RangeError for a value outside what {@link GroupFramingOptions} allows, or a bad member. */
59
+ constructor(members: readonly (CameraTarget | GroupMember)[], options?: GroupFramingOptions);
60
+ /** Forgets the shot: the next update frames the group at once, as after a teleport. */
61
+ reset(): void;
62
+ /** Writes the weighted centre to `goal`; false when no member counts. */
63
+ private weighted;
64
+ /** The axes of a view from `back`: right and top, with up as near world up as the view allows. */
65
+ private axes;
66
+ /** The smallest camera distance from the centre that holds every member at these half-angle tangents. */
67
+ private fitDistance;
68
+ /** The half-angle tangent up the screen that holds every member from `distance`, or Infinity when none can. */
69
+ private fitTan;
70
+ /** Stage hook. With no member that counts it leaves the pose alone. @throws RangeError for a bad member or target. */
71
+ update(pose: CameraPose, delta: number, context: StageContext): void;
72
+ }
package/dist/group.js ADDED
@@ -0,0 +1,90 @@
1
+ import { t as e } from "./target-CZNe0IXh.js";
2
+ //#region src/group.ts
3
+ var t = (e) => {
4
+ if (!((e.radius ?? 0) >= 0 && (e.radius ?? 0) < Infinity) || !((e.weight ?? 1) >= 0)) throw RangeError("Invalid group member; pass a finite radius and a weight of 0 or more");
5
+ }, n = (e) => "target" in e, r = class {
6
+ constructor(e, r = {}) {
7
+ this.center = /* @__PURE__ */ new Float64Array(3), this.fits = !0, this.point = /* @__PURE__ */ new Float64Array(3), this.goal = /* @__PURE__ */ new Float64Array(3), this.back = /* @__PURE__ */ new Float64Array(3), this.right = /* @__PURE__ */ new Float64Array(3), this.top = /* @__PURE__ */ new Float64Array(3), this.distance = 0, this.fov = 0, this.started = !1;
8
+ let { mode: i = "dolly", padding: a = .1, minDistance: o = 1, maxDistance: s = Infinity, minFov: c = 10, maxFov: l = 100, damping: u = 4 } = r;
9
+ if (i !== "dolly" && i !== "zoom" && i !== "both") throw RangeError("Invalid group mode; pass 'dolly', 'zoom' or 'both'");
10
+ if (!(a >= 0 && a < .5)) throw RangeError("Invalid group padding; pass 0 or more and below 0.5");
11
+ if (!(o > 0 && o < Infinity && s >= o)) throw RangeError("Invalid group distance; pass a minDistance above 0 and a maxDistance at least as large");
12
+ if (!(c > 0 && l >= c && l < 180)) throw RangeError("Invalid group fov; pass a minFov above 0 and a maxFov at least as large, below 180");
13
+ if (!(u > 0 && u < Infinity)) throw RangeError("Invalid group damping; pass a rate above 0");
14
+ this.members = e.map((e) => n(e) ? e : { target: e }), this.members.forEach(t), this.mode = i, this.padding = a, this.minDistance = o, this.maxDistance = s, this.minFov = c, this.maxFov = l, this.damping = u;
15
+ }
16
+ reset() {
17
+ this.started = !1;
18
+ }
19
+ weighted() {
20
+ let { goal: n, point: r } = this, i = 0;
21
+ n.fill(0);
22
+ for (let a of this.members) {
23
+ t(a);
24
+ let o = a.weight ?? 1;
25
+ if (o) {
26
+ e(a.target, r), i += o;
27
+ for (let e = 0; e < 3; e++) n[e] += r[e] * o;
28
+ }
29
+ }
30
+ if (!i) return !1;
31
+ for (let e = 0; e < 3; e++) n[e] /= i;
32
+ return !0;
33
+ }
34
+ axes(e) {
35
+ let { back: t, right: n, top: r } = this;
36
+ n[0] = e[1] * t[2] - e[2] * t[1], n[1] = e[2] * t[0] - e[0] * t[2], n[2] = e[0] * t[1] - e[1] * t[0];
37
+ let i = Math.hypot(n[0], n[1], n[2]);
38
+ if (i < 1e-9) {
39
+ let e = Math.abs(t[0]) < .9;
40
+ n[0] = e ? 0 : -t[2], n[1] = e ? t[2] : 0, n[2] = e ? -t[1] : t[0], i = Math.hypot(n[0], n[1], n[2]);
41
+ }
42
+ n[0] /= i, n[1] /= i, n[2] /= i, r[0] = t[1] * n[2] - t[2] * n[1], r[1] = t[2] * n[0] - t[0] * n[2], r[2] = t[0] * n[1] - t[1] * n[0];
43
+ }
44
+ fitDistance(t, n) {
45
+ let { back: r, right: i, top: a, center: o, point: s } = this, c = t / Math.hypot(1, t), l = n / Math.hypot(1, n), u = 0;
46
+ for (let d of this.members) {
47
+ if (!(d.weight ?? 1)) continue;
48
+ e(d.target, s);
49
+ let f = s[0] - o[0], p = s[1] - o[1], m = s[2] - o[2], h = d.radius ?? 0, g = Math.abs(f * i[0] + p * i[1] + m * i[2]), _ = Math.abs(f * a[0] + p * a[1] + m * a[2]), v = f * r[0] + p * r[1] + m * r[2];
50
+ u = Math.max(u, v + g / t + h / c, v + _ / n + h / l);
51
+ }
52
+ return u;
53
+ }
54
+ fitTan(t, n, r) {
55
+ let { back: i, right: a, top: o, center: s, point: c } = this, l = 0;
56
+ for (let u of this.members) {
57
+ if (!(u.weight ?? 1)) continue;
58
+ e(u.target, c);
59
+ let d = c[0] - s[0], f = c[1] - s[1], p = c[2] - s[2], m = u.radius ?? 0, h = Math.abs(d * a[0] + f * a[1] + p * a[2]), g = Math.abs(d * o[0] + f * o[1] + p * o[2]), _ = t - (d * i[0] + f * i[1] + p * i[2]);
60
+ for (let e = 0; e < 2; e++) {
61
+ let t = e ? g : h, i = Math.hypot(t, _);
62
+ if (_ <= 0 || i <= m) return Infinity;
63
+ let a = Math.atan2(t, _) + Math.asin(m / i);
64
+ if (a >= Math.PI / 2) return Infinity;
65
+ l = Math.max(l, Math.tan(a) / (r * (e ? 1 : n)));
66
+ }
67
+ }
68
+ return l;
69
+ }
70
+ update(e, t, n) {
71
+ if (!this.weighted()) return;
72
+ let { position: r, target: i } = e, { center: a, goal: o, back: s } = this, c = this.started ? Math.exp(-this.damping * t) : 0;
73
+ for (let e = 0; e < 3; e++) a[e] = o[e] + (a[e] - o[e]) * c;
74
+ let l = this.mode === "zoom", u = r[0] - (l ? a[0] : i[0]), d = r[1] - (l ? a[1] : i[1]), f = r[2] - (l ? a[2] : i[2]), p = Math.hypot(u, d, f);
75
+ p > 0 || (u = 0, d = 0, f = 1);
76
+ let m = p > 0 ? p : 1;
77
+ s[0] = u / m, s[1] = d / m, s[2] = f / m, this.axes(e.up);
78
+ let h = 1 - 2 * this.padding, g = Math.tan(e.fov * Math.PI / 360) * h, _ = this.minDistance, v = this.maxDistance, y = l ? p : this.fitDistance(g * n.aspect, g), b = y;
79
+ l || (y = Math.min(v, Math.max(_, y)));
80
+ let x = e.fov, S = l || y >= b;
81
+ if (this.mode !== "dolly") {
82
+ let e = this.fitTan(y, n.aspect, h), t = this.minFov, r = this.maxFov, i = e === Infinity ? Infinity : Math.atan(e) * 360 / Math.PI;
83
+ (l || y !== b) && (x = Math.min(r, Math.max(t, i))), S = i <= r;
84
+ }
85
+ this.started ? (this.distance = y + (this.distance - y) * c, this.fov = x + (this.fov - x) * c) : (this.distance = y, this.fov = x), this.started = !0, this.fits = S, e.fov = this.fov;
86
+ for (let e = 0; e < 3; e++) i[e] = a[e], l || (r[e] = a[e] + s[e] * this.distance);
87
+ }
88
+ };
89
+ //#endregion
90
+ export { r as GroupFraming };
@@ -0,0 +1,112 @@
1
+ /// <reference lib="esnext.disposable" preserve="true" />
2
+ import type { EngineKernel, Mesh, Vec3 } from '@margoengine/core';
3
+ import { type Engine, type EnginePlugin } from '@margoengine/core/extension';
4
+ /**
5
+ * Distance from `origin` along the unit `direction` to the first obstacle within `distance`, or null/undefined for none.
6
+ * The arrays are reused every frame: read them, do not keep them.
7
+ */
8
+ export type CameraCollision = (origin: Float64Array, direction: Float64Array, distance: number) => number | null | undefined;
9
+ /** Settings for {@link Cinematic}. Distances are world units. */
10
+ export interface CinematicOptions {
11
+ /** Camera position relative to the target; finite and non-zero. Default [0, 3, 6]. */
12
+ offset?: Vec3;
13
+ /** Follow spring rate in 1/seconds (higher is stiffer); finite and > 0. Default 6. */
14
+ damping?: number;
15
+ /** Look-at spring rate in 1/seconds; finite and > 0. Default 8. */
16
+ lookDamping?: number;
17
+ /** Ground height at world `(x, z)`; the camera stays `clearance` above it along the arm. Must return finite values. */
18
+ ground?: (x: number, z: number) => number;
19
+ /** Space kept between the camera and the ground, and between the camera and a `collide` hit. Default 0.65. */
20
+ clearance?: number;
21
+ /**
22
+ * Walls and ceilings: queried each frame along the arm from the look-at point to the camera. On a hit the camera moves
23
+ * in at once to `clearance` short of it, and eases back out at the follow damping once the arm is clear. For example
24
+ * `(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`.
25
+ */
26
+ collide?: CameraCollision;
27
+ }
28
+ /** Critically damped virtual camera, with independent follow/look springs and additive shake. */
29
+ export declare class Cinematic implements EnginePlugin {
30
+ readonly options: CinematicOptions;
31
+ readonly name = "cinematic";
32
+ /** Current camera offset from the target in world units; edit in place or with `setOrbitOffset`. */
33
+ readonly offset: Float64Array;
34
+ /** Smoothed camera position in world units, before shake. */
35
+ readonly position: Float64Array<ArrayBuffer>;
36
+ /** Smoothed look-at point in world units. */
37
+ readonly lookAt: Float64Array<ArrayBuffer>;
38
+ private readonly velocity;
39
+ private readonly target;
40
+ /** Where the last update put the camera: spring, shake, ground and walls included. Read it, do not keep it. */
41
+ readonly cameraPosition: Float32Array<ArrayBuffer>;
42
+ /** What the last update aimed at. Read it, do not keep it. */
43
+ readonly cameraTarget: Float32Array<ArrayBuffer>;
44
+ private readonly armDirection;
45
+ /** Arm length allowed by the last `collide` hit, easing back out; Infinity when unobstructed. */
46
+ private reach;
47
+ private engine?;
48
+ private mesh?;
49
+ private amplitude;
50
+ private remaining;
51
+ private shakeDuration;
52
+ private frequency;
53
+ private elapsed;
54
+ private initialized;
55
+ /**
56
+ * @throws TypeError when `offset` is not 3 values or `collide` is not a function.
57
+ * @throws RangeError for a non-finite or zero offset, invalid damping, a non-function `ground`, or invalid clearance.
58
+ */
59
+ constructor(options?: CinematicOptions);
60
+ /** Create a rig and add it to `engine` as the 'cinematic' plugin; it then updates before every frame. */
61
+ static attach(engine: EngineKernel, options?: CinematicOptions): Cinematic;
62
+ /**
63
+ * Set `offset` from spherical coordinates: `yaw`/`pitch` in radians, `distance` (> 0) and extra `height` (default 0)
64
+ * in world units.
65
+ * @throws RangeError for non-finite values or a non-positive distance.
66
+ */
67
+ setOrbitOffset(yaw: number, pitch: number, distance: number, height?: number): void;
68
+ /**
69
+ * Follow a mesh (its world position, read each update) or a fixed world point.
70
+ * @throws TypeError for a point that is not 3 values or a mesh of another engine.
71
+ * @throws RangeError for a non-finite point.
72
+ * @throws MargoError (code 'disposed') for a disposed mesh.
73
+ */
74
+ follow(target: Mesh | Vec3): void;
75
+ /**
76
+ * Start a shake that fades out quadratically, replacing any running one.
77
+ * @param amplitude World units, >= 0.
78
+ * @param duration Seconds, > 0.
79
+ * @param frequency Oscillation rate in radians per second, > 0. Default 25.
80
+ * @throws RangeError for an out-of-range argument.
81
+ */
82
+ shake(amplitude: number, duration: number, frequency?: number): void;
83
+ /**
84
+ * Step the springs, shake, ground and wall avoidance by `delta` seconds and write the engine camera when attached.
85
+ * Called automatically when attached as a plugin.
86
+ * @throws RangeError for a negative or non-finite delta, invalid options, or non-finite ground or collision results.
87
+ */
88
+ update(delta: number): void;
89
+ /** Shortens the rendered arm (look-at point to camera) to stay `clearance` in front of the first `collide` hit. */
90
+ private avoidWalls;
91
+ private validateGround;
92
+ private groundOffset;
93
+ /**
94
+ * Plugin hook: bind the rig to `engine`.
95
+ * @throws MargoError `'attached'` when already attached.
96
+ * @throws TypeError when the followed mesh belongs to another engine.
97
+ */
98
+ setup(engine: Engine): void;
99
+ /** Seconds the rig has followed (its shake clock). */
100
+ get time(): number;
101
+ /**
102
+ * One frame of the rig with no draw: {@link Cinematic.update}, all CPU (springs, shake, ground and wall queries, the
103
+ * engine camera). Each frame update runs it, so `seek` from `@margoengine/cutscene/seek` replays the follow and the
104
+ * shake exactly while film code moves the target on the way.
105
+ */
106
+ advanceTime(delta: number): void;
107
+ /** Plugin hook: runs {@link Cinematic.update} with the frame delta in seconds. */
108
+ onPreUpdate(delta: number): void;
109
+ /** Detach from the engine (removing the plugin) and stop following; the rig can be attached again. */
110
+ dispose(): void;
111
+ [Symbol.dispose]: () => void;
112
+ }
package/dist/index.js ADDED
@@ -0,0 +1,115 @@
1
+ // @margo/core-built 1.0.0
2
+ import {coreRequirement as __margoCoreRequirement,assertCore as __margoAssertCore} from '@margoengine/core/extension';
3
+ const t=(engine,version="1.0.0",source=import.meta.url)=>__margoRuntime(engine,version,source);
4
+ import { MargoError as e } from "@margoengine/math/errors";
5
+ import { engineRuntime as __margoRuntime, meshRuntime as n } from "@margoengine/core/extension";
6
+ //#region src/index.ts
7
+ var r = (e) => {
8
+ if (e.length !== 3) throw TypeError("Expected 3D target");
9
+ for (let t = 0; t < 3; t++) if (!Number.isFinite(e[t])) throw RangeError("Target must be finite");
10
+ }, i = class i {coreRequirement=__margoCoreRequirement("1.0.0",import.meta.url);
11
+ constructor(e = {}) {
12
+ this.options = e, this.name = "cinematic", this.position = /* @__PURE__ */ new Float64Array(3), this.lookAt = /* @__PURE__ */ new Float64Array(3), this.velocity = /* @__PURE__ */ new Float64Array(6), this.target = /* @__PURE__ */ new Float64Array(3), this.cameraPosition = /* @__PURE__ */ new Float32Array(3), this.cameraTarget = /* @__PURE__ */ new Float32Array(3), this.armDirection = /* @__PURE__ */ new Float64Array(3), this.reach = Infinity, this.amplitude = 0, this.remaining = 0, this.shakeDuration = 1, this.frequency = 25, this.elapsed = 0, this.initialized = !1;
13
+ let t = e.offset ?? [
14
+ 0,
15
+ 3,
16
+ 6
17
+ ];
18
+ if (r(t), !Number.isFinite(e.damping ?? 6) || (e.damping ?? 6) <= 0 || !Number.isFinite(e.lookDamping ?? 8) || (e.lookDamping ?? 8) <= 0) throw RangeError("Invalid camera damping; pass damping and lookDamping above 0");
19
+ if (!Math.hypot(t[0], t[1], t[2])) throw RangeError("Camera offset cannot be zero; pass a non-zero offset such as [0, 2, 6]");
20
+ this.validateGround(), this.offset = new Float64Array(t);
21
+ }
22
+ static attach(e, n = {}) {__margoAssertCore(e,__margoCoreRequirement("1.0.0",import.meta.url));
23
+ let r = new i(n);
24
+ return t(e).use(r), r;
25
+ }
26
+ setOrbitOffset(e, t, n, r = 0) {
27
+ if (!Number.isFinite(e) || !Number.isFinite(t) || !Number.isFinite(n) || n <= 0 || !Number.isFinite(r)) throw RangeError("Invalid camera orbit; pass finite yaw, pitch and height and a distance above 0");
28
+ this.offset[0] = Math.sin(e) * Math.cos(t) * n, this.offset[1] = Math.sin(t) * n + r, this.offset[2] = Math.cos(e) * Math.cos(t) * n;
29
+ }
30
+ follow(e) {
31
+ if (Array.isArray(e)) r(e), this.target.set(e), this.mesh = void 0;
32
+ else {
33
+ let t = n(e);
34
+ if (t.check(), this.engine && t.engine !== this.engine) throw TypeError("Target belongs to another engine; follow a mesh of the engine this rig is attached to");
35
+ this.mesh = e;
36
+ }
37
+ }
38
+ shake(e, t, n = 25) {
39
+ if (!Number.isFinite(e) || e < 0 || !Number.isFinite(t) || t <= 0 || !Number.isFinite(n) || n <= 0) throw RangeError("Invalid camera shake; pass amplitude >= 0, duration > 0 and frequency > 0, all finite");
40
+ this.amplitude = e, this.remaining = this.shakeDuration = t, this.frequency = n;
41
+ }
42
+ update(e) {
43
+ if (!Number.isFinite(e) || e < 0) throw RangeError("Invalid camera delta; pass a finite delta of 0 or more seconds");
44
+ r(this.offset), this.validateGround();
45
+ let t = this.options.damping ?? 6, i = this.options.lookDamping ?? 8;
46
+ if (!Number.isFinite(t) || t <= 0 || !Number.isFinite(i) || i <= 0) throw RangeError("Invalid camera damping; pass damping and lookDamping above 0");
47
+ if (this.mesh) {
48
+ let e = n(this.mesh);
49
+ e.check(), e.engine.store.tick(!1), this.target[0] = e.matrix[12], this.target[1] = e.matrix[13], this.target[2] = e.matrix[14];
50
+ }
51
+ let a = this.groundOffset(this.target, this.offset[0], this.offset[1], this.offset[2]), o = Math.exp(-t * e), s = Math.exp(-i * e);
52
+ for (let n = 0; n < 3; n++) {
53
+ let r = n === 1 ? a : this.offset[n];
54
+ this.initialized || (this.position[n] = this.target[n] + r, this.lookAt[n] = this.target[n]);
55
+ for (let a = 0; a < 2; a++) {
56
+ let c = a ? this.lookAt : this.position, l = this.target[n] + (a ? 0 : r), u = a ? i : t, d = a * 3 + n, f = c[n] - l, p = this.velocity[d] + u * f, m = a ? s : o;
57
+ c[n] = l + (f + p * e) * m, this.velocity[d] = (this.velocity[d] - u * p * e) * m;
58
+ }
59
+ }
60
+ this.initialized = !0, this.elapsed += e, this.remaining = Math.max(0, this.remaining - e);
61
+ let c = this.amplitude * (this.remaining / this.shakeDuration) ** 2;
62
+ for (let e = 0; e < 3; e++) this.cameraPosition[e] = this.position[e] + Math.sin(this.elapsed * this.frequency * (1 + e * .37) + e * 2) * c, this.cameraTarget[e] = this.lookAt[e];
63
+ let l = this.cameraPosition[1] - this.lookAt[1], u = this.groundOffset(this.lookAt, this.cameraPosition[0] - this.lookAt[0], l, this.cameraPosition[2] - this.lookAt[2]) - l;
64
+ u > 0 && (this.cameraPosition[1] += u, this.position[1] += u, this.velocity[1] = Math.max(0, this.velocity[1])), this.options.ground && this.offset[1] < 0 && (this.cameraTarget[1] += Math.min(Math.max(0, this.cameraPosition[1] - this.lookAt[1] - this.offset[1]), a - this.offset[1] + Math.max(0, u))), this.avoidWalls(o), this.engine && (this.engine.camera.position = this.cameraPosition, this.engine.camera.target = this.cameraTarget);
65
+ }
66
+ avoidWalls(e) {
67
+ let t = this.options.collide;
68
+ if (!t) return;
69
+ let n = this.lookAt, r = this.cameraPosition, i = this.armDirection;
70
+ i[0] = r[0] - n[0], i[1] = r[1] - n[1], i[2] = r[2] - n[2];
71
+ let a = Math.sqrt(i[0] * i[0] + i[1] * i[1] + i[2] * i[2]);
72
+ if (!(a > 0)) return;
73
+ i[0] /= a, i[1] /= a, i[2] /= a;
74
+ let o = t(n, i, a);
75
+ if (o != null && (typeof o != "number" || !Number.isFinite(o))) throw RangeError("Camera collision distance must be finite");
76
+ let s = o == null || o >= a ? a : Math.max(0, o - (this.options.clearance ?? .65));
77
+ if (this.reach = s <= this.reach ? s : this.reach + (s - this.reach) * (1 - e), s === a && a - this.reach < 1e-4 && (this.reach = Infinity), this.reach < a) for (let e = 0; e < 3; e++) r[e] = n[e] + i[e] * this.reach;
78
+ }
79
+ validateGround() {
80
+ if (this.options.collide !== void 0 && typeof this.options.collide != "function") throw TypeError("Camera collide must be a function");
81
+ if (this.options.ground !== void 0 && typeof this.options.ground != "function" || !Number.isFinite(this.options.clearance ?? .65) || (this.options.clearance ?? .65) < 0) throw RangeError("Invalid camera ground clearance; pass a finite clearance of 0 or more");
82
+ }
83
+ groundOffset(e, t, n, r) {
84
+ let i = this.options.ground;
85
+ if (i) for (let a = 1; a <= 6; a++) {
86
+ let o = a / 6, s = i(e[0] + t * o, e[2] + r * o);
87
+ if (!Number.isFinite(s)) throw RangeError("Camera ground height must be finite");
88
+ n = Math.max(n, (s + (this.options.clearance ?? .65) - e[1]) / o);
89
+ }
90
+ return n;
91
+ }
92
+ setup(t) {
93
+ if (this.engine) throw new e("attached", "Camera rig already attached; dispose() it before attaching it again, or create another rig");
94
+ if (this.mesh && n(this.mesh).engine !== t) throw TypeError("Target belongs to another engine; follow a mesh of the engine this rig is attached to");
95
+ this.engine = t;
96
+ }
97
+ get time() {
98
+ return this.elapsed;
99
+ }
100
+ advanceTime(e) {
101
+ this.update(e);
102
+ }
103
+ onPreUpdate(e) {
104
+ this.advanceTime(e);
105
+ }
106
+ dispose() {
107
+ let e = this.engine;
108
+ this.engine = void 0, this.mesh = void 0, e?.sceneOf(this)?.removePlugin(this.name);
109
+ }
110
+ [Symbol.dispose ?? Symbol()]() {
111
+ this.dispose();
112
+ }
113
+ };
114
+ //#endregion
115
+ export { i as Cinematic };