@margoengine/oit 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.
package/dist/peel.d.ts ADDED
@@ -0,0 +1,50 @@
1
+ import type { EngineKernel } from '@margoengine/core';
2
+ import { type PassContext } from '@margoengine/core/extension';
3
+ import { TransparentPass } from './pass.js';
4
+ type Context = Extract<PassContext, {
5
+ backend: 'webgpu';
6
+ }>;
7
+ /** Fixed settings for texture-based exact transparency on WebGPU and full WebGL2 compatibility devices. */
8
+ export interface PeelOITOptions {
9
+ /** Maximum nearest distinct depth layers per pixel. Default 10, a positive integer. Farther layers are omitted. */
10
+ layers?: number;
11
+ /** Frame graph order, after opaque drawing and before post processing. Default 8. */
12
+ order?: number;
13
+ }
14
+ /**
15
+ * Exact per-pixel depth order without fragment storage or float blending. Each layer redraws the registered models,
16
+ * then layers composite far to near against opaque scene depth. Single-sample transparent coverage, including in an
17
+ * MSAA scene. Coplanar fragments share one layer; no refraction or custom blending. Use `layers` to cover scene depth.
18
+ * @throws RangeError for a nonpositive/noninteger layer count or invalid order; use positive settings.
19
+ * @throws MargoError on the small preview device; use the full WebGL2 compatibility layer or WebGPU.
20
+ */
21
+ export declare class PeelOIT extends TransparentPass {
22
+ readonly targets: readonly GPUColorTargetState[];
23
+ /** @internal The model hook must write its private nearest-depth buffer. */
24
+ readonly depthWrite = true;
25
+ readonly layout: readonly GPUBindGroupLayoutEntry[];
26
+ readonly layers: number;
27
+ private readonly code;
28
+ private readonly surfaceCode;
29
+ private textures;
30
+ private colors;
31
+ private depths;
32
+ private nearest?;
33
+ private first?;
34
+ private size;
35
+ private layer;
36
+ private readonly pipelines;
37
+ private readonly groups;
38
+ /** The snapshot the linear resolve groups read. */
39
+ private groupScene?;
40
+ static attach(engine: EngineKernel, options?: PeelOITOptions): PeelOIT;
41
+ constructor({ order, layers }?: PeelOITOptions);
42
+ declarations(group: number): string;
43
+ surface(group: number): string;
44
+ bindings(): GPUBindGroupEntry[];
45
+ begin(): GPURenderPassEncoder;
46
+ protected render(c: Context): void;
47
+ protected release(): void;
48
+ protected freeDevice(): void;
49
+ }
50
+ export {};
package/dist/peel.js ADDED
@@ -0,0 +1,219 @@
1
+ // @margo/core-built 0.1.0
2
+ import {coreRequirement as __margoCoreRequirement,assertCore as __margoAssertCore} from '@margoengine/core/extension';
3
+ const c=(engine,version="0.1.0",source=import.meta.url)=>__margoRuntime(engine,version,source);
4
+ import { i as e, n as t, o as n, r, t as i } from "./pass-D7U8kWzv.js";
5
+ import { i as a, r as o, t as s } from "./pass-DdYrWNpT.js";
6
+ import { engineRuntime as __margoRuntime } from "@margoengine/core/extension";
7
+ //#region src/peel.ts
8
+ var l = (e) => `
9
+ override margoLinear:bool=false;
10
+ struct MargoTransparent {@location(0) color:vec4f, @location(1) depth:f32}
11
+ @group(${e}) @binding(120) var margoPrevious:texture_2d<f32>;
12
+ fn margoTransparentAt(color:vec4f,clip:vec4f,depth:f32)->MargoTransparent {
13
+ let previous=textureLoad(margoPrevious,vec2i(clip.xy),0).r;
14
+ if(color.a<=0.0 || clip.z>=previous){discard;}
15
+ let a=clamp(color.a,0.0,1.0); return MargoTransparent(vec4f(color.rgb,select(a,-a,margoLinear)),clip.z);
16
+ }
17
+ `, u = (e) => `
18
+ @group(0) @binding(0) var colorMap:texture_2d<f32>;
19
+ @group(0) @binding(1) var depthMap:texture_2d<f32>;
20
+ ${e === 2 ? "@group(0) @binding(2) var sceneMap:texture_2d<f32>;" + o : ""}
21
+ struct Result {@location(0) color:vec4f, @builtin(frag_depth) depth:f32}
22
+ @vertex fn vertex(@builtin(vertex_index) i:u32)->@builtin(position) vec4f {
23
+ return vec4f(f32(i&1u)*4-1,f32(i>>1u)*4-1,0,1);
24
+ }
25
+ @fragment fn fragment(@builtin(position) p:vec4f)->Result {
26
+ let q=vec2i(p.xy); var color=textureLoad(colorMap,q,0);
27
+ ${[
28
+ "if(color.a==0.0){discard;} color.a=abs(color.a);",
29
+ "if(color.a<=0.0){discard;}",
30
+ "if(color.a>=0.0){discard;} color=overLinear(vec4f(color.rgb,-color.a),textureLoad(sceneMap,q,0));"
31
+ ][e]}
32
+ return Result(color,textureLoad(depthMap,q,0).r);
33
+ }
34
+ `, d = class o extends s {
35
+ static attach(e, t) {__margoAssertCore(e,__margoCoreRequirement("0.1.0",import.meta.url));
36
+ let n = new o(t);
37
+ return c(e).use(n), n;
38
+ }
39
+ constructor({ order: e = 8, layers: t = 10 } = {}) {
40
+ if (super(e), this.targets = [{ format: "rgba16float" }, { format: "r32float" }], this.depthWrite = !0, this.layout = [{
41
+ binding: 120,
42
+ visibility: 2,
43
+ texture: { sampleType: "unfilterable-float" }
44
+ }], this.code = /* @__PURE__ */ new Map(), this.surfaceCode = /* @__PURE__ */ new Map(), this.textures = [], this.colors = [], this.depths = [], this.size = "", this.layer = 0, this.pipelines = /* @__PURE__ */ new Map(), this.groups = /* @__PURE__ */ new Map(), !Number.isSafeInteger(t) || t < 1) throw RangeError("Invalid PeelOIT layers; use a positive safe integer");
45
+ this.layers = t;
46
+ }
47
+ declarations(e) {
48
+ return t(this.code, e, (e) => this.surface(e) + a);
49
+ }
50
+ surface(e) {
51
+ return t(this.surfaceCode, e, l);
52
+ }
53
+ bindings() {
54
+ return [{
55
+ binding: 120,
56
+ resource: this.layer ? this.depths[this.layer - 1] : this.first
57
+ }];
58
+ }
59
+ begin() {
60
+ if (this.pass) return this.pass;
61
+ let e = this.context;
62
+ return this.pass = e.encoder.beginRenderPass({
63
+ label: "oit:peel",
64
+ colorAttachments: [this.colors[this.layer], this.depths[this.layer]].map((e) => ({
65
+ view: e,
66
+ clearValue: [
67
+ 0,
68
+ 0,
69
+ 0,
70
+ 0
71
+ ],
72
+ loadOp: "clear",
73
+ storeOp: "store"
74
+ })),
75
+ depthStencilAttachment: {
76
+ view: this.nearest,
77
+ depthClearValue: 0,
78
+ depthLoadOp: "clear",
79
+ depthStoreOp: "discard"
80
+ }
81
+ }), n(this.pass, e), this.pass;
82
+ }
83
+ render(e) {
84
+ if (r(e.device, e.view ?? e), this.disposed || this.empty) return;
85
+ let t = e.device, a = e.width + "x" + e.height;
86
+ if (a !== this.size) {
87
+ this.release(), this.size = a;
88
+ let n = (n) => {
89
+ let r = t.createTexture({
90
+ label: "oit:peel:" + n,
91
+ size: [e.width, e.height],
92
+ format: n,
93
+ usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.TEXTURE_BINDING
94
+ });
95
+ return this.textures.push(r), r.createView();
96
+ };
97
+ this.nearest = n("depth32float"), this.first = n("r32float");
98
+ for (let e = 0; e < this.layers; e++) this.colors.push(n("rgba16float")), this.depths.push(n("r32float"));
99
+ }
100
+ e.encoder.beginRenderPass({
101
+ label: "oit:peel:reset",
102
+ colorAttachments: [{
103
+ view: this.first,
104
+ clearValue: [
105
+ 2,
106
+ 0,
107
+ 0,
108
+ 0
109
+ ],
110
+ loadOp: "clear",
111
+ storeOp: "store"
112
+ }]
113
+ }).end();
114
+ let { depth: o, descriptor: s } = e, c;
115
+ e.depth = this.nearest, e.descriptor = {
116
+ ...s,
117
+ multisample: { count: 1 },
118
+ depthStencil: { format: "depth32float" }
119
+ };
120
+ try {
121
+ for (this.layer = 0; this.layer < this.layers; this.layer++) {
122
+ if (!this.drawModels(e)) return;
123
+ c ??= this.scene;
124
+ }
125
+ } finally {
126
+ e.depth = o, e.descriptor = s, this.scene = void 0;
127
+ }
128
+ let l = s.multisample?.count ?? 1, d = s.depthStencil.format, f = (n, r) => {
129
+ let a = e.format + l + d + n, o = this.pipelines.get(a);
130
+ if (!o) {
131
+ let r = t.createShaderModule({ code: u(n) }), s = t.createBindGroupLayout({ entries: (n === 2 ? [
132
+ 0,
133
+ 1,
134
+ 2
135
+ ] : [0, 1]).map((e) => ({
136
+ binding: e,
137
+ visibility: 2,
138
+ texture: { sampleType: "unfilterable-float" }
139
+ })) });
140
+ this.pipelines.set(a, o = t.createRenderPipeline({
141
+ label: "oit:peel:resolve",
142
+ layout: t.createPipelineLayout({ bindGroupLayouts: [s] }),
143
+ vertex: {
144
+ module: r,
145
+ entryPoint: "vertex"
146
+ },
147
+ fragment: {
148
+ module: r,
149
+ entryPoint: "fragment",
150
+ targets: [{
151
+ format: e.format,
152
+ blend: n === 2 ? void 0 : i
153
+ }]
154
+ },
155
+ depthStencil: {
156
+ format: d,
157
+ depthWriteEnabled: !1,
158
+ depthCompare: "greater-equal"
159
+ },
160
+ multisample: { count: l }
161
+ }));
162
+ }
163
+ let s = this.groups.get(o);
164
+ return (!s || r && this.groupScene !== r) && (r && (this.groupScene = r), this.groups.set(o, s = this.colors.map((e, n) => t.createBindGroup({
165
+ layout: o.getBindGroupLayout(0),
166
+ entries: [
167
+ {
168
+ binding: 0,
169
+ resource: e
170
+ },
171
+ {
172
+ binding: 1,
173
+ resource: this.depths[n]
174
+ },
175
+ ...r ? [{
176
+ binding: 2,
177
+ resource: r
178
+ }] : []
179
+ ]
180
+ })))), [o, s];
181
+ }, p = () => {
182
+ let t = e.encoder.beginRenderPass({
183
+ label: "oit:peel:resolve",
184
+ colorAttachments: [{
185
+ view: e.color,
186
+ loadOp: "load",
187
+ storeOp: "store"
188
+ }],
189
+ depthStencilAttachment: {
190
+ view: e.depth,
191
+ depthReadOnly: !0,
192
+ stencilReadOnly: !0
193
+ }
194
+ });
195
+ return n(t, e), t;
196
+ };
197
+ if (!c) {
198
+ let [e, t] = f(0), n = p();
199
+ n.setPipeline(e);
200
+ for (let e = this.layers - 1; e >= 0; e--) n.setBindGroup(0, t[e]), n.draw(3);
201
+ n.end();
202
+ return;
203
+ }
204
+ let [m, h] = f(1);
205
+ for (let e = this.layers - 1; e >= 0; e--) {
206
+ let [t, n] = f(2, c()), r = p();
207
+ r.setPipeline(m), r.setBindGroup(0, h[e]), r.draw(3), r.setPipeline(t), r.setBindGroup(0, n[e]), r.draw(3), r.end();
208
+ }
209
+ }
210
+ release() {
211
+ for (let t of this.textures) e(this.device, t);
212
+ this.textures = [], this.colors = [], this.depths = [], this.first = this.nearest = void 0, this.size = "", this.groups.clear(), this.groupScene = void 0;
213
+ }
214
+ freeDevice() {
215
+ this.release(), this.pipelines.clear();
216
+ }
217
+ };
218
+ //#endregion
219
+ export { d as PeelOIT };
@@ -0,0 +1,49 @@
1
+ import type { EngineKernel } from '@margoengine/core';
2
+ import { type Engine, type PassContext } from '@margoengine/core/extension';
3
+ import { TransparentPass } from './pass.js';
4
+ type Context = Extract<PassContext, {
5
+ backend: 'webgpu';
6
+ }>;
7
+ /** Fixed settings for float32 weighted accumulation. Transmission and custom blending retain their sorted paths. */
8
+ export interface PreciseOITOptions {
9
+ /** Frame graph order, after opaque drawing and before post processing. Default 8. */
10
+ order?: number;
11
+ /** Depth-weight distance in world units. Default the camera's distance to its target, recomputed each frame. */
12
+ depthScale?: number;
13
+ }
14
+ /**
15
+ * Weighted transparency with four R32F accumulation channels instead of half-float sums. The weighting and coverage
16
+ * match OIT; bright stacked layers no longer overflow at 65504. Five render targets and float32 blending are required.
17
+ * On WebGPU request `features: ['float32-blendable']` when creating the engine; WebGL2 needs EXT_float_blend.
18
+ * Scene MSAA is preserved by reading and averaging the scalar samples in the composite, without a hardware resolve.
19
+ * @throws RangeError for invalid order/depthScale; use positive finite settings.
20
+ * @throws MargoError 'unsupported' without float32 blending or five targets; request the feature or use OIT.
21
+ */
22
+ export declare class PreciseOIT extends TransparentPass {
23
+ readonly targets: readonly GPUColorTargetState[];
24
+ readonly layout: readonly GPUBindGroupLayoutEntry[];
25
+ private readonly depthScale?;
26
+ private readonly code;
27
+ private readonly surfaceCode;
28
+ private readonly values;
29
+ private uniform?;
30
+ private binding?;
31
+ private textures;
32
+ private views;
33
+ private size;
34
+ private readonly pipelines;
35
+ private readonly groups;
36
+ static attach(engine: EngineKernel, options?: PreciseOITOptions): PreciseOIT;
37
+ constructor({ order, depthScale }?: PreciseOITOptions);
38
+ setup(engine: Engine): void;
39
+ declarations(group: number): string;
40
+ surface(group: number): string;
41
+ bindings(): GPUBindGroupEntry[];
42
+ begin(): GPURenderPassEncoder;
43
+ protected render(c: Context): void;
44
+ /** The linear composite's group: the five targets and the snapshot (KB3148e). */
45
+ private linearGroup?;
46
+ protected release(): void;
47
+ protected freeDevice(): void;
48
+ }
49
+ export {};
@@ -0,0 +1,256 @@
1
+ // @margo/core-built 0.1.0
2
+ import {coreRequirement as __margoCoreRequirement,assertCore as __margoAssertCore} from '@margoengine/core/extension';
3
+ const f=(engine,version="0.1.0",source=import.meta.url)=>__margoRuntime(engine,version,source);
4
+ import { i as e, r as t, t as n } from "./compat-CLA5cArM.js";
5
+ import { a as r, i, n as a, o, r as s, t as c } from "./pass-D7U8kWzv.js";
6
+ import { i as l, n as u, t as d } from "./pass-DdYrWNpT.js";
7
+ import { engineRuntime as __margoRuntime } from "@margoengine/core/extension";
8
+ //#region src/precise.ts
9
+ var p = {
10
+ color: {
11
+ srcFactor: "one",
12
+ dstFactor: "one"
13
+ },
14
+ alpha: {
15
+ srcFactor: "one",
16
+ dstFactor: "one"
17
+ }
18
+ }, m = (e) => `
19
+ override margoLinear:bool=false;
20
+ struct MargoTransparent {
21
+ @location(0) r:f32, @location(1) g:f32, @location(2) b:f32, @location(3) weight:f32, @location(4) reveal:vec2f
22
+ }
23
+ @group(${e}) @binding(120) var<uniform> margoOIT:vec4f;
24
+ fn margoTransparentAt(color:vec4f,clip:vec4f,depth:f32)->MargoTransparent {
25
+ let a=clamp(color.a,0.0,1.0); let d=max(depth*margoOIT.x,1e-4);
26
+ let w=a*clamp(10.0/pow(d,6.0),0.01,1000.0);
27
+ return MargoTransparent(color.r*w,color.g*w,color.b*w,w,vec2f(a,select(0.0,1.0,margoLinear)));
28
+ }
29
+ `, h = (e) => `
30
+ ${[
31
+ 0,
32
+ 1,
33
+ 2,
34
+ 3,
35
+ 4
36
+ ].map((t) => `@group(0) @binding(${t}) var map${t}:${e > 1 ? "texture_multisampled_2d" : "texture_2d"}<f32>;`).join("\n")}
37
+ @vertex fn vertex(@builtin(vertex_index) i:u32)->@builtin(position) vec4f {
38
+ return vec4f(f32(i&1u)*4-1,f32(i>>1u)*4-1,0,1);
39
+ }
40
+ @fragment fn fragment(@builtin(position) p:vec4f)->@location(0) vec4f {
41
+ let q=vec2i(p.xy); var sum=vec4f(0.0); var reveal=0.0;
42
+ for(var s=0;s<${e};s+=1){
43
+ sum+=vec4f(${[
44
+ 0,
45
+ 1,
46
+ 2,
47
+ 3
48
+ ].map((t) => `textureLoad(map${t},q,${e > 1 ? "s" : "0"}).r`).join(",")});
49
+ reveal+=textureLoad(map4,q,${e > 1 ? "s" : "0"}).r;
50
+ }
51
+ return vec4f(sum.rgb/max(sum.a,${e}.0*1e-5),1.0-reveal/${e}.0);
52
+ }
53
+ `, g = (e) => u([
54
+ 0,
55
+ 1,
56
+ 2,
57
+ 3,
58
+ 4
59
+ ].map((t) => `@group(0) @binding(${t}) var map${t}:${e > 1 ? "texture_multisampled_2d" : "texture_2d"}<f32>;`).join("\n"), `var sum=vec4f(0.0); var reveal=vec2f(0.0);
60
+ for(var s=0;s<${e};s+=1){
61
+ sum+=vec4f(${[
62
+ 0,
63
+ 1,
64
+ 2,
65
+ 3
66
+ ].map((t) => `textureLoad(map${t},q,${e > 1 ? "s" : "0"}).r`).join(",")});
67
+ reveal+=textureLoad(map4,q,${e > 1 ? "s" : "0"}).rg;
68
+ }
69
+ let avg=sum.rgb/max(sum.a,${e}.0*1e-5); let cover=1.0-reveal.x/${e}.0; let mark=reveal.y/${e}.0;`), _ = class u extends d {coreRequirement=__margoCoreRequirement("0.1.0",import.meta.url);
70
+ static attach(e, t) {__margoAssertCore(e,__margoCoreRequirement("0.1.0",import.meta.url));
71
+ let n = new u(t);
72
+ return f(e).use(n), n;
73
+ }
74
+ constructor({ order: e = 8, depthScale: t } = {}) {
75
+ if (super(e), this.targets = [...[
76
+ 0,
77
+ 1,
78
+ 2,
79
+ 3
80
+ ].map(() => ({
81
+ format: "r32float",
82
+ blend: p
83
+ })), {
84
+ format: "rg16float",
85
+ blend: {
86
+ color: {
87
+ srcFactor: "zero",
88
+ dstFactor: "one-minus-src"
89
+ },
90
+ alpha: {
91
+ srcFactor: "zero",
92
+ dstFactor: "one-minus-src"
93
+ }
94
+ }
95
+ }], this.layout = [{
96
+ binding: 120,
97
+ visibility: 2,
98
+ buffer: {}
99
+ }], this.code = /* @__PURE__ */ new Map(), this.surfaceCode = /* @__PURE__ */ new Map(), this.values = /* @__PURE__ */ new Float32Array(4), this.textures = [], this.views = [], this.size = "", this.pipelines = /* @__PURE__ */ new Map(), this.groups = /* @__PURE__ */ new Map(), t !== void 0 && !(t > 0 && Number.isFinite(t))) throw RangeError("Invalid PreciseOIT depthScale; use a positive finite number");
100
+ this.depthScale = t;
101
+ }
102
+ setup(r) {
103
+ super.setup(r);
104
+ let i = r.gpu;
105
+ t(i, "PreciseOIT");
106
+ let a = i.adapter?.capabilities?.extensions;
107
+ if (!(n(i) === "webgl2" ? a?.EXT_float_blend : i.features.has("float32-blendable")) || i.limits.maxColorAttachments < 5) throw e("unsupported", "PreciseOIT needs five targets and float32 blending; request features: ['float32-blendable'] on WebGPU or EXT_float_blend on WebGL2, or use OIT", "compatibility-layer");
108
+ this.uniform = i.createBuffer({
109
+ size: 16,
110
+ usage: GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST
111
+ });
112
+ }
113
+ declarations(e) {
114
+ return a(this.code, e, (e) => this.surface(e) + l);
115
+ }
116
+ surface(e) {
117
+ return a(this.surfaceCode, e, m);
118
+ }
119
+ bindings() {
120
+ return [{
121
+ binding: 120,
122
+ resource: this.binding ?? { buffer: this.uniform }
123
+ }];
124
+ }
125
+ begin() {
126
+ if (this.pass) return this.pass;
127
+ let e = this.context;
128
+ return this.pass = e.encoder.beginRenderPass({
129
+ label: "oit:precise:accumulate",
130
+ colorAttachments: this.views.map((e, t) => ({
131
+ view: e,
132
+ clearValue: t === 4 ? [
133
+ 1,
134
+ 1,
135
+ 0,
136
+ 0
137
+ ] : [
138
+ 0,
139
+ 0,
140
+ 0,
141
+ 0
142
+ ],
143
+ loadOp: "clear",
144
+ storeOp: "store"
145
+ })),
146
+ depthStencilAttachment: {
147
+ view: e.depth,
148
+ depthReadOnly: !0,
149
+ stencilReadOnly: !0
150
+ }
151
+ }), o(this.pass, e), this.pass;
152
+ }
153
+ render(e) {
154
+ if (s(e.device, e.view ?? e), this.disposed || this.empty) return;
155
+ let t = e.device, n = e.descriptor.multisample?.count ?? 1, i = e.width + "x" + e.height + "x" + n;
156
+ if (i !== this.size) {
157
+ this.release(), this.size = i;
158
+ for (let r of this.targets) {
159
+ let i = t.createTexture({
160
+ label: "oit:precise:" + r.format,
161
+ size: [e.width, e.height],
162
+ format: r.format,
163
+ sampleCount: n,
164
+ usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.TEXTURE_BINDING
165
+ });
166
+ this.textures.push(i), this.views.push(i.createView());
167
+ }
168
+ }
169
+ let a = this.depthScale ?? Math.hypot(...e.camera.position.map((t, n) => t - e.camera.target[n]));
170
+ this.values[0] = 1 / (a || 1), this.binding = r(t, this.uniform, this.values, e.view ?? e);
171
+ let l;
172
+ try {
173
+ if (!this.drawModels(e)) return;
174
+ l = this.scene?.();
175
+ } finally {
176
+ this.binding = void 0, this.scene = void 0;
177
+ }
178
+ let u = (r) => {
179
+ let i = e.format + n + (r ? "l" : ""), a = this.pipelines.get(i);
180
+ if (!a) {
181
+ let o = t.createShaderModule({ code: (r ? g : h)(n) }), s = t.createBindGroupLayout({ entries: [...this.views.map((e, t) => ({
182
+ binding: t,
183
+ visibility: 2,
184
+ texture: {
185
+ sampleType: "unfilterable-float",
186
+ multisampled: n > 1
187
+ }
188
+ })), ...r ? [{
189
+ binding: 9,
190
+ visibility: 2,
191
+ texture: { sampleType: "unfilterable-float" }
192
+ }] : []] });
193
+ this.pipelines.set(i, a = t.createRenderPipeline({
194
+ label: r ? "oit:precise:composite-linear" : "oit:precise:composite",
195
+ layout: t.createPipelineLayout({ bindGroupLayouts: [s] }),
196
+ vertex: {
197
+ module: o,
198
+ entryPoint: "vertex"
199
+ },
200
+ fragment: {
201
+ module: o,
202
+ entryPoint: "fragment",
203
+ targets: [{
204
+ format: e.format,
205
+ blend: r ? void 0 : c
206
+ }]
207
+ },
208
+ multisample: { count: n }
209
+ }));
210
+ }
211
+ return a;
212
+ }, d = u(!1), f = this.groups.get(d);
213
+ f || this.groups.set(d, f = t.createBindGroup({
214
+ layout: d.getBindGroupLayout(0),
215
+ entries: this.views.map((e, t) => ({
216
+ binding: t,
217
+ resource: e
218
+ }))
219
+ }));
220
+ let p = e.encoder.beginRenderPass({
221
+ label: "oit:precise:composite",
222
+ colorAttachments: [{
223
+ view: e.color,
224
+ loadOp: "load",
225
+ storeOp: "store"
226
+ }]
227
+ });
228
+ if (o(p, e), p.setPipeline(d), p.setBindGroup(0, f), p.draw(3), l) {
229
+ let e = u(!0), n = this.linearGroup;
230
+ (n?.view !== l || n.pipeline !== e) && (this.linearGroup = n = {
231
+ view: l,
232
+ pipeline: e,
233
+ group: t.createBindGroup({
234
+ layout: e.getBindGroupLayout(0),
235
+ entries: [...this.views.map((e, t) => ({
236
+ binding: t,
237
+ resource: e
238
+ })), {
239
+ binding: 9,
240
+ resource: l
241
+ }]
242
+ })
243
+ }), p.setPipeline(e), p.setBindGroup(0, n.group), p.draw(3);
244
+ }
245
+ p.end();
246
+ }
247
+ release() {
248
+ for (let e of this.textures) i(this.device, e);
249
+ this.textures = [], this.views = [], this.size = "", this.groups.clear(), this.linearGroup = void 0;
250
+ }
251
+ freeDevice() {
252
+ this.release(), this.pipelines.clear(), i(this.device, this.uniform), this.uniform = void 0;
253
+ }
254
+ };
255
+ //#endregion
256
+ export { _ as PreciseOIT };
@@ -0,0 +1,53 @@
1
+ /** A reusable pass descriptor drawing over the frame: colour load/store, depth and stencil read only. */
2
+ export function overlayPass(): GPURenderPassDescriptor & {
3
+ colorAttachments: [GPURenderPassColorAttachment];
4
+ depthStencilAttachment: GPURenderPassDepthStencilAttachment;
5
+ };
6
+ /** {@link overlayPass} that also loads and stores depth. */
7
+ export function overlayDepthPass(): GPURenderPassDescriptor & {
8
+ colorAttachments: [GPURenderPassColorAttachment];
9
+ depthStencilAttachment: GPURenderPassDepthStencilAttachment;
10
+ };
11
+ /** Straight (non-premultiplied) alpha blending. */
12
+ export const alphaBlend: GPUBlendState;
13
+ /** Straight alpha blending that leaves the target's alpha channel unchanged: precipitation and other overlays drawn into a frame. */
14
+ export const overlayBlend: GPUBlendState;
15
+
16
+ /** `mesh` when it is null or a core mesh handle (checked live); else a TypeError. */
17
+ export function attachableMesh<M extends { check(): void } | null>(mesh: M): M;
18
+ /**
19
+ * What an order-independent pass offers an effect that is no PBR surface (particles, splats, points), in place of
20
+ * gltf/pbr's transparency hook. Same contract, but `surface` declares `fn margoTransparentAt(color:vec4f,clip:vec4f,
21
+ * depth:f32)->MargoTransparent`: `clip` is the fragment's position builtin, `depth` its view depth.
22
+ */
23
+ export interface SurfaceTransparency {
24
+ /** Module-scope WGSL: `struct MargoTransparent` (one output per target), `margoTransparentAt` and its bindings in `group`. */
25
+ surface(group: number): string;
26
+ /** Layout of those bindings, for an effect with explicit pipeline layouts. */
27
+ readonly layout: readonly GPUBindGroupLayoutEntry[];
28
+ /** Entries for those bindings. */
29
+ bindings(): GPUBindGroupEntry[];
30
+ /** True: declarations hold `override margoKind:u32`, 0 normal, 1 additive; additive surfaces may draw here. */
31
+ readonly blends?: boolean;
32
+ /** Colour targets of the transparent pass, in `MargoTransparent` location order. */
33
+ readonly targets: readonly GPUColorTargetState[];
34
+ /** This frame's transparent pass, begun on the first draw and ended by the owner. */
35
+ begin(): GPURenderPassEncoder;
36
+ }
37
+ /** The fragment entry `transparent` of an effect under a transparency hook: `inputs` are its parameters, the rest WGSL expressions. */
38
+ export function surfaceEntry(declarations: string, inputs: string, color: string, clip: string, depth: string): string;
39
+ /** Holds an effect's transparency hook: `set` takes it and `released`, and returns the remover. */
40
+ export function transparencySlot(): {
41
+ hook?: SurfaceTransparency;
42
+ released?: () => void;
43
+ set(hook: SurfaceTransparency, released?: () => void): () => void;
44
+ };
45
+ /** `hook`'s pass with `pipeline` set, `group` at group 0 and the hook's bindings at group 1, for an effect with an auto layout. */
46
+ export function surfacePass(
47
+ device: GPUDevice,
48
+ hook: SurfaceTransparency,
49
+ pipeline: GPURenderPipeline,
50
+ group: GPUBindGroup,
51
+ ): GPURenderPassEncoder;
52
+ /** The WGSL `make(group)` builds for bind group `group`, made once per group and kept in `cache`. */
53
+ export function groupCode(cache: Map<number, string>, group: number, make: (group: number) => string): string;
package/dist/vfx.d.ts ADDED
@@ -0,0 +1,11 @@
1
+ import { TransparentPass, type TransparentEffect } from './pass.js';
2
+ export type { TransparentEffect, TransparentPass };
3
+ /**
4
+ * Draws an effect in an order-independent pass (`OIT`, `ExactOIT`, `MomentOIT`), with the models added to it: `VFX` from
5
+ * `@margoengine/vfx`, `Splats` from `@margoengine/splats`, or a `PointsPlugin` from `@margoengine/points`, whose
6
+ * transparent clouds and sprites go in. The effect leaves its own draw until the returned function is called, the effect
7
+ * is disposed or the pass is.
8
+ * @throws TypeError for anything that is not such an effect, or a model-only depth-peeling pass; use OIT, ExactOIT or MomentOIT for effects.
9
+ * @throws MargoError `'disposed'` after the pass's `dispose()`, `'state'` before its `attach`.
10
+ */
11
+ export declare function addEffect(oit: TransparentPass, effect: TransparentEffect): () => void;
package/dist/vfx.js ADDED
@@ -0,0 +1,17 @@
1
+ //#region src/vfx.ts
2
+ function e(e, t) {
3
+ if (typeof t?.setTransparency != "function" || typeof t.drawTransparent != "function") throw TypeError("addEffect needs a VFX, Splats or PointsPlugin");
4
+ if (e.ready(), "depthWrite" in e && e.depthWrite) throw TypeError("addEffect needs OIT, ExactOIT or MomentOIT; depth peeling takes models only");
5
+ let n = e.effects.get(t);
6
+ if (!n) {
7
+ let r = () => {
8
+ e.effects.get(t) === n && e.effects.delete(t);
9
+ }, i = t.setTransparency(e, r);
10
+ n = () => {
11
+ r(), i();
12
+ }, e.effects.set(t, n);
13
+ }
14
+ return n;
15
+ }
16
+ //#endregion
17
+ export { e as addEffect };