@margoengine/lighting2d 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/gi.js ADDED
@@ -0,0 +1,546 @@
1
+ // @margo/core-built 1.0.0
2
+ import {coreRequirement as __margoCoreRequirement,assertCore as __margoAssertCore} from '@margoengine/core/extension';
3
+ const m=(engine,version="1.0.0",source=import.meta.url)=>__margoRuntime(engine,version,source);
4
+ import { a as e, c as t, i as n, l as r, n as i, o as a, r as o, t as s, u as c } from "./resources-Cskg0FqE.js";
5
+ import { c as l, l as u, o as d, s as f } from "./src-8W7SHUG7.js";
6
+ import { hexColor as p } from "@margoengine/math";
7
+ import { engineRuntime as __margoRuntime } from "@margoengine/core/extension";
8
+ //#region src/sdf-shader.ts
9
+ var h = "\nstruct PaintSettings { camera:vec4f, material:vec4f }\n@group(3)@binding(0)var<uniform>paint:PaintSettings;\n@group(3)@binding(1)var paintedColor:texture_2d<f32>;\n@group(3)@binding(2)var paintedEmission:texture_2d<f32>;\n@group(3)@binding(3)var paintedDistance:texture_2d<f32>;\n@group(3)@binding(4)var<storage,read>paintChanged:array<u32>;\n\nfn tracePaint(p:vec2f,d:vec2f,reach:f32)->vec4f {\n let size=textureDimensions(paintedDistance);let origin=(p-paint.camera.xy)*paint.camera.z;\n let ray=d*paint.camera.z;var near=0.0;var far=reach;\n for(var j=0u;j<2u;j++){\n if(abs(ray[j])<1e-20){if(origin[j]<0||origin[j]>=f32(size[j])){return vec4f(0,0,0,-1);}}\n else{let a=-origin[j]/ray[j];let b=(f32(size[j])-origin[j])/ray[j];near=max(near,min(a,b));far=min(far,max(a,b));}\n }\n if(near>far){return vec4f(0,0,0,-1);}\n var t=near;\n for(var step=0u;step<size.x+size.y+4u;step++){\n if(t>far){break;}\n let q=origin+ray*t;let cell=vec2i(floor(q+sign(ray)*1e-5));\n if(any(cell<vec2i(0))||any(cell>=vec2i(size))){break;}\n let field=textureLoad(paintedDistance,cell,0);\n if(field.y>0){\n let e=textureLoad(paintedEmission,cell,0);var rgb=e.rgb*e.a*paint.material.y;\n if(t>1e-6){\n let f=q-vec2f(cell);let delta=select(vec2f(1)-f,f,ray>vec2f(0));\n var face=select(1u,0u,ray.x>0);if(abs(ray.x)<1e-20||(abs(ray.y)>1e-20&&delta.y<delta.x)){face=select(3u,2u,ray.y>0);}\n rgb+=surfaces[u.counts.x*2u+(u32(cell.y)*size.x+u32(cell.x))*4u+face].rgb;\n }\n return vec4f(rgb,t);\n }\n var next=vec2f(1e30);\n for(var j=0u;j<2u;j++){\n if(abs(ray[j])>1e-20){let boundary=f32(cell[j])+select(0.0,1.0,ray[j]>0);next[j]=(boundary-q[j])/ray[j];}\n }\n let safe=max(0,field.x-.7071068-length(q-(vec2f(cell)+.5)))/paint.camera.z;\n t+=max(safe,min(next.x,next.y)+1e-5/paint.camera.z);\n }\n return vec4f(0,0,0,-1);\n}\n", g = "\nfn bouncePaint(index:u32){\n let size=textureDimensions(paintedDistance);let pixel=index/4u;if(pixel>=size.x*size.y){return;}\n let cell=vec2i(i32(pixel%size.x),i32(pixel/size.x));let face=index%4u;\n let at=u.counts.x*2u+index;\n if(textureLoad(paintedDistance,cell,0).y==0){output[at]=vec4f(0);return;}\n var n=vec2f(-1,0);if(face==1u){n=vec2f(1,0);}if(face==2u){n=vec2f(0,-1);}if(face==3u){n=vec2f(0,1);}\n let neighbour=cell+vec2i(n);\n if(all(neighbour>=vec2i(0))&&all(neighbour<vec2i(size))){\n if(textureLoad(paintedDistance,neighbour,0).y>0){output[at]=vec4f(0);return;}\n }\n let p=paint.camera.xy+(vec2f(cell)+.5+n*.501)/paint.camera.z;\n var rgb=direct(p,n);var cosineSum=0.0;\n for(var k=0u;k<32u;k++){cosineSum+=max(0,dot(n,direction(k,32u)));}\n for(var k=0u;k<32u;k++){\n let d=direction(k,32u);rgb+=trace(p,d,u.misc.w).rgb*(max(0,dot(n,d))/cosineSum);\n }\n output[at]=vec4f(rgb*clamp(textureLoad(paintedColor,cell,0).rgb,vec3f(0),vec3f(1))*u.material.x,0);\n}\n", _ = 0, v = 2 * Math.PI, y = (e, t) => [Math.cos(v * (e + .5) / t), Math.sin(v * (e + .5) / t)], b = (e, t, n) => [e[0] + t[0] * n, e[1] + t[1] * n], x = (e = 16777215) => {
10
+ if (Array.isArray(e) && e.length === 3 && e.every((e) => Number.isFinite(e) && e >= 0)) return [...e];
11
+ let t = p(typeof e == "number" ? "#" + e.toString(16).padStart(6, "0") : e);
12
+ if (!t) throw r("Invalid GI color", "pixel-lighting");
13
+ return [
14
+ t[0],
15
+ t[1],
16
+ t[2]
17
+ ];
18
+ };
19
+ function S(t, n) {
20
+ let i = [], o = f(t.occluders ?? []);
21
+ for (let e = 0; e < o.length; e += 4) {
22
+ let t = o[e + 2] - o[e], a = o[e + 3] - o[e + 1], s = Math.hypot(t, a), c = Math.ceil(s / n);
23
+ if (i.length + c > 65536) throw r("GI surface patch limit (65536)", "pixel-lighting");
24
+ for (let n = 0; n < c; n++) i.push({
25
+ a: [o[e] + t * n / c, o[e + 1] + a * n / c],
26
+ b: [o[e] + t * (n + 1) / c, o[e + 1] + a * (n + 1) / c],
27
+ n: [-a / s, t / s]
28
+ });
29
+ }
30
+ let s = (t.emitters ?? []).map((e) => {
31
+ let t = e.shape === "circle" || e.shape === void 0 && e.radius !== void 0, n = t ? [e.radius ?? e.width ?? 10, e.radius ?? e.width ?? 10] : [e.width ?? 10, e.height ?? 10], i = e.intensity ?? 1;
32
+ if (![
33
+ e.x,
34
+ e.y,
35
+ ...n,
36
+ i
37
+ ].every(Number.isFinite) || n.some((e) => e <= 0) || i < 0 || e.shape !== void 0 && e.shape !== "circle" && e.shape !== "rect") throw r("Invalid GI emitter", "pixel-lighting");
38
+ return {
39
+ p: [e.x, e.y],
40
+ size: n,
41
+ color: x(e.color).map((e) => e * i),
42
+ circle: t
43
+ };
44
+ }), c = t.layer ?? 4294967295, l = t.lights ?? [];
45
+ e(c);
46
+ for (let e of l) a(e);
47
+ return {
48
+ patches: i,
49
+ emitters: s,
50
+ lights: l,
51
+ layer: c
52
+ };
53
+ }
54
+ function C(e, t, n, r, i) {
55
+ let a = n, o = -1, s = [
56
+ 0,
57
+ 0,
58
+ 0
59
+ ], c = !1;
60
+ for (let n = 0; n < r.patches.length; n++) {
61
+ let i = r.patches[n], s = i.b[0] - i.a[0], l = i.b[1] - i.a[1], u = t[0] * l - t[1] * s;
62
+ if (Math.abs(u) < 1e-7) continue;
63
+ let d = i.a[0] - e[0], f = i.a[1] - e[1], p = (d * l - f * s) / u, m = (d * t[1] - f * t[0]) / u;
64
+ p > 1e-4 && p <= a && m >= -1e-4 && m <= 1.0001 && (a = p, c = !0, o = n * 2 + +(t[0] * i.n[0] + t[1] * i.n[1] > 0));
65
+ }
66
+ o >= 0 && (s = [
67
+ i[o * 4],
68
+ i[o * 4 + 1],
69
+ i[o * 4 + 2]
70
+ ]);
71
+ for (let i of r.emitters) {
72
+ let r = [e[0] - i.p[0], e[1] - i.p[1]], o = 0, l = n;
73
+ if (i.circle) {
74
+ let e = r[0] * t[0] + r[1] * t[1], n = e * e - r[0] ** 2 - r[1] ** 2 + i.size[0] ** 2;
75
+ if (n < 0) continue;
76
+ o = Math.max(0, -e - Math.sqrt(n)), l = Math.min(l, -e + Math.sqrt(n));
77
+ } else for (let e = 0; e < 2; e++) if (Math.abs(t[e]) < 1e-7) Math.abs(r[e]) > i.size[e] / 2 && (l = -1);
78
+ else {
79
+ let n = (-i.size[e] / 2 - r[e]) / t[e], a = (i.size[e] / 2 - r[e]) / t[e];
80
+ o = Math.max(o, Math.min(n, a)), l = Math.min(l, Math.max(n, a));
81
+ }
82
+ o <= l && o <= a && (a = o, c = !0, s = i.color);
83
+ }
84
+ return [...s, +!c];
85
+ }
86
+ function w(e, t) {
87
+ let n = new Float32Array(e.patches.length * 8), r = t.baseDistance * t.intervalRatio ** (t.cascades - 1);
88
+ for (let i = 0; i < t.bounces; i++) {
89
+ let i = new Float32Array(n.length);
90
+ e.patches.forEach((a, o) => {
91
+ for (let s = 0; s < 2; s++) {
92
+ let c = [a.n[0] * (s ? -1 : 1), a.n[1] * (s ? -1 : 1)], l = b([(a.a[0] + a.b[0]) / 2, (a.a[1] + a.b[1]) / 2], c, .001), u = [
93
+ 0,
94
+ 0,
95
+ 0
96
+ ], f = 0;
97
+ for (let e = 0; e < 32; e++) {
98
+ let t = y(e, 32);
99
+ f += Math.max(0, c[0] * t[0] + c[1] * t[1]);
100
+ }
101
+ for (let t = 0; t < 32; t++) {
102
+ let i = y(t, 32), a = Math.max(0, c[0] * i[0] + c[1] * i[1]) / f, o = C(l, i, r, e, n);
103
+ for (let e = 0; e < 3; e++) u[e] += o[e] * a;
104
+ }
105
+ for (let t of e.lights) {
106
+ let r = t.kind === "directional" ? [-Math.cos(t.angle), -Math.sin(t.angle)] : [t.x - l[0], t.y - l[1]], i = Math.hypot(...r), a = i ? [r[0] / i, r[1] / i] : [0, 0];
107
+ if (t.shadows && C(l, a, t.kind === "directional" ? 1e10 : Math.max(0, i - .001), e, n)[3] === 0) continue;
108
+ let o = d(t, l[0], l[1], [...c, 0], e.layer);
109
+ for (let e = 0; e < 3; e++) u[e] += o[e] / 2;
110
+ }
111
+ i.set(u.map((e) => e * t.albedo), (o * 2 + s) * 4);
112
+ }
113
+ }), n = i;
114
+ }
115
+ return n;
116
+ }
117
+ function T(e, t, n) {
118
+ let i = /* @__PURE__ */ new Map(), a = 0;
119
+ function o(s, c, l) {
120
+ if (++a > 8e6) throw r("GI CPU sample limit (8000000)", "pixel-lighting");
121
+ let u = t.baseRays * t.angularRatio ** c, d = y(l, u), f = c ? t.baseDistance * t.intervalRatio ** (c - 1) : 0, p = t.baseDistance * t.intervalRatio ** c, m = b(s, d, f);
122
+ if (c === t.cascades - 1) return C(m, d, p - f, e, n);
123
+ let h = 2 ** (c + 1), g = (s[0] - .5) / h, _ = (s[1] - .5) / h, v = Math.floor(g), x = Math.floor(_), S = g - v, w = _ - x, T = [
124
+ 0,
125
+ 0,
126
+ 0,
127
+ 0
128
+ ];
129
+ for (let r = 0; r < t.angularRatio; r++) {
130
+ let a = l * t.angularRatio + r, s = y(a, u * t.angularRatio), d = Array.from({ length: 4 }, () => [
131
+ 0,
132
+ 0,
133
+ 0,
134
+ 0
135
+ ]);
136
+ for (let r = 0; r < 4; r++) {
137
+ let l = v + (r & 1), u = x + (r >> 1);
138
+ if (!((r & 1 ? S : 1 - S) * (r >> 1 ? w : 1 - w) / t.angularRatio)) continue;
139
+ let f = [l * h + .5, u * h + .5], g = b(f, s, p), _ = g[0] - m[0], y = g[1] - m[1], T = Math.hypot(_, y), E = C(m, T ? [_ / T, y / T] : s, T, e, n);
140
+ if (E[3]) {
141
+ let e = `${c + 1},${l},${u},${a}`, t = i.get(e);
142
+ t || (t = o(f, c + 1, a), i.set(e, t));
143
+ for (let e = 0; e < 3; e++) E[e] += E[3] * t[e];
144
+ E[3] *= t[3];
145
+ }
146
+ d[r] = E;
147
+ }
148
+ for (let e = 0; e < 4; e++) {
149
+ let t = d[0][e] + (d[1][e] - d[0][e]) * S, n = t + (d[2][e] + (d[3][e] - d[2][e]) * S - t) * w;
150
+ T[e] += (n - T[e]) / (r + 1);
151
+ }
152
+ }
153
+ return T;
154
+ }
155
+ return (e, n) => {
156
+ if (!e.every(Number.isFinite) || n && !n.every(Number.isFinite)) throw r("Invalid GI query", "pixel-lighting");
157
+ let i = [
158
+ 0,
159
+ 0,
160
+ 0
161
+ ], a = n ? Math.hypot(...n) : 0;
162
+ for (let r = 0; r < t.baseRays; r++) {
163
+ let s = o(e, 0, r), c = y(r, t.baseRays), l = (a ? Math.PI * Math.max(0, c[0] * n[0] + c[1] * n[1]) / a : 1) * t.intensity / t.baseRays;
164
+ for (let e = 0; e < 3; e++) i[e] += s[e] * l;
165
+ }
166
+ return i;
167
+ };
168
+ }
169
+ var E = class {
170
+ constructor(e = {}) {
171
+ let { cascades: t = 4, baseRays: n = 4, baseDistance: i = 16, intervalRatio: a = 4, angularRatio: o = 4, bounces: s = 1, albedo: c = .5, intensity: l = 1 } = e;
172
+ if (!Number.isInteger(t) || t < 1 || t > 8) throw r("cascades must be an integer from 1 to 8", "pixel-lighting");
173
+ if (!Number.isInteger(n) || n < 1 || n > 32) throw r("baseRays must be an integer from 1 to 32", "pixel-lighting");
174
+ if (!Number.isFinite(i) || i <= 0) throw r("baseDistance must be a positive number", "pixel-lighting");
175
+ if (!Number.isFinite(a) || a <= 1) throw r("intervalRatio must be greater than 1", "pixel-lighting");
176
+ if (!Number.isInteger(o) || o < 1 || o > 8) throw r("angularRatio must be an integer from 1 to 8", "pixel-lighting");
177
+ if (!Number.isInteger(s) || s < 0 || s > 4) throw r("bounces must be an integer from 0 to 4", "pixel-lighting");
178
+ if (!Number.isFinite(c) || c < 0 || c > 1) throw r("albedo must be from 0 to 1", "pixel-lighting");
179
+ if (!Number.isFinite(l) || l < 0) throw r("intensity must be a nonnegative number", "pixel-lighting");
180
+ if (!Number.isFinite(Math.fround(i * a ** (t - 1)))) throw r("Cascade reach overflows", "pixel-lighting");
181
+ this.cascades = t, this.baseRays = n, this.baseDistance = i, this.intervalRatio = a, this.angularRatio = o, this.bounces = s, this.albedo = c, this.intensity = l;
182
+ }
183
+ evaluateAt(e, t, n = {}) {
184
+ let r = S(n, this.baseDistance);
185
+ return T(r, this, w(r, this))(e, t);
186
+ }
187
+ computeGrid(e, t, n = {}, i = 1) {
188
+ if (!Number.isInteger(e) || e <= 0 || !Number.isInteger(t) || t <= 0) throw r("Grid dimensions must be positive integers", "pixel-lighting");
189
+ if (!Number.isFinite(i) || i <= 0) throw r("Invalid GI spacing", "pixel-lighting");
190
+ let a = S(n, this.baseDistance), o = T(a, this, w(a, this)), s = new Float32Array(e * t * 3);
191
+ for (let n = 0; n < t; n++) for (let t = 0; t < e; t++) s.set(o([t * i, n * i]), (n * e + t) * 3);
192
+ return s;
193
+ }
194
+ };
195
+ function D(e, t, n = {}, r) {
196
+ return new E(r).evaluateAt(e, t, n);
197
+ }
198
+ var O = "\nstruct Params {\n camera:vec4f, ambient:vec4f, config:vec4f, material:vec4f, counts:vec4u,\n grid:vec4f, upper:vec4f, misc:vec4f,\n}\nstruct Patch { a:vec2f,b:vec2f,n:vec2f,pad:vec2f }\nstruct Emitter { p:vec2f,size:vec2f,color:vec3f,circle:f32 }\nstruct Light { pos:vec4f,color:vec4f,geo:vec4f,flags:vec4u,bounds:vec4f,mask:vec4f }\n@group(0)@binding(0)var<uniform>u:Params;\n@group(0)@binding(1)var<storage,read>patches:array<Patch>;\n@group(0)@binding(2)var<storage,read>emitters:array<Emitter>;\n@group(0)@binding(3)var<storage,read>lights:array<Light>;\n@group(1)@binding(0)var<storage,read>upper:array<vec4f>;\n@group(1)@binding(1)var<storage,read>surfaces:array<vec4f>;\n@group(2)@binding(0)var<storage,read_write>output:array<vec4f>;\nfn rayCount(level:u32)->u32 {\n var count=u32(u.config.y);for(var i=0u;i<level;i++){count*=u32(u.config.w);}return count;\n}\nfn direction(i:u32,count:u32)->vec2f {\n let a=6.28318530718*(f32(i)+.5)/f32(count);return vec2f(cos(a),sin(a));\n}\nfn trace(p:vec2f,d:vec2f,length:f32)->vec4f {\n var nearest=length;var rgb=vec3f(0);var hit=false;\n for(var i=0u;i<u.counts.x;i++){\n let e=patches[i];let v=e.b-e.a;let den=d.x*v.y-d.y*v.x;\n if(abs(den)<1e-7){continue;}\n let w=e.a-p;let t=(w.x*v.y-w.y*v.x)/den;let s=(w.x*d.y-w.y*d.x)/den;\n if(t>1e-4&&t<=nearest&&s>=-1e-4&&s<=1.0001){nearest=t;hit=true;rgb=surfaces[i*2u+select(0u,1u,dot(d,e.n)>0)].rgb;}\n }\n for(var i=0u;i<u.counts.y;i++){\n let e=emitters[i];let w=p-e.p;var near=0.0;var far=length;\n if(e.circle>0){\n let b=dot(w,d);let disc=b*b-dot(w,w)+e.size.x*e.size.x;\n if(disc<0){continue;}\n near=max(0,-b-sqrt(disc));far=min(far,-b+sqrt(disc));\n }else{\n for(var j=0u;j<2u;j++){\n if(abs(d[j])<1e-7){if(abs(w[j])>e.size[j]*.5){far=-1;}}\n else{let a=(-e.size[j]*.5-w[j])/d[j];let b=(e.size[j]*.5-w[j])/d[j];near=max(near,min(a,b));far=min(far,max(a,b));}\n }\n }\n if(near<=far&&near<=nearest){nearest=near;hit=true;rgb=e.color;}\n }\n return vec4f(rgb,select(1.0,0.0,hit));\n}\nfn direct(p:vec2f,n:vec2f)->vec3f {\n var sum=vec3f(0);\n for(var i=0u;i<u.counts.z;i++){\n let l=lights[i];if((l.flags.y&u.counts.w)==0u||!maskVisible(p,l.bounds,l.mask)){continue;}\n var d=l.pos.xy-p;var distance=length(d);var shade=1.0;var cosine=1.0;\n if(l.flags.x==2u){\n d=-vec2f(cos(l.geo.y),sin(l.geo.y));distance=1e10;cosine=max(0,dot(n,d)*cos(l.geo.x));\n }else{\n shade=pow(max(0,1-distance/l.pos.z),l.pos.w);\n let len=sqrt(distance*distance+l.geo.x*l.geo.x);\n cosine=select(1.0,max(0,dot(n,d)/max(len,1e-20)),len>0);\n if(l.flags.x==1u){\n var along=1.0;if(distance>0){along=-dot(d,vec2f(cos(l.geo.y),sin(l.geo.y)))/distance;}\n let outer=cos(l.geo.z);let inner=cos(l.geo.z*(1-l.geo.w));\n if(inner>outer){shade*=clamp((along-outer)/(inner-outer),0,1);}else if(along<outer){shade=0;}\n }\n if(distance>0){d/=distance;}\n }\n if(l.flags.z>0u&&trace(p,d,max(0,distance-.001)).w==0){continue;}\n sum+=l.color.rgb*(l.color.w*shade*cosine*.5);\n }\n return sum;\n}\n@compute @workgroup_size(64)fn bounce(@builtin(global_invocation_id)id:vec3u){\n let i=id.x;if(i>=u.counts.x*2u){return;}\n let e=patches[i/2u];let n=e.n*select(1.0,-1.0,i%2u==1u);let p=(e.a+e.b)*.5+n*.001;\n var rgb=direct(p,n);var cosineSum=0.0;\n for(var k=0u;k<32u;k++){cosineSum+=max(0,dot(n,direction(k,32u)));}\n for(var k=0u;k<32u;k++){\n let d=direction(k,32u);rgb+=trace(p,d,u.misc.w).rgb*(max(0,dot(n,d))/cosineSum);\n }\n output[i]=vec4f(rgb*u.material.x,0);\n}\n\nfn merge(p:vec2f,angle:u32)->vec4f{\n let level=u.misc.x;let count=rayCount(u32(level));let d=direction(angle,count);\n var near=0.0;if(level>0){near=u.config.z*pow(u.material.z,level-1);}\n let far=u.config.z*pow(u.material.z,level);let start=p+d*near;\n if(level==u.config.x-1){return trace(start,d,far-near);}\n let scale=f32(1u<<(u32(level)+1u));let g=(p-vec2f(.5))/scale;let cell=floor(g);let f=fract(g);\n let branch=u32(u.config.w);let upperCount=count*branch;var sum=vec4f(0);\n for(var child=0u;child<branch;child++){\n let a=angle*branch+child;let cd=direction(a,upperCount);var rays:array<vec4f,4>;\n for(var j=0u;j<4u;j++){\n let offset=vec2f(f32(j&1u),f32(j>>1u));let xy=cell+offset;let q=xy*scale+vec2f(.5);\n let delta=q+cd*far-start;let length=length(delta);\n var ray=trace(start,delta/max(length,1e-20),length);\n let index=vec2u(xy-u.upper.xy);let sample=upper[(index.y*u32(u.upper.z)+index.x)*upperCount+a];\n ray=vec4f(ray.rgb+ray.w*sample.rgb,ray.w*sample.w);\n rays[j]=ray;\n }\n let lo=rays[0]+(rays[1]-rays[0])*f.x;let hi=rays[2]+(rays[3]-rays[2])*f.x;\n let value=lo+(hi-lo)*f.y;sum+=(value-sum)/f32(child+1u);\n }\n return sum;\n}\n@compute @workgroup_size(64)fn cascade(@builtin(global_invocation_id)id:vec3u){\n let count=rayCount(u32(u.misc.x));let total=u32(u.grid.z*u.grid.w)*count;\n let i=id.x;if(i>=total){return;}\n let probe=i/count;let xy=vec2f(f32(probe%u32(u.grid.z)),f32(probe/u32(u.grid.z)))+u.grid.xy;\n output[i]=merge(xy*f32(1u<<u32(u.misc.x))+vec2f(.5),i%count);\n}\n@vertex fn wide(@builtin(vertex_index)i:u32)->@builtin(position)vec4f{\n let xy=vec2f(f32((i<<1u)&2u),f32(i&2u));return vec4f(xy*vec2f(2,-2)+vec2f(-1,1),0,1);\n}\n@fragment fn show(@builtin(position)p:vec4f)->@location(0)vec4f{\n let world=u.camera.xy+p.xy/u.camera.z;var rgb=vec3f(0);\n for(var i=0u;i<u32(u.config.y);i++){rgb+=merge(world,i).rgb;}\n return vec4f(u.ambient.rgb+rgb*(u.material.y/u.config.y),1);\n}\n", k = class a {coreRequirement=__margoCoreRequirement("1.0.0",import.meta.url);
199
+ #e;
200
+ #t = !1;
201
+ #n;
202
+ #r;
203
+ #i;
204
+ #a;
205
+ #o;
206
+ #s;
207
+ #c;
208
+ #l = !1;
209
+ #u;
210
+ #d;
211
+ #f;
212
+ #p;
213
+ #m;
214
+ #h;
215
+ #g = /* @__PURE__ */ new Map();
216
+ #_ = new l();
217
+ #v = new s();
218
+ #y;
219
+ constructor(e) {
220
+ if (!e?.target) throw c("target is required for GILighting2D", "pixel-lighting");
221
+ if (this.#y = new o(e.target, "GILighting2D target", "setTarget"), this.painted = e.painted, this.temporal = e.temporal ?? !0, typeof this.temporal != "boolean") throw c("temporal must be true or false", "pixel-lighting");
222
+ this.name = e.name ?? `gi-lighting2d-${++_}`, this.order = e.order ?? 20, this.cascades = new E(e.cascades), this.camera = e.camera ?? {
223
+ x: 0,
224
+ y: 0,
225
+ zoom: 1
226
+ }, this.ambient = e.ambient ?? 0, this.layer = e.layer ?? 4294967295, this.emitters = [...e.emitters ?? []], this.lights = [...e.lights ?? []], this.occluders = [...e.occluders ?? []];
227
+ }
228
+ static attach(e, t) {__margoAssertCore(e,__margoCoreRequirement("1.0.0",import.meta.url));
229
+ let n = new a(t);
230
+ return m(e).use(n), n;
231
+ }
232
+ setup(e) {
233
+ if (this.#t) throw t("disposed", "GILighting2D disposed; create a new one");
234
+ if (e.backend !== "webgpu" || !e.gpu) throw t("unsupported", "GILighting2D needs WebGPU", "webgpu");
235
+ this.#e = e, this.#y.fix(e.gpu), e.frameGraph.add({
236
+ name: this.name,
237
+ order: this.order,
238
+ execute: (e) => {
239
+ e.backend === "webgpu" && !e.view?.index && this.#S(e);
240
+ }
241
+ });
242
+ }
243
+ setTarget(e) {
244
+ if (!e) throw c("target is required for GILighting2D", "pixel-lighting");
245
+ this.#y.set(e, this.#e?.gpu);
246
+ }
247
+ #b(e, t, n = !1) {
248
+ let i = this.#n;
249
+ if (t = Math.max(16, t), !Number.isSafeInteger(t) || t > (n ? i.limits.maxBufferSize : i.limits.maxStorageBufferBindingSize)) throw r("GI buffer exceeds device limit", "pixel-lighting");
250
+ let a = this.#g.get(e);
251
+ return (!a || a.size < t) && (a?.destroy(), a = i.createBuffer({
252
+ label: `gi ${e}`,
253
+ size: t,
254
+ usage: (n ? GPUBufferUsage.UNIFORM : GPUBufferUsage.STORAGE) | GPUBufferUsage.COPY_DST
255
+ }), this.#g.set(e, a)), a;
256
+ }
257
+ #x(e, t, n) {
258
+ (this.#n !== e || this.#l !== !!n) && (this.#C(), this.#n = e, this.#l = !!n);
259
+ let r = GPUShaderStage.COMPUTE | GPUShaderStage.FRAGMENT;
260
+ if (!this.#r) {
261
+ let t = n ? O.replace("return vec4f(rgb,select(1.0,0.0,hit));", "\n let paintedHit=tracePaint(p,d,nearest);\n if(paintedHit.w>=0){rgb=paintedHit.rgb;hit=true;}\n return vec4f(rgb,select(1.0,0.0,hit));").replace("let i=id.x;if(i>=u.counts.x*2u){return;}", "let i=id.x;if(reuseIntervals()){return;}if(i>=u.counts.x*2u){bouncePaint(i-u.counts.x*2u);return;}") + h + g : O.replace("let i=id.x;if(i>=u.counts.x*2u){return;}", "let i=id.x;if(reuseIntervals()||i>=u.counts.x*2u){return;}");
262
+ t = t.replace("let count=rayCount(u32(u.misc.x));let total=", "if(reuseIntervals()){return;}let count=rayCount(u32(u.misc.x));let total="), t += `\nfn reuseIntervals()->bool {return u.misc.y>0${n ? "&&paintChanged[0]==0u" : ""};}\n`, this.#r = e.createShaderModule({
263
+ label: "radiance cascades",
264
+ code: u(4) + t
265
+ }), this.#i = e.createBindGroupLayout({ entries: [{
266
+ binding: 0,
267
+ visibility: r,
268
+ buffer: {
269
+ type: "uniform",
270
+ hasDynamicOffset: !0,
271
+ minBindingSize: 128
272
+ }
273
+ }, ...[
274
+ 1,
275
+ 2,
276
+ 3,
277
+ 4
278
+ ].map((e) => ({
279
+ binding: e,
280
+ visibility: r,
281
+ buffer: { type: "read-only-storage" }
282
+ }))] }), this.#a = e.createBindGroupLayout({ entries: [0, 1].map((e) => ({
283
+ binding: e,
284
+ visibility: r,
285
+ buffer: { type: "read-only-storage" }
286
+ })) }), this.#o = e.createBindGroupLayout({ entries: [{
287
+ binding: 0,
288
+ visibility: GPUShaderStage.COMPUTE,
289
+ buffer: { type: "storage" }
290
+ }] }), n && (this.#s = e.createBindGroupLayout({ entries: [
291
+ {
292
+ binding: 0,
293
+ visibility: r,
294
+ buffer: { type: "uniform" }
295
+ },
296
+ ...[
297
+ 1,
298
+ 2,
299
+ 3
300
+ ].map((e) => ({
301
+ binding: e,
302
+ visibility: r,
303
+ texture: { sampleType: "unfilterable-float" }
304
+ })),
305
+ {
306
+ binding: 4,
307
+ visibility: r,
308
+ buffer: { type: "read-only-storage" }
309
+ }
310
+ ] }));
311
+ let i = e.createPipelineLayout({ bindGroupLayouts: [
312
+ this.#i,
313
+ this.#a,
314
+ this.#o,
315
+ ...this.#s ? [this.#s] : []
316
+ ] });
317
+ this.#f = e.createComputePipeline({
318
+ layout: i,
319
+ compute: {
320
+ module: this.#r,
321
+ entryPoint: "cascade"
322
+ }
323
+ }), this.#p = e.createComputePipeline({
324
+ layout: i,
325
+ compute: {
326
+ module: this.#r,
327
+ entryPoint: "bounce"
328
+ }
329
+ });
330
+ }
331
+ if (t !== this.#h) {
332
+ this.#h = t;
333
+ let n = e.createBindGroupLayout({ entries: [] });
334
+ this.#c = e.createBindGroup({
335
+ layout: n,
336
+ entries: []
337
+ }), this.#m = e.createRenderPipeline({
338
+ layout: e.createPipelineLayout({ bindGroupLayouts: this.#s ? [
339
+ this.#i,
340
+ this.#a,
341
+ n,
342
+ this.#s
343
+ ] : [this.#i, this.#a] }),
344
+ vertex: {
345
+ module: this.#r,
346
+ entryPoint: "wide"
347
+ },
348
+ fragment: {
349
+ module: this.#r,
350
+ entryPoint: "show",
351
+ targets: [{ format: t }]
352
+ }
353
+ });
354
+ }
355
+ }
356
+ #S(t) {
357
+ let a = t.device, o = this.#y.get(a, this.#e);
358
+ if (!o) return;
359
+ if (n(this.camera), e(this.layer), typeof this.temporal != "boolean") throw c("temporal must be true or false", "pixel-lighting");
360
+ let s = this.cascades, l = S({
361
+ emitters: this.emitters,
362
+ lights: this.lights,
363
+ occluders: this.occluders,
364
+ layer: this.layer
365
+ }, s.baseDistance), u = x(this.ambient), d = this.painted?.encode(a, t.encoder, this.#e) ? this.painted : void 0;
366
+ this.#x(a, o.format, d);
367
+ let f = d?.bindGroup(a, this.#s), p = JSON.stringify([
368
+ this.camera,
369
+ o.width,
370
+ o.height,
371
+ this.cascades,
372
+ this.emitters,
373
+ this.lights,
374
+ this.occluders,
375
+ this.layer
376
+ ]), m = this.temporal && this.#u === p && this.#d === d;
377
+ this.#_.upload(a, this.lights);
378
+ let h = new Float32Array(Math.max(8, l.patches.length * 8));
379
+ l.patches.forEach((e, t) => h.set([
380
+ ...e.a,
381
+ ...e.b,
382
+ ...e.n
383
+ ], t * 8));
384
+ let g = new Float32Array(Math.max(8, l.emitters.length * 8));
385
+ l.emitters.forEach((e, t) => g.set([
386
+ ...e.p,
387
+ ...e.size,
388
+ ...e.color,
389
+ +!!e.circle
390
+ ], t * 8));
391
+ let _ = new Float32Array(Math.max(24, this.lights.length * 24)), v = new Uint32Array(_.buffer);
392
+ this.lights.forEach((e, t) => {
393
+ let n = t * 24;
394
+ _.set([
395
+ e.x,
396
+ e.y,
397
+ e.radius,
398
+ e.falloff,
399
+ ...x(e.color),
400
+ e.intensity,
401
+ e.kind === "directional" ? e.elevation : e.height,
402
+ e.angle,
403
+ e.cone,
404
+ e.softness
405
+ ], n), v.set([
406
+ e.kind === "directional" ? 2 : +(e.kind === "spot"),
407
+ e.layers,
408
+ +!!e.shadows,
409
+ 0
410
+ ], n + 12), _.set(this.#_.fields[t], n + 16);
411
+ });
412
+ let y = [
413
+ h,
414
+ g,
415
+ _
416
+ ], b = y.map((e, t) => this.#b(`scene${t}`, e.byteLength));
417
+ y.forEach((e, t) => a.queue.writeBuffer(b[t], 0, e));
418
+ let C = l.patches.length * 2 + (d ? d.distanceTexture.width * d.distanceTexture.height * 4 : 0), w = [this.#b("surface0", C * 16), this.#b("surface1", C * 16)], T = this.#b("empty", 16), E = this.#b("zero", C * 16), D = Math.max(256, a.limits.minUniformBufferOffsetAlignment), O = new Float32Array((s.bounces + s.cascades) * D / 4), k = this.#b("uniforms", O.byteLength, !0), A = this.#v.get(a, "scene", this.#i, [
419
+ {
420
+ binding: 0,
421
+ resource: {
422
+ buffer: k,
423
+ size: 128
424
+ }
425
+ },
426
+ {
427
+ binding: 1,
428
+ resource: { buffer: b[0] }
429
+ },
430
+ {
431
+ binding: 2,
432
+ resource: { buffer: b[1] }
433
+ },
434
+ {
435
+ binding: 3,
436
+ resource: { buffer: b[2] }
437
+ },
438
+ {
439
+ binding: 4,
440
+ resource: { buffer: this.#_.buffer }
441
+ }
442
+ ]), j = (e, t, n) => this.#v.get(a, e, this.#a, [{
443
+ binding: 0,
444
+ resource: { buffer: t }
445
+ }, {
446
+ binding: 1,
447
+ resource: { buffer: n }
448
+ }]), M = [[
449
+ 0,
450
+ 0,
451
+ 0,
452
+ 0
453
+ ]], N = [this.camera.x + .5 / this.camera.zoom, this.camera.y + .5 / this.camera.zoom], P = [this.camera.x + (o.width - .5) / this.camera.zoom, this.camera.y + (o.height - .5) / this.camera.zoom];
454
+ for (let e = 1; e < s.cascades; e++) {
455
+ let t = 2 ** e, n = N.map((e) => Math.floor((e - .5) / t)), r = P.map((e) => Math.floor((e - .5) / t) + 1);
456
+ M.push([
457
+ n[0],
458
+ n[1],
459
+ r[0] - n[0] + 1,
460
+ r[1] - n[1] + 1
461
+ ]), N = n.map((e) => e * t + .5), P = r.map((e) => e * t + .5);
462
+ }
463
+ let F = 0, I = (e) => {
464
+ let t = F++ * D, n = new Float32Array(O.buffer, t, 32), r = new Uint32Array(O.buffer, t, 32);
465
+ return n.set([
466
+ this.camera.x,
467
+ this.camera.y,
468
+ this.camera.zoom,
469
+ 0,
470
+ ...u,
471
+ 0,
472
+ s.cascades,
473
+ s.baseRays,
474
+ s.baseDistance,
475
+ s.angularRatio,
476
+ s.albedo,
477
+ s.intensity,
478
+ s.intervalRatio,
479
+ 0
480
+ ]), r.set([
481
+ l.patches.length,
482
+ l.emitters.length,
483
+ this.lights.length,
484
+ this.layer
485
+ ], 16), n.set(M[e], 20), n.set(M[e + 1] ?? [
486
+ 0,
487
+ 0,
488
+ 1,
489
+ 1
490
+ ], 24), n.set([
491
+ e,
492
+ +!!m,
493
+ 0,
494
+ s.baseDistance * s.intervalRatio ** (s.cascades - 1)
495
+ ], 28), t;
496
+ }, L = (e, n, i, o, s, c) => {
497
+ let l = Math.ceil(i / 64);
498
+ if (l > a.limits.maxComputeWorkgroupsPerDimension) throw r("GI dispatch exceeds device limit", "pixel-lighting");
499
+ let u = t.encoder.beginComputePass();
500
+ u.setPipeline(n), u.setBindGroup(0, A, [o]), u.setBindGroup(1, s), f && u.setBindGroup(3, f), u.setBindGroup(2, this.#v.get(a, e + " out", this.#o, [{
501
+ binding: 0,
502
+ resource: { buffer: c }
503
+ }])), u.dispatchWorkgroups(l), u.end();
504
+ }, R = E;
505
+ for (let e = 0; e < s.bounces; e++) {
506
+ let t = w[(e + 1) % 2], n = `bounce ${e}`;
507
+ L(n, this.#p, C, I(0), j(n, T, R), t), R = t;
508
+ }
509
+ let z = T;
510
+ for (let e = s.cascades - 1; e >= 1; e--) {
511
+ let t = M[e], n = t[2] * t[3] * s.baseRays * s.angularRatio ** e, r = this.#b(`cascade${e}`, n * 16), i = `cascade ${e}`;
512
+ L(i, this.#f, n, I(e), j(i, z, R), r), z = r;
513
+ }
514
+ let B = I(0), V = t.encoder.beginRenderPass({ colorAttachments: [{
515
+ view: i(o),
516
+ loadOp: "clear",
517
+ clearValue: [
518
+ 0,
519
+ 0,
520
+ 0,
521
+ 1
522
+ ],
523
+ storeOp: "store"
524
+ }] });
525
+ V.setPipeline(this.#m), V.setBindGroup(0, A, [B]), V.setBindGroup(1, j("show", z, R)), f && (V.setBindGroup(2, this.#c), V.setBindGroup(3, f)), V.draw(3), V.end(), a.queue.writeBuffer(k, 0, O), this.#u = p, this.#d = d;
526
+ }
527
+ resetHistory() {
528
+ this.#u = void 0;
529
+ }
530
+ onDeviceRestored() {
531
+ this.#C();
532
+ }
533
+ #C() {
534
+ this.#u = void 0, this.#d = void 0;
535
+ for (let e of this.#g.values()) e.destroy();
536
+ this.#g.clear(), this.#v.clear(), this.#_.dispose(), this.#n = this.#r = this.#i = this.#a = this.#o = this.#s = this.#c = this.#f = this.#p = this.#m = this.#h = void 0;
537
+ }
538
+ dispose() {
539
+ this.#t || (this.#t = !0, this.#C(), this.#e?.sceneOf(this)?.removePlugin(this.name), this.#e = void 0);
540
+ }
541
+ [Symbol.dispose]() {
542
+ this.dispose();
543
+ }
544
+ };
545
+ //#endregion
546
+ export { k as GILighting2D, E as RadianceCascade2D, D as evaluate2DGI };
@@ -0,0 +1,115 @@
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 { type Point2D, type Light2DOptions, Light2D } from './index.js';
5
+ /** A 2.5D height occluder for top-down perspective and self-shadowing. */
6
+ export interface HeightOccluder2D {
7
+ /** The 2D footprint shape of the occluder. */
8
+ shape: 'box' | 'circle' | 'segment';
9
+ /** Vertical height / extrusion of the occluder in world units (z-axis). Must be > 0. */
10
+ height: number;
11
+ /** Base elevation above the ground plane (z-axis). Default 0. */
12
+ elevation?: number;
13
+ /** Width in x for box occluders. Default 16. */
14
+ width?: number;
15
+ /** Depth in y for box occluders. Default 16. */
16
+ depth?: number;
17
+ /** 2D center offset [x, y] for box or circle, or start point for segment. Default [0, 0]. */
18
+ offset?: Point2D;
19
+ /** Rotation angle in radians for box occluders. Default 0. */
20
+ rotation?: number;
21
+ /** Radius for circle occluders. Default 8. */
22
+ radius?: number;
23
+ /** End point [x, y] for segment occluders. */
24
+ to?: Point2D;
25
+ /** Whether this occluder casts self-shadows on its own lower surfaces. Default true. */
26
+ selfShadow?: boolean;
27
+ }
28
+ /** Validates a {@link HeightOccluder2D} object. Throws RangeError if invalid. */
29
+ export declare function checkHeightOccluder(o: HeightOccluder2D): void;
30
+ /** Options for a {@link HeightLight2D}. */
31
+ export interface HeightLight2DOptions extends Light2DOptions {
32
+ /** Light height (z-elevation) above the ground plane. Default 32. */
33
+ height?: number;
34
+ /** Directional light elevation angle above horizon in radians. Default Math.PI / 4. */
35
+ elevation?: number;
36
+ }
37
+ /** One 2.5D height light for top-down games. */
38
+ export declare class HeightLight2D extends Light2D {
39
+ constructor(options?: HeightLight2DOptions);
40
+ }
41
+ /** Helper factory to create a {@link HeightOccluder2D}. */
42
+ export declare function createHeightOccluder(options: HeightOccluder2D): HeightOccluder2D;
43
+ /**
44
+ * Tests whether world point (x, y) at receiver elevation z is in shadow from `light`
45
+ * due to any height occluder.
46
+ */
47
+ export declare function inHeightShadow(light: Light2D, occluders: readonly HeightOccluder2D[], x: number, y: number, receiverElevation?: number): boolean;
48
+ /** Computes the shadow visibility factor (0: full shadow, 1: fully lit) for a height light. */
49
+ export declare function heightShadowFactor(light: Light2D, occluders: readonly HeightOccluder2D[], x: number, y: number, receiverElevation?: number): number;
50
+ /**
51
+ * Computes illuminated [r, g, b] at world point (x, y) with elevation z,
52
+ * factoring in 2.5D height shadowing and self-shadowing.
53
+ */
54
+ export declare function heightLightAt(light: Light2D, occluders: readonly HeightOccluder2D[], x: number, y: number, receiverElevation?: number, normal?: readonly number[], layer?: number): number[];
55
+ /** Options for the {@link HeightLighting2D} plugin. */
56
+ export interface HeightLighting2DOptions {
57
+ /**
58
+ * Target texture, or a function read each frame. A plain texture lost at a device restore skips the pass, reported
59
+ * once, until {@link HeightLighting2D.setTarget} gives a new one.
60
+ */
61
+ target?: GPUTexture | (() => GPUTexture);
62
+ /** Receiver ground elevation. Default 0. */
63
+ elevation?: number;
64
+ /** Active height occluders. */
65
+ occluders?: readonly HeightOccluder2D[];
66
+ /** Initial lights. */
67
+ lights?: readonly HeightLight2D[];
68
+ /** Camera configuration. Default { x: 0, y: 0, zoom: 1 }. */
69
+ camera?: {
70
+ x: number;
71
+ y: number;
72
+ zoom: number;
73
+ };
74
+ /** Pass name. */
75
+ name?: string;
76
+ /** Pass order in frameGraph. Default 15. */
77
+ order?: number;
78
+ /** Layer mask for filtering lights. Default ~0. */
79
+ layer?: number;
80
+ }
81
+ /**
82
+ * 2.5D Height & Self Shadowing Engine plugin for top-down games.
83
+ * Supports height-based ray occlusion, ground projection, and self-shadowing.
84
+ */
85
+ export declare class HeightLighting2D implements EnginePlugin, Disposable {
86
+ #private;
87
+ readonly name: string;
88
+ readonly order: number;
89
+ receiverElevation: number;
90
+ layer: number;
91
+ camera: {
92
+ x: number;
93
+ y: number;
94
+ zoom: number;
95
+ };
96
+ constructor(options?: HeightLighting2DOptions);
97
+ static attach(instance: EngineKernel, options?: HeightLighting2DOptions): HeightLighting2D;
98
+ setup(engine: Engine): void;
99
+ /**
100
+ * Replaces the texture the attached pass draws to, from the next frame: a texture, a function read each frame, or
101
+ * undefined for none. After a device restore, hand in a texture made on `engine.gpu` here.
102
+ */
103
+ setTarget(target: GPUTexture | (() => GPUTexture) | undefined): void;
104
+ /** Adds a light to the height lighting pass. */
105
+ addLight(options?: HeightLight2DOptions): HeightLight2D;
106
+ /** Removes a light. */
107
+ removeLight(light: HeightLight2D): boolean;
108
+ /** Sets the active height occluders. */
109
+ setOccluders(occluders: readonly HeightOccluder2D[]): void;
110
+ /** Renders the height lighting pass onto target. */
111
+ render(targetTexture: GPUTexture | (() => GPUTexture) | undefined, commandEncoder?: GPUCommandEncoder): void;
112
+ dispose(): void;
113
+ [Symbol.dispose](): void;
114
+ onDeviceRestored(): void;
115
+ }