@margoengine/labels 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,103 @@
1
+ import type { Backend } from '@margoengine/math/mat4';
2
+ export type { Backend };
3
+ /** Three numbers [x, y, z] in world units. */
4
+ export type Vec3 = readonly [number, number, number];
5
+ /**
6
+ * Right-handed look-at view matrix (column-major), the same matrix core's `Camera` builds.
7
+ *
8
+ * The camera's local Z points from `target` back to `position`, X = up x Z and Y = Z x X; the rotation rows are X, Y
9
+ * and Z, and the translation is the rotated position negated.
10
+ *
11
+ * @param position - Eye position in world space.
12
+ * @param target - Point the camera looks at.
13
+ * @param out - Destination, written and returned (default: a new Float64Array(16)).
14
+ * @param up - World up direction (default +Y).
15
+ * @throws RangeError when `position` equals `target`, or when the view direction is parallel to `up`.
16
+ */
17
+ export declare function lookAtView(position: Vec3, target: Vec3, out?: Float64Array, up?: Vec3): Float64Array;
18
+ /**
19
+ * CSS `perspective` length in pixels that reproduces a vertical field of view on a viewport.
20
+ *
21
+ * Pinhole geometry: half the viewport height over the tangent of half the field of view.
22
+ *
23
+ * @param fov - Vertical field of view in degrees.
24
+ * @param height - Viewport height in CSS pixels.
25
+ */
26
+ export declare const cssPerspective: (fov: number, height: number) => number;
27
+ /**
28
+ * CSS transform for the camera element (sized `width` x `height`) under a perspective camera.
29
+ *
30
+ * The list pushes the scene back by the viewer's perspective distance, applies the view matrix with its Y row negated
31
+ * (world Y up to CSS Y down), then moves the origin to the element's centre. Use with the viewer element's
32
+ * `perspective` set to the same `perspective` length.
33
+ *
34
+ * @param view - Column-major view matrix, e.g. from {@link lookAtView}.
35
+ * @param perspective - The viewer's CSS perspective in pixels, from {@link cssPerspective}.
36
+ * @param width - Viewport width in CSS pixels.
37
+ * @param height - Viewport height in CSS pixels.
38
+ */
39
+ export declare function cameraCSSTransform(view: ArrayLike<number>, perspective: number, width: number, height: number): string;
40
+ /**
41
+ * CSS transform for the camera element under an orthographic view-projection (viewer `perspective: none`).
42
+ *
43
+ * World points map straight to CSS pixels about the viewport centre through `matrix` itself, so zoom, offsets and
44
+ * custom projections carry over. Depth is scaled so one world unit along the view axis is as long in CSS as one along
45
+ * screen Y, with the sign chosen so nearer points get larger CSS z on either backend's depth convention.
46
+ *
47
+ * @param matrix - Column-major orthographic view-projection (clip matrix).
48
+ * @param width - Viewport width in CSS pixels.
49
+ * @param height - Viewport height in CSS pixels.
50
+ * @param backend - Clip-space convention of `matrix` (default 'webgpu', reversed Z).
51
+ */
52
+ export declare function orthographicCSSTransform(matrix: ArrayLike<number>, width: number, height: number, backend?: Backend): string;
53
+ /**
54
+ * CSS transform for a CSS3D object element from its world matrix.
55
+ *
56
+ * The element is first centred on its origin (-50% of its own box), then placed by the world matrix with CSS pixels
57
+ * scaled to world units and CSS Y flipped to world Y: one pixel right is `pixelScale` along the matrix's X axis, one
58
+ * pixel down is `-pixelScale` along its Y axis.
59
+ *
60
+ * @param world - Column-major world matrix.
61
+ * @param pixelScale - World units per CSS pixel (default 1).
62
+ */
63
+ export declare function objectCSSTransform(world: ArrayLike<number>, pixelScale?: number): string;
64
+ /**
65
+ * World position of a point on a CSS3D object given in element pixels from the element centre (x right, y down).
66
+ *
67
+ * The inverse of the placement {@link objectCSSTransform} makes; useful for hit testing.
68
+ *
69
+ * @param world - Column-major world matrix of the object (affine).
70
+ * @param pixelScale - World units per CSS pixel.
71
+ * @param x - Pixels right of the element centre.
72
+ * @param y - Pixels below the element centre.
73
+ */
74
+ export declare function cssPointToWorld(world: ArrayLike<number>, pixelScale: number, x: number, y: number): [number, number, number];
75
+ /**
76
+ * Column-major translation-rotation-scale matrix.
77
+ *
78
+ * @param position - Translation.
79
+ * @param quaternion - Rotation [x, y, z, w], normalised here; a zero quaternion gives no rotation (default identity).
80
+ * @param scale - Scale per local axis (default [1, 1, 1]).
81
+ * @param out - Destination, written and returned (default: a new Float64Array(16)).
82
+ */
83
+ export declare function composeMatrix(position: Vec3, quaternion?: readonly number[], scale?: Vec3, out?: Float64Array): Float64Array;
84
+ /** A face of a box: the anchor sits at the centre of that face. */
85
+ export type BoxFace = 'left' | 'right' | 'bottom' | 'top' | 'back' | 'front';
86
+ /**
87
+ * Where on a box to pin: a face name, 'center', or a `[x, y, z]` triple of -1 (the min side), 0 (the middle) and 1 (the
88
+ * max side) per axis. `[1, 1, 1]` is the max corner, `[0, 1, 0]` the middle of the top face, `[1, 1, 0]` a top edge.
89
+ */
90
+ export type BoxAnchorSpec = BoxFace | 'center' | readonly [number, number, number];
91
+ /**
92
+ * World position of a corner, edge, face centre or the centre of a box, to pin a label or CSS 3D object to it
93
+ * (`label.setPosition(boxAnchorPoint(min, max, 'top'))`). Pass the box's world matrix (for example a mesh's) and the
94
+ * point follows a moved, rotated or scaled box, so a box fitted in local space stays pinned.
95
+ *
96
+ * @param min - Smallest corner of the box.
97
+ * @param max - Largest corner of the box.
98
+ * @param anchor - Face name, 'center' or a [-1|0|1, -1|0|1, -1|0|1] triple (default 'center').
99
+ * @param matrix - Optional column-major 4x4 matrix applied to the point (default identity).
100
+ * @param out - Destination, written and returned (default: a new array).
101
+ * @throws RangeError when a bound is not finite, `min` exceeds `max`, or the anchor is not a face name, 'center' or a triple of -1, 0 and 1.
102
+ */
103
+ export declare function boxAnchorPoint(min: Vec3, max: Vec3, anchor?: BoxAnchorSpec, matrix?: ArrayLike<number>, out?: [number, number, number]): [number, number, number];
@@ -0,0 +1,274 @@
1
+ /// <reference lib="esnext.disposable" preserve="true" />
2
+ import type { EngineKernel, EnginePlugin, Mesh, RenderView } from '@margoengine/core';
3
+ import { type FrameGraph } from '@margoengine/core/extension';
4
+ import { type Vec3 } from './projection.js';
5
+ import { type ScreenPoint } from '@margoengine/math/mat4';
6
+ /** Where a label sits this frame: its screen position, depth, distance from the camera and world anchor. */
7
+ export interface LabelInfo {
8
+ /** Projected position in CSS pixels relative to the canvas. */
9
+ readonly x: number;
10
+ readonly y: number;
11
+ /** Normalized depth, 0 near to 1 far. */
12
+ readonly depth: number;
13
+ /** Euclidean distance from the camera in world units. */
14
+ readonly distance: number;
15
+ /** World-space anchor point. */
16
+ readonly world: Vec3;
17
+ }
18
+ /** Return true to hide the label this frame (custom occlusion, for example a raycast against the scene). */
19
+ export type OccludeHook = (label: Label, info: LabelInfo) => boolean;
20
+ /**
21
+ * Return true to hide the CSS 3D object this frame, for example when scene geometry is in front of it. `info`
22
+ * describes the object's origin; its `x` and `y` are NaN when the origin is behind the camera.
23
+ */
24
+ export type CSS3DOccludeHook = (object: CSS3DObject, info: LabelInfo) => boolean;
25
+ /** Scales a label by distance: a reference distance, optionally clamped between min and max scale. */
26
+ export type DistanceScale = number | {
27
+ reference: number;
28
+ min?: number;
29
+ max?: number;
30
+ };
31
+ /**
32
+ * What a {@link LabelLayout} gets each update: the view size, each label's measured size, and the two decisions it
33
+ * can make. The renderer applies them in the same update, before any label is drawn.
34
+ */
35
+ export interface LayoutContext {
36
+ /** Size of the view rectangle in CSS pixels; label `screen` coordinates are relative to its corner. */
37
+ readonly width: number;
38
+ readonly height: number;
39
+ /** The overlay root the labels sit in, with its corner at the view's corner; for layouts that draw (`Callouts`). */
40
+ readonly root: HTMLElement;
41
+ /**
42
+ * The element's size in CSS pixels before distance scaling, measured once (`offsetWidth`, `offsetHeight`) and
43
+ * kept until `label.remeasure()`. Multiply by `label.scale` for its size on screen.
44
+ */
45
+ size(label: Label): readonly [number, number];
46
+ /** Hides the label this update; `label.onScreen` reads false. */
47
+ hide(label: Label): void;
48
+ /** Places the label with another anchor this update; its own `anchor` is kept for the next one. */
49
+ place(label: Label, anchor: readonly [number, number]): void;
50
+ }
51
+ /**
52
+ * Arranges the labels that passed culling and occlusion before they are drawn, for example to remove overlaps
53
+ * (`Declutter` from `@margoengine/labels/declutter`). Called once per update with the labels in the order added,
54
+ * also with none, so a layout can clear what it drew.
55
+ */
56
+ export interface LabelLayout {
57
+ arrange(labels: readonly Label[], context: LayoutContext): void;
58
+ }
59
+ /** Options of a label: the mesh or position it follows, its offset, anchor, culling, occlusion and visibility. */
60
+ export interface LabelOptions {
61
+ /** Mesh to follow. The anchor is the mesh origin plus `offset`. */
62
+ mesh?: Mesh | null;
63
+ /** World position when not following a mesh. */
64
+ position?: Vec3;
65
+ /** Offset from the mesh origin, in the mesh's local space (like a child object) or world space. */
66
+ offset?: Vec3;
67
+ offsetSpace?: 'local' | 'world';
68
+ /** Which point of the element sits on the anchor, as fractions of its size. Default [0.5, 0.5] (center). */
69
+ anchor?: readonly [number, number];
70
+ /**
71
+ * Moves the element this many CSS pixels from its projected point, x right and y down, for a callout with a leader
72
+ * line (`Callouts` from `@margoengine/labels/callouts`). Default [0, 0].
73
+ */
74
+ screenOffset?: readonly [number, number];
75
+ /** 'none' lets pointer events pass through to the canvas (default); 'auto' makes the label interactive. */
76
+ pointerEvents?: 'none' | 'auto';
77
+ /** Hide when outside the view frustum. Default true. Labels behind the camera are always hidden. */
78
+ frustumCulling?: boolean;
79
+ /** Hide while the mesh or an ancestor is hidden. Default true. */
80
+ followVisibility?: boolean;
81
+ /** Scale the element by `reference / distance` (clamped to min..max). */
82
+ distanceScale?: DistanceScale;
83
+ /** Take part in depth sorting (z-index). Default true. */
84
+ sort?: boolean;
85
+ /** Rank for a {@link LabelLayout}: a decluttering layout keeps higher priorities first. Default 0. */
86
+ priority?: number;
87
+ occlude?: OccludeHook;
88
+ visible?: boolean;
89
+ }
90
+ /** Options of a CSS3D object: the mesh or matrix it follows, its pixel scale and visibility. */
91
+ export interface CSS3DOptions {
92
+ mesh?: Mesh | null;
93
+ /** Column-major world matrix when not following a mesh. */
94
+ matrix?: ArrayLike<number>;
95
+ position?: Vec3;
96
+ /** Quaternion [x, y, z, w]. */
97
+ quaternion?: readonly number[];
98
+ /** World units per CSS pixel. Default 0.01, so a 100 px wide element spans one world unit. */
99
+ pixelScale?: number;
100
+ pointerEvents?: 'none' | 'auto';
101
+ followVisibility?: boolean;
102
+ /** Hides the object while it returns true; CSS 3D objects are not depth-tested against the canvas. */
103
+ occlude?: CSS3DOccludeHook;
104
+ visible?: boolean;
105
+ }
106
+ /** Options of LabelRenderer: parent element, z-index, default occlusion, frame-pass order and view. */
107
+ export interface LabelRendererOptions {
108
+ /** Element that receives the overlay. Default: the canvas's parent, right after the canvas. */
109
+ parent?: HTMLElement;
110
+ /** z-index of the overlay root. Default 1. */
111
+ zIndex?: number;
112
+ /** Optional class name for the overlay root. */
113
+ className?: string;
114
+ /** Default occlusion hook for every label. */
115
+ occlude?: OccludeHook;
116
+ name?: string;
117
+ /** Frame-pass order. Default 1000, after the scene and other overlays. */
118
+ order?: number;
119
+ /** Arranges the visible labels each update, for example `new Declutter()`; see {@link LabelRenderer.layout}. */
120
+ layout?: LabelLayout | null;
121
+ /** Engine view the labels belong to; see {@link LabelRenderer.view}. Default the engine camera and whole canvas. */
122
+ view?: LabelView;
123
+ }
124
+ /**
125
+ * The camera and rectangle labels are placed in, as in an engine `RenderView`: `viewport` is fractions of the canvas,
126
+ * or drawing-buffer pixels with `pixels`. Labels outside the rectangle are clipped.
127
+ */
128
+ export type LabelView = Pick<RenderView, 'camera' | 'viewport' | 'pixels'>;
129
+ type StyleCache = Record<string, string>;
130
+ declare abstract class Item {
131
+ readonly element: HTMLElement;
132
+ visible: boolean;
133
+ followVisibility: boolean;
134
+ /** True when the element was shown at the last update. */
135
+ onScreen: boolean;
136
+ /** Euclidean distance to the camera at the last update. */
137
+ distance: number;
138
+ protected meshValue: Mesh | null;
139
+ /** @internal */ readonly cache: StyleCache;
140
+ /** @internal */ owner: LabelRenderer | null;
141
+ constructor(owner: LabelRenderer, element: HTMLElement, mesh: Mesh | null | undefined, followVisibility: boolean | undefined, visible: boolean | undefined);
142
+ /** @internal Element size in CSS pixels, measured once (`offsetWidth`, `offsetHeight`); null until measured. */
143
+ measured: [number, number] | null;
144
+ get mesh(): Mesh | null;
145
+ /** Measures the element again at the next update, after its content or style changed its size. */
146
+ remeasure(): this;
147
+ /** Removes the element from the overlay and stops tracking it. */
148
+ remove(): void;
149
+ }
150
+ /** A 2D HTML label pinned to a projected world point. */
151
+ export declare class Label extends Item {
152
+ anchor: [number, number];
153
+ /** CSS pixels the element is moved from its projected point, x right and y down. */
154
+ screenOffset: [number, number];
155
+ frustumCulling: boolean;
156
+ distanceScale: DistanceScale | null;
157
+ sort: boolean;
158
+ occlude: OccludeHook | null;
159
+ private priorityValue;
160
+ /** Distance scale applied at the last update; 1 without `distanceScale`. */
161
+ scale: number;
162
+ /** Anchor used at the last update: `anchor`, or the one a layout placed the label with. */
163
+ readonly placedAnchor: [number, number];
164
+ /** @internal Layout decision of the current update: hidden, or placed with another anchor. */
165
+ layoutHidden: boolean;
166
+ /** @internal */ layoutAnchor: [number, number] | null;
167
+ /** Projected position at the last update. */
168
+ readonly screen: ScreenPoint;
169
+ /** World anchor at the last update. */
170
+ readonly world: [number, number, number];
171
+ /** @internal Numbers the current transform text was built from: x, y, scaled flag, scale, anchor. */
172
+ readonly placement: Float64Array<ArrayBuffer>;
173
+ private positionValue;
174
+ private offsetValue;
175
+ offsetSpace: 'local' | 'world';
176
+ constructor(owner: LabelRenderer, element: HTMLElement, options: LabelOptions);
177
+ /** Rank for a {@link LabelLayout}; higher is kept first. */
178
+ get priority(): number;
179
+ set priority(value: number);
180
+ get position(): Vec3;
181
+ get offset(): Vec3;
182
+ setMesh(mesh: Mesh | null): this;
183
+ /** Pins the label to a world position and stops following a mesh. */
184
+ setPosition(position: Vec3): this;
185
+ setOffset(offset: Vec3): this;
186
+ }
187
+ /** An HTML element placed in world space with a CSS matrix3d transform. */
188
+ export declare class CSS3DObject extends Item {
189
+ pixelScale: number;
190
+ occlude: CSS3DOccludeHook | null;
191
+ /** True when part of the element was behind the near plane at the last update and was cut off (`clip-path`). */
192
+ clipped: boolean;
193
+ /** World matrix used at the last update (column-major). */
194
+ readonly matrix: Float64Array<ArrayBuffer>;
195
+ private readonly own;
196
+ constructor(owner: LabelRenderer, element: HTMLElement, options: CSS3DOptions);
197
+ setMesh(mesh: Mesh | null): this;
198
+ /** Sets a world matrix (column-major) and stops following a mesh. */
199
+ setMatrix(matrix: ArrayLike<number>): this;
200
+ setPose(position: Vec3, quaternion?: readonly number[]): this;
201
+ /** @internal */ get ownMatrix(): Float64Array;
202
+ }
203
+ /**
204
+ * Engine plugin that keeps HTML labels and CSS 3D objects registered over the canvas every frame.
205
+ * DOM writes happen only when a value changes.
206
+ */
207
+ export declare class LabelRenderer implements EnginePlugin {
208
+ readonly name: string;
209
+ /** Overlay root; created in setup, removed on dispose. */
210
+ root: HTMLDivElement | null;
211
+ occlude: OccludeHook | null;
212
+ /** Arranges the visible labels each update (for example `new Declutter()`); null places each label on its own. */
213
+ layout: LabelLayout | null;
214
+ private readonly order;
215
+ private readonly options;
216
+ private engine;
217
+ private readonly labels;
218
+ private readonly objects;
219
+ private viewer;
220
+ private cameraElement;
221
+ private readonly rootCache;
222
+ private readonly viewerCache;
223
+ private readonly cameraCache;
224
+ private readonly cssView;
225
+ private readonly point;
226
+ /** Signed distances in front of the near plane at a CSS 3D element's corners, reused every update. */
227
+ private readonly depths;
228
+ private readonly visibleLabels;
229
+ private readonly shownLabels;
230
+ private readonly layoutContext;
231
+ private readonly world;
232
+ private left;
233
+ private top;
234
+ /** CSS scale written on the root, from the canvas's ancestor scale over the root's; 1 when they agree. */
235
+ private rootScale;
236
+ /** Number of style properties written during the last update (diagnostics and tests). */
237
+ writes: number;
238
+ /**
239
+ * Same as `engine.use(new LabelRenderer(...))`; returns the LabelRenderer.
240
+ * @throws MargoError with code `state` and reuse/name guidance when the plugin name is already registered.
241
+ */
242
+ static attach(engine: EngineKernel, options?: LabelRendererOptions): LabelRenderer;
243
+ /**
244
+ * Engine view the labels belong to: they project through its camera and sit in its rectangle, clipped to it, and
245
+ * hook and `LabelInfo` coordinates are relative to its corner. Null: the engine camera and the whole canvas.
246
+ */
247
+ view: LabelView | null;
248
+ constructor(options?: LabelRendererOptions);
249
+ setup(engine: EngineKernel): void;
250
+ registerPasses(graph: FrameGraph): void;
251
+ /** Adds a 2D label. The element is moved into the overlay. */
252
+ add(element: HTMLElement, options?: LabelOptions): Label;
253
+ /** Adds a CSS 3D object. The element is moved into the overlay's 3D layer. */
254
+ add3D(element: HTMLElement, options?: CSS3DOptions): CSS3DObject;
255
+ remove(item: Label | CSS3DObject): void;
256
+ get size(): number;
257
+ /** Positions every label and CSS 3D object for the current camera. Runs as a frame pass; safe to call manually. */
258
+ update(): void;
259
+ private update3D;
260
+ /** Removes the overlay root, every label and CSS 3D element, and detaches from the engine. */
261
+ dispose(): void;
262
+ [Symbol.dispose]: () => void;
263
+ private measure;
264
+ /**
265
+ * The part of a `w` x `h` element in front of the near plane, as a CSS `polygon()` in element pixels: one-plane
266
+ * Sutherland-Hodgman clipping of its corners by the signed distances in `depths` (corner order (0, 0), (w, 0),
267
+ * (w, h), (0, h)).
268
+ */
269
+ private nearClip;
270
+ private set;
271
+ private syncRoot;
272
+ private mount;
273
+ }
274
+ export {};
package/package.json CHANGED
@@ -1,6 +1,74 @@
1
- {
2
- "name": "@margoengine/labels",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
1
+ {
2
+ "name": "@margoengine/labels",
3
+ "version": "0.1.0",
4
+ "description": "HTML labels and CSS 3D objects positioned over a Margo Engine canvas.",
5
+ "keywords": [
6
+ "margoengine",
7
+ "webgpu",
8
+ "3d",
9
+ "labels"
10
+ ],
11
+ "homepage": "https://margoengine.com",
12
+ "bugs": {
13
+ "url": "https://github.com/scottcampbelldata/margoengine/issues"
14
+ },
15
+ "repository": {
16
+ "type": "git",
17
+ "url": "git+https://github.com/scottcampbelldata/margoengine.git",
18
+ "directory": "packages/labels"
19
+ },
20
+ "license": "Apache-2.0",
21
+ "author": "Scott Campbell",
22
+ "type": "module",
23
+ "publishConfig": {
24
+ "access": "public"
25
+ },
26
+ "scripts": {
27
+ "build": "node scripts/build.js",
28
+ "test": "npm run build && node --test tests/*.test.js ../../examples/package-benchmarks/proofs/package-guard.mjs",
29
+ "test:browser": "npm run build && node scripts/test-browser.js",
30
+ "prepack": "npm run build"
31
+ },
32
+ "sideEffects": false,
33
+ "exports": {
34
+ ".": {
35
+ "types": "./dist/index.d.ts",
36
+ "import": "./dist/index.js"
37
+ },
38
+ "./declutter": {
39
+ "types": "./dist/declutter.d.ts",
40
+ "import": "./dist/declutter.js"
41
+ },
42
+ "./callouts": {
43
+ "types": "./dist/callouts.d.ts",
44
+ "import": "./dist/callouts.js"
45
+ },
46
+ "./gpu": {
47
+ "types": "./dist/gpu.d.ts",
48
+ "import": "./dist/gpu.js"
49
+ },
50
+ "./distance": {
51
+ "types": "./dist/distance.d.ts",
52
+ "import": "./dist/distance.js"
53
+ },
54
+ "./cluster": {
55
+ "types": "./dist/cluster.d.ts",
56
+ "import": "./dist/cluster.js"
57
+ },
58
+ "./callouts-route": {
59
+ "types": "./dist/callouts-route.d.ts",
60
+ "import": "./dist/callouts-route.js"
61
+ }
62
+ },
63
+ "files": [
64
+ "dist",
65
+ "NOTICE"
66
+ ],
67
+ "dependencies": {
68
+ "@margoengine/math": "^0.1.0",
69
+ "@margoengine/text": "^0.1.0"
70
+ },
71
+ "peerDependencies": {
72
+ "@margoengine/core": "^0.1.0"
73
+ }
74
+ }