@margoengine/ui 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.
Files changed (61) hide show
  1. package/LICENSE +201 -0
  2. package/NOTICE +4 -0
  3. package/README.md +1224 -2
  4. package/dist/basic.d.ts +87 -0
  5. package/dist/collections.d.ts +180 -0
  6. package/dist/color.d.ts +24 -0
  7. package/dist/controls.d.ts +130 -0
  8. package/dist/curved.d.ts +41 -0
  9. package/dist/curved.js +105 -0
  10. package/dist/dom-CWJhpotq.js +340 -0
  11. package/dist/dom-host.d.ts +67 -0
  12. package/dist/dom-host.js +563 -0
  13. package/dist/dom-spec.d.ts +21 -0
  14. package/dist/dom.d.ts +63 -0
  15. package/dist/draw.d.ts +107 -0
  16. package/dist/editor.d.ts +83 -0
  17. package/dist/editor.js +323 -0
  18. package/dist/errors-CDgOgzCd.js +7 -0
  19. package/dist/focus.d.ts +12 -0
  20. package/dist/forms.d.ts +114 -0
  21. package/dist/forms.js +354 -0
  22. package/dist/gl-bb768Mje.js +165 -0
  23. package/dist/gl-load-wwKmojhb.js +5 -0
  24. package/dist/gl-load.d.ts +3 -0
  25. package/dist/gl.d.ts +30 -0
  26. package/dist/i18n.d.ts +69 -0
  27. package/dist/i18n.js +117 -0
  28. package/dist/image.d.ts +74 -0
  29. package/dist/image.js +295 -0
  30. package/dist/index.d.ts +36 -0
  31. package/dist/index.js +4 -0
  32. package/dist/input-dom.d.ts +14 -0
  33. package/dist/input.d.ts +92 -0
  34. package/dist/input.js +315 -0
  35. package/dist/interaction.d.ts +106 -0
  36. package/dist/keyboard.d.ts +40 -0
  37. package/dist/keyboard.js +132 -0
  38. package/dist/layout.d.ts +116 -0
  39. package/dist/markup.d.ts +89 -0
  40. package/dist/markup.js +369 -0
  41. package/dist/meters-yaZRtwsX.js +1401 -0
  42. package/dist/meters.d.ts +72 -0
  43. package/dist/mirror.d.ts +30 -0
  44. package/dist/overlays.d.ts +89 -0
  45. package/dist/painter.d.ts +115 -0
  46. package/dist/pass-CAn29pqc.js +15 -0
  47. package/dist/react.d.ts +99 -0
  48. package/dist/react.js +246 -0
  49. package/dist/renderer-Vs-YtiWv.js +1741 -0
  50. package/dist/renderer.d.ts +138 -0
  51. package/dist/rsc/react.js +3 -0
  52. package/dist/shader.d.ts +6 -0
  53. package/dist/theme.d.ts +104 -0
  54. package/dist/ui.d.ts +328 -0
  55. package/dist/virtual.d.ts +81 -0
  56. package/dist/widget.d.ts +196 -0
  57. package/dist/world-gl.d.ts +32 -0
  58. package/dist/world-gl.js +195 -0
  59. package/dist/world.d.ts +216 -0
  60. package/dist/world.js +561 -0
  61. package/package.json +117 -4
@@ -0,0 +1,196 @@
1
+ /// <reference lib="esnext.disposable" preserve="true" />
2
+ import type { DrawList } from './draw.js';
3
+ import { type LayoutNode, type LayoutStyle, type Rect } from './layout.js';
4
+ import type { Theme, ThemeColors } from './theme.js';
5
+ import type { Ui } from './ui.js';
6
+ /** What an event handler receives. Which optional fields are set depends on `type`; each widget documents its events. */
7
+ export interface UiEvent {
8
+ /** `'click'`, `'change'`, `'select'`, `'move'`, `'focus'`, `'blur'`, `'hover'`, `'press'`, `'close'` and so on. */
9
+ type: string;
10
+ /** The widget the event happened on. */
11
+ target: Widget;
12
+ /** The new value of a `'change'`. */
13
+ value?: number | boolean | string;
14
+ /** The index of a `'select'` or `'use'`, or the target slot of a `'move'`. */
15
+ index?: number;
16
+ /** The source slot of a `'move'`. */
17
+ from?: number;
18
+ /** The item of a `'select'` or `'use'`. */
19
+ item?: unknown;
20
+ }
21
+ /** Handler for {@link Widget.on}. */
22
+ export type UiHandler = (event: UiEvent) => void;
23
+ /** Returned by {@link Widget.on}: call it to unsubscribe, or put it in a `using` declaration. */
24
+ export type Unsubscribe = (() => void) & {
25
+ [Symbol.dispose](): void;
26
+ };
27
+ /** The input commands that move focus and operate controls: from the keyboard, a gamepad or code. */
28
+ export type UiCommand = 'up' | 'down' | 'left' | 'right' | 'accept' | 'cancel' | 'next' | 'previous';
29
+ /** Everything a widget needs to draw itself. */
30
+ export interface DrawContext {
31
+ list: DrawList;
32
+ ui: Ui;
33
+ theme: Theme;
34
+ }
35
+ /** Options shared by every widget, on top of the {@link LayoutStyle} fields. */
36
+ export interface WidgetOptions extends LayoutStyle {
37
+ /** Stable name for tests and lookups with `ui.find(id)`. Default `w1`, `w2`, ... */
38
+ id?: string;
39
+ /** Hidden widgets take no space and cannot be focused. Default true. */
40
+ visible?: boolean;
41
+ /** Disabled widgets draw dimmed and ignore pointer, keyboard and gamepad. Default true. */
42
+ enabled?: boolean;
43
+ /** Name for screen readers; defaults to the widget's text. */
44
+ label?: string;
45
+ /** Longer description for screen readers. */
46
+ description?: string;
47
+ /** Text shown after hovering for half a second, or when the keyboard focuses the widget. */
48
+ tooltip?: string;
49
+ /** Whether pointers hit this widget. Default `'auto'` for anything that draws or reacts, `'none'` for plain layout boxes and labels. */
50
+ pointerEvents?: 'auto' | 'none';
51
+ /** Children, as with {@link Widget.add}. */
52
+ children?: readonly Widget[];
53
+ }
54
+ /**
55
+ * Base of every widget: a box in the layout tree with children, state, events and a draw method. Subclasses draw
56
+ * themselves in `draw` and call `invalidate()` when something that changes size or looks has changed.
57
+ */
58
+ export declare class Widget implements LayoutNode {
59
+ /** Stable name, unique within a {@link Ui}. */
60
+ readonly id: string;
61
+ /** Child widgets in draw and focus order. Change them with `add`, `remove` and `clear`. */
62
+ readonly children: Widget[];
63
+ parent: Widget | null;
64
+ /** The UI this widget is part of, or null while detached. */
65
+ ui: Ui | null;
66
+ /** Position and size in UI units, written by the layout. */
67
+ rect: Rect;
68
+ scrollX: number;
69
+ scrollY: number;
70
+ contentWidth: number;
71
+ contentHeight: number;
72
+ /** The screen reader role this widget mirrors. */
73
+ role: string;
74
+ /** True while a pointer is over the widget. */
75
+ hovered: boolean;
76
+ /** True while a pointer or the accept key is held on the widget. */
77
+ pressed: boolean;
78
+ /** True while the widget has input focus. */
79
+ focused: boolean;
80
+ /** True when the focus ring shows: focus that came from the keyboard or a gamepad. */
81
+ focusVisible: boolean;
82
+ /** Opacity of the widget and its children, 0..1. Default 1. */
83
+ get opacity(): number;
84
+ /** Whether keyboard, gamepad and tab navigation can land on this widget. Controls set it. */
85
+ focusable: boolean;
86
+ /** Smoothed 0..1 hover, press and focus levels for transitions. */
87
+ protected readonly levels: {
88
+ hover: number;
89
+ press: number;
90
+ focus: number;
91
+ };
92
+ private readonly handlers;
93
+ private _style;
94
+ private _visible;
95
+ private _enabled;
96
+ private _label?;
97
+ private _description?;
98
+ private _tooltip?;
99
+ pointerEvents: 'auto' | 'none';
100
+ /** @throws TypeError or RangeError for an invalid style field, `children` entry or `pointerEvents`. */
101
+ constructor(options?: WidgetOptions);
102
+ /** The layout style. Change it with {@link Widget.setStyle}. */
103
+ get style(): Readonly<LayoutStyle>;
104
+ /** Merge layout fields into the style (set a field to `undefined` to reset it). */
105
+ setStyle(patch: LayoutStyle): this;
106
+ /** @internal Change the style without asking for a layout; for the UI's own layers. */
107
+ setStyleQuiet(patch: LayoutStyle): void;
108
+ get visible(): boolean;
109
+ set visible(value: boolean);
110
+ get enabled(): boolean;
111
+ set enabled(value: boolean);
112
+ /** The accessible name: the `label` option, or the widget's own text. */
113
+ get label(): string;
114
+ set label(value: string | undefined);
115
+ get description(): string | undefined;
116
+ set description(value: string | undefined);
117
+ get tooltip(): string | undefined;
118
+ set tooltip(value: string | undefined);
119
+ /** Text the widget shows, if any. Labels, buttons and toggles override it. */
120
+ get text(): string | undefined;
121
+ /** True when this widget and every ancestor is visible. */
122
+ get shown(): boolean;
123
+ /** True when this widget and every ancestor is enabled. */
124
+ get active(): boolean;
125
+ /**
126
+ * Append children, moving a child that already has a parent.
127
+ * @throws TypeError for a non-widget or a widget's own ancestor.
128
+ */
129
+ add(...children: Widget[]): this;
130
+ /** Insert `child` at `index` (clamped), moving it if it already has a parent. */
131
+ insert(child: Widget, index: number): this;
132
+ /** Remove `child` if it is one of the children. */
133
+ remove(child: Widget): this;
134
+ /** Remove every child. */
135
+ clear(): this;
136
+ /** Remove this widget from its parent. */
137
+ removeFromParent(): this;
138
+ private detach;
139
+ /** @internal Set `ui` for this subtree. */
140
+ attachTo(ui: Ui | null): void;
141
+ /** Called when the widget joins or leaves a {@link Ui}. */
142
+ protected attached(_ui: Ui | null): void;
143
+ /** The first widget in this subtree with this `id`, or undefined. */
144
+ find(id: string): Widget | undefined;
145
+ /** Visit this widget and every descendant, parents first. */
146
+ walk(visit: (widget: Widget) => void): void;
147
+ /**
148
+ * Listen for an event. Returns a function that removes the listener; it is also disposable, so
149
+ * `using off = button.on('click', fn)` works.
150
+ */
151
+ on(type: string, handler: UiHandler): Unsubscribe;
152
+ /** Call the listeners of `type`. */
153
+ emit(type: string, detail?: Omit<UiEvent, 'type' | 'target'>): void;
154
+ /** Ask the UI to lay out (default) or only redraw the next frame. */
155
+ invalidate(layout?: boolean): void;
156
+ /** Content size without padding, for a box with no children; wrapped to at most `maxWidth`. */
157
+ measure(_maxWidth: number): {
158
+ width: number;
159
+ height: number;
160
+ };
161
+ /** Draw this widget's own look; the children are drawn after it. */
162
+ draw(_context: DrawContext): void;
163
+ /** Draw above the children, for example a dragged item. */
164
+ drawAfter(_context: DrawContext): void;
165
+ /**
166
+ * Advance transitions by `dt` seconds. Return true while something still moves, which keeps the UI redrawing.
167
+ * Subclasses extend it and call `super.tick`.
168
+ */
169
+ tick(dt: number): boolean;
170
+ /**
171
+ * Handle a navigation or accept command before the UI uses it to move focus. Return true to consume it:
172
+ * a slider takes left and right, a text field would take everything.
173
+ */
174
+ command(_command: UiCommand): boolean;
175
+ /** Do what the widget does when clicked, tapped, or accepted with the keyboard or a gamepad. */
176
+ activate(): void;
177
+ /** A pointer went down on this widget (`x`, `y` in UI units). Return true to capture the pointer for drags. */
178
+ pointerDown(_x: number, _y: number): boolean;
179
+ /** A captured pointer moved. */
180
+ pointerMove(_x: number, _y: number): void;
181
+ /** A captured pointer was released. */
182
+ pointerUp(_x: number, _y: number): void;
183
+ /** The wheel turned over this widget (`dy` in UI units, positive scrolls down). Return true if it was used. */
184
+ wheel(dy: number): boolean;
185
+ /** The deepest widget under (x, y) in UI units that takes pointer events, honouring clipping. */
186
+ hitTest(x: number, y: number): Widget | null;
187
+ /** Draw the focus ring around the widget when the keyboard or gamepad focus is on it. */
188
+ protected drawFocus({ list, theme }: DrawContext, grow?: number): void;
189
+ /** Scroll the scrolling ancestors so this widget is fully visible. */
190
+ scrollIntoView(): void;
191
+ /** Remove the widget from its parent and release what it holds. */
192
+ dispose(): void;
193
+ [Symbol.dispose]: () => void;
194
+ }
195
+ /** A colour role of the theme or a `#rrggbb[aa]` string. */
196
+ export type ColorRef = keyof ThemeColors | (string & {});
@@ -0,0 +1,32 @@
1
+ /// <reference lib="esnext.disposable" preserve="true" />
2
+ import type { EngineKernel } from '@margoengine/core';
3
+ import type { Engine, FrameGraph } from '@margoengine/core/extension';
4
+ import { WorldPanels as BaseWorldPanels, WorldPanel, type WorldPanelsOptions } from '@margoengine/ui/world';
5
+ /** World panels on both native backends. The existing WebGPU renderer is reused unchanged. */
6
+ export declare class GlWorldPanels extends BaseWorldPanels {
7
+ private glEngine?;
8
+ private glDevice?;
9
+ private glProgram?;
10
+ private glVao?;
11
+ private glDetach?;
12
+ private readonly glPanels;
13
+ private readonly glOptions;
14
+ private gpuMode;
15
+ private glFrame;
16
+ private glPaintFrame;
17
+ onPreUpdate(delta: number): void;
18
+ /** Attach once; supports native WebGPU, complete compatibility and core's preview WebGL2 backend. */
19
+ static attach(engine: EngineKernel, options?: WorldPanelsOptions): GlWorldPanels;
20
+ constructor(options?: WorldPanelsOptions);
21
+ setup(engine: Engine): void;
22
+ registerPasses(graph: FrameGraph): void;
23
+ private initialize;
24
+ private resourcesGl;
25
+ private drawPanels;
26
+ remove(panel: WorldPanel): void;
27
+ private releaseGl;
28
+ onDeviceRestored(engine: Engine): void;
29
+ dispose(): void;
30
+ }
31
+ export * from '@margoengine/ui/world';
32
+ export { GlWorldPanels as WorldPanels };
@@ -0,0 +1,195 @@
1
+ // @margo/core-built 1.0.0
2
+ import {coreRequirement as __margoCoreRequirement,assertCore as __margoAssertCore} from '@margoengine/core/extension';
3
+
4
+ import { n as e, t } from "./errors-CDgOgzCd.js";
5
+ import { a as n, n as r, r as i } from "./dom-CWJhpotq.js";
6
+ import { t as a } from "./gl-bb768Mje.js";
7
+ import { WorldPanels as o, screenRay as s } from "@margoengine/ui/world";
8
+ export * from "@margoengine/ui/world";
9
+ //#region src/world-gl.ts
10
+ var c = "#version 300 es\nprecision highp float;\nuniform mat4 model; uniform mat4 viewProj; uniform vec2 size; uniform vec4 surface; uniform vec3 eye;\nout vec2 uv; out float facing;\nvoid main(){int v=gl_VertexID%6;int cell=gl_VertexID/6;int cols=int(surface.z);\nvec2 c=(vec2(float(cell%cols),float(cell/cols))+vec2(float((0x32>>v)&1),float((0x2c>>v)&1)))/surface.zw;\nvec3 p=vec3((c.x-.5)*size.x,(.5-c.y)*size.y,0.);vec3 n=vec3(0.,0.,1.);\nif(surface.y>.5){float r=surface.x;float a=p.x/r;float b=surface.y>1.5?p.y/r:0.;n=vec3(sin(a)*cos(b),sin(b),cos(a)*cos(b));p=vec3(r*n.x,surface.y>1.5?r*n.y:p.y,r*(n.z-1.));}\nvec4 world=model*vec4(p,1.);facing=dot(eye-world.xyz,(model*vec4(n,0.)).xyz);gl_Position=viewProj*world;uv=c;}", l = "#version 300 es\nprecision highp float;\nuniform sampler2D panel; uniform bool doubleSided;in vec2 uv;in float facing;out vec4 color;\nvoid main(){if(facing<0.&&!doubleSided)discard;color=texture(panel,vec2(facing<0.?1.-uv.x:uv.x,uv.y));}", u = class u extends o {coreRequirement=__margoCoreRequirement("1.0.0",import.meta.url);
11
+ onPreUpdate(e) {
12
+ super.onPreUpdate(e), this.glFrame++;
13
+ }
14
+ static attach(e, t) {__margoAssertCore(e,__margoCoreRequirement("1.0.0",import.meta.url));
15
+ let n = new u(t);
16
+ return e.use(n), n;
17
+ }
18
+ constructor(e = {}) {
19
+ super(e), this.glPanels = /* @__PURE__ */ new Map(), this.gpuMode = !1, this.glFrame = 0, this.glPaintFrame = -1, this.glOptions = { ...e };
20
+ }
21
+ setup(e) {
22
+ if (this.glEngine = e, this.gpuMode = e.backend === "webgpu", this.gpuMode) {
23
+ super.setup(e);
24
+ return;
25
+ }
26
+ let t = e.canvas;
27
+ if ((this.glOptions.input ?? !0) && t && !this.glDetach) {
28
+ let a = /* @__PURE__ */ new Set(), o = [], c = (n, r) => s(e.camera, n, r, t.clientWidth || 1, t.clientHeight || 1);
29
+ r({
30
+ pointerMove: (e, t, n) => this.pointer(c(e, t), a.has(n.id ?? 0), n),
31
+ pointerDown: (e, t, n) => {
32
+ if (n.button) return !1;
33
+ a.add(n.id ?? 0);
34
+ let r = this.pointer(c(e, t), !0, n);
35
+ return r || a.delete(n.id ?? 0), r;
36
+ },
37
+ pointerUp: (e, t, n) => a.delete(n.id ?? 0) ? this.pointer(c(e, t), !1, n) : !1,
38
+ pointerCancel: () => {
39
+ a.clear(), this.cancel();
40
+ },
41
+ pointerLeave: () => {
42
+ if (!a.size) for (let e of this.list) e.ui.pointerLeave();
43
+ },
44
+ wheel: (e, t, n) => {
45
+ let r, i = null, a = c(e, t);
46
+ for (let e of this.list) {
47
+ if (!e.visible) continue;
48
+ let t = e.intersect(a);
49
+ t?.inside && (!i || t.distance < i.distance) && (r = e, i = t);
50
+ }
51
+ return !!r && !!i && r.ui.wheel(i.x, i.y, n);
52
+ }
53
+ }, t, n(t, o)), this.glDetach = i(o, this.glOptions.signal);
54
+ }
55
+ }
56
+ registerPasses(e) {
57
+ this.gpuMode ? super.registerPasses(e) : e.add({
58
+ name: `${this.name}:draw`,
59
+ order: this.order,
60
+ execute: (e) => this.drawPanels(e)
61
+ });
62
+ }
63
+ initialize(e) {
64
+ if (this.glDevice === e && this.glProgram) return;
65
+ this.glDevice = e;
66
+ let n = e.createProgram();
67
+ for (let [t, r] of [[e.VERTEX_SHADER, c], [e.FRAGMENT_SHADER, l]]) {
68
+ let i = e.createShader(t);
69
+ e.shaderSource(i, r), e.compileShader(i), e.attachShader(n, i), e.deleteShader(i);
70
+ }
71
+ if (e.linkProgram(n), !e.getProgramParameter(n, e.LINK_STATUS)) throw t("failed", `World panel WebGL2 shader failed: ${e.getProgramInfoLog(n)}; report the browser and GPU`, "ui");
72
+ this.glProgram = n, this.glVao = e.createVertexArray();
73
+ }
74
+ resourcesGl(n, r) {
75
+ let i = this.glPanels.get(n);
76
+ if (i) return i;
77
+ let o = Math.round(n.cssWidth * n.pixelRatio), s = Math.round(n.cssHeight * n.pixelRatio), c = r.getParameter(r.MAX_TEXTURE_SIZE);
78
+ if (o < 1 || s < 1 || o > c || s > c) throw e(`World panel ${o} by ${s} exceeds the WebGL2 limit ${c}; lower the size or pixelRatio`, "ui");
79
+ let l = r.createTexture(), u = r.createFramebuffer();
80
+ if (r.bindTexture(r.TEXTURE_2D, l), r.texStorage2D(r.TEXTURE_2D, Math.floor(Math.log2(Math.max(o, s))) + 1, r.RGBA8, o, s), r.texParameteri(r.TEXTURE_2D, r.TEXTURE_MIN_FILTER, r.LINEAR_MIPMAP_LINEAR), r.texParameteri(r.TEXTURE_2D, r.TEXTURE_MAG_FILTER, r.LINEAR), r.texParameteri(r.TEXTURE_2D, r.TEXTURE_WRAP_S, r.CLAMP_TO_EDGE), r.texParameteri(r.TEXTURE_2D, r.TEXTURE_WRAP_T, r.CLAMP_TO_EDGE), r.bindFramebuffer(r.FRAMEBUFFER, u), r.framebufferTexture2D(r.FRAMEBUFFER, r.COLOR_ATTACHMENT0, r.TEXTURE_2D, l, 0), r.checkFramebufferStatus(r.FRAMEBUFFER) !== r.FRAMEBUFFER_COMPLETE) throw t("failed", "World panel framebuffer is incomplete; lower its pixelRatio", "ui");
81
+ let d = {
82
+ texture: l,
83
+ framebuffer: u,
84
+ width: o,
85
+ height: s,
86
+ painter: new a(r, {
87
+ atlasSize: 1024,
88
+ colorAtlasSize: 512,
89
+ maxPages: 16
90
+ }, {
91
+ rects: 0,
92
+ glyphs: 0,
93
+ drawCalls: 0,
94
+ uploads: 0
95
+ }),
96
+ version: -1
97
+ };
98
+ return this.glPanels.set(n, d), d;
99
+ }
100
+ drawPanels(e) {
101
+ if (e.backend !== "webgl2" || !this.glEngine || e.gl.isContextLost()) return;
102
+ let t = e.gl, n = d(t);
103
+ this.stats.panels = this.stats.drawCalls = 0, this.glPaintFrame !== this.glFrame && (this.stats.repaints = 0), this.glPaintFrame = this.glFrame;
104
+ try {
105
+ t.bindBuffer(t.PIXEL_UNPACK_BUFFER, null);
106
+ for (let e of [
107
+ t.UNPACK_ROW_LENGTH,
108
+ t.UNPACK_IMAGE_HEIGHT,
109
+ t.UNPACK_SKIP_PIXELS,
110
+ t.UNPACK_SKIP_ROWS,
111
+ t.UNPACK_SKIP_IMAGES,
112
+ t.UNPACK_FLIP_Y_WEBGL,
113
+ t.UNPACK_PREMULTIPLY_ALPHA_WEBGL
114
+ ]) t.pixelStorei(e, 0);
115
+ t.pixelStorei(t.UNPACK_COLORSPACE_CONVERSION_WEBGL, t.NONE), this.initialize(t), t.bindSampler(0, null), t.bindSampler(1, null);
116
+ let r = [];
117
+ for (let n of this.list) {
118
+ if (!n.visible) continue;
119
+ let i = this.resourcesGl(n, t), a = n.ui.draw();
120
+ i.version !== a.version && (t.bindFramebuffer(t.FRAMEBUFFER, i.framebuffer), t.disable(t.SCISSOR_TEST), t.colorMask(!0, !0, !0, !0), t.clearColor(0, 0, 0, 0), t.clear(t.COLOR_BUFFER_BIT), i.painter.draw(a, i.width, i.height, i.framebuffer), t.activeTexture(t.TEXTURE0), t.bindTexture(t.TEXTURE_2D, i.texture), t.generateMipmap(t.TEXTURE_2D), i.version = a.version, this.stats.repaints++), (n.doubleSided || n.side(e.camera.position) > 0) && r.push([n, i]);
121
+ }
122
+ t.bindFramebuffer(t.FRAMEBUFFER, n.framebuffer);
123
+ let i = e.view?.viewport ?? [
124
+ 0,
125
+ 0,
126
+ e.width,
127
+ e.height
128
+ ], a = e.view?.scissor ?? i;
129
+ t.viewport(i[0], e.height - i[1] - i[3], i[2], i[3]), t.enable(t.SCISSOR_TEST), t.scissor(a[0], e.height - a[1] - a[3], a[2], a[3]), t.enable(t.DEPTH_TEST), t.depthFunc(t.LEQUAL), t.depthMask(!1), t.disable(t.CULL_FACE), t.enable(t.BLEND), t.blendFuncSeparate(t.ONE, t.ONE_MINUS_SRC_ALPHA, t.ONE, t.ONE_MINUS_SRC_ALPHA), t.blendEquation(t.FUNC_ADD), t.colorMask(!0, !0, !0, !0);
130
+ let o = this.glProgram;
131
+ t.useProgram(o), t.bindVertexArray(this.glVao), t.activeTexture(t.TEXTURE0), t.uniform1i(t.getUniformLocation(o, "panel"), 0), t.uniformMatrix4fv(t.getUniformLocation(o, "viewProj"), !1, e.camera.matrix);
132
+ for (let [n, i] of r) t.bindTexture(t.TEXTURE_2D, i.texture), t.uniformMatrix4fv(t.getUniformLocation(o, "model"), !1, n.matrix), t.uniform2f(t.getUniformLocation(o, "size"), n.width, n.height), t.uniform4fv(t.getUniformLocation(o, "surface"), n.surface), t.uniform3fv(t.getUniformLocation(o, "eye"), e.camera.position), t.uniform1i(t.getUniformLocation(o, "doubleSided"), +!!n.doubleSided), t.drawArrays(t.TRIANGLES, 0, 6 * n.surface[2] * n.surface[3]), this.stats.panels++, this.stats.drawCalls++;
133
+ } finally {
134
+ n.apply();
135
+ }
136
+ }
137
+ remove(e) {
138
+ this.releaseGl(e), super.remove(e);
139
+ }
140
+ releaseGl(e) {
141
+ let t = this.glPanels.get(e), n = this.glDevice;
142
+ t && n && (t.painter.dispose(), n.deleteTexture(t.texture), n.deleteFramebuffer(t.framebuffer), this.glPanels.delete(e));
143
+ }
144
+ onDeviceRestored(e) {
145
+ this.gpuMode ? super.onDeviceRestored(e) : (this.glPanels.clear(), this.glProgram = this.glVao = void 0, this.glDevice = void 0, this.setup(e));
146
+ }
147
+ dispose() {
148
+ let e = this.glEngine;
149
+ this.glDetach?.(), this.glDetach = void 0;
150
+ for (let e of this.glPanels.keys()) this.releaseGl(e);
151
+ this.glDevice && (this.glDevice.deleteProgram(this.glProgram ?? null), this.glDevice.deleteVertexArray(this.glVao ?? null)), this.glProgram = this.glVao = void 0, this.glDevice = this.glEngine = void 0, super.dispose(), e?.sceneOf(this)?.removePlugin(this.name);
152
+ }
153
+ };
154
+ function d(e) {
155
+ let t = e.getParameter(e.PIXEL_UNPACK_BUFFER_BINDING), n = [
156
+ e.UNPACK_ROW_LENGTH,
157
+ e.UNPACK_IMAGE_HEIGHT,
158
+ e.UNPACK_SKIP_PIXELS,
159
+ e.UNPACK_SKIP_ROWS,
160
+ e.UNPACK_SKIP_IMAGES,
161
+ e.UNPACK_FLIP_Y_WEBGL,
162
+ e.UNPACK_PREMULTIPLY_ALPHA_WEBGL,
163
+ e.UNPACK_COLORSPACE_CONVERSION_WEBGL
164
+ ].map((t) => [t, e.getParameter(t)]), r = e.getParameter(e.DRAW_FRAMEBUFFER_BINDING), i = e.getParameter(e.READ_FRAMEBUFFER_BINDING), a = e.getParameter(e.VIEWPORT), o = e.getParameter(e.SCISSOR_BOX), s = e.getParameter(e.CURRENT_PROGRAM), c = e.getParameter(e.VERTEX_ARRAY_BINDING), l = e.getParameter(e.ARRAY_BUFFER_BINDING), u = e.getParameter(e.ACTIVE_TEXTURE), d = e.getParameter(e.COLOR_CLEAR_VALUE), f = e.getParameter(e.COLOR_WRITEMASK), p = e.getParameter(e.DEPTH_WRITEMASK), m = e.getParameter(e.DEPTH_FUNC), h = e.getParameter(e.UNPACK_ALIGNMENT), g = [
165
+ e.DEPTH_TEST,
166
+ e.BLEND,
167
+ e.CULL_FACE,
168
+ e.SCISSOR_TEST
169
+ ].map((t) => [t, e.isEnabled(t)]), _ = [
170
+ e.BLEND_SRC_RGB,
171
+ e.BLEND_DST_RGB,
172
+ e.BLEND_SRC_ALPHA,
173
+ e.BLEND_DST_ALPHA,
174
+ e.BLEND_EQUATION_RGB,
175
+ e.BLEND_EQUATION_ALPHA
176
+ ].map((t) => e.getParameter(t)), v = [0, 1].map((t) => (e.activeTexture(e.TEXTURE0 + t), [
177
+ e.getParameter(e.TEXTURE_BINDING_2D),
178
+ e.getParameter(e.TEXTURE_BINDING_2D_ARRAY),
179
+ e.getParameter(e.SAMPLER_BINDING)
180
+ ]));
181
+ return e.activeTexture(u), {
182
+ framebuffer: r,
183
+ apply() {
184
+ e.bindFramebuffer(e.DRAW_FRAMEBUFFER, r), e.bindFramebuffer(e.READ_FRAMEBUFFER, i), e.viewport(...a), e.scissor(...o), e.useProgram(s), e.bindVertexArray(c), e.bindBuffer(e.ARRAY_BUFFER, l), e.clearColor(...d), e.colorMask(...f), e.depthMask(p), e.depthFunc(m), e.pixelStorei(e.UNPACK_ALIGNMENT, h);
185
+ for (let [t, r] of n) e.pixelStorei(t, Number(r));
186
+ e.bindBuffer(e.PIXEL_UNPACK_BUFFER, t), e.blendFuncSeparate(_[0], _[1], _[2], _[3]), e.blendEquationSeparate(_[4], _[5]);
187
+ for (let [t, n] of g) n ? e.enable(t) : e.disable(t);
188
+ v.forEach((t, n) => {
189
+ e.activeTexture(e.TEXTURE0 + n), e.bindTexture(e.TEXTURE_2D, t[0]), e.bindTexture(e.TEXTURE_2D_ARRAY, t[1]), e.bindSampler(n, t[2]);
190
+ }), e.activeTexture(u);
191
+ }
192
+ };
193
+ }
194
+ //#endregion
195
+ export { u as GlWorldPanels, u as WorldPanels };
@@ -0,0 +1,216 @@
1
+ /// <reference lib="esnext.disposable" preserve="true" />
2
+ import type { EngineKernel } from '@margoengine/core';
3
+ import type { Engine, EnginePlugin, FrameGraph } from '@margoengine/core/extension';
4
+ import type { PointerInfo } from './interaction.js';
5
+ import type { Ui } from './ui.js';
6
+ type Vec3 = readonly [number, number, number];
7
+ /** A ray in world space; `direction` need not be unit length. */
8
+ export interface UiRay {
9
+ origin: ArrayLike<number>;
10
+ direction: ArrayLike<number>;
11
+ }
12
+ /** Where a ray meets a {@link WorldPanel}. */
13
+ export interface PanelHit {
14
+ /** Distance along the ray in units of its direction's length (metres for a unit direction). */
15
+ distance: number;
16
+ /** The world point. */
17
+ point: [number, number, number];
18
+ /** The point in the panel's UI, in CSS pixels from its top left (as `ui.pointerMove` takes them). */
19
+ x: number;
20
+ y: number;
21
+ /** True when the point lies on the panel rather than elsewhere on its plane. */
22
+ inside: boolean;
23
+ /** True when the ray comes from the panel's back (only a double-sided panel is hit there). */
24
+ back: boolean;
25
+ }
26
+ /** Options for {@link WorldPanel}. */
27
+ export interface WorldPanelOptions {
28
+ /** Width in world units (metres with glTF scenes). Default 1. */
29
+ width?: number;
30
+ /** Height in world units. Default: the width times the UI's height over its width, so the UI keeps its shape. */
31
+ height?: number;
32
+ /** Centre of the panel. Default `[0, 0, 0]`. */
33
+ position?: Vec3;
34
+ /** Orientation as a unit quaternion `[x, y, z, w]`; the UI faces +Z with +Y up. Default `[0, 0, 0, 1]`. */
35
+ rotation?: readonly [number, number, number, number];
36
+ /** Texture pixels per CSS pixel of the UI: higher is sharper up close and costs memory. Default 1. */
37
+ pixelRatio?: number;
38
+ /** Show (and take input on) the back too, mirrored so its text reads right. Default false: the back is invisible. */
39
+ doubleSided?: boolean;
40
+ }
41
+ /**
42
+ * A {@link Ui} on a flat rectangle in the 3D scene: a diegetic screen, a VR menu or a wrist panel. The UI keeps its CSS
43
+ * pixel size (`new Ui({ width, height })`) and is drawn into a texture that a {@link WorldPanels} renderer puts in the
44
+ * scene, depth-tested against it. Pointer, touch and XR controller rays reach its widgets through `pointerMove`,
45
+ * `pointerDown` and `pointerUp`, which take a ray instead of a point.
46
+ *
47
+ * `matrix` is the panel's pose (column-major, rigid); set `position` and `rotation`, or copy a pose into `matrix` (an XR
48
+ * grip, say) and call nothing else. Width and height are in world units along the matrix's X and Y axes.
49
+ *
50
+ * @example
51
+ * const menu = new Ui({ width: 640, height: 400 });
52
+ * const panel = new WorldPanel(menu, { width: 1.6, position: [0, 1.5, -2] });
53
+ * WorldPanels.attach(engine).add(panel);
54
+ */
55
+ export declare class WorldPanel {
56
+ readonly ui: Ui;
57
+ /** Optional parametric surface: radius, kind (1 cylinder, 2 sphere), horizontal and vertical segments. */
58
+ get surface(): readonly [number, number, number, number];
59
+ /** The pose: column-major, rotation and translation only. */
60
+ readonly matrix: Float32Array<ArrayBuffer>;
61
+ /** Width in world units. */
62
+ width: number;
63
+ /** Height in world units. */
64
+ height: number;
65
+ /** Draw and hit the back as well. */
66
+ doubleSided: boolean;
67
+ /** Hidden panels are neither drawn nor hit. Default true. */
68
+ visible: boolean;
69
+ /** Texture pixels per CSS pixel. */
70
+ readonly pixelRatio: number;
71
+ /** The UI's size in CSS pixels, fixed when the panel is made. */
72
+ readonly cssWidth: number;
73
+ readonly cssHeight: number;
74
+ /**
75
+ * @throws TypeError for a missing `ui`.
76
+ * @throws RangeError for a size or pixel ratio that is not finite and positive, or a rotation that is not a unit quaternion.
77
+ */
78
+ constructor(ui: Ui, options?: WorldPanelOptions);
79
+ /**
80
+ * Place the panel: centre `position`, orientation `rotation` (a unit quaternion `[x, y, z, w]`).
81
+ * @throws RangeError for non-finite values or a quaternion whose length is not 1.
82
+ */
83
+ setPose(position: Vec3, rotation: readonly [number, number, number, number]): void;
84
+ /** The side `eye` is on: +1 in front, -1 behind, 0 on the plane. */
85
+ side(eye: ArrayLike<number>): number;
86
+ /**
87
+ * Where `ray` meets the panel's plane, or null when it runs parallel to it, points away from it, or comes from a
88
+ * one-sided panel's back. `inside` says whether the point is on the panel itself.
89
+ */
90
+ intersect(ray: UiRay): PanelHit | null;
91
+ /** Hover with a ray (a mouse, or a controller's pointing ray). Returns true when the UI used it. */
92
+ pointerMove(ray: UiRay, info?: PointerInfo): boolean;
93
+ /** Press with a ray. Returns true when it landed on a widget; otherwise the game should have it. */
94
+ pointerDown(ray: UiRay, info?: PointerInfo): boolean;
95
+ /** Release with a ray. Returns true when it ends a press that began on the UI; a ray off the panel still ends it. */
96
+ pointerUp(ray: UiRay, info?: PointerInfo): boolean;
97
+ }
98
+ /**
99
+ * The world ray under a point of the canvas: from the camera's `position` through (`x`, `y`) CSS pixels of a
100
+ * `width` by `height` view, for core's perspective `engine.camera` (its matrix is set once a frame has been drawn).
101
+ * @throws TypeError for a camera without a 16-element matrix; RangeError for one with no inverse yet.
102
+ */
103
+ export declare function screenRay(camera: {
104
+ readonly matrix: ArrayLike<number>;
105
+ readonly position: ArrayLike<number>;
106
+ }, x: number, y: number, width: number, height: number): UiRay;
107
+ /** An XR pointing ray from a column-major pose matrix (WebXR's target ray space points along its -Z axis). */
108
+ export declare function rayFromMatrix(matrix: ArrayLike<number>): UiRay;
109
+ /** The nearest visible panel that `ray` lands on, with the hit, or null. */
110
+ export declare function pickPanel(panels: Iterable<WorldPanel>, ray: UiRay): {
111
+ panel: WorldPanel;
112
+ hit: PanelHit;
113
+ } | null;
114
+ /** A controller as `@margoengine/xr`'s `XRController` has it: a target-ray pose and button values. */
115
+ export interface RayController {
116
+ /** Column-major pose of the pointing ray; all zero when untracked. */
117
+ readonly targetRayMatrix: ArrayLike<number>;
118
+ /** Per button: value, pressed, touched. Button 0 (the trigger) presses. */
119
+ readonly buttons: ArrayLike<number>;
120
+ }
121
+ /** Options for {@link WorldPanels}. */
122
+ export interface WorldPanelsOptions {
123
+ /** Plugin name, unique per engine. Default `'ui-world'`. */
124
+ name?: string;
125
+ /** Frame graph order. Default 25: after the scene and lines, before post-processing resolves at 30, so panels are part of the picture. */
126
+ order?: number;
127
+ /** Route the canvas's mouse, pen and touch to the panels by camera ray. Default true. */
128
+ input?: boolean;
129
+ /** Detach the canvas listeners when the signal aborts. */
130
+ signal?: AbortSignal;
131
+ }
132
+ /**
133
+ * Engine plugin that draws {@link WorldPanel}s in the scene and routes rays to them. Each frame it steps every panel's
134
+ * UI, redraws a panel's texture only when its UI changed (with mipmaps, so a distant panel does not shimmer), and draws
135
+ * each visible panel as a depth-tested quad in every view, XR eyes included. With `input` (the default) a mouse, pen or
136
+ * touch on the canvas reaches the nearest panel under it, and an event a panel used does not reach the game; call
137
+ * {@link WorldPanels.controller} each frame for each XR controller.
138
+ *
139
+ * WebGPU only; on WebGL2 the panels still update and take rays, but nothing is drawn.
140
+ *
141
+ * @example
142
+ * const panels = WorldPanels.attach(engine);
143
+ * panels.add(new WorldPanel(menuUi, { width: 1.2, position: [0, 1.4, -1.5] }));
144
+ * xr.onFrame(() => panels.controller(xr.controllers[0], 1)); // trigger presses, the ray hovers
145
+ */
146
+ export declare class WorldPanels implements EnginePlugin {
147
+ readonly name: string;
148
+ readonly order: number;
149
+ /** Counts for the latest frame: panels drawn, panel textures redrawn and draw calls. */
150
+ readonly stats: {
151
+ panels: number;
152
+ repaints: number;
153
+ drawCalls: number;
154
+ };
155
+ private readonly panels;
156
+ private readonly gpu;
157
+ private readonly pointers;
158
+ private readonly input;
159
+ private readonly signal?;
160
+ private readonly descriptor;
161
+ private readonly cameras;
162
+ private readonly cameraData;
163
+ private readonly panelData;
164
+ private readonly mipCache;
165
+ private readonly pipelines;
166
+ private engine?;
167
+ private device?;
168
+ private module?;
169
+ private panelLayout?;
170
+ private cameraLayout?;
171
+ private pipelineLayout?;
172
+ private sampler?;
173
+ private detach?;
174
+ private frameDrawn;
175
+ private frame;
176
+ /** Same as `engine.use(new WorldPanels(options))`; returns the plugin. */
177
+ static attach(engine: EngineKernel, options?: WorldPanelsOptions): WorldPanels;
178
+ /** @throws TypeError for an empty name or a non-finite order. */
179
+ constructor(options?: WorldPanelsOptions);
180
+ /** Add panels; returns this. */
181
+ add(...panels: WorldPanel[]): this;
182
+ /** Remove a panel and free its texture. The panel's `Ui` is not disposed. */
183
+ remove(panel: WorldPanel): void;
184
+ /** The panels, in the order they were added. */
185
+ get list(): readonly WorldPanel[];
186
+ /**
187
+ * One pointer's ray and button state, from any device: hovers the nearest panel under the ray, leaves the one it
188
+ * left, and on a change of `pressed` presses or releases. A pressed pointer stays with the panel it pressed until it
189
+ * is released, even off the panel (dragging a slider). Returns true when a panel used it.
190
+ */
191
+ pointer(ray: UiRay, pressed: boolean, info?: PointerInfo): boolean;
192
+ /**
193
+ * Feed an XR controller (or anything with a target-ray pose and buttons) for this frame: its ray hovers, button 0 (the
194
+ * trigger) presses. `id` keeps two hands apart. An untracked controller (all-zero pose) leaves the panels.
195
+ */
196
+ controller(source: RayController, id?: number): boolean;
197
+ /** Take a press away from every panel (the canvas lost focus, an XR session ended). */
198
+ cancel(): void;
199
+ setup(engine: Engine): void;
200
+ registerPasses(graph: FrameGraph): void;
201
+ onPreUpdate(delta: number): void;
202
+ /** Mouse, pen and touch on the canvas, as screen rays from the engine's camera. */
203
+ private listen;
204
+ private resources;
205
+ /** Redraw a panel's texture when its UI changed; the UI pass and the mipmaps go in their own submissions. */
206
+ private paint;
207
+ private camera;
208
+ private pipeline;
209
+ private readonly execute;
210
+ private release;
211
+ onDeviceRestored(engine: Engine): void;
212
+ /** Free every panel texture and detach the canvas listeners. The panels' `Ui`s are not disposed. */
213
+ dispose(): void;
214
+ [Symbol.dispose]: () => void;
215
+ }
216
+ export {};