@margoengine/terrain 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 (88) hide show
  1. package/LICENSE +201 -0
  2. package/NOTICE +4 -0
  3. package/README.md +2366 -2
  4. package/dist/bed-mesh.d.ts +40 -0
  5. package/dist/bed-mesh.js +95 -0
  6. package/dist/blend.d.ts +70 -0
  7. package/dist/blend.js +159 -0
  8. package/dist/colors.d.ts +170 -0
  9. package/dist/deform.d.ts +134 -0
  10. package/dist/deform.js +404 -0
  11. package/dist/displace.d.ts +60 -0
  12. package/dist/displace.js +254 -0
  13. package/dist/dunes.d.ts +86 -0
  14. package/dist/dunes.js +88 -0
  15. package/dist/elevation.d.ts +182 -0
  16. package/dist/elevation.js +155 -0
  17. package/dist/errors-fc4i1pSL.js +7 -0
  18. package/dist/far.d.ts +66 -0
  19. package/dist/far.js +191 -0
  20. package/dist/furrows.d.ts +74 -0
  21. package/dist/furrows.js +157 -0
  22. package/dist/grid.d.ts +14 -0
  23. package/dist/ground-change-settings.d.ts +29 -0
  24. package/dist/ground-change-settings.js +69 -0
  25. package/dist/ground-change.d.ts +227 -0
  26. package/dist/ground-change.js +1412 -0
  27. package/dist/ground-contact-settings.d.ts +27 -0
  28. package/dist/ground-contact-settings.js +22 -0
  29. package/dist/ground-contact.d.ts +91 -0
  30. package/dist/ground-contact.js +241 -0
  31. package/dist/ground-model.d.ts +372 -0
  32. package/dist/hdr-format-DRhzGS7G.js +30 -0
  33. package/dist/height-grid.d.ts +65 -0
  34. package/dist/height-grid.js +74 -0
  35. package/dist/heightfield.d.ts +38 -0
  36. package/dist/holes.d.ts +37 -0
  37. package/dist/holes.js +97 -0
  38. package/dist/imagery.d.ts +109 -0
  39. package/dist/imagery.js +472 -0
  40. package/dist/index.d.ts +408 -0
  41. package/dist/index.js +1 -0
  42. package/dist/layers-pbr.d.ts +78 -0
  43. package/dist/layers-pbr.js +128 -0
  44. package/dist/lighting-layout-CaDtDa5G.js +34 -0
  45. package/dist/lighting-layout.d.ts +5 -0
  46. package/dist/mesh-patch-BThCHCeS.js +21 -0
  47. package/dist/mesh-patch.d.ts +14 -0
  48. package/dist/noise3-sQdnbz4B.js +11 -0
  49. package/dist/noise3.d.ts +3 -0
  50. package/dist/overlays.d.ts +74 -0
  51. package/dist/overlays.js +297 -0
  52. package/dist/planet-complex.d.ts +31 -0
  53. package/dist/planet-craters.d.ts +80 -0
  54. package/dist/planet-rays.d.ts +37 -0
  55. package/dist/planet-recipes.d.ts +84 -0
  56. package/dist/planet-recipes.js +442 -0
  57. package/dist/planet.d.ts +144 -0
  58. package/dist/planet.js +610 -0
  59. package/dist/query.d.ts +150 -0
  60. package/dist/query.js +243 -0
  61. package/dist/relief-lighting.d.ts +53 -0
  62. package/dist/relief-lighting.js +221 -0
  63. package/dist/require-webgpu--tUXPsmA.js +7 -0
  64. package/dist/rock-settings.d.ts +39 -0
  65. package/dist/rock-settings.js +84 -0
  66. package/dist/rock-surface.d.ts +114 -0
  67. package/dist/rock-surface.js +380 -0
  68. package/dist/rocks.d.ts +258 -0
  69. package/dist/rocks.js +488 -0
  70. package/dist/rvt.d.ts +136 -0
  71. package/dist/rvt.js +518 -0
  72. package/dist/scour.d.ts +90 -0
  73. package/dist/scour.js +153 -0
  74. package/dist/sculpt.d.ts +103 -0
  75. package/dist/sculpt.js +361 -0
  76. package/dist/settings-B9BSdnhD.js +72 -0
  77. package/dist/settings.d.ts +81 -0
  78. package/dist/settings.js +152 -0
  79. package/dist/shader.d.ts +176 -0
  80. package/dist/shared/settings.d.ts +89 -0
  81. package/dist/src-Cr7Gm4n0.js +1366 -0
  82. package/dist/stream-window.d.ts +123 -0
  83. package/dist/stream.d.ts +169 -0
  84. package/dist/stream.js +531 -0
  85. package/dist/surface-height.d.ts +16 -0
  86. package/dist/wet-ground.d.ts +82 -0
  87. package/dist/wet-ground.js +147 -0
  88. package/package.json +173 -4
package/dist/deform.js ADDED
@@ -0,0 +1,404 @@
1
+ // @margo/core-built 1.0.0
2
+ import {coreRequirement as __margoCoreRequirement,assertCore as __margoAssertCore} from '@margoengine/core/extension';
3
+ const t=(engine,version="1.0.0",source=import.meta.url)=>__margoRuntime(engine,version,source);
4
+ import { n as e } from "./mesh-patch-BThCHCeS.js";
5
+ import { engineRuntime as __margoRuntime, meshRuntime as n } from "@margoengine/core/extension";
6
+ import { MargoError as r } from "@margoengine/math/errors";
7
+ //#region src/deform.ts
8
+ var i = [
9
+ 0,
10
+ 0,
11
+ 0
12
+ ], a = 110, o = 1024, s = "\nstruct Window {origin:vec2i,previous:vec2i,size:u32,first:u32,fade:f32,texel:f32,rim:f32,count:u32,pad:vec2f}\nstruct Stamp {shape:vec4f,ends:vec4f,turn:vec4f,box:vec4i}\n@group(0) @binding(0) var<uniform> w:Window;\n@group(0) @binding(1) var<storage,read_write> marks:array<atomic<u32>>;\n@group(0) @binding(2) var<storage,read> stamps:array<Stamp>;\n@group(0) @binding(3) var relief:texture_storage_2d<rgba16float,write>;\nfn slot(world:vec2i)->u32 {let s=i32(w.size);let m=((world%s)+s)%s;return u32(m.y)*w.size+u32(m.x);}\nfn inside(world:vec2i,origin:vec2i)->bool {return all(world>=origin)&&all(world<origin+vec2i(i32(w.size)));}\n@compute @workgroup_size(8,8) fn age(@builtin(global_invocation_id) id:vec3u) {\n if(any(id.xy>=vec2u(w.size))){return;}\n let k=id.y*w.size+id.x;let n=w.size*w.size;let s=i32(w.size);\n let world=w.origin+(((vec2i(id.xy)-w.origin)%s)+s)%s;\n if(w.first==1u||!inside(world,w.previous)){atomicStore(&marks[k],0u);atomicStore(&marks[n+k],0u);return;}\n if(w.fade>0.0){\n atomicStore(&marks[k],bitcast<u32>(max(bitcast<f32>(atomicLoad(&marks[k]))-w.fade,0.0)));\n atomicStore(&marks[n+k],bitcast<u32>(max(bitcast<f32>(atomicLoad(&marks[n+k]))-w.fade*w.rim,0.0)));\n }\n}\n@compute @workgroup_size(8,8) fn stamp(@builtin(global_invocation_id) id:vec3u) {\n if(id.z>=w.count){return;}\n let s=stamps[id.z];if(any(vec2i(id.xy)>=s.box.zw)){return;}\n let world=s.box.xy+vec2i(id.xy);if(!inside(world,w.origin)){return;}\n let p=(vec2f(id.xy)+0.5)*w.texel;var t:f32;\n if(s.shape.x<0.5){let d=p-s.ends.xy;t=length(vec2f(d.x*s.turn.x+d.y*s.turn.y,d.y*s.turn.x-d.x*s.turn.y)/s.shape.wz);}\n else{let ab=s.ends.zw-s.ends.xy;let h=clamp(dot(p-s.ends.xy,ab)/max(dot(ab,ab),1e-12),0.0,1.0);t=length(p-s.ends.xy-ab*h)/s.shape.z;}\n let depth=s.shape.y*(1.0-smoothstep(0.55,1.0,t));let raised=s.shape.y*w.rim*(1.0-smoothstep(0.0,0.45,abs(t-1.2)));\n let k=slot(world);\n if(depth>0.0){atomicMax(&marks[k],bitcast<u32>(depth));}\n if(raised>0.0){atomicMax(&marks[w.size*w.size+k],bitcast<u32>(raised));}\n}\nfn heightAt(c:vec2i)->f32 {\n let s=i32(w.size);let m=((c%s)+s)%s;let k=u32(m.y)*w.size+u32(m.x);\n let d=bitcast<f32>(atomicLoad(&marks[k]));let r=bitcast<f32>(atomicLoad(&marks[w.size*w.size+k]));\n return r*(1.0-smoothstep(0.0,0.02,d))-d;\n}\n@compute @workgroup_size(8,8) fn resolve(@builtin(global_invocation_id) id:vec3u) {\n if(any(id.xy>=vec2u(w.size))){return;}\n let c=vec2i(id.xy);let d=bitcast<f32>(atomicLoad(&marks[id.y*w.size+id.x]));\n let gx=(heightAt(c+vec2i(1,0))-heightAt(c-vec2i(1,0)))/(2.0*w.texel);\n let gz=(heightAt(c+vec2i(0,1))-heightAt(c-vec2i(0,1)))/(2.0*w.texel);\n textureStore(relief,c,vec4f(heightAt(c),gx,gz,clamp(d/0.02,0.0,1.0)));\n}", c = (e, t) => `
13
+ struct TerrainDeformFrame {window:vec4f,params:vec4f,extra:vec4f,softness:array<vec4f,4>,layers:array<vec4f,4>}
14
+ @group(${e}) @binding(${a}) var<uniform> terrainDeform:TerrainDeformFrame;
15
+ @group(${e}) @binding(111) var terrainDeformMap:texture_2d<f32>;
16
+ var<private> terrainDeformTint:f32=1.0;
17
+ fn terrainDeformAt(xz:vec2f)->vec4f {
18
+ let f=terrainDeform.window;let d=max(abs(xz.x-f.x),abs(xz.y-f.y))*2.0/f.z;
19
+ return textureSampleLevel(terrainDeformMap,terrainSampler,xz/f.z,0.0)*(1.0-smoothstep(1.0-8.0/f.w,1.0-2.0/f.w,d));
20
+ }
21
+ fn terrainDeformSoftness(xz:vec2f)->f32 {${t ? `
22
+ let dd=vec2f(textureDimensions(terrainWeights0));let uv=clamp((xz-frame.map.xy)/frame.map.zw,vec2f(0.5)/dd,vec2f(1)-vec2f(0.5)/dd);var soft=0.0;var total=0.0;
23
+ ${Array.from({ length: t }, (e, t) => `{let wv=textureSampleLevel(terrainWeights${t},terrainSampler,uv,0.0);soft+=dot(wv,terrainDeform.softness[${t}]);total+=dot(wv,terrainDeform.layers[${t}]);}`).join("")}
24
+ return select(terrainDeform.extra.y,soft/total,total>0.00001);` : "\n return terrainDeform.extra.y;"}
25
+ }
26
+ fn terrainDeformShift(i:Output)->Output {
27
+ var j=i;let n=normalize(i.normal);let reach=terrainDeform.params.x;let dist=distance(frame.eye.xyz,i.position);
28
+ if(dist>=reach||n.y<0.2){return j;}
29
+ let soft=terrainDeformSoftness(i.position.xz)*(1.0-smoothstep(reach*0.75,reach,dist));if(soft<=0.0){return j;}
30
+ let v=normalize(i.position-frame.eye.xyz);let vn=min(dot(v,n),-0.05);
31
+ let top=terrainDeform.extra.x*soft;let bottom=-terrainDeform.params.w*soft;let t0=top/vn;
32
+ let span=min(bottom/vn-t0,8.0*(top-bottom)/max(sqrt(max(1.0-vn*vn,0.0)),0.0001));let steps=terrainDeform.params.y;
33
+ var before=t0;var gap0=top-terrainDeformAt((i.position+v*t0).xz).x*soft;var hit=t0+span;
34
+ for(var k=1.0;k<=steps;k+=1.0){
35
+ let t=t0+span*k/steps;let gap=t*vn-terrainDeformAt((i.position+v*t).xz).x*soft;
36
+ if(gap<=0.0){hit=mix(before,t,gap0/max(gap0-gap,0.000001));break;}
37
+ before=t;gap0=gap;
38
+ }
39
+ let p=i.position+v*hit;let delta=p.xz-i.position.xz;let sample=terrainDeformAt(p.xz);
40
+ j.position=vec3f(p.x,i.position.y-(n.x*delta.x+n.z*delta.y)/n.y,p.z);
41
+ let g=vec3f(sample.y,0.0,sample.z)*soft;j.normal=normalize(n-(g-n*dot(n,g)));
42
+ terrainDeformTint=1.0-terrainDeform.params.z*sample.w*soft;
43
+ return j;
44
+ }
45
+ `, l = 16384, u = "let terrainColorFootprint=max(length(dpdx(i.position)),length(dpdy(i.position)));", d = "n=s.normal;}";
46
+ function f(t, n, r) {
47
+ let i = e(t);
48
+ if (!i) return t;
49
+ let { code: o } = i, s = o.lastIndexOf(d), l = o.indexOf(u), f = s >= 0 ? s + 12 : l >= 0 ? l + 81 : i.at, p = (c(0, 0).replace(`@binding(${a})`, `@binding(${r})`).replace("@binding(111)", `@binding(${r + 1})`).replace("textureSampleLevel(terrainDeformMap,terrainSampler,xz/f.z,0.0)", "terrainDeformLoad(xz/f.z)") + "fn terrainDeformLoad(uv:vec2f)->vec4f {\n let size=vec2i(textureDimensions(terrainDeformMap));let p=fract(uv)*vec2f(size)-0.5;let lo=vec2i(floor(p));let t=p-vec2f(lo);\n let a=(lo+size)%size;let b=(lo+1)%size;\n return mix(mix(textureLoad(terrainDeformMap,a,0),textureLoad(terrainDeformMap,vec2i(b.x,a.y),0),t.x),mix(textureLoad(terrainDeformMap,vec2i(a.x,b.y),0),textureLoad(terrainDeformMap,b,0),t.x),t.y);\n}\n").replace(/terrainDeform[A-Za-z]*/g, (e) => `${e}_${n}`), m = `if(i.terrainId==${n + 1}.0){let d=terrainDeformShift_${n}(i);let g=normalize(i.normal);n=normalize(mix(n,g,terrainDeformAt_${n}(d.position.xz).w)+d.normal-g);i.position=d.position;i.color*=terrainDeformTint_${n};}`;
50
+ return p + o.slice(0, f) + m + o.slice(f);
51
+ }
52
+ function p(e, t, n) {
53
+ let r = (Math.imul(e, 2654435761) ^ Math.imul(t * 4 + n + 1, 2246822507)) >>> 0;
54
+ return r = Math.imul(r ^ r >>> 16, 2146121005) >>> 0, r = Math.imul(r ^ r >>> 15, 2221713035) >>> 0, ((r ^ r >>> 16) >>> 0) / 2147483647 - 1;
55
+ }
56
+ var m = "@fragment fn fragment(i:Output)->@location(0) vec4f {", h = "fn terrainColor(position:vec3f,normal:vec3f)->vec3f {", g = 0, _ = class e {coreRequirement=__margoCoreRequirement("1.0.0",import.meta.url);
57
+ #e;
58
+ #t;
59
+ #n;
60
+ #r;
61
+ #i;
62
+ #a;
63
+ #o;
64
+ #s;
65
+ #c;
66
+ #l;
67
+ #u;
68
+ #d;
69
+ #f;
70
+ #p;
71
+ #m;
72
+ #h;
73
+ #g;
74
+ #_;
75
+ #v;
76
+ #y;
77
+ #b;
78
+ #x;
79
+ constructor(e, t = {}) {
80
+ this.options = t, this.name = "terrain-deform:" + g++, this.disposed = !1, this.#s = [], this.#u = /* @__PURE__ */ new Float64Array(3), this.#d = [], this.#f = [], this.#h = "", this.#g = "", this.#_ = 0, this.#v = !0, this.#y = /* @__PURE__ */ new Map(), this.#b = /* @__PURE__ */ new ArrayBuffer(48), this.#x = /* @__PURE__ */ new ArrayBuffer(o * 64);
81
+ let n = typeof e?.setGeometry == "function", r = n ? void 0 : e, i = n ? 0 : r?.options?.layers?.length ?? 0;
82
+ if (!n && (!i || typeof r.addLighting != "function")) throw TypeError("Invalid terrain deformation; pass a Terrain or a ground Mesh");
83
+ this.#p = r, this.#m = n ? e : void 0;
84
+ let a = t ?? {}, s = (e) => typeof e == "number" && e >= 0 && e <= 1, c = (e) => typeof e == "number" && e > 0 && Number.isFinite(e);
85
+ if (!Number.isInteger(a.size ?? 1024) || (a.size ?? 1024) < 64 || (a.size ?? 1024) > 2048 || !c(a.texel ?? .025) || !c(a.depth ?? .15) || !s(a.rim ?? .25) || !(typeof (a.fade ?? 120) == "number" && (a.fade ?? 120) >= 0 && Number.isFinite(a.fade ?? 120)) || a.persist !== void 0 && typeof a.persist != "boolean" || a.persist === !0 && (a.fade ?? 0) !== 0 || !s(a.softness ?? 1) || !(a.layers === void 0 || Array.isArray(a.layers) && a.layers.length <= i && a.layers.every(s)) || !s(a.darken ?? .25) || !c(a.distance ?? 40) || !Number.isInteger(a.steps ?? 12) || (a.steps ?? 12) < 4 || (a.steps ?? 12) > 32 || a.follow !== void 0 && typeof a.follow != "function") throw RangeError("Invalid terrain deformation; give size 64..2048, texel, depth and distance above 0, rim, softness, darken and each layers entry 0..1 (at most one per terrain layer), fade 0 or more, steps 4..32 and follow as a function; persist needs fade 0.");
86
+ this.size = a.size ?? 1024, this.texel = r?.options.floatingOrigin ? Math.fround(this.size * (a.texel ?? .025)) / this.size : a.texel ?? .025, this.depth = a.depth ?? .15;
87
+ }
88
+ static attach(n, r, i = {}) {__margoAssertCore(n,__margoCoreRequirement("1.0.0",import.meta.url));
89
+ let a = new e(r, i);
90
+ return t(n).use(a), a;
91
+ }
92
+ footprint(e, t, n = {}) {
93
+ let r = n.length ?? .28, i = n.width ?? .11, a = n.angle ?? 0;
94
+ this.#S([
95
+ e,
96
+ t,
97
+ a
98
+ ], r, i, n.depth);
99
+ let o = Math.max(r, i) * .85, s = Math.floor((e - o) / this.texel), c = Math.floor((t - o) / this.texel), l = Math.ceil(2 * o / this.texel) + 2;
100
+ return this.#w([
101
+ 0,
102
+ this.#C(n.depth),
103
+ i / 2,
104
+ r / 2,
105
+ e - s * this.texel,
106
+ t - c * this.texel,
107
+ 0,
108
+ 0,
109
+ Math.cos(a),
110
+ Math.sin(a),
111
+ 0,
112
+ 0,
113
+ s,
114
+ c,
115
+ l,
116
+ l
117
+ ]), this;
118
+ }
119
+ track(e, t, n = {}) {
120
+ let r = n.width ?? .25;
121
+ this.#S([
122
+ e?.[0],
123
+ e?.[1],
124
+ t?.[0],
125
+ t?.[1]
126
+ ], r, r, n.depth);
127
+ let i = this.#C(n.depth), a = r * .85, o = 188 * this.texel - 2 * a, s = Math.hypot(t[0] - e[0], t[1] - e[1]), c = Math.max(1, Math.ceil(s / o));
128
+ for (let n = 0; n < c; n++) {
129
+ let o = [e[0] + (t[0] - e[0]) * n / c, e[1] + (t[1] - e[1]) * n / c], s = [e[0] + (t[0] - e[0]) * (n + 1) / c, e[1] + (t[1] - e[1]) * (n + 1) / c], l = Math.floor((Math.min(o[0], s[0]) - a) / this.texel), u = Math.floor((Math.min(o[1], s[1]) - a) / this.texel), d = Math.ceil((Math.max(o[0], s[0]) + a) / this.texel), f = Math.ceil((Math.max(o[1], s[1]) + a) / this.texel), p = l * this.texel, m = u * this.texel;
130
+ this.#w([
131
+ 1,
132
+ i,
133
+ r / 2,
134
+ 0,
135
+ o[0] - p,
136
+ o[1] - m,
137
+ s[0] - p,
138
+ s[1] - m,
139
+ 1,
140
+ 0,
141
+ 0,
142
+ 0,
143
+ l,
144
+ u,
145
+ d - l + 1,
146
+ f - u + 1
147
+ ]);
148
+ }
149
+ return this;
150
+ }
151
+ trail(e, t = {}) {
152
+ if (!Array.isArray(e)) throw RangeError("Invalid terrain trail; pass an array of [x, z] points");
153
+ for (let n = 1; n < e.length; n++) this.track(e[n - 1], e[n], t);
154
+ return e.length === 1 && this.track(e[0], e[0], t), this;
155
+ }
156
+ walk(e, t = {}) {
157
+ let n = t.step ?? .75, r = t.straddle ?? .08, i = t.toeOut ?? .12, a = t.length ?? .28, o = t.width ?? .11, s = t.jitter ?? .5, c = t.seed ?? 1;
158
+ if (!Array.isArray(e) || e.length < 2 || !e.every((e) => Number.isFinite(e?.[0]) && Number.isFinite(e?.[1])) || !(n > 0 && Number.isFinite(n)) || !(r >= 0 && Number.isFinite(r)) || !(Math.abs(i) <= 1.5) || !(s >= 0 && s <= 1) || !Number.isInteger(c)) throw RangeError("Invalid terrain walk; pass two or more finite [x, z] points, step above 0, straddle 0 or more, toeOut -1.5 to 1.5, jitter 0 to 1 and an integer seed.");
159
+ this.#S([i], a, o, t.depth);
160
+ let l = this.#C(t.depth), u = n / 2, d = 0;
161
+ for (let t = 1; t < e.length; t++) {
162
+ let [f, m] = e[t - 1], [h, g] = e[t], _ = Math.hypot(h - f, g - m);
163
+ if (!_) continue;
164
+ let v = Math.atan2(g - m, h - f), y = Math.cos(v), b = Math.sin(v);
165
+ for (; u <= _; d++) {
166
+ let e = d % 2 ? 1 : -1, t = r / 2 * e + .04 * s * p(c, d, 0), h = f + y * u - b * t, g = m + b * u + y * t, _ = v + e * i + .1 * s * p(c, d, 1), x = l * (1 - .35 * s * Math.abs(p(c, d, 2))), S = Math.cos(_), C = Math.sin(_);
167
+ this.footprint(h - S * a * .31, g - C * a * .31, {
168
+ angle: _,
169
+ length: a * .38,
170
+ width: o * .8,
171
+ depth: x * .85
172
+ }), this.footprint(h + S * a * .18, g + C * a * .18, {
173
+ angle: _,
174
+ length: a * .64,
175
+ width: o,
176
+ depth: x
177
+ }), u += n * (1 + .12 * s * p(c, d, 3));
178
+ }
179
+ u -= _;
180
+ }
181
+ return this;
182
+ }
183
+ clear() {
184
+ return this.#d = [], this.#f.length = 0, this.#v = !0, this;
185
+ }
186
+ get texture() {
187
+ return this.#i;
188
+ }
189
+ get pending() {
190
+ return this.#d.length;
191
+ }
192
+ #S(e, t, n, r) {
193
+ let i = 188 * this.texel * .5;
194
+ if (!e.every((e) => typeof e == "number" && Number.isFinite(e)) || !(t > 0 && t <= i) || !(n > 0 && n <= i) || !(r === void 0 || typeof r == "number" && r >= 0 && Number.isFinite(r))) throw RangeError(`Invalid terrain print; give finite positions, length and width above 0 up to ${i.toFixed(3)} world units and depth 0 or more.`);
195
+ }
196
+ #C(e) {
197
+ return Math.min(e ?? this.depth, this.depth);
198
+ }
199
+ #w(e) {
200
+ if (this.options.persist) {
201
+ if (this.#f.length >= l) throw RangeError(`Terrain deformation keeps at most ${l} prints under persist; clear() or lay fewer`);
202
+ this.#f.push(e);
203
+ }
204
+ this.#d.push(e);
205
+ }
206
+ #T(e, t) {
207
+ let n = this.size, r = new Set(this.#d);
208
+ for (let i of this.#f) {
209
+ let [a, o, s, c] = [
210
+ i[12],
211
+ i[13],
212
+ i[14],
213
+ i[15]
214
+ ], l = a < e[0] + n && a + s > e[0] && o < e[1] + n && o + c > e[1], u = !!t && a >= t[0] && a + s <= t[0] + n && o >= t[1] && o + c <= t[1] + n;
215
+ l && !u && !r.has(i) && this.#d.push(i);
216
+ }
217
+ }
218
+ setup(e) {
219
+ if (this.disposed || !e.gpu) throw new r(this.disposed ? "disposed" : "unsupported", "Terrain deformation requires WebGPU and a live module; attach a new one to a WebGPU engine; see https://margoengine.com/errors#webgpu");
220
+ let t = e.gpu, i = this.size, c = 8 * i * i;
221
+ if (i > t.limits.maxTextureDimension2D || c > t.limits.maxStorageBufferBindingSize) throw new r("unsupported", "The terrain deformation map is larger than this device allows; pass a smaller size");
222
+ this.owner = e, this.#e = t.createBuffer({
223
+ size: c,
224
+ usage: 128
225
+ }), this.#t = t.createBuffer({
226
+ size: o * 64,
227
+ usage: 136
228
+ }), this.#n = t.createBuffer({
229
+ size: 48,
230
+ usage: 72
231
+ }), this.#r = t.createBuffer({
232
+ size: 176,
233
+ usage: 72
234
+ }), this.#i = t.createTexture({
235
+ size: [i, i],
236
+ format: "rgba16float",
237
+ usage: 13
238
+ });
239
+ let l = t.createBindGroupLayout({ entries: [
240
+ {
241
+ binding: 0,
242
+ visibility: 4,
243
+ buffer: { type: "uniform" }
244
+ },
245
+ {
246
+ binding: 1,
247
+ visibility: 4,
248
+ buffer: { type: "storage" }
249
+ },
250
+ {
251
+ binding: 2,
252
+ visibility: 4,
253
+ buffer: { type: "read-only-storage" }
254
+ },
255
+ {
256
+ binding: 3,
257
+ visibility: 4,
258
+ storageTexture: {
259
+ access: "write-only",
260
+ format: "rgba16float"
261
+ }
262
+ }
263
+ ] }), u = t.createShaderModule({ code: s }), d = t.createPipelineLayout({ bindGroupLayouts: [l] }), f = (e) => t.createComputePipeline({
264
+ layout: d,
265
+ compute: {
266
+ module: u,
267
+ entryPoint: e
268
+ }
269
+ });
270
+ this.#o = {
271
+ age: f("age"),
272
+ stamp: f("stamp"),
273
+ resolve: f("resolve")
274
+ }, this.#a = t.createBindGroup({
275
+ layout: l,
276
+ entries: [
277
+ {
278
+ binding: 0,
279
+ resource: { buffer: this.#n }
280
+ },
281
+ {
282
+ binding: 1,
283
+ resource: { buffer: this.#e }
284
+ },
285
+ {
286
+ binding: 2,
287
+ resource: { buffer: this.#t }
288
+ },
289
+ {
290
+ binding: 3,
291
+ resource: this.#i.createView()
292
+ }
293
+ ]
294
+ });
295
+ let p = this.options, m = /* @__PURE__ */ new Float32Array(44), h = this.#p?.options.layers.length ?? 0;
296
+ m.set([
297
+ 1e30,
298
+ 1e30,
299
+ i * this.texel,
300
+ i
301
+ ], 0), m.set([
302
+ p.distance ?? 40,
303
+ p.steps ?? 12,
304
+ p.darken ?? .25,
305
+ this.depth
306
+ ], 4), m.set([
307
+ this.depth * (p.rim ?? .25),
308
+ p.softness ?? 1,
309
+ 0,
310
+ 0
311
+ ], 8);
312
+ for (let e = 0; e < h; e++) m[12 + e] = p.layers?.[e] ?? p.softness ?? 1, m[28 + e] = 1;
313
+ if (t.queue.writeBuffer(this.#r, 0, m), this.#l = void 0, this.#v = !0, this.#s = [{
314
+ binding: a,
315
+ resource: { buffer: this.#r }
316
+ }, {
317
+ binding: 111,
318
+ resource: this.#i.createView()
319
+ }], this.#p) this.#c ??= this.#p.addLighting(this);
320
+ else if (n(this.#m).engine !== e) throw new r("attached", "The ground mesh belongs to another engine; attach to the mesh's engine");
321
+ this.#h = "";
322
+ }
323
+ registerPasses(e) {
324
+ e.add({
325
+ name: this.name,
326
+ order: -5,
327
+ execute: (e) => {
328
+ e.backend === "webgpu" && !(e.view?.index ?? 0) && this.#E(e);
329
+ }
330
+ }), this.#m && e.add({
331
+ name: this.name + ":mesh",
332
+ order: -.5,
333
+ execute: (e) => {
334
+ if (e.backend !== "webgpu" || this.disposed || !this.#s.length) return;
335
+ let t = n(this.#m);
336
+ if (t.check(), this.#h !== e.shader) {
337
+ let n = 44;
338
+ for (; e.bindings.some((e) => e.binding === n || e.binding === n + 1);) n++;
339
+ this.#h = e.shader, this.#_ = n, this.#g = f(e.shader, t.id, n);
340
+ }
341
+ this.#g !== e.shader && (this.#s.forEach((t, n) => e.bindings.push({
342
+ binding: this.#_ + n,
343
+ resource: t.resource
344
+ })), e.shader = this.#g);
345
+ }
346
+ });
347
+ }
348
+ #E(e) {
349
+ if (this.disposed || !this.#o) return;
350
+ let t = this.size, n = !!this.#p?.options.floatingOrigin, r = n ? this.#p.shift : i, a = this.options.follow?.() ?? (n ? [e.camera.position[0] + r[0], e.camera.position[2] + r[2]] : [e.camera.position[0], e.camera.position[2]]);
351
+ if (!Number.isFinite(a[0]) || !Number.isFinite(a[1])) return;
352
+ let s = [Math.floor(a[0] / this.texel) - t / 2, Math.floor(a[1] / this.texel) - t / 2], c = this.#l ?? s, l = this.#v, u = n && (this.#u[0] !== r[0] || this.#u[2] !== r[2]), d = c[0] !== s[0] || c[1] !== s[1] || !this.#l, f = this.options.fade ?? (this.options.persist ? 0 : 120), p = f > 0 ? this.depth * Math.max(e.delta, 0) / f : 0;
353
+ this.options.persist && (l || d) && this.#T(s, l ? void 0 : c);
354
+ let m = Math.min(this.#d.length, o);
355
+ if (u || d && n) {
356
+ let n = t * this.texel, i = (e) => e - Math.floor(e / n) * n;
357
+ e.device.queue.writeBuffer(this.#r, 0, new Float32Array([(s[0] + t / 2) * this.texel - r[0], (s[1] + t / 2) * this.texel - r[2]])), e.device.queue.writeBuffer(this.#r, 40, new Float32Array([i(r[0]), i(r[2])])), this.#u.set([
358
+ r[0],
359
+ r[1],
360
+ r[2]
361
+ ]);
362
+ }
363
+ if (!l && !d && !p && !m) return;
364
+ let h = new Int32Array(this.#b), g = new Float32Array(this.#b), _ = new Uint32Array(this.#b);
365
+ h.set([
366
+ s[0],
367
+ s[1],
368
+ c[0],
369
+ c[1]
370
+ ]), _[4] = t, _[5] = +l, g[6] = p, g[7] = this.texel, g[8] = this.options.rim ?? .25, _[9] = m, e.device.queue.writeBuffer(this.#n, 0, this.#b), d && !n && e.device.queue.writeBuffer(this.#r, 0, new Float32Array([(s[0] + t / 2) * this.texel, (s[1] + t / 2) * this.texel])), d && (this.#l = s);
371
+ let v = e.encoder.beginComputePass(), y = Math.ceil(t / 8);
372
+ if (v.setBindGroup(0, this.#a), (l || d || p) && (v.setPipeline(this.#o.age), v.dispatchWorkgroups(y, y)), m) {
373
+ let t = this.#d.splice(0, m), n = new Float32Array(this.#x), r = new Int32Array(this.#x), i = 1;
374
+ t.forEach((e, t) => {
375
+ n.set(e.slice(0, 12), t * 16), r.set(e.slice(12), t * 16 + 12), i = Math.max(i, e[14], e[15]);
376
+ }), e.device.queue.writeBuffer(this.#t, 0, this.#x, 0, m * 64), v.setPipeline(this.#o.stamp), v.dispatchWorkgroups(Math.ceil(i / 8), Math.ceil(i / 8), m);
377
+ }
378
+ v.setPipeline(this.#o.resolve), v.dispatchWorkgroups(y, y), v.end(), this.#v = !1;
379
+ }
380
+ bindings() {
381
+ return this.#s;
382
+ }
383
+ shader(e, t) {
384
+ let n = t + e, i = this.#y.get(n);
385
+ if (i) return i;
386
+ if (e.split(m).length !== 2) throw new r("unsupported", "Terrain deformation needs the terrain's lit fragment shader; attach it before effects that replace it");
387
+ let a = [...e.matchAll(/var terrainWeights(\d):texture_2d<f32>;/g)].length, o = e.replace(m, "fn terrainDeformInner(i:Output)->vec4f {");
388
+ return o.split(h).length === 2 && (o = o.replace(h, "fn terrainColorUndeformed(position:vec3f,normal:vec3f)->vec3f {")), o = (this.#p.options.floatingOrigin ? c(t, a).replace("xz/f.z,0.0)", "(xz+terrainDeform.extra.zw)/f.z,0.0)") : c(t, a)) + o + (o.includes("terrainColorUndeformed") ? `\n${h}return terrainColorUndeformed(position,normal)*terrainDeformTint;}` : "") + `\n${m}return terrainDeformInner(terrainDeformShift(i));}`, this.#y.size >= 16 && this.#y.clear(), this.#y.set(n, o), o;
389
+ }
390
+ onDeviceRestored(e) {
391
+ this.#D(), this.setup(e);
392
+ }
393
+ #D() {
394
+ this.#e?.destroy(), this.#t?.destroy(), this.#n?.destroy(), this.#r?.destroy(), this.#i?.destroy(), this.#e = this.#t = this.#n = this.#r = this.#i = void 0, this.#a = this.#o = void 0, this.#s = [];
395
+ }
396
+ dispose() {
397
+ this.disposed || (this.disposed = !0, this.#c?.(), this.#c = void 0, this.owner?.sceneOf(this)?.removePlugin(this.name), this.#D(), this.#y.clear(), this.#d = [], this.owner = void 0);
398
+ }
399
+ [Symbol.dispose ?? Symbol()]() {
400
+ this.dispose();
401
+ }
402
+ };
403
+ //#endregion
404
+ export { _ as TerrainDeformation };
@@ -0,0 +1,60 @@
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 { Terrain, TerrainLighting } from './index.js';
5
+ import type { TerrainMaterials } from './layers-pbr.js';
6
+ /** One layer's relief. */
7
+ export interface TerrainLayerRelief {
8
+ /** World depth from the height map's 1 (top) to its 0, 0 to 1. Default the displacement's `depth`. */
9
+ depth?: number;
10
+ }
11
+ /** Settings of {@link TerrainDisplacement.attach}, fixed at attachment. Invalid values throw RangeError. */
12
+ export interface TerrainDisplacementOptions {
13
+ /** World depth of every layer's relief, 0 to 1. Default 0.05 (5 cm). */
14
+ depth?: number;
15
+ /** Per layer depths, in the order of `TerrainOptions.layers` (fewer: the rest take `depth`). */
16
+ layers?: readonly TerrainLayerRelief[];
17
+ /** World distance from the camera within which the relief shows, fading out over its last quarter, above 0. Default 30. */
18
+ distance?: number;
19
+ /** Most search steps a fragment takes (a quarter of them facing the surface), 4 to 64. Default 24. */
20
+ steps?: number;
21
+ /**
22
+ * Whether the relief shadows itself from the sun. Needs square, power-of-two surface maps; adds a maximum mipmap of
23
+ * them (4 bytes per texel per layer, plus a third for its smaller levels). Default true.
24
+ */
25
+ shadows?: boolean;
26
+ }
27
+ /**
28
+ * Near displacement (parallax occlusion) of a terrain's layer height maps, for a terrain with `TerrainMaterials`:
29
+ * `TerrainDisplacement.attach(engine, terrain, materials, options)` after `TerrainMaterials.attach`; WebGPU only.
30
+ * Ground within `distance` of the camera and no steeper than about 57 degrees shows its relief's depth, occlusion and
31
+ * self-shadow; the outline of the ground against the sky stays the clipmap's (no real geometry moves).
32
+ * @throws RangeError when an option is out of range.
33
+ * @throws MargoError `'unsupported'` when the terrain's shader has no layer materials, or shadows meet surface maps
34
+ * that are not square and a power of two; `'disposed'` after dispose.
35
+ */
36
+ export declare class TerrainDisplacement implements EnginePlugin, TerrainLighting {
37
+ #private;
38
+ private readonly terrain;
39
+ private readonly materials;
40
+ readonly options: TerrainDisplacementOptions;
41
+ readonly name: string;
42
+ disposed: boolean;
43
+ owner?: Engine;
44
+ private constructor();
45
+ /** Attaches displacement to `terrain`, after its `materials`. `dispose()` removes it. */
46
+ static attach(engine: EngineKernel, terrain: Terrain, materials: TerrainMaterials, options?: TerrainDisplacementOptions): TerrainDisplacement;
47
+ setup(engine: Engine): void;
48
+ /** The group-1 entries the patched shader reads. */
49
+ bindings(): GPUBindGroupEntry[];
50
+ /** The terrain's lit shader (with layer materials) shading the point each near view ray hits (bindings in `group`). */
51
+ shader(source: string, group: number): string;
52
+ /**
53
+ * Moves the sun shadow lookups that effects attached after it added (`@margoengine/shadows` `Shadows` and
54
+ * `VirtualShadows`) to where each displaced point's ray toward the sun leaves the clipmap surface.
55
+ */
56
+ finish(source: string): string;
57
+ onDeviceRestored(engine: Engine): void;
58
+ dispose(): void;
59
+ [Symbol.dispose]: () => void;
60
+ }