@margoengine/terrain 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.
Files changed (71) hide show
  1. package/LICENSE +201 -0
  2. package/NOTICE +4 -0
  3. package/README.md +1808 -3
  4. package/dist/blend.d.ts +70 -0
  5. package/dist/blend.js +159 -0
  6. package/dist/colors.d.ts +164 -0
  7. package/dist/deform.d.ts +103 -0
  8. package/dist/deform.js +322 -0
  9. package/dist/displace.d.ts +60 -0
  10. package/dist/displace.js +254 -0
  11. package/dist/dunes.d.ts +86 -0
  12. package/dist/dunes.js +88 -0
  13. package/dist/errors-fc4i1pSL.js +7 -0
  14. package/dist/grid.d.ts +11 -0
  15. package/dist/ground-change-settings.d.ts +29 -0
  16. package/dist/ground-change-settings.js +69 -0
  17. package/dist/ground-change.d.ts +227 -0
  18. package/dist/ground-change.js +1291 -0
  19. package/dist/ground-model.d.ts +290 -0
  20. package/dist/hdr-format-DRhzGS7G.js +30 -0
  21. package/dist/height-grid.d.ts +65 -0
  22. package/dist/height-grid.js +74 -0
  23. package/dist/heightfield.d.ts +38 -0
  24. package/dist/holes.d.ts +37 -0
  25. package/dist/holes.js +97 -0
  26. package/dist/imagery.d.ts +109 -0
  27. package/dist/imagery.js +472 -0
  28. package/dist/index.d.ts +297 -0
  29. package/dist/index.js +1 -0
  30. package/dist/layers-pbr.d.ts +78 -0
  31. package/dist/layers-pbr.js +128 -0
  32. package/dist/lighting-layout-CaDtDa5G.js +34 -0
  33. package/dist/lighting-layout.d.ts +5 -0
  34. package/dist/mesh-patch-BThCHCeS.js +21 -0
  35. package/dist/mesh-patch.d.ts +14 -0
  36. package/dist/noise3-sQdnbz4B.js +11 -0
  37. package/dist/noise3.d.ts +3 -0
  38. package/dist/overlays.d.ts +74 -0
  39. package/dist/overlays.js +297 -0
  40. package/dist/planet-craters.d.ts +55 -0
  41. package/dist/planet-recipes.d.ts +75 -0
  42. package/dist/planet-recipes.js +216 -0
  43. package/dist/planet.d.ts +139 -0
  44. package/dist/planet.js +602 -0
  45. package/dist/query.d.ts +150 -0
  46. package/dist/query.js +243 -0
  47. package/dist/relief-lighting.d.ts +46 -0
  48. package/dist/relief-lighting.js +208 -0
  49. package/dist/require-webgpu--tUXPsmA.js +7 -0
  50. package/dist/rock-settings.d.ts +39 -0
  51. package/dist/rock-settings.js +84 -0
  52. package/dist/rock-surface.d.ts +111 -0
  53. package/dist/rock-surface.js +368 -0
  54. package/dist/rocks.d.ts +258 -0
  55. package/dist/rocks.js +488 -0
  56. package/dist/rvt.d.ts +136 -0
  57. package/dist/rvt.js +518 -0
  58. package/dist/sculpt.d.ts +103 -0
  59. package/dist/sculpt.js +361 -0
  60. package/dist/settings-B9BSdnhD.js +72 -0
  61. package/dist/settings.d.ts +81 -0
  62. package/dist/settings.js +152 -0
  63. package/dist/shader.d.ts +61 -0
  64. package/dist/shared/settings.d.ts +89 -0
  65. package/dist/src-C6dtSaAb.js +1155 -0
  66. package/dist/stream.d.ts +100 -0
  67. package/dist/stream.js +339 -0
  68. package/dist/surface-height.d.ts +16 -0
  69. package/dist/wet-ground.d.ts +82 -0
  70. package/dist/wet-ground.js +147 -0
  71. package/package.json +148 -6
package/dist/rvt.js ADDED
@@ -0,0 +1,518 @@
1
+ // @margo/core-built 0.1.0
2
+ import {coreRequirement as __margoCoreRequirement,assertCore as __margoAssertCore} from '@margoengine/core/extension';
3
+ const t=(engine,version="0.1.0",source=import.meta.url)=>__margoRuntime(engine,version,source);
4
+ import { t as e } from "./lighting-layout-CaDtDa5G.js";
5
+ import { engineRuntime as __margoRuntime } from "@margoengine/core/extension";
6
+ import { MargoError as n } from "@margoengine/math/errors";
7
+ //#region src/rvt.ts
8
+ var r = 4096, i = [
9
+ 0,
10
+ 0,
11
+ 0
12
+ ], a = 94, o = "fn terrainVirtualSurface(color:vec3f,position:vec2f,footprint:f32)->vec3f {var terrainSurfaceColor=color;return terrainSurfaceColor;}\n", s = "fn terrainColor(position:vec3f,normal:vec3f)->vec3f {", c = "let dx=dpdx(position);let dy=dpdy(position);", l = "let base=terrainColor(i.position,";
13
+ function u(e) {
14
+ if (e.split(s).length !== 2 || e.split(c).length !== 2) throw new n("unsupported", "The terrain virtual texture needs the terrain's own colour function; attach it before effects that replace it");
15
+ return "var<private> terrainDx:vec3f;var<private> terrainDy:vec3f;\n" + e.replace(s, `${s}terrainDx=dpdx(position);terrainDy=dpdy(position);return terrainColorAt(position,normal);}\nfn terrainColorAt(position:vec3f,normal:vec3f)->vec3f {`).replace(c, "let dx=terrainDx;let dy=terrainDy;");
16
+ }
17
+ var d = (e, t, n = !1) => {
18
+ let r = `
19
+ struct TerrainVirtualFrame {eye:vec4f,params:vec4f}
20
+ @group(${e}) @binding(${t}) var terrainVirtualCache:texture_2d_array<f32>;
21
+ @group(${e}) @binding(${t + 1}) var terrainVirtualSampler:sampler;
22
+ @group(${e}) @binding(${t + 2}) var<uniform> terrainVirtual:TerrainVirtualFrame;
23
+ fn terrainVirtualColor(position:vec3f,footprint:f32)->vec4f {
24
+ let e=terrainVirtual.eye;let top=terrainVirtual.params.x-1.0;let half=(e.w*0.5-2.0)*e.z;
25
+ let far=log2(max(max(abs(position.x-e.x),abs(position.z-e.y)),1e-9)/half)+1.0;
26
+ let level=clamp(max(log2(max(footprint,1e-9)/e.z),far),0.0,top);let a=floor(level);let t=level-a;
27
+ let uv=position.xz/(e.z*e.w*exp2(a));
28
+ var c=textureSampleLevel(terrainVirtualCache,terrainVirtualSampler,uv,i32(a),0.0).rgb;
29
+ if(t>0.0){c=mix(c,textureSampleLevel(terrainVirtualCache,terrainVirtualSampler,uv*0.5,i32(a)+1,0.0).rgb,t);}
30
+ return vec4f(c,1.0-clamp((far-top-0.5)*2.0,0.0,1.0));
31
+ }`;
32
+ return n ? r.replace("params:vec4f}", "params:vec4f,map:vec4f,anchor:vec4f}").replace("let uv=position.xz/", "let uv=(position.xz+terrainVirtual.params.zw)/") : r;
33
+ }, f = "\nfn terrainVirtualGround(position:vec3f,normal:vec3f)->vec3f {\n terrainDx=dpdx(position);terrainDy=dpdy(position);\n let cached=terrainVirtualColor(position,max(length(terrainDx.xz),length(terrainDy.xz)));\n let steep=terrainVirtual.params.y;let slope=1.0-clamp(normal.y,0.0,1.0);\n let full=max(1.0-cached.a,select(smoothstep(steep-0.1,steep,slope),0.0,steep>=1.0));\n if(full<=0.0){return cached.rgb;}\n return mix(cached.rgb,terrainColorAt(position,normal),full);\n}", p = "\nstruct TerrainVirtualBake {origin:vec2i,size:i32,count:u32,texel:f32,start:u32,pad:vec2f}\nstruct TerrainVirtualDecal {box:vec4f,turn:vec4f,extra:vec4f}\n@group(1) @binding(0) var<uniform> terrainBake:TerrainVirtualBake;\n@group(1) @binding(1) var<storage,read> terrainDecals:array<TerrainVirtualDecal>;\n@group(1) @binding(2) var<storage,read> terrainDecalList:array<u32>;\n@group(1) @binding(3) var terrainDecalPictures:texture_2d_array<f32>;\n@vertex fn terrainBakeVertex(@builtin(vertex_index) k:u32)->@builtin(position) vec4f {\n return vec4f(f32((k<<1u)&2u)*2.0-1.0,f32(k&2u)*2.0-1.0,0.0,1.0);\n}\n@fragment fn terrainBakeTexel(@builtin(position) pixel:vec4f)->@location(0) vec4f {\n let n=terrainBake.size;let o=terrainBake.origin;let w=o+(((vec2i(pixel.xy)-o)%n)+n)%n;let e=terrainBake.texel;\n let xz=(vec2f(w)+0.5)*e;let step=frame.map.zw/max(vec2f(textureDimensions(heightMap))-1.0,vec2f(1.0));\n var normal=normalize(vec3f((height(xz-vec2f(step.x,0.0))-height(xz+vec2f(step.x,0.0)))/(2.0*step.x),1.0,(height(xz-vec2f(0.0,step.y))-height(xz+vec2f(0.0,step.y)))/(2.0*step.y)));\n if(frame.offset.w>0.5){let d=vec2i(textureDimensions(normalMap));let uv=clamp((xz-frame.map.xy)/frame.map.zw,vec2f(0.0),vec2f(1.0));let s=textureLoad(normalMap,min(vec2i(uv*vec2f(d)),d-vec2i(1)),0).xyz*2.0-1.0;if(dot(s,s)>0.00001){normal=normalize(s);}}\n terrainDx=vec3f(e,height(xz+vec2f(e*0.5,0.0))-height(xz-vec2f(e*0.5,0.0)),0.0);\n terrainDy=vec3f(0.0,height(xz+vec2f(0.0,e*0.5))-height(xz-vec2f(0.0,e*0.5)),e);\n var c=terrainColorAt(vec3f(xz.x,height(xz),xz.y),normal);\n for(var k=0u;k<terrainBake.count;k++){\n let d=terrainDecals[terrainDecalList[terrainBake.start+k]];let r=xz-d.box.xy;\n let u=dot(r,d.turn.xy)/d.box.z;let v=dot(r,vec2f(-d.turn.y,d.turn.x))/d.box.w;\n if(abs(u)>1.0||abs(v)>1.0){continue;}\n let ru=0.5*d.extra.x/d.box.z;let rv=0.5/d.box.w;\n let s=textureSampleGrad(terrainDecalPictures,terrainSampler,vec2f((u*0.5+0.5)*d.extra.x,v*0.5+0.5),i32(d.turn.z),e*vec2f(d.turn.x*ru,-d.turn.y*rv),e*vec2f(d.turn.y*ru,d.turn.x*rv));\n c=mix(c,s.rgb,s.a*d.turn.w);\n }\n return vec4f(c,1.0);\n}";
34
+ function m(e, t, n) {
35
+ let r = (e % n + n) % n;
36
+ return r + t <= n ? [[r, r + t]] : [[r, n], [0, r + t - n]];
37
+ }
38
+ function h(e, t, n, r = []) {
39
+ let [i, a] = t, o = [];
40
+ if (!e || Math.abs(i - e[0]) >= n || Math.abs(a - e[1]) >= n) o.push([
41
+ i,
42
+ a,
43
+ i + n,
44
+ a + n
45
+ ]);
46
+ else {
47
+ let [t, r] = e;
48
+ i > t && o.push([
49
+ t + n,
50
+ a,
51
+ i + n,
52
+ a + n
53
+ ]), i < t && o.push([
54
+ i,
55
+ a,
56
+ t,
57
+ a + n
58
+ ]);
59
+ let s = i > t ? i : i < t ? t : i, c = i > t ? t + n : i + n;
60
+ a > r && o.push([
61
+ s,
62
+ r + n,
63
+ c,
64
+ a + n
65
+ ]), a < r && o.push([
66
+ s,
67
+ a,
68
+ c,
69
+ r
70
+ ]);
71
+ }
72
+ for (let [e, t, s, c] of r) {
73
+ let r = Math.max(e, i), l = Math.max(t, a), u = Math.min(s, i + n), d = Math.min(c, a + n);
74
+ r < u && l < d && o.push([
75
+ r,
76
+ l,
77
+ u,
78
+ d
79
+ ]);
80
+ }
81
+ let s = [];
82
+ for (let [e, t, r, i] of o) if (r > e && i > t) for (let [a, o] of m(e, r - e, n)) for (let [e, r] of m(t, i - t, n)) s.push([
83
+ a,
84
+ e,
85
+ o - a,
86
+ r - e
87
+ ]);
88
+ return s;
89
+ }
90
+ function g(e, t, n, r, i, a = new Float64Array(i * 2), o) {
91
+ for (let s = 0; s < i; s++) {
92
+ let i = n * 2 ** s;
93
+ if (a[s * 2] = Math.floor(e[0] / i) - r / 2, a[s * 2 + 1] = Math.floor(e[2] / i) - r / 2, o) {
94
+ let e = Math.floor(t[0] / i), n = Math.floor(t[2] / i);
95
+ o.set([
96
+ e,
97
+ n,
98
+ e * i - t[0],
99
+ n * i - t[2]
100
+ ], s * 4);
101
+ }
102
+ }
103
+ let s = n * r * 2 ** (i - 1), c = (e) => e - Math.floor(e / s) * s;
104
+ return [c(t[0]), c(t[2])];
105
+ }
106
+ var _ = 0, v = class s {coreRequirement=__margoCoreRequirement("0.1.0",import.meta.url);
107
+ #e;
108
+ #t;
109
+ #n;
110
+ #r;
111
+ #i;
112
+ #a;
113
+ #o;
114
+ #s;
115
+ #c;
116
+ #l;
117
+ #u;
118
+ #d;
119
+ #f;
120
+ #p;
121
+ #m;
122
+ #h;
123
+ #g;
124
+ #_;
125
+ #v;
126
+ #y;
127
+ #b;
128
+ #x;
129
+ #S;
130
+ #C;
131
+ #w;
132
+ #T;
133
+ #E;
134
+ #D;
135
+ #O;
136
+ #k;
137
+ #A;
138
+ #j;
139
+ addSurface(e) {
140
+ if (this.disposed || !e || typeof e.shader != "function" || typeof e.bindings != "function") throw TypeError("Invalid virtual surface; pass a live provider with shader() and bindings().");
141
+ if (e.owner && this.owner && e.owner !== this.owner) throw new n("attached", "Virtual surface belongs to another engine; attach it to the same engine.");
142
+ let t = new Set([...this.#h, ...[...this.#j].flatMap((e) => e.bindings())].map((e) => e.binding));
143
+ if (e.bindings().some((e) => t.has(e.binding))) throw RangeError("Virtual surface binding collision; select distinct bindings for each provider.");
144
+ this.#j.add(e);
145
+ let r = () => this.refreshSurfaces();
146
+ return r(), () => {
147
+ this.#j.delete(e) && r();
148
+ };
149
+ }
150
+ refreshSurfaces() {
151
+ this.#m = void 0, this.#A.clear(), this.invalidate();
152
+ }
153
+ constructor(e, t) {
154
+ if (this.terrain = e, this.options = t, this.name = "terrain-rvt:" + _++, this.disposed = !1, this.baked = 0, this.#i = [], this.#h = [], this.#g = [], this.#_ = [], this.#v = /* @__PURE__ */ new Map(), this.#y = !0, this.#b = 0, this.#C = /* @__PURE__ */ new Float64Array(3), this.#w = /* @__PURE__ */ new Float64Array(), this.#T = /* @__PURE__ */ new Float64Array(), this.#E = /* @__PURE__ */ new Float64Array(3), this.#O = /* @__PURE__ */ new ArrayBuffer(0), this.#k = /* @__PURE__ */ new Uint32Array(), this.#A = /* @__PURE__ */ new Map(), this.#j = /* @__PURE__ */ new Set(), !e?.options?.layers || typeof e.addLighting != "function") throw TypeError("Invalid terrain virtual texture; pass a Terrain");
155
+ this.#S = !!e.options.floatingOrigin, this.#D = new Float32Array(this.#S ? 16 : 8);
156
+ let n = t ?? {};
157
+ if (this.texel = n.texel ?? .05, this.size = n.size ?? 1024, this.levels = n.levels ?? 6, this.#e = n.steep ?? .5, this.#t = n.format ?? "rgba8unorm-srgb", !(Number.isFinite(Math.fround(this.texel)) && this.texel > 0) || ![
158
+ 256,
159
+ 512,
160
+ 1024,
161
+ 2048,
162
+ 4096
163
+ ].includes(this.size) || !Number.isInteger(this.levels) || this.levels < 1 || this.levels > 12 || !(this.#e >= 0 && this.#e <= 1) || !["rgba8unorm-srgb", "rgba16float"].includes(this.#t) || n.decals !== void 0 && typeof n.decals != "function") throw RangeError("Invalid terrain virtual texture; give texel above 0, size 256, 512, 1024, 2048 or 4096, levels 1..12, steep 0..1, format rgba8unorm-srgb or rgba16float and decals as a function.");
164
+ }
165
+ static attach(e, n, r = {}) {__margoAssertCore(e,__margoCoreRequirement("0.1.0",import.meta.url));
166
+ let i = new s(n, r);
167
+ return t(e).use(i), i;
168
+ }
169
+ setup(e) {
170
+ if (this.disposed || !e.gpu) throw new n(this.disposed ? "disposed" : "unsupported", "The terrain virtual texture requires WebGPU and a live module; attach a new one to a WebGPU engine; see https://margoengine.com/errors#webgpu");
171
+ this.owner = e;
172
+ let t = this.#n = e.gpu;
173
+ if (this.size > t.limits.maxTextureDimension2D || this.levels > t.limits.maxTextureArrayLayers) throw RangeError("Terrain virtual texture size or levels exceed the device limits; lower them.");
174
+ this.#r = t.createTexture({
175
+ size: [
176
+ this.size,
177
+ this.size,
178
+ this.levels
179
+ ],
180
+ format: this.#t,
181
+ usage: GPUTextureUsage.TEXTURE_BINDING | GPUTextureUsage.RENDER_ATTACHMENT
182
+ }), this.#i = Array.from({ length: this.levels }, (e, t) => this.#r.createView({
183
+ dimension: "2d",
184
+ baseArrayLayer: t,
185
+ arrayLayerCount: 1
186
+ }));
187
+ let i = this.options.decals?.(t);
188
+ if (i && (i.dimension !== "2d" || !(i.usage & GPUTextureUsage.TEXTURE_BINDING) || i.sampleCount !== 1 || !["rgba8unorm", "rgba8unorm-srgb"].includes(i.format))) throw i.destroy(), TypeError("Terrain decal pictures must be one texture; return one rgba8unorm or rgba8unorm-srgb 2D array texture from options.decals.");
189
+ i || (i = t.createTexture({
190
+ size: [
191
+ 1,
192
+ 1,
193
+ 1
194
+ ],
195
+ format: "rgba8unorm",
196
+ usage: GPUTextureUsage.TEXTURE_BINDING | GPUTextureUsage.COPY_DST
197
+ }), t.queue.writeTexture({ texture: i }, /* @__PURE__ */ new Uint8Array(4), { bytesPerRow: 4 }, [
198
+ 1,
199
+ 1,
200
+ 1
201
+ ])), this.#a = i, this.#o = t.createSampler({
202
+ addressModeU: "repeat",
203
+ addressModeV: "repeat",
204
+ magFilter: "linear",
205
+ minFilter: "linear"
206
+ }), this.#s = t.createBuffer({
207
+ size: this.#D.byteLength,
208
+ usage: GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST
209
+ }), this.#c = t.createBuffer({
210
+ size: 256 * this.levels,
211
+ usage: GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST
212
+ }), this.#l = t.createBuffer({
213
+ size: r * 48,
214
+ usage: GPUBufferUsage.STORAGE | GPUBufferUsage.COPY_DST
215
+ }), this.#u = t.createBuffer({
216
+ size: r * 4 * this.levels,
217
+ usage: GPUBufferUsage.STORAGE | GPUBufferUsage.COPY_DST
218
+ }), this.#d = t.createBindGroupLayout({ entries: [
219
+ {
220
+ binding: 0,
221
+ visibility: 2,
222
+ buffer: {
223
+ type: "uniform",
224
+ hasDynamicOffset: !0,
225
+ minBindingSize: this.#S ? 40 : 32
226
+ }
227
+ },
228
+ {
229
+ binding: 1,
230
+ visibility: 2,
231
+ buffer: { type: "read-only-storage" }
232
+ },
233
+ {
234
+ binding: 2,
235
+ visibility: 2,
236
+ buffer: { type: "read-only-storage" }
237
+ },
238
+ {
239
+ binding: 3,
240
+ visibility: 2,
241
+ texture: { viewDimension: "2d-array" }
242
+ }
243
+ ] }), this.#f = t.createBindGroup({
244
+ layout: this.#d,
245
+ entries: [
246
+ {
247
+ binding: 0,
248
+ resource: {
249
+ buffer: this.#c,
250
+ size: this.#S ? 40 : 32
251
+ }
252
+ },
253
+ {
254
+ binding: 1,
255
+ resource: { buffer: this.#l }
256
+ },
257
+ {
258
+ binding: 2,
259
+ resource: { buffer: this.#u }
260
+ },
261
+ {
262
+ binding: 3,
263
+ resource: i.createView({ dimension: "2d-array" })
264
+ }
265
+ ]
266
+ }), this.#h = this.entries(a), this.#O = /* @__PURE__ */ new ArrayBuffer(256 * this.levels), this.#k = new Uint32Array(r * this.levels), this.#g = [], this.#y = !0, this.#x ??= this.terrain.addLighting(this);
267
+ }
268
+ registerPasses(e) {
269
+ e.add({
270
+ name: this.name,
271
+ order: -5,
272
+ execute: (e) => {
273
+ e.backend === "webgpu" && this.#N(e);
274
+ }
275
+ });
276
+ }
277
+ bindings() {
278
+ return this.#j.size ? [...this.#h, ...[...this.#j].flatMap((e) => e.bindings())] : this.#h;
279
+ }
280
+ shader(e, t) {
281
+ let r = t + e, i = this.#A.get(r);
282
+ if (i) return i;
283
+ if (e.includes("terrainPbr") || e.split(l).length !== 2) throw new n("unsupported", "The terrain virtual texture needs the terrain lit shader without layer materials; attach it without TerrainMaterials");
284
+ let s = d(t, a, this.#S) + f + u(e).replace(l, "let base=terrainVirtualGround(i.position,");
285
+ if (this.#j.size) {
286
+ s = o + s.replace("terrainColorAt(position,normal),full)", `terrainVirtualSurface(terrainColorAt(position,normal),position.xz${this.#S ? "+frame.anchor.xy" : ""},max(length(terrainDx.xz),length(terrainDy.xz))),full)`);
287
+ for (let e of this.#j) s = e.shader(s, t);
288
+ }
289
+ return this.#A.size >= 16 && this.#A.clear(), this.#A.set(r, s), s;
290
+ }
291
+ declarations(e, t) {
292
+ return d(e, t, this.#S);
293
+ }
294
+ entries(e) {
295
+ return !this.#r || !this.#o || !this.#s ? [] : [
296
+ {
297
+ binding: e,
298
+ resource: this.#r.createView({ dimension: "2d-array" })
299
+ },
300
+ {
301
+ binding: e + 1,
302
+ resource: this.#o
303
+ },
304
+ {
305
+ binding: e + 2,
306
+ resource: { buffer: this.#s }
307
+ }
308
+ ];
309
+ }
310
+ get texture() {
311
+ return this.#r;
312
+ }
313
+ invalidate(e, t, n, r) {
314
+ if (e === void 0) this.#g = [], this.#_ = [];
315
+ else {
316
+ if (![
317
+ e,
318
+ t,
319
+ n,
320
+ r
321
+ ].every((e) => typeof e == "number" && !Number.isNaN(e))) throw RangeError("Invalid terrain virtual texture area; pass four numbers x0, z0, x1, z1.");
322
+ this.#_.push([
323
+ Math.min(e, n),
324
+ Math.min(t, r),
325
+ Math.max(e, n),
326
+ Math.max(t, r)
327
+ ]);
328
+ }
329
+ }
330
+ addDecal(e) {
331
+ if (this.disposed || !this.options.decals) throw new n(this.disposed ? "disposed" : "unsupported", "Terrain decals need a live virtual texture made with a decals texture; pass options.decals");
332
+ let t = {
333
+ center: e?.center,
334
+ size: e?.size,
335
+ angle: e?.angle ?? 0,
336
+ layer: e?.layer ?? 0,
337
+ opacity: e?.opacity ?? 1,
338
+ repeat: e?.repeat ?? 1
339
+ }, i = this.#a?.depthOrArrayLayers ?? Infinity;
340
+ if (!Array.isArray(t.center) || !Array.isArray(t.size) || ![
341
+ ...t.center,
342
+ ...t.size,
343
+ t.angle,
344
+ t.repeat
345
+ ].every(Number.isFinite) || !(t.size[0] > 0 && t.size[1] > 0 && t.repeat > 0) || !Number.isInteger(t.layer) || t.layer < 0 || t.layer >= i || !(t.opacity >= 0 && t.opacity <= 1)) throw RangeError("Invalid terrain decal; give a finite center, a size above 0, a whole layer of the decals texture, opacity 0..1 and repeat above 0.");
346
+ if (this.#v.size >= r) throw RangeError(`Terrain decals are limited to ${r}; remove one before adding another.`);
347
+ let a = this.#b++;
348
+ return this.#v.set(a, t), this.#y = !0, this.#M(t), a;
349
+ }
350
+ removeDecal(e) {
351
+ let t = this.#v.get(e);
352
+ return t ? (this.#v.delete(e), this.#y = !0, this.#M(t), !0) : !1;
353
+ }
354
+ road(e, t, n = {}) {
355
+ if (!Array.isArray(e) || e.length < 2 || !(t > 0)) throw RangeError("Invalid terrain road; pass 2 or more [x, z] points and a width above 0.");
356
+ let r = [];
357
+ for (let i = 1; i < e.length; i++) {
358
+ let [a, o] = e[i - 1], [s, c] = e[i], l = Math.hypot(s - a, c - o);
359
+ l > 0 && r.push(this.addDecal({
360
+ ...n,
361
+ center: [(a + s) / 2, (o + c) / 2],
362
+ size: [l, t],
363
+ angle: Math.atan2(c - o, s - a),
364
+ repeat: l / t
365
+ }));
366
+ }
367
+ return r;
368
+ }
369
+ #M(e) {
370
+ let t = Math.abs(Math.cos(e.angle)), n = Math.abs(Math.sin(e.angle)), r = (e.size[0] * t + e.size[1] * n) / 2, i = (e.size[0] * n + e.size[1] * t) / 2;
371
+ this.#_.push([
372
+ e.center[0] - r,
373
+ e.center[1] - i,
374
+ e.center[0] + r,
375
+ e.center[1] + i
376
+ ]);
377
+ }
378
+ #N(t) {
379
+ let n = this.terrain.colorSource?.();
380
+ if (this.disposed || !n || !this.#r) return;
381
+ let r = t.device, a = this.size, s = t.camera.position, c = this.#S, l = c ? this.terrain.shift : i, d = this.levels, f = s;
382
+ if (c) {
383
+ for (let e = 0; e < 3; e++) this.#E[e] = s[e] + l[e];
384
+ f = this.#E;
385
+ }
386
+ let m = c ? Math.fround(this.texel) : this.texel;
387
+ this.#w.length !== d * 2 && (this.#w = new Float64Array(d * 2), this.#T = new Float64Array(d * 4));
388
+ let [_, v] = g(f, l, m, a, d, this.#w, c ? this.#T : void 0);
389
+ if (this.#D.set([
390
+ s[0],
391
+ s[2],
392
+ this.texel,
393
+ a,
394
+ d,
395
+ this.#e,
396
+ c ? _ : 0,
397
+ c ? v : 0
398
+ ]), c) {
399
+ let e = this.terrain.options;
400
+ this.#D.set([
401
+ (e.origin?.[0] ?? 0) - l[0],
402
+ (e.origin?.[1] ?? 0) - l[2],
403
+ (e.heightOffset ?? 0) - l[1],
404
+ 0,
405
+ l[0] - this.terrain.anchor[0],
406
+ l[2] - this.terrain.anchor[1]
407
+ ], 8);
408
+ let t = this.#C;
409
+ (t[0] !== l[0] || t[2] !== l[2]) && (t.set([
410
+ l[0],
411
+ l[1],
412
+ l[2]
413
+ ]), this.#y = !0);
414
+ }
415
+ if (r.queue.writeBuffer(this.#s, 0, this.#D), this.#m !== n.layout) {
416
+ let t = u(n.code) + p;
417
+ c && (t = t.replace("pad:vec2f}", "pad:vec2f,anchor:vec2i}").replace("let xz=(vec2f(w)+0.5)*e;", "let xz=terrainBake.pad+(vec2f(w-terrainBake.anchor)+0.5)*e;")), this.#j.size && (t = o + t.replace("var c=terrainColorAt(vec3f(xz.x,height(xz),xz.y),normal);", `var c=terrainVirtualSurface(terrainColorAt(vec3f(xz.x,height(xz),xz.y),normal),xz${c ? "+frame.anchor.xy" : ""},terrainBake.texel);`));
418
+ for (let e of this.#j) t = e.shader(t, 2);
419
+ let i = r.createShaderModule({ code: t }), a = [n.layout, this.#d];
420
+ this.#j.size && a.push(r.createBindGroupLayout({ entries: e(t, [...this.#j].flatMap((e) => e.bindings()), 2) })), this.#p = r.createRenderPipeline({
421
+ layout: r.createPipelineLayout({ bindGroupLayouts: a }),
422
+ vertex: {
423
+ module: i,
424
+ entryPoint: "terrainBakeVertex"
425
+ },
426
+ fragment: {
427
+ module: i,
428
+ entryPoint: "terrainBakeTexel",
429
+ targets: [{ format: this.#t }]
430
+ }
431
+ }), this.#m = n.layout, this.#g = [];
432
+ }
433
+ this.baked = 0;
434
+ let y = this.#_.length > 0;
435
+ for (let e = 0; e < d && !y; e++) {
436
+ let t = this.#g[e];
437
+ y = !t || t[0] !== this.#w[e * 2] || t[1] !== this.#w[e * 2 + 1];
438
+ }
439
+ if (!y) return;
440
+ let b = [...this.#v.values()];
441
+ if (this.#y) {
442
+ let e = new Float32Array(Math.max(1, b.length) * 12);
443
+ b.forEach((t, n) => e.set([
444
+ t.center[0] - (c ? l[0] : 0),
445
+ t.center[1] - (c ? l[2] : 0),
446
+ t.size[0] / 2,
447
+ t.size[1] / 2,
448
+ Math.cos(t.angle),
449
+ Math.sin(t.angle),
450
+ t.layer,
451
+ t.opacity,
452
+ t.repeat
453
+ ], n * 12)), r.queue.writeBuffer(this.#l, 0, e), this.#y = !1;
454
+ }
455
+ let x = this.#_, S = this.#O, C = this.#k, w = new Int32Array(S), T = new Float32Array(S), E = [];
456
+ this.#_ = [];
457
+ let D = 0;
458
+ for (let e = 0; e < d; e++) {
459
+ let t = m * 2 ** e, n = [this.#w[e * 2], this.#w[e * 2 + 1]], r = h(this.#g[e], n, a, x.map(([e, n, r, i]) => [
460
+ Math.floor(e / t),
461
+ Math.floor(n / t),
462
+ Math.ceil(r / t),
463
+ Math.ceil(i / t)
464
+ ]));
465
+ if (this.#g[e] = n, !r.length) continue;
466
+ let i = D, o = n[0] * t, s = n[1] * t, l = o + a * t, u = s + a * t;
467
+ b.forEach((e, t) => {
468
+ let n = Math.hypot(e.size[0], e.size[1]) / 2;
469
+ e.center[0] + n > o && e.center[0] - n < l && e.center[1] + n > s && e.center[1] - n < u && (C[D++] = t);
470
+ });
471
+ let d = 64 * e;
472
+ w.set([
473
+ n[0],
474
+ n[1],
475
+ a,
476
+ D - i
477
+ ], d), T[d + 4] = t, w[d + 5] = i, c && (T[d + 6] = this.#T[e * 4 + 2], T[d + 7] = this.#T[e * 4 + 3], w[d + 8] = this.#T[e * 4], w[d + 9] = this.#T[e * 4 + 1]), E.push([e, r]);
478
+ }
479
+ if (!E.length) return;
480
+ let O = this.#j.size ? r.createBindGroup({
481
+ layout: this.#p.getBindGroupLayout(2),
482
+ entries: [...this.#j].flatMap((e) => e.bindings())
483
+ }) : void 0;
484
+ r.queue.writeBuffer(this.#c, 0, S), D && r.queue.writeBuffer(this.#u, 0, C, 0, D);
485
+ for (let [e, r] of E) {
486
+ let i = t.encoder.beginRenderPass({ colorAttachments: [{
487
+ view: this.#i[e],
488
+ loadOp: "load",
489
+ storeOp: "store"
490
+ }] });
491
+ i.setPipeline(this.#p), i.setBindGroup(0, n.group), i.setBindGroup(1, this.#f, [256 * e]), O && i.setBindGroup(2, O);
492
+ for (let [e, t, n, a] of r) i.setScissorRect(e, t, n, a), i.draw(3), this.baked += n * a;
493
+ i.end();
494
+ }
495
+ }
496
+ onDeviceRestored(e) {
497
+ this.#P(), this.setup(e);
498
+ }
499
+ #P() {
500
+ for (let e of [
501
+ this.#r,
502
+ this.#a,
503
+ this.#s,
504
+ this.#c,
505
+ this.#l,
506
+ this.#u
507
+ ]) e?.destroy();
508
+ this.#r = this.#a = this.#s = this.#c = this.#l = this.#u = void 0, this.#i = [], this.#h = [], this.#p = this.#m = this.#d = this.#f = this.#o = void 0;
509
+ }
510
+ dispose() {
511
+ this.disposed || (this.disposed = !0, this.#x?.(), this.#x = void 0, this.owner?.sceneOf(this)?.removePlugin(this.name), this.#P(), this.#A.clear(), this.#v.clear(), this.#j.clear(), this.owner = this.#n = void 0);
512
+ }
513
+ [Symbol.dispose ?? Symbol()]() {
514
+ this.dispose();
515
+ }
516
+ };
517
+ //#endregion
518
+ export { v as TerrainVirtualTexture, h as bakeRects, g as planWindows, u as splitTerrainColor };
@@ -0,0 +1,103 @@
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 } from './index.js';
5
+ /** What a brush does: move heights up or down, blur them, pull them to one height, or paint a layer's weight. */
6
+ export type TerrainBrush = 'raise' | 'lower' | 'smooth' | 'flatten' | 'paint';
7
+ /** How a brush fades from its centre to its edge. */
8
+ export type TerrainBrushFalloff = 'smooth' | 'linear' | 'constant';
9
+ /** Brush settings, for {@link TerrainSculpt.dab}, a stroke, or the sculpt's defaults. */
10
+ export interface TerrainBrushOptions {
11
+ /** Default `'raise'`. */
12
+ brush?: TerrainBrush;
13
+ /** World radius, above 0. Default 8. */
14
+ radius?: number;
15
+ /** 0 to 1: the share of `amount` (raise, lower) or of the way to the result (smooth, flatten, paint) a dab moves at its centre. Default 0.5. */
16
+ strength?: number;
17
+ /** Default `'smooth'`: Wendland's (1 - t)^4 (4t + 1) of the distance over the radius. */
18
+ falloff?: TerrainBrushFalloff;
19
+ /** World Y a raise or lower dab moves at its centre at strength 1, above 0. Default a tenth of the radius. */
20
+ amount?: number;
21
+ /** Flatten's world Y. Default the height under the stroke's first dab, as `heights` held it when the stroke began. */
22
+ height?: number;
23
+ /** The layer `paint` raises (the others fall to keep their shares), 0 to the terrain's layers - 1. Default 0. */
24
+ layer?: number;
25
+ }
26
+ /** {@link TerrainSculpt.attach} options. */
27
+ export interface TerrainSculptOptions extends TerrainBrushOptions {
28
+ /** Strokes kept for undo, 0 to 1,000. Default 32. */
29
+ undoLimit?: number;
30
+ /** Aborts the initial read back. */
31
+ signal?: AbortSignal;
32
+ }
33
+ /** A texel rectangle that changed: in the heightmap, or in weight texture `weights` (an index into `TerrainSculpt.weights`). */
34
+ export interface TerrainSculptChange {
35
+ readonly weights?: number;
36
+ readonly u: number;
37
+ readonly v: number;
38
+ readonly width: number;
39
+ readonly depth: number;
40
+ }
41
+ /** An open stroke: `end()` (or `using`) closes it into one undo step. */
42
+ export interface TerrainStroke extends Disposable {
43
+ end(): void;
44
+ }
45
+ /**
46
+ * Sculpt and paint brushes on a live {@link Terrain}: raise, lower, smooth, flatten and paint layer weights, on the
47
+ * GPU, with undo. The terrain's heightmap must be `r32float` and its weight textures (if any) `rgba8unorm`, all with
48
+ * `STORAGE_BINDING | COPY_SRC | COPY_DST | TEXTURE_BINDING` usage (15). Make one with `await TerrainSculpt.attach`.
49
+ */
50
+ export declare class TerrainSculpt implements EnginePlugin {
51
+ #private;
52
+ readonly name: string;
53
+ /** CPU copy of the heightmap, row by row (as `TerrainQuery` takes it): holds every finished stroke once `flush()` resolves. */
54
+ heights: Float32Array;
55
+ /** Heightmap texels per row and rows. */
56
+ columns: number;
57
+ rows: number;
58
+ /** CPU copies of the distinct weight textures, RGBA bytes, with their sizes. */
59
+ weights: readonly {
60
+ readonly data: Uint8Array;
61
+ readonly columns: number;
62
+ readonly rows: number;
63
+ }[];
64
+ /** Brush settings used where a dab or stroke leaves one out. */
65
+ readonly brush: Required<Omit<TerrainBrushOptions, 'height' | 'amount'>> & Pick<TerrainBrushOptions, 'height' | 'amount'>;
66
+ disposed: boolean;
67
+ private constructor();
68
+ /**
69
+ * Attaches brushes to `terrain`, which must already be attached to `engine`, and reads its heightmap and weights back
70
+ * once for the CPU copy. `dispose()` removes them (the terrain keeps its edits).
71
+ * @throws RangeError for bad options; TypeError for a heightmap or weights of the wrong format or usage; MargoError
72
+ * `'unsupported'` on WebGL or a terrain that is not attached.
73
+ */
74
+ static attach(engine: EngineKernel, terrain: Terrain, options?: TerrainSculptOptions): Promise<TerrainSculpt>;
75
+ setup(engine: Engine): void;
76
+ /**
77
+ * Opens a stroke: the dabs until `end()` are one undo step and share `options` (over the sculpt's `brush`).
78
+ * @example
79
+ * { using stroke = sculpt.stroke({brush: 'smooth'}); sculpt.dab(10, 4); sculpt.dab(12, 5); }
80
+ * @throws Error (MargoError 'state') when a stroke is already open; RangeError for bad options.
81
+ */
82
+ stroke(options?: TerrainBrushOptions): TerrainStroke;
83
+ /**
84
+ * One dab at world (x, z): inside an open stroke, or as a stroke of its own. Runs on the GPU now; `heights` follows
85
+ * once the stroke ends and its read back lands (`flush()`).
86
+ */
87
+ dab(x: number, z: number, options?: TerrainBrushOptions): void;
88
+ /** Undoes the last finished stroke, once the pending read backs land. Resolves false with nothing to undo. */
89
+ undo(): Promise<boolean>;
90
+ /** Redoes the last undone stroke. Resolves false with nothing to redo; a new stroke clears the redo steps. */
91
+ redo(): Promise<boolean>;
92
+ /** Resolves when `heights` and `weights` hold every finished stroke (rejects with a read back's failure). */
93
+ flush(): Promise<void>;
94
+ /**
95
+ * Calls `callback` for every rectangle the CPU copies take (after a stroke's read back, an undo or a redo), for a
96
+ * `TerrainQuery` over `heights`: `query.refresh(u, v, width, depth)` when `weights` is undefined. Returns the remover.
97
+ */
98
+ onChange(callback: (change: TerrainSculptChange) => void): () => void;
99
+ /** Puts the CPU copies (with every edit) into the terrain's new textures after device restoration. */
100
+ onDeviceRestored(engine: Engine): void;
101
+ dispose(): void;
102
+ [Symbol.dispose]: () => void;
103
+ }