@margoengine/pixel 0.0.0-stage → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/follow.js ADDED
@@ -0,0 +1,172 @@
1
+ // @margo/core-built 1.0.0
2
+ import {coreRequirement as __margoCoreRequirement,assertCore as __margoAssertCore} from '@margoengine/core/extension';
3
+ const i=(engine,version="1.0.0",source=import.meta.url)=>__margoRuntime(engine,version,source);
4
+ import { n as e, t } from "./errors-CDgOgzCd.js";
5
+ import { n, t as r } from "./blit-DyxX_nQq.js";
6
+ import { engineRuntime as __margoRuntime } from "@margoengine/core/extension";
7
+ //#region src/follow.ts
8
+ var a = `
9
+ struct S { rect:vec4i, color:vec4f }
10
+ @group(0) @binding(0) var<uniform> s:S;
11
+ @group(0) @binding(1) var image:texture_2d<f32>;
12
+ ${n}
13
+ @fragment fn fs()->@location(0) vec4f { return s.color*textureLoad(image,vec2i(0),0); }
14
+ `, o = (t, n, r = -Infinity, i = Infinity) => {
15
+ if (!Number.isFinite(t) || t < r || t > i) throw e(`PixelFollow ${n} must be finite in [${r}, ${i}], got ${t}`, "pixel-options");
16
+ return t;
17
+ }, s = (e) => e.map((e) => o(e, "color", 0, 1)), c = (e, t, n) => Math.max(t, Math.min(n, e)), l = 0, u = class n extends r {coreRequirement=__margoCoreRequirement("1.0.0",import.meta.url);
18
+ #e;
19
+ #t;
20
+ #n;
21
+ #r = 0;
22
+ #i;
23
+ #a;
24
+ #o = [
25
+ 0,
26
+ 0,
27
+ 0,
28
+ 0
29
+ ];
30
+ #s;
31
+ #c;
32
+ #l = !1;
33
+ constructor(t) {
34
+ let n = {};
35
+ if (super({
36
+ source: () => n.value,
37
+ fit: "stretch",
38
+ order: t.order ?? 100,
39
+ layers: t.layers,
40
+ name: t.name
41
+ }, "PixelFollow", a, 32, `pixel-follow-${++l}`), !t.camera) throw e("PixelFollow needs a camera", "pixel-options");
42
+ this.camera = t.camera, this.target = t.target, this.lerp = t.lerp ?? 1, this.deadZone = t.deadZone ?? [0, 0], this.offset = t.offset ?? [0, 0], this.bounds = t.bounds, this.#e = [this.camera.x, this.camera.y], this.#t = [...this.#e], this.#s = n, this.update(0);
43
+ }
44
+ static attach(e, t) {__margoAssertCore(e,__margoCoreRequirement("1.0.0",import.meta.url));
45
+ let r = new n(t);
46
+ return i(e).use(r), r;
47
+ }
48
+ setup(e) {
49
+ super.setup(e), this.#c = e, this.#u();
50
+ }
51
+ #u() {
52
+ let e = this.#c.gpu;
53
+ this.#s.value = e.createTexture({
54
+ size: [1, 1],
55
+ format: "rgba8unorm",
56
+ usage: 6
57
+ }), e.queue.writeTexture({ texture: this.#s.value }, new Uint8Array([
58
+ 255,
59
+ 255,
60
+ 255,
61
+ 255
62
+ ]), { bytesPerRow: 4 }, [1, 1]);
63
+ }
64
+ onDeviceRestored() {
65
+ super.onDeviceRestored(), this.#s.value?.destroy(), this.#u();
66
+ }
67
+ get time() {
68
+ return this.#r;
69
+ }
70
+ advanceTime(e) {
71
+ this.update(e), this.#r += e;
72
+ }
73
+ onPreUpdate(e) {
74
+ super.onPreUpdate(e), this.advanceTime(e);
75
+ }
76
+ update(e) {
77
+ if (this.#l) throw t("disposed", "PixelFollow disposed; create a new rig", "disposed");
78
+ o(e, "delta", 0);
79
+ let n = this.camera, r = n.unitsPerPixel, i = typeof this.target == "function" ? this.target() : this.target, a = [0, 0];
80
+ for (let t of [0, 1]) {
81
+ let s = t === 0 ? "x" : "y", l = t === 0 ? n.width : n.height, u = o(n[s], `camera.${s}`);
82
+ u !== this.#t[t] && (this.#e[t] = u);
83
+ let d = o(typeof this.lerp == "number" ? this.lerp : this.lerp[t], "lerp", 0, 1), f = o(this.deadZone[t], "deadZone", 0, l) * r / 2, p = o(this.offset[t], "offset"), m = this.#e[t];
84
+ if (i) {
85
+ let t = o(i[s], `target.${s}`) + p - m - l * r / 2, n = t - c(t, -f, f);
86
+ m += n * (e === 0 ? 0 : -Math.expm1(Math.log1p(-d) * e * 60));
87
+ }
88
+ let h = -Infinity, g = Infinity;
89
+ if (this.bounds) {
90
+ let e = o(this.bounds[s], `bounds.${s}`), n = o(t === 0 ? this.bounds.width : this.bounds.height, "bounds size", 0);
91
+ h = Math.ceil(e / r), g = Math.floor((e + n - l * r) / r), h > g && (h = g = Math.round((e + (n - l * r) / 2) / r)), m = c(m, h * r, g * r);
92
+ }
93
+ this.#e[t] = m;
94
+ let _ = 0;
95
+ if (this.#a) {
96
+ let n = this.#a, r = n.elapsed + e;
97
+ if (r < n.duration) {
98
+ let e = Math.floor(r * 60) + 1 ^ n.seed ^ t * 2654435769;
99
+ e = Math.imul(e ^ e >>> 16, 73244475), e = Math.imul(e ^ e >>> 16, 73244475), _ = Math.round((((e ^ e >>> 16) >>> 0) / 4294967295 * 2 - 1) * n.amplitude[t] * (1 - r / n.duration));
100
+ }
101
+ }
102
+ a[t] = c(Math.round(m / r) + _, h, g) * r;
103
+ }
104
+ this.#a && (this.#a.elapsed += e) >= this.#a.duration && (this.#a = void 0), this.camera.x = a[0], this.camera.y = a[1], this.#t = a;
105
+ let s = [
106
+ 0,
107
+ 0,
108
+ 0,
109
+ 0
110
+ ];
111
+ for (let t of [this.#i, this.#n]) if (t) {
112
+ t.elapsed = Math.min(t.duration, t.elapsed + e);
113
+ let n = t.from + (t.to - t.from) * t.elapsed / t.duration;
114
+ for (let e = 0; e < 3; e++) s[e] = t.color[e] * n + s[e] * (1 - n);
115
+ s[3] = n + s[3] * (1 - n);
116
+ }
117
+ return this.#o = s, this;
118
+ }
119
+ get overlay() {
120
+ return [...this.#o];
121
+ }
122
+ shake(e = .25, t = 4, n = 1) {
123
+ let r = typeof t == "number" ? [t, t] : t;
124
+ return r.forEach((e) => o(e, "amplitude", 0)), o(n, "seed"), this.#a = {
125
+ elapsed: 0,
126
+ duration: o(e, "duration", Number.MIN_VALUE),
127
+ amplitude: [...r],
128
+ seed: n
129
+ }, this.update(0);
130
+ }
131
+ flash(e = .25, t = [
132
+ 1,
133
+ 1,
134
+ 1
135
+ ]) {
136
+ return this.#n = this.#d(e, t, 1, 0), this.update(0);
137
+ }
138
+ fadeOut(e = .5, t = [
139
+ 0,
140
+ 0,
141
+ 0
142
+ ]) {
143
+ return this.#i = this.#d(e, t, 0, 1), this.update(0);
144
+ }
145
+ fadeIn(e = .5, t = [
146
+ 0,
147
+ 0,
148
+ 0
149
+ ]) {
150
+ return this.#i = this.#d(e, t, 1, 0), this.update(0);
151
+ }
152
+ #d(e, t, n, r) {
153
+ return {
154
+ elapsed: 0,
155
+ duration: o(e, "duration", Number.MIN_VALUE),
156
+ color: s(t),
157
+ from: n,
158
+ to: r
159
+ };
160
+ }
161
+ resetEffects() {
162
+ return this.#a = this.#n = this.#i = void 0, this.update(0);
163
+ }
164
+ fill(e, t) {
165
+ new Int32Array(e).set(t), new Float32Array(e).set(this.#o, 4);
166
+ }
167
+ dispose() {
168
+ this.#l ||= (super.dispose(), this.#s.value?.destroy(), this.#c = void 0, !0);
169
+ }
170
+ };
171
+ //#endregion
172
+ export { u as PixelFollow };
@@ -0,0 +1,160 @@
1
+ /// <reference lib="esnext.disposable" preserve="true" />
2
+ import type { EngineKernel } from '@margoengine/core';
3
+ import { type Engine, type EnginePlugin } from '@margoengine/core/extension';
4
+ import { PixelCamera, type Parallax, type PixelCameraOptions } from './camera.js';
5
+ export { PixelCamera, type LayerScroll, type Parallax, type PixelCameraOptions, type PixelProjection, } from './camera.js';
6
+ /** How a layer's colours mix with what is below it. */
7
+ export type PixelBlend = 'normal' | 'add' | 'multiply' | 'screen';
8
+ /**
9
+ * Who moves a layer when the camera scrolls. `'view'`: whatever draws it follows {@link PixelLayer.camera}, so the
10
+ * layer holds what the camera sees. `'world'`: the layer holds a fixed picture and the compositor moves it.
11
+ */
12
+ export type LayerAnchor = 'view' | 'world';
13
+ /** Straight-alpha RGBA8 texels, row by row from the top: `ImageData` fits. */
14
+ export interface PixelImage {
15
+ width: number;
16
+ height: number;
17
+ data: Uint8Array | Uint8ClampedArray;
18
+ }
19
+ /** A camera in the shape a sprite layer reads each frame: the world point at the top-left and pixels per world unit. */
20
+ export interface LayerCamera {
21
+ readonly x: number;
22
+ readonly y: number;
23
+ readonly zoom: number;
24
+ }
25
+ /** Settings of {@link PixelLayer}, passed to {@link LayerCompositor.addLayer}. */
26
+ export interface PixelLayerOptions {
27
+ /** Target width in low-res pixels. Default the camera's. */
28
+ width?: number;
29
+ /** Target height in low-res pixels. Default the camera's. */
30
+ height?: number;
31
+ /** See {@link LayerAnchor}. Default `'view'`. */
32
+ anchor?: LayerAnchor;
33
+ /** Scroll factor against the camera. Default 1. */
34
+ parallax?: Parallax;
35
+ /** Extra offset in low-res pixels. Default 0. */
36
+ x?: number;
37
+ /** Extra offset in low-res pixels. Default 0. */
38
+ y?: number;
39
+ /** Multiplies the layer's colours, 0 to 1. Default 1. */
40
+ opacity?: number;
41
+ /** Default `'normal'`. */
42
+ blend?: PixelBlend;
43
+ /** Clockwise turn about {@link pivot}, radians. Default 0. */
44
+ rotation?: number;
45
+ /** The point it turns about, in low-res view pixels. Default the middle of the view. */
46
+ pivot?: readonly [number, number];
47
+ /** Higher draws over lower; equal `z` keeps the order added. Default 0. */
48
+ z?: number;
49
+ /** False leaves it out of the composite. Default true. */
50
+ visible?: boolean;
51
+ }
52
+ /** Settings of {@link LayerCompositor}. */
53
+ export interface LayerCompositorOptions {
54
+ /** The view, a {@link PixelCamera} or the options to make one. Required. */
55
+ camera: PixelCamera | PixelCameraOptions;
56
+ /** Frame-graph order. 30 runs before a Tonemap (31); 40 keeps the bytes out of it. Default 30. */
57
+ order?: number;
58
+ /** Render-layer bits; a canvas view whose `layers` shares none gets no composite. Default 1. */
59
+ layers?: number;
60
+ /** Plugin name, unique per scene. Default `pixel-1`, `pixel-2`, ... */
61
+ name?: string;
62
+ }
63
+ /**
64
+ * One low-res `rgba8unorm` target and how it reaches the screen. Make one with {@link LayerCompositor.addLayer}. Draw
65
+ * into it with a sprite layer (`target: layer.target, camera: layer.camera`), a core view
66
+ * (`target: {color: layer.texture}`) or {@link write}. Colours in it are premultiplied by alpha.
67
+ */
68
+ export declare class PixelLayer {
69
+ readonly width: number;
70
+ readonly height: number;
71
+ readonly anchor: LayerAnchor;
72
+ /** Scroll factor against the camera, read each frame. */
73
+ parallax: Parallax;
74
+ /** Extra offset in low-res pixels, read each frame. */
75
+ x: number;
76
+ /** Extra offset in low-res pixels, read each frame. */
77
+ y: number;
78
+ /** Multiplies the layer's colours, 0 to 1, read each frame. */
79
+ opacity: number;
80
+ /** How the layer mixes with what is below it, read each frame. */
81
+ blend: PixelBlend;
82
+ /** Clockwise turn in radians, read each frame. Each output pixel still shows exactly one source pixel. */
83
+ rotation: number;
84
+ /** The point it turns about in low-res view pixels, read each frame. Undefined is the middle of the view. */
85
+ pivot?: readonly [number, number];
86
+ /** Higher draws over lower, read each frame. */
87
+ z: number;
88
+ /** False leaves it out of the composite, read each frame. */
89
+ visible: boolean;
90
+ /** The target as a function, for options that read one each frame such as a sprite layer's `target`. */
91
+ readonly target: () => GPUTexture;
92
+ /** The camera whatever draws a `'view'` layer should use, live: whole pixels only, at this layer's parallax. */
93
+ readonly camera: LayerCamera;
94
+ private made?;
95
+ private image?;
96
+ private readonly margin;
97
+ /** Use {@link LayerCompositor.addLayer}; a layer belongs to its compositor. */
98
+ constructor(owner: LayerCompositor, camera: PixelCamera, options?: PixelLayerOptions);
99
+ /**
100
+ * The target. A `smooth` camera's `'view'` layer has one more pixel each way, to show when it shifts. Read it each
101
+ * frame: it is a new texture after a device loss.
102
+ * @throws MargoError `'state'` before the compositor is attached, `'disposed'` once the layer is removed.
103
+ */
104
+ get texture(): GPUTexture;
105
+ /** Puts a picture at the top-left of the target, kept and put back after a device loss. Bytes are straight alpha. */
106
+ write(image: PixelImage | ImageBitmap): void;
107
+ private upload;
108
+ }
109
+ /**
110
+ * Draws low-res layers to the screen at a whole-number scale with no filtering. Every output pixel works out which
111
+ * source pixel it shows, so a turned layer stays made of source colours with no blur. Each layer has its own target;
112
+ * the composite is one frame-graph pass over whatever the frame has drawn. Canvas views get it, views into a texture
113
+ * do not. WebGPU only.
114
+ * @throws TypeError / RangeError on invalid options or, each frame, an invalid layer field.
115
+ * @throws MargoError `'unsupported'` on a WebGL engine, `'disposed'` after `dispose()`, `'state'` when a layer's texture
116
+ * is read before the compositor is attached.
117
+ */
118
+ export declare class LayerCompositor implements EnginePlugin {
119
+ readonly name: string;
120
+ readonly camera: PixelCamera;
121
+ private readonly order;
122
+ private readonly layerMask;
123
+ private engine?;
124
+ private list;
125
+ private added;
126
+ private disposed;
127
+ private uniformLayout?;
128
+ private imageLayout?;
129
+ private pipelineLayout?;
130
+ private module?;
131
+ private readonly pipelines;
132
+ private readonly offsets;
133
+ private readonly next;
134
+ private readonly scroll;
135
+ private readonly attachments;
136
+ private readonly pass;
137
+ private readonly states;
138
+ constructor(options: LayerCompositorOptions);
139
+ /** Creates a compositor and attaches it to `instance`. */
140
+ static attach(instance: EngineKernel, options: LayerCompositorOptions): LayerCompositor;
141
+ /** The layers, in draw order as of the last frame. Change them through {@link addLayer} and {@link removeLayer}. */
142
+ get layers(): readonly PixelLayer[];
143
+ /** Adds a layer with its own target and returns it. */
144
+ addLayer(options?: PixelLayerOptions): PixelLayer;
145
+ /** Takes a layer out and frees its target; false when it is not in this compositor. */
146
+ removeLayer(layer: PixelLayer): boolean;
147
+ setup(engine: Engine): void;
148
+ onPreUpdate(delta: number): void;
149
+ onDeviceRestored(): void;
150
+ dispose(): void;
151
+ [Symbol.dispose]: () => void;
152
+ private release;
153
+ private pipeline;
154
+ private prepare;
155
+ /** Stable insertion sort by z then add order, in place: most frames find it sorted and allocate nothing. */
156
+ private sort;
157
+ /** Puts one layer's uniform values at `at` (floats), in output pixels; true when any differ from what was there. */
158
+ private fill;
159
+ private composite;
160
+ }
package/dist/index.js ADDED
@@ -0,0 +1,345 @@
1
+ // @margo/core-built 1.0.0
2
+ import {coreRequirement as __margoCoreRequirement,assertCore as __margoAssertCore} from '@margoengine/core/extension';
3
+ const a=(engine,version="1.0.0",source=import.meta.url)=>__margoRuntime(engine,version,source);
4
+ import { n as e, r as t, t as n } from "./errors-CDgOgzCd.js";
5
+ import { n as r, t as i } from "./view-rect-sVPGRhlO.js";
6
+ import { engineRuntime as __margoRuntime } from "@margoengine/core/extension";
7
+ //#region src/camera.ts
8
+ var o = 1e-6, s = (t, n) => {
9
+ let r = typeof t == "number" ? t : t[n];
10
+ if (!Number.isFinite(r)) throw e("Invalid parallax", "pixel-options");
11
+ return r;
12
+ }, c = (t, n, r) => {
13
+ if (!Number.isInteger(t) || t < r) throw e(`Invalid ${n}`, "pixel-options");
14
+ return t;
15
+ }, l = class {
16
+ constructor(t) {
17
+ this.width = c(t?.width, "pixel camera width", 1), this.height = c(t?.height, "pixel camera height", 1), this.minZoom = c(t.minZoom ?? 1, "pixel camera minZoom", 1), this.maxZoom = c(t.maxZoom ?? 64, "pixel camera maxZoom", this.minZoom);
18
+ let n = t.unitsPerPixel ?? 1;
19
+ if (!(n > 0) || n === Infinity) throw e("Invalid unitsPerPixel", "pixel-options");
20
+ this.unitsPerPixel = n, this.smooth = t.smooth ?? !1, this.x = t.x ?? 0, this.y = t.y ?? 0, this.current = this.minZoom, this.autoFit = t.zoom === void 0, t.zoom !== void 0 && (this.zoom = t.zoom);
21
+ }
22
+ get zoom() {
23
+ return this.current;
24
+ }
25
+ set zoom(t) {
26
+ if (!Number.isInteger(t) || t < this.minZoom || t > this.maxZoom) throw e("Invalid pixel camera zoom", "pixel-options");
27
+ this.current = t, this.autoFit = !1;
28
+ }
29
+ fit(t, n) {
30
+ if (!(t > 0) || !(n > 0)) throw e("Invalid fit size", "pixel-options");
31
+ let r = Math.floor(Math.min(t / this.width, n / this.height));
32
+ return this.current = Math.min(this.maxZoom, Math.max(this.minZoom, r)), this.current;
33
+ }
34
+ pixelX(e = 1) {
35
+ return Math.floor(this.exactX(e) + o);
36
+ }
37
+ pixelY(e = 1) {
38
+ return Math.floor(this.exactY(e) + o);
39
+ }
40
+ scroll(e = 1, t = {
41
+ x: 0,
42
+ y: 0,
43
+ subX: 0,
44
+ subY: 0
45
+ }) {
46
+ return t.x = this.pixelX(e), t.y = this.pixelY(e), t.subX = Math.max(0, this.exactX(e) - t.x), t.subY = Math.max(0, this.exactY(e) - t.y), t;
47
+ }
48
+ projection(e = 1) {
49
+ let t = this.unitsPerPixel, n = this.pixelX(e) * t, r = -this.pixelY(e) * t;
50
+ return {
51
+ mode: "orthographic",
52
+ left: n,
53
+ right: n + this.width * t,
54
+ top: r,
55
+ bottom: r - this.height * t,
56
+ zoom: 1
57
+ };
58
+ }
59
+ exactX(t) {
60
+ if (!Number.isFinite(this.x)) throw e("Invalid pixel camera position", "pixel-options");
61
+ return this.x / this.unitsPerPixel * s(t, 0);
62
+ }
63
+ exactY(t) {
64
+ if (!Number.isFinite(this.y)) throw e("Invalid pixel camera position", "pixel-options");
65
+ return this.y / this.unitsPerPixel * s(t, 1);
66
+ }
67
+ }, u = "\nstruct Layer{origin:vec2f,zoom:f32,opacity:f32,pivot:vec2f,turn:vec2f,offset:vec2f}\n@group(0) @binding(0) var<uniform> layer:Layer;\n@group(1) @binding(0) var image:texture_2d<f32>;\n@vertex fn vertexMain(@builtin(vertex_index) i:u32)->@builtin(position) vec4f{\n return vec4f(f32(i&1u)*4-1,f32(i>>1u)*4-1,0,1);\n}\n@fragment fn fragmentMain(@builtin(position) p:vec4f)->@location(0) vec4f{\n let q=p.xy-layer.origin-layer.pivot;\n let r=vec2f(q.x*layer.turn.x+q.y*layer.turn.y,q.y*layer.turn.x-q.x*layer.turn.y)+layer.pivot-layer.offset;\n let t=vec2i(floor(r/layer.zoom));\n if(any(t<vec2i(0))||any(t>=vec2i(textureDimensions(image)))){discard;}\n return textureLoad(image,t,0)*layer.opacity;\n}", d = {
68
+ normal: {
69
+ color: {
70
+ srcFactor: "one",
71
+ dstFactor: "one-minus-src-alpha"
72
+ },
73
+ alpha: {
74
+ srcFactor: "one",
75
+ dstFactor: "one-minus-src-alpha"
76
+ }
77
+ },
78
+ add: {
79
+ color: {
80
+ srcFactor: "one",
81
+ dstFactor: "one"
82
+ },
83
+ alpha: {
84
+ srcFactor: "zero",
85
+ dstFactor: "one"
86
+ }
87
+ },
88
+ multiply: {
89
+ color: {
90
+ srcFactor: "dst",
91
+ dstFactor: "one-minus-src-alpha"
92
+ },
93
+ alpha: {
94
+ srcFactor: "zero",
95
+ dstFactor: "one"
96
+ }
97
+ },
98
+ screen: {
99
+ color: {
100
+ srcFactor: "one",
101
+ dstFactor: "one-minus-src"
102
+ },
103
+ alpha: {
104
+ srcFactor: "one",
105
+ dstFactor: "one-minus-src-alpha"
106
+ }
107
+ }
108
+ }, f = 256, p = 40, m = 0, h = class {
109
+ constructor(t, n, r = {}) {
110
+ if (this.target = () => this.texture, this.order = 0, this.owner = t, this.width = r.width ?? n.width, this.height = r.height ?? n.height, !Number.isInteger(this.width) || !Number.isInteger(this.height) || this.width < 1 || this.height < 1) throw e("Invalid pixel layer size", "pixel-options");
111
+ if (this.anchor = r.anchor ?? "view", this.anchor !== "view" && this.anchor !== "world") throw e("Invalid pixel layer anchor", "pixel-options");
112
+ this.margin = n.smooth && this.anchor === "view" ? 1 : 0, this.parallax = r.parallax ?? 1, this.x = r.x ?? 0, this.y = r.y ?? 0, this.opacity = r.opacity ?? 1, this.blend = r.blend ?? "normal", this.rotation = r.rotation ?? 0, this.pivot = r.pivot, this.z = r.z ?? 0, this.visible = r.visible ?? !0;
113
+ let i = this;
114
+ this.camera = {
115
+ get x() {
116
+ return n.pixelX(i.parallax) * n.unitsPerPixel;
117
+ },
118
+ get y() {
119
+ return n.pixelY(i.parallax) * n.unitsPerPixel;
120
+ },
121
+ get zoom() {
122
+ return 1 / n.unitsPerPixel;
123
+ }
124
+ };
125
+ }
126
+ get texture() {
127
+ if (!this.owner) throw n("disposed", "Pixel layer removed; add a new one", "disposed");
128
+ let e = this.owner.currentDevice();
129
+ return this.made || (this.made = e.createTexture({
130
+ label: "pixel layer",
131
+ size: [this.width + this.margin, this.height + this.margin],
132
+ format: "rgba8unorm",
133
+ usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.TEXTURE_BINDING | GPUTextureUsage.COPY_DST | GPUTextureUsage.COPY_SRC
134
+ }), this.group = void 0, this.image && this.upload(e)), this.made;
135
+ }
136
+ write(t) {
137
+ if (!this.owner) throw n("disposed", "Pixel layer removed; add a new one", "disposed");
138
+ let { width: r, height: i } = t;
139
+ if (!(r > 0) || !(i > 0) || r > this.width + this.margin || i > this.height + this.margin) throw e("Invalid pixel image", "pixel-options");
140
+ if ("data" in t) {
141
+ if (t.data.length !== r * i * 4) throw e("Invalid pixel image", "pixel-options");
142
+ let n = new Uint8Array(t.data);
143
+ for (let e = 0; e < n.length; e += 4) {
144
+ let t = n[e + 3];
145
+ if (t < 255) for (let r = 0; r < 3; r++) n[e + r] = Math.round(n[e + r] * t / 255);
146
+ }
147
+ this.image = {
148
+ width: r,
149
+ height: i,
150
+ data: n
151
+ };
152
+ } else this.image = t;
153
+ let a = this.owner.device;
154
+ a && (this.made ? this.upload(a) : this.texture);
155
+ }
156
+ upload(e) {
157
+ let t = this.image, { width: n, height: r } = t, i = this.made;
158
+ "data" in t ? e.queue.writeTexture({ texture: i }, t.data, { bytesPerRow: n * 4 }, [n, r]) : e.queue.copyExternalImageToTexture({ source: t }, {
159
+ texture: i,
160
+ premultipliedAlpha: !0
161
+ }, [n, r]);
162
+ }
163
+ release(e) {
164
+ e && this.made?.destroy(), this.made = this.group = void 0;
165
+ }
166
+ }, g = class o {coreRequirement=__margoCoreRequirement("1.0.0",import.meta.url);
167
+ constructor(n) {
168
+ if (this.list = [], this.added = 0, this.disposed = !1, this.pipelines = /* @__PURE__ */ new Map(), this.offsets = /* @__PURE__ */ new Uint32Array(1), this.next = new Float32Array(p / 4), this.scroll = {
169
+ x: 0,
170
+ y: 0,
171
+ subX: 0,
172
+ subY: 0
173
+ }, this.attachments = [{
174
+ view: void 0,
175
+ loadOp: "load",
176
+ storeOp: "store"
177
+ }], this.pass = { colorAttachments: this.attachments }, this.states = new i(() => ({ values: /* @__PURE__ */ new Float32Array() }), (e) => e.buffer?.destroy()), !n?.camera) throw t("LayerCompositor needs a camera", "pixel-options");
178
+ let a = n.order ?? 30;
179
+ if (!Number.isFinite(a)) throw e("Invalid pixel order", "pixel-options");
180
+ this.camera = n.camera instanceof l ? n.camera : new l(n.camera), this.order = a, this.layerMask = r(n.layers ?? 1, "LayerCompositor layers"), this.name = n.name ?? `pixel-${++m}`;
181
+ }
182
+ static attach(e, t) {__margoAssertCore(e,__margoCoreRequirement("1.0.0",import.meta.url));
183
+ let n = new o(t);
184
+ return a(e).use(n), n;
185
+ }
186
+ get layers() {
187
+ return this.list;
188
+ }
189
+ addLayer(e) {
190
+ if (this.disposed) throw n("disposed", "LayerCompositor disposed; create a new one", "disposed");
191
+ let t = new h(this, this.camera, e);
192
+ return t.order = this.added++, this.list.push(t), t;
193
+ }
194
+ removeLayer(e) {
195
+ let t = this.list.indexOf(e);
196
+ return t < 0 ? !1 : (this.list.splice(t, 1), e.release(!0), e.owner = void 0, !0);
197
+ }
198
+ setup(e) {
199
+ if (this.disposed || e.backend !== "webgpu") throw n(this.disposed ? "disposed" : "unsupported", this.disposed ? "LayerCompositor disposed; create a new one" : "LayerCompositor needs WebGPU", this.disposed ? "disposed" : "webgpu");
200
+ this.engine = e, this.device = e.gpu ?? void 0, e.frameGraph.add({
201
+ name: this.name,
202
+ order: this.order,
203
+ execute: (e) => {
204
+ e.backend === "webgpu" && this.composite(e);
205
+ }
206
+ });
207
+ }
208
+ onPreUpdate(e) {
209
+ e > 0 && this.states.prune();
210
+ }
211
+ onDeviceRestored() {
212
+ this.release(), this.device = this.engine?.gpu ?? void 0;
213
+ }
214
+ dispose() {
215
+ if (!this.disposed) {
216
+ this.disposed = !0, this.engine?.sceneOf(this)?.removePlugin(this.name), this.engine = void 0;
217
+ for (let e of this.list.slice()) this.removeLayer(e);
218
+ this.release();
219
+ }
220
+ }
221
+ [Symbol.dispose ?? Symbol()]() {
222
+ this.dispose();
223
+ }
224
+ currentDevice() {
225
+ let e = this.engine?.gpu;
226
+ if (!e) throw n("state", "Pixel layer texture needs an attached compositor", "pixel-state");
227
+ return e !== this.device && (this.release(), this.device = e), e;
228
+ }
229
+ release() {
230
+ this.states.clear();
231
+ for (let e of this.list) e.release(!1);
232
+ this.uniformLayout = this.imageLayout = this.pipelineLayout = this.module = this.device = void 0, this.pipelines.clear();
233
+ }
234
+ pipeline(e, t, n, r) {
235
+ let i = `${t}/${n}/${r}`, a = this.pipelines.get(i);
236
+ return a || (a = e.createRenderPipeline({
237
+ label: "pixel composite",
238
+ layout: this.pipelineLayout,
239
+ vertex: {
240
+ module: this.module,
241
+ entryPoint: "vertexMain"
242
+ },
243
+ fragment: {
244
+ module: this.module,
245
+ entryPoint: "fragmentMain",
246
+ targets: [{
247
+ format: t,
248
+ blend: d[r]
249
+ }]
250
+ },
251
+ multisample: { count: n }
252
+ }), this.pipelines.set(i, a)), a;
253
+ }
254
+ prepare(e) {
255
+ this.device !== e && (this.device && this.release(), this.device = e), !this.module && (this.uniformLayout = e.createBindGroupLayout({ entries: [{
256
+ binding: 0,
257
+ visibility: GPUShaderStage.FRAGMENT,
258
+ buffer: {
259
+ type: "uniform",
260
+ hasDynamicOffset: !0,
261
+ minBindingSize: p
262
+ }
263
+ }] }), this.imageLayout = e.createBindGroupLayout({ entries: [{
264
+ binding: 0,
265
+ visibility: GPUShaderStage.FRAGMENT,
266
+ texture: { sampleType: "unfilterable-float" }
267
+ }] }), this.pipelineLayout = e.createPipelineLayout({ bindGroupLayouts: [this.uniformLayout, this.imageLayout] }), this.module = e.createShaderModule({
268
+ label: "pixel composite",
269
+ code: u
270
+ }));
271
+ }
272
+ sort() {
273
+ let t = this.list;
274
+ for (let n = 1; n < t.length; n++) {
275
+ let r = t[n];
276
+ if (!Number.isFinite(r.z)) throw e("Invalid pixel layer", "pixel-options");
277
+ let i = n - 1;
278
+ for (; i >= 0 && (t[i].z > r.z || t[i].z === r.z && t[i].order > r.order);) t[i + 1] = t[i], i--;
279
+ t[i + 1] = r;
280
+ }
281
+ }
282
+ fill(t, n, r, i, a) {
283
+ let { opacity: o, rotation: s, x: c, y: l } = r, u = this.camera, f = u.zoom;
284
+ if (!(o >= 0 && o <= 1) || !Number.isFinite(s + c + l) || !d[r.blend] || r.pivot && !Number.isFinite(r.pivot[0] + r.pivot[1])) throw e("Invalid pixel layer", "pixel-options");
285
+ let p = Math.cos(s), m = Math.sin(s);
286
+ Math.abs(p) < 1e-9 ? (p = 0, m = Math.sign(m)) : Math.abs(m) < 1e-9 && (m = 0, p = Math.sign(p));
287
+ let h = r.parallax, g = r.anchor === "world", _ = g ? u.pixelX(h) : 0, v = g ? u.pixelY(h) : 0, y = Math.round((c - _) * f), b = Math.round((l - v) * f);
288
+ if (u.smooth) {
289
+ let e = u.scroll(h, this.scroll);
290
+ y -= Math.floor(e.subX * f), b -= Math.floor(e.subY * f);
291
+ }
292
+ let x = this.next;
293
+ x[0] = i, x[1] = a, x[2] = f, x[3] = o, x[4] = (r.pivot ? r.pivot[0] : u.width / 2) * f, x[5] = (r.pivot ? r.pivot[1] : u.height / 2) * f, x[6] = p, x[7] = m, x[8] = y, x[9] = b;
294
+ let S = !1;
295
+ for (let e = 0; e < x.length; e++) t[n + e] !== x[e] && (t[n + e] = x[e], S = !0);
296
+ return S;
297
+ }
298
+ composite(e) {
299
+ let t = e.view;
300
+ if (t?.target || t?.layers !== void 0 && !(t.layers & this.layerMask)) return;
301
+ let n = e.device, r = this.camera, i = this.list;
302
+ this.prepare(n);
303
+ let a = t ? t.viewport[0] : 0, o = t ? t.viewport[1] : 0, s = t ? t.viewport[2] : e.width, c = t ? t.viewport[3] : e.height;
304
+ r.autoFit && r.fit(s, c);
305
+ let l = r.zoom, u = r.width * l, d = r.height * l, m = a + Math.floor((s - u) / 2), h = o + Math.floor((c - d) / 2), g = t?.scissor ? t.scissor[0] : a, _ = t?.scissor ? t.scissor[1] : o, v = t?.scissor ? t.scissor[2] : s, y = t?.scissor ? t.scissor[3] : c, b = Math.max(m, g, 0), x = Math.max(h, _, 0), S = Math.min(m + u, g + v, e.width), C = Math.min(h + d, _ + y, e.height);
306
+ if (this.sort(), S <= b || C <= x || !i.length) return;
307
+ let w = this.states.get(e), T = i.length * (f / 4);
308
+ w.values.length < T && (w.values = new Float32Array(T), w.buffer?.destroy(), w.buffer = n.createBuffer({
309
+ label: "pixel composite",
310
+ size: w.values.byteLength,
311
+ usage: GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST
312
+ }), w.group = n.createBindGroup({
313
+ layout: this.uniformLayout,
314
+ entries: [{
315
+ binding: 0,
316
+ resource: {
317
+ buffer: w.buffer,
318
+ size: p
319
+ }
320
+ }]
321
+ }));
322
+ for (let e = 0; e < i.length; e++) {
323
+ let t = f / 4 * e;
324
+ this.fill(w.values, t, i[e], m, h) && n.queue.writeBuffer(w.buffer, t * 4, w.values, t, p / 4);
325
+ }
326
+ this.attachments[0].view = e.color;
327
+ let E = e.encoder.beginRenderPass(this.pass), D = e.format, O = e.descriptor.multisample?.count ?? 1;
328
+ E.setScissorRect(b, x, S - b, C - x);
329
+ for (let e = 0; e < i.length; e++) {
330
+ let t = i[e];
331
+ if (!t.visible || t.opacity === 0) continue;
332
+ let r = t.texture;
333
+ t.group ??= n.createBindGroup({
334
+ layout: this.imageLayout,
335
+ entries: [{
336
+ binding: 0,
337
+ resource: r.createView()
338
+ }]
339
+ }), E.setPipeline(this.pipeline(n, D, O, t.blend)), this.offsets[0] = e * f, E.setBindGroup(0, w.group, this.offsets), E.setBindGroup(1, t.group), E.draw(3);
340
+ }
341
+ E.end();
342
+ }
343
+ };
344
+ //#endregion
345
+ export { g as LayerCompositor, l as PixelCamera, h as PixelLayer };