@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/scour.js ADDED
@@ -0,0 +1,153 @@
1
+ import { computeVertexNormals as e } from "@margoengine/geometry/utils";
2
+ //#region src/scour.ts
3
+ function t(e, t) {
4
+ return Math.cbrt(e * e * t);
5
+ }
6
+ var n = [
7
+ [7.5, 5.6],
8
+ [10, 2.9],
9
+ [15, 1.6],
10
+ [20, 1.3]
11
+ ];
12
+ function r(e, t) {
13
+ let r = 0;
14
+ for (; r < n.length - 2 && t > n[r + 1][0];) r++;
15
+ let [i, a] = n[r], [o, s] = n[r + 1], c = Math.min(1, Math.max(0, (t - i) / (o - i)));
16
+ return e * (a + (s - a) * c);
17
+ }
18
+ var i = (e, t, n) => {
19
+ let r = Math.min(1, Math.max(0, (n - e) / (t - e)));
20
+ return r * r * (3 - 2 * r);
21
+ }, a = Math.exp(-9), o = (e, t) => Math.max(0, Math.exp(-((e / t) ** 2)) - a) / (1 - a), s = (e, t, n, r) => {
22
+ if (!(Number.isFinite(t) && t >= n && t <= r)) throw RangeError(`windScour: ${e} must be from ${n} to ${r}.`);
23
+ return t;
24
+ }, c = (e, t) => {
25
+ if (!(t?.length === 2 && Number.isFinite(t[0]) && Number.isFinite(t[1]))) throw RangeError(`windScour: ${e} must be two finite numbers.`);
26
+ }, l = (e, t) => {
27
+ if (!(Number.isFinite(t) && t > 0)) throw RangeError(`windScour: ${e} must be above 0.`);
28
+ return t;
29
+ };
30
+ function u(e, t, n, r, i, a, o) {
31
+ let s = Infinity, c = Infinity, l = -Infinity, u = -Infinity;
32
+ for (let d of [i, a]) for (let i of [-o, o]) {
33
+ let a = e + d * n - i * r, o = t + d * r + i * n;
34
+ s = Math.min(s, a), l = Math.max(l, a), c = Math.min(c, o), u = Math.max(u, o);
35
+ }
36
+ return [
37
+ s,
38
+ c,
39
+ l,
40
+ u
41
+ ];
42
+ }
43
+ function d(e = {}) {
44
+ let n = s("wind", e.wind ?? 90, -3600, 3600) * Math.PI / 180, a = s("speed", e.speed ?? 11, 0, 200), d = l("threshold", e.threshold ?? 6.6), f = s("scour", e.scour ?? .06, 0, .075), p = s("deposit", e.deposit ?? .07, 0, .3), m = s("tail", e.tail ?? 3, .5, 8), h = Math.tan(s("slope", e.slope ?? 20, 5, 32) * Math.PI / 180), g = Math.cos(n), _ = Math.sin(n), v = i(d, 1.3 * d, a), y = (e.buildings ?? []).map((e) => {
45
+ c("a building center", e.center), c("a building size", e.size);
46
+ let [n, r] = e.center, a = l("a building size", e.size[0]) / 2, d = l("a building size", e.size[1]) / 2, h = l("a building height", e.height), v = s("a building yaw", e.yaw ?? 0, -1e3, 1e3), y = Math.cos(v), b = Math.sin(v), x = Math.abs(-y * _ - b * g) * a + Math.abs(-b * _ + y * g) * d, S = Math.abs(y * g - b * _) * a + Math.abs(b * g + y * _) * d, C = t(2 * x, h), w = m * C, T = .65 * h, E = .18 * h, D = .45 * h, O = .22 * C, k = .45 * h, A = .12, j = [-1, 1].flatMap((e) => [-1, 1].map((t) => [n + y * e * a + b * t * d, r - b * e * a + y * t * d])), M = (e, t) => {
47
+ let i = e - n, o = t - r;
48
+ return Math.hypot(Math.max(0, Math.abs(y * i - b * o) - a), Math.max(0, Math.abs(b * i + y * o) - d));
49
+ }, N = x + T + A * w + 3 * Math.max(D, O), P = u(n, r, g, _, -S - T - 3 * D - x, S + w, N + S);
50
+ return {
51
+ bounds: P,
52
+ distance: M,
53
+ at(e, t) {
54
+ if (e < P[0] || e > P[2] || t < P[1] || t > P[3]) return 0;
55
+ let a = M(e, t);
56
+ if (a <= 0) return 0;
57
+ let s = e - n, c = t - r, l = s * g + c * _, u = Math.abs(c * g - s * _), d = 0;
58
+ if (a < k) {
59
+ let n = (1 - .7 * i(-S, S + .3 * h, l)) * (1 - i(S, S + .4 * h, l)), r = Math.max(...j.map(([n, r]) => Math.exp(-((e - n) ** 2 + (t - r) ** 2) / (.5 * h) ** 2)));
60
+ d -= Math.min(.075 * h, f * h * n * (1 + .5 * r)) * Math.sin(Math.PI * a / k) ** 2;
61
+ }
62
+ let m = Math.hypot(Math.max(0, -S - l), Math.max(0, u - x)), v = l < -S ? m - T : u - (x + T + A * Math.max(0, l - S)), y = i(-S, S + C, l), b = (v < 0 ? E : D) * (1 - y) + O * y, N = 1 - i(S + .3 * w, S + w, l);
63
+ return d += p * h * o(v, b) * N, d;
64
+ }
65
+ };
66
+ }), b = r(1, a), x = (e.plants ?? []).map((e) => {
67
+ c("a plant center", e.center);
68
+ let [t, n] = e.center, r = l("a plant width", e.width) / 2, i = b * 2 * r;
69
+ return {
70
+ bounds: u(t, n, g, _, -r, i, r),
71
+ at(e, a) {
72
+ let o = e - t, s = a - n, c = o * g + s * _, l = Math.abs(s * g - o * _), u = c < 0 ? r - Math.hypot(c, l) : r * (1 - c / i) - l;
73
+ return u > 0 ? h * u : 0;
74
+ }
75
+ };
76
+ }), S = /* @__PURE__ */ new Map();
77
+ for (let e of x) {
78
+ let [t, n, r, i] = e.bounds;
79
+ for (let a = Math.floor(n / 4); a <= Math.floor(i / 4); a++) for (let n = Math.floor(t / 4); n <= Math.floor(r / 4); n++) {
80
+ let t = `${n},${a}`, r = S.get(t);
81
+ r ? r.push(e) : S.set(t, [e]);
82
+ }
83
+ }
84
+ return {
85
+ bounds: [...y.map((e) => e.bounds), ...x.map((e) => e.bounds)],
86
+ change(e, t) {
87
+ if (v <= 0) return 0;
88
+ let n = 0;
89
+ for (let r of S.get(`${Math.floor(e / 4)},${Math.floor(t / 4)}`) ?? []) n = Math.max(n, r.at(e, t));
90
+ let r = Infinity;
91
+ for (let i of y) r = Math.min(r, i.distance(e, t)), n += i.at(e, t);
92
+ return r > 0 ? v * n * i(0, .3, r) : 0;
93
+ }
94
+ };
95
+ }
96
+ function f(t, n) {
97
+ let { size: r, resolution: i = 192, regions: a, subdivide: o = 5, add: s } = n, c = n.origin ?? [-r?.[0] / 2, -r?.[1] / 2];
98
+ if (typeof t != "function" || !(r?.length === 2 && r[0] > 0 && r[1] > 0 && Number.isFinite(r[0] + r[1])) || !(c.length === 2 && Number.isFinite(c[0] + c[1])) || !(Number.isInteger(i) && i >= 1 && i <= 1024) || !(Number.isInteger(o) && o >= 1 && o <= 16) || !Array.isArray(a) || !a.every((e) => e?.length === 4 && e.every(Number.isFinite) && e[2] >= e[0] && e[3] >= e[1]) || s !== void 0 && typeof s != "function") throw RangeError("refinedHeightfieldGeometry: pass a height function, a positive size, a resolution 1 to 1024, subdivide 1 to 16 and regions as [minX, minZ, maxX, maxZ].");
99
+ let l = r[0] / i, u = r[1] / i, d = new Uint8Array(i * i);
100
+ for (let [e, t, n, r] of a) {
101
+ let a = Math.max(0, Math.floor((e - c[0]) / l)), s = Math.min(i - 1, Math.ceil((n - c[0]) / l) - 1), f = Math.max(0, Math.floor((t - c[1]) / u)), p = Math.min(i - 1, Math.ceil((r - c[1]) / u) - 1);
102
+ for (let e = f; e <= p; e++) for (let t = a; t <= s; t++) d[e * i + t] = +(o > 1);
103
+ }
104
+ let f = (e, t) => e >= 0 && t >= 0 && e < i && t < i && d[t * i + e] === 1, p = [], m = [], h = [], g = (e, t, n) => {
105
+ let i = p.length / 3, a = n + (s ? s(e, t) : 0);
106
+ if (!Number.isFinite(Math.fround(a))) throw RangeError("Terrain height must be finite");
107
+ if (i >= 4e6) throw RangeError("refinedHeightfieldGeometry: over 4,000,000 vertices; split fewer cells.");
108
+ return p.push(e, a, t), m.push((e - c[0]) / r[0], 1 - (t - c[1]) / r[1]), i;
109
+ }, _ = new Float64Array((i + 1) * (i + 1));
110
+ for (let e = 0; e <= i; e++) for (let n = 0; n <= i; n++) {
111
+ let r = c[0] + n * l, a = c[1] + e * u, o = t(r, a);
112
+ _[e * (i + 1) + n] = o, g(r, a, o);
113
+ }
114
+ let v = /* @__PURE__ */ new Map(), y = i * o + 1, b = (e, t) => {
115
+ if (e % o === 0 && t % o === 0) return t / o * (i + 1) + e / o;
116
+ let n = t * y + e, r = v.get(n);
117
+ if (r === void 0) {
118
+ let a = Math.min(i - 1, Math.floor(e / o)), s = Math.min(i - 1, Math.floor(t / o)), d = e / o - a, f = t / o - s, p = s * (i + 1) + a, m = _[p], h = _[p + 1], y = _[p + i + 1], b = _[p + i + 2], x = d + f <= 1 ? m + d * (h - m) + f * (y - m) : b + (1 - d) * (y - b) + (1 - f) * (h - b);
119
+ r = g(c[0] + e * l / o, c[1] + t * u / o, x), v.set(n, r);
120
+ }
121
+ return r;
122
+ }, x = (e, t, n) => {
123
+ let r = b(e, t), i = b(e + n, t), a = b(e, t + n), o = b(e + n, t + n);
124
+ h.push(r, a, i, i, a, o);
125
+ };
126
+ for (let e = 0; e < i; e++) for (let t = 0; t < i; t++) {
127
+ let n = t * o, r = e * o;
128
+ if (f(t, e)) {
129
+ for (let e = 0; e < o; e++) for (let t = 0; t < o; t++) x(n + t, r + e, 1);
130
+ continue;
131
+ }
132
+ let a = f(t - 1, e), s = f(t, e + 1), d = f(t + 1, e), p = f(t, e - 1);
133
+ if (!(a || s || d || p)) {
134
+ x(n, r, o);
135
+ continue;
136
+ }
137
+ let m = [], v = (e, t) => {
138
+ let n = e ? o : 1;
139
+ for (let e = 0; e < n; e++) m.push(t(e * o / n));
140
+ };
141
+ v(a, (e) => b(n, r + e)), v(s, (e) => b(n + e, r + o)), v(d, (e) => b(n + o, r + o - e)), v(p, (e) => b(n + o - e, r));
142
+ let y = g(c[0] + (t + .5) * l, c[1] + (e + .5) * u, (_[e * (i + 1) + t + 1] + _[(e + 1) * (i + 1) + t]) / 2);
143
+ for (let e = 0; e < m.length; e++) h.push(y, m[e], m[(e + 1) % m.length]);
144
+ }
145
+ return e({
146
+ positions: Float32Array.from(p),
147
+ normals: new Float32Array(p.length),
148
+ uvs: Float32Array.from(m),
149
+ indices: Uint32Array.from(h)
150
+ });
151
+ }
152
+ //#endregion
153
+ export { f as refinedHeightfieldGeometry, t as scourScale, r as shadowDuneLength, d as windScour };
@@ -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
+ }
package/dist/sculpt.js ADDED
@@ -0,0 +1,361 @@
1
+ // @margo/core-built 1.0.0
2
+ import {coreRequirement as __margoCoreRequirement,assertCore as __margoAssertCore} from '@margoengine/core/extension';
3
+ const e=(engine,version="1.0.0",source=import.meta.url)=>__margoRuntime(engine,version,source);
4
+ import { engineRuntime as __margoRuntime } from "@margoengine/core/extension";
5
+ import { MargoError as t } from "@margoengine/math/errors";
6
+ //#region src/sculpt.ts
7
+ var n = (e) => `
8
+ struct Dab {center:vec2f,radius:f32,strength:f32,amount:f32,goal:f32,mode:u32,falloff:u32,lo:vec2i,hi:vec2i,origin:vec2i,spacing:vec2f,paint:vec4f}
9
+ @group(0) @binding(0) var<uniform> dab:Dab;
10
+ @group(0) @binding(1) var source:texture_2d<f32>;
11
+ @group(0) @binding(2) var dest:texture_storage_2d<${e},write>;
12
+ fn fall(t:f32)->f32 {
13
+ if(t>=1.0){return 0.0;}if(dab.falloff==1u){return 1.0-t;}if(dab.falloff==2u){return 1.0;}
14
+ let s=1.0-t;return s*s*s*s*(4.0*t+1.0);
15
+ }
16
+ fn at(p:vec2i)->vec4f {return textureLoad(source,clamp(p-dab.origin,vec2i(0),vec2i(textureDimensions(source))-vec2i(1)),0);}
17
+ @compute @workgroup_size(8,8) fn main(@builtin(global_invocation_id) id:vec3u) {
18
+ let p=dab.lo+vec2i(id.xy);if(any(p>=dab.hi)){return;}
19
+ let f=fall(length((vec2f(p)-dab.center)*dab.spacing)/dab.radius)*dab.strength;let h=at(p);var out=h;
20
+ ${e === "rgba8unorm" ? "let d=dab.paint-h;let s=d*f;out=h+select(s,sign(d)*min(abs(d),vec4f(1.0/255.0)),(abs(s)<vec4f(0.5/255.0))&(abs(d)>vec4f(0.0))&vec4<bool>(f>0.0));" : "switch dab.mode {\n case 0u:{out.x=h.x+dab.amount*f;}\n case 1u:{out.x=h.x-dab.amount*f;}\n case 2u:{var k=array<f32,5>(1,4,6,4,1);var s=0.0;for(var j=-2;j<=2;j++){for(var i=-2;i<=2;i++){s+=k[i+2]*k[j+2]*at(p+vec2i(i,j)).x;}}out.x=mix(h.x,s/256.0,f);}\n default:{out.x=mix(h.x,dab.goal,f);}\n }"}
21
+ textureStore(dest,p,out);
22
+ }`, r = 0, i = {
23
+ raise: 0,
24
+ lower: 1,
25
+ smooth: 2,
26
+ flatten: 3,
27
+ paint: 4
28
+ }, a = {
29
+ smooth: 0,
30
+ linear: 1,
31
+ constant: 2
32
+ };
33
+ async function o(e, t, n, r, i) {
34
+ let a = n.u1 - n.u0, o = n.v1 - n.v0, s = Math.ceil(a * r / 256) * 256, c = e.createBuffer({
35
+ size: s * o,
36
+ usage: GPUBufferUsage.MAP_READ | GPUBufferUsage.COPY_DST
37
+ }), l = e.createCommandEncoder();
38
+ l.copyTextureToBuffer({
39
+ texture: t,
40
+ origin: [n.u0, n.v0]
41
+ }, {
42
+ buffer: c,
43
+ bytesPerRow: s,
44
+ rowsPerImage: o
45
+ }, [a, o]), e.queue.submit([l.finish()]);
46
+ try {
47
+ await c.mapAsync(GPUMapMode.READ), i?.throwIfAborted();
48
+ let e = new Uint8Array(c.getMappedRange()), t = new Uint8Array(a * o * r);
49
+ for (let n = 0; n < o; n++) t.set(e.subarray(n * s, n * s + a * r), n * a * r);
50
+ return t;
51
+ } finally {
52
+ c.destroy();
53
+ }
54
+ }
55
+ var s = class s {coreRequirement=__margoCoreRequirement("1.0.0",import.meta.url);
56
+ #e;
57
+ #t;
58
+ #n;
59
+ #r;
60
+ #i;
61
+ #a;
62
+ #o;
63
+ #s;
64
+ #c;
65
+ #l;
66
+ #u;
67
+ #d;
68
+ #f;
69
+ #p;
70
+ constructor(e, t) {
71
+ if (this.name = "terrain-sculpt:" + r++, this.columns = 0, this.rows = 0, this.weights = [], this.disposed = !1, this.#n = [], this.#r = [], this.#i = /* @__PURE__ */ new Set(), this.#s = [], this.#c = /* @__PURE__ */ new Map(), this.#u = /* @__PURE__ */ new Map(), this.#f = Promise.resolve(), this.#e = e, this.#t = t.undoLimit ?? 32, !Number.isInteger(this.#t) || this.#t < 0 || this.#t > 1e3) throw RangeError("Invalid terrain sculpt undoLimit; give a whole number from 0 to 1000 (default 32).");
72
+ this.brush = {
73
+ brush: "raise",
74
+ radius: 8,
75
+ strength: .5,
76
+ falloff: "smooth",
77
+ layer: 0,
78
+ ...this.#_(t)
79
+ };
80
+ }
81
+ static async attach(t, n, r = {}) {__margoAssertCore(t,__margoCoreRequirement("1.0.0",import.meta.url));
82
+ if (!n || typeof n.invalidate != "function") throw TypeError("Invalid terrain sculpt; pass a Terrain attached to the engine.");
83
+ let i = new s(n, r);
84
+ e(t).use(i);
85
+ try {
86
+ await i.#h(r.signal);
87
+ } catch (e) {
88
+ throw i.dispose(), e;
89
+ }
90
+ return i;
91
+ }
92
+ setup(e) {
93
+ if (this.disposed || !e.gpu || !this.#e.heightmap) throw new t(this.disposed ? "disposed" : "unsupported", "Terrain sculpting requires WebGPU and an attached terrain; attach the Terrain first, on a WebGPU engine");
94
+ this.#a = e, this.#o = e.gpu, this.#m();
95
+ }
96
+ #m() {
97
+ let e = this.#e.heightmap, t = GPUTextureUsage.STORAGE_BINDING | GPUTextureUsage.COPY_SRC | GPUTextureUsage.COPY_DST, n = [...new Set(this.#e.weights ?? [])];
98
+ if (e.format !== "r32float" || (e.usage & t) !== t) throw TypeError("Terrain sculpting needs an r32float heightmap with STORAGE_BINDING, COPY_SRC and COPY_DST usage (15 with TEXTURE_BINDING); create it so in the textures factory.");
99
+ if (n.some((e) => e.format !== "rgba8unorm" || (e.usage & t) !== t)) throw TypeError("Terrain weight painting needs rgba8unorm weights with STORAGE_BINDING, COPY_SRC and COPY_DST usage (15 with TEXTURE_BINDING); create them so in the textures factory.");
100
+ let r = this.#s;
101
+ this.#s = [e, ...n].map((e, t) => ({
102
+ texture: e,
103
+ columns: e.width,
104
+ rows: e.height,
105
+ channels: t ? 4 : 1,
106
+ data: r[t]?.data ?? (t ? new Uint8Array(e.width * e.height * 4) : new Float32Array(e.width * e.height))
107
+ }));
108
+ }
109
+ async #h(e) {
110
+ let t = this.#o;
111
+ for (let n of this.#s) {
112
+ let r = await o(t, n.texture, {
113
+ u0: 0,
114
+ v0: 0,
115
+ u1: n.columns,
116
+ v1: n.rows
117
+ }, 4, e);
118
+ n.data = n.channels === 1 ? new Float32Array(r.buffer) : r;
119
+ }
120
+ this.#g();
121
+ }
122
+ #g() {
123
+ let [e, ...t] = this.#s;
124
+ this.heights = e.data, this.columns = e.columns, this.rows = e.rows, this.weights = t.map((e) => ({
125
+ data: e.data,
126
+ columns: e.columns,
127
+ rows: e.rows
128
+ }));
129
+ }
130
+ #_(e) {
131
+ let t = e ?? {}, n = this.#e.options.layers.length;
132
+ if (t.brush !== void 0 && !(t.brush in i) || t.falloff !== void 0 && !(t.falloff in a) || t.radius !== void 0 && !(t.radius > 0 && Number.isFinite(t.radius)) || t.strength !== void 0 && !(t.strength >= 0 && t.strength <= 1) || t.amount !== void 0 && !(t.amount > 0 && Number.isFinite(t.amount)) || t.height !== void 0 && !Number.isFinite(t.height) || t.layer !== void 0 && !(Number.isInteger(t.layer) && t.layer >= 0 && t.layer < n)) throw RangeError(`Invalid terrain brush; give brush raise, lower, smooth, flatten or paint, falloff smooth, linear or constant, radius and amount above 0, strength 0..1, a finite height and a layer 0..${n - 1}.`);
133
+ let r = {};
134
+ for (let e of [
135
+ "brush",
136
+ "radius",
137
+ "strength",
138
+ "falloff",
139
+ "amount",
140
+ "height",
141
+ "layer"
142
+ ]) t[e] !== void 0 && (r[e] = t[e]);
143
+ return r;
144
+ }
145
+ stroke(e = {}) {
146
+ if (this.#w(), this.#d) throw new t("state", "A terrain stroke is already open; end it before starting another");
147
+ let n = this.#d = {
148
+ options: this.#_(e),
149
+ dirty: /* @__PURE__ */ new Map()
150
+ }, r = () => {
151
+ this.#d === n && (this.#d = void 0, n.dirty.size && this.#b(n.dirty));
152
+ };
153
+ return {
154
+ end: r,
155
+ [Symbol.dispose]: r
156
+ };
157
+ }
158
+ dab(e, t, n = {}) {
159
+ if (this.#w(), !Number.isFinite(e) || !Number.isFinite(t)) throw TypeError("Invalid terrain dab; pass a finite world x and z.");
160
+ let r = this.#d ? void 0 : this.stroke();
161
+ try {
162
+ let r = this.#d, o = {
163
+ ...this.brush,
164
+ ...r.options,
165
+ ...this.#_(n)
166
+ }, s = this.#e.options, [c, l] = s.origin ?? [0, 0], [u, d] = s.size, f = s.heightScale ?? 100, p = s.heightOffset ?? 0;
167
+ o.brush === "flatten" && (r.target ??= o.height === void 0 ? this.#v(e, t) : (o.height - p) / f);
168
+ let m = o.brush === "paint";
169
+ if (m && this.#s.length < 2) throw RangeError("Invalid terrain brush; paint needs a terrain with weights.");
170
+ let h = m ? this.#s.slice(1).map((e, t) => [t + 1, e]) : [[0, this.#s[0]]];
171
+ for (let [n, s] of h) {
172
+ let p = m ? u / s.columns : u / Math.max(s.columns - 1, 1), h = m ? d / s.rows : d / Math.max(s.rows - 1, 1), g = (e - c) / p - (m ? .5 : 0), _ = (t - l) / h - (m ? .5 : 0), v = {
173
+ u0: Math.max(0, Math.floor(g - o.radius / p)),
174
+ v0: Math.max(0, Math.floor(_ - o.radius / h)),
175
+ u1: Math.min(s.columns, Math.ceil(g + o.radius / p) + 1),
176
+ v1: Math.min(s.rows, Math.ceil(_ + o.radius / h) + 1)
177
+ };
178
+ if (v.u1 <= v.u0 || v.v1 <= v.v0) continue;
179
+ let y = /* @__PURE__ */ new Float32Array(4);
180
+ m && Math.floor(o.layer / 4) === n - 1 && (y[o.layer % 4] = 1), this.#y(s, v, [g, _], [p, h], {
181
+ radius: o.radius,
182
+ strength: o.strength,
183
+ amount: (o.amount ?? o.radius / 10) / f,
184
+ target: r.target ?? 0,
185
+ mode: i[o.brush],
186
+ falloff: a[o.falloff],
187
+ paint: y
188
+ });
189
+ let b = r.dirty.get(n);
190
+ b ? (b.u0 = Math.min(b.u0, v.u0), b.v0 = Math.min(b.v0, v.v0), b.u1 = Math.max(b.u1, v.u1), b.v1 = Math.max(b.v1, v.v1)) : r.dirty.set(n, { ...v });
191
+ }
192
+ this.#e.invalidate();
193
+ } finally {
194
+ r?.end();
195
+ }
196
+ }
197
+ #v(e, t) {
198
+ let n = this.#e.options, [r, i] = n.origin ?? [0, 0], a = this.columns, o = this.rows, s = Math.min(Math.max((e - r) / n.size[0] * (a - 1), 0), a - 1), c = Math.min(Math.max((t - i) / n.size[1] * (o - 1), 0), o - 1), l = Math.floor(s), u = Math.floor(c), d = Math.min(l + 1, a - 1), f = Math.min(u + 1, o - 1), p = this.heights, m = p[u * a + l] + (p[u * a + d] - p[u * a + l]) * (s - l);
199
+ return m + (p[f * a + l] + (p[f * a + d] - p[f * a + l]) * (s - l) - m) * (c - u);
200
+ }
201
+ #y(e, t, r, i, a) {
202
+ let o = this.#o, s = e.texture.format, c = [Math.max(0, t.u0 - 2), Math.max(0, t.v0 - 2)], l = [Math.min(e.columns, t.u1 + 2), Math.min(e.rows, t.v1 + 2)], u = l[0] - c[0], d = l[1] - c[1], f = this.#u.get(s);
203
+ if (!f || f.width < u || f.height < d) {
204
+ f?.destroy();
205
+ let e = (e) => 2 ** Math.ceil(Math.log2(Math.max(e, 16)));
206
+ f = o.createTexture({
207
+ size: [Math.max(e(u), f?.width ?? 0), Math.max(e(d), f?.height ?? 0)],
208
+ format: s,
209
+ usage: GPUTextureUsage.TEXTURE_BINDING | GPUTextureUsage.COPY_DST
210
+ }), this.#u.set(s, f);
211
+ }
212
+ let p = this.#c.get(s);
213
+ p || (p = o.createComputePipeline({
214
+ layout: "auto",
215
+ compute: {
216
+ module: o.createShaderModule({ code: n(s) }),
217
+ entryPoint: "main"
218
+ }
219
+ }), this.#c.set(s, p)), this.#l ??= o.createBuffer({
220
+ size: 80,
221
+ usage: GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST
222
+ });
223
+ let m = /* @__PURE__ */ new ArrayBuffer(80), h = new Float32Array(m), g = new Int32Array(m), _ = new Uint32Array(m);
224
+ h.set([
225
+ r[0],
226
+ r[1],
227
+ a.radius,
228
+ a.strength,
229
+ a.amount,
230
+ a.target
231
+ ]), _[6] = a.mode, _[7] = a.falloff, g.set([
232
+ t.u0,
233
+ t.v0,
234
+ t.u1,
235
+ t.v1,
236
+ c[0],
237
+ c[1]
238
+ ], 8), h.set(i, 14), h.set(a.paint, 16), o.queue.writeBuffer(this.#l, 0, m);
239
+ let v = o.createCommandEncoder();
240
+ v.copyTextureToTexture({
241
+ texture: e.texture,
242
+ origin: c
243
+ }, { texture: f }, [u, d]);
244
+ let y = v.beginComputePass();
245
+ y.setPipeline(p), y.setBindGroup(0, o.createBindGroup({
246
+ layout: p.getBindGroupLayout(0),
247
+ entries: [
248
+ {
249
+ binding: 0,
250
+ resource: { buffer: this.#l }
251
+ },
252
+ {
253
+ binding: 1,
254
+ resource: f.createView()
255
+ },
256
+ {
257
+ binding: 2,
258
+ resource: e.texture.createView()
259
+ }
260
+ ]
261
+ })), y.dispatchWorkgroups(Math.ceil((t.u1 - t.u0) / 8), Math.ceil((t.v1 - t.v0) / 8)), y.end(), o.queue.submit([v.finish()]);
262
+ }
263
+ #b(e) {
264
+ let t = this.#o, n = [...e].map(([e, n]) => {
265
+ let r = this.#s[e];
266
+ return o(t, r.texture, n, 4).then((t) => ({
267
+ index: e,
268
+ rect: n,
269
+ bytes: t
270
+ }));
271
+ });
272
+ this.#r.length = 0, this.#f = this.#f.then(async () => {
273
+ let e = [];
274
+ for (let { index: t, rect: r, bytes: i } of await Promise.all(n)) {
275
+ let n = this.#s[t], a = n.channels === 1 ? new Float32Array(i.buffer) : i;
276
+ e.push({
277
+ map: t,
278
+ u: r.u0,
279
+ v: r.v0,
280
+ width: r.u1 - r.u0,
281
+ depth: r.v1 - r.v0,
282
+ before: this.#x(n, r),
283
+ after: a
284
+ }), this.#S(t, r, a);
285
+ }
286
+ this.#t && (this.#n.push(e), this.#n.length > this.#t && this.#n.shift());
287
+ }), this.#f.catch((e) => this.#p ??= e);
288
+ }
289
+ #x(e, t) {
290
+ let n = e.channels, r = (t.u1 - t.u0) * n, i = n === 1 ? new Float32Array(r * (t.v1 - t.v0)) : new Uint8Array(r * (t.v1 - t.v0));
291
+ for (let a = t.v0; a < t.v1; a++) i.set(e.data.subarray((a * e.columns + t.u0) * n, (a * e.columns + t.u1) * n), (a - t.v0) * r);
292
+ return i;
293
+ }
294
+ #S(e, t, n) {
295
+ let r = this.#s[e], i = r.channels, a = (t.u1 - t.u0) * i;
296
+ for (let e = t.v0; e < t.v1; e++) r.data.set(n.subarray((e - t.v0) * a, (e - t.v0 + 1) * a), (e * r.columns + t.u0) * i);
297
+ let o = {
298
+ u: t.u0,
299
+ v: t.v0,
300
+ width: t.u1 - t.u0,
301
+ depth: t.v1 - t.v0
302
+ };
303
+ for (let t of [...this.#i]) t(e ? {
304
+ ...o,
305
+ weights: e - 1
306
+ } : o);
307
+ }
308
+ #C(e, t) {
309
+ let n = this.#o.queue;
310
+ for (let r of e) {
311
+ let e = this.#s[r.map], i = r[t], a = {
312
+ u0: r.u,
313
+ v0: r.v,
314
+ u1: r.u + r.width,
315
+ v1: r.v + r.depth
316
+ };
317
+ n.writeTexture({
318
+ texture: e.texture,
319
+ origin: [r.u, r.v]
320
+ }, i, { bytesPerRow: r.width * 4 }, [r.width, r.depth]), this.#S(r.map, a, i);
321
+ }
322
+ this.#e.invalidate();
323
+ }
324
+ async undo() {
325
+ await this.flush();
326
+ let e = this.#n.pop();
327
+ return e ? (this.#C(e, "before"), this.#r.push(e), !0) : !1;
328
+ }
329
+ async redo() {
330
+ await this.flush();
331
+ let e = this.#r.pop();
332
+ return e ? (this.#C(e, "after"), this.#n.push(e), !0) : !1;
333
+ }
334
+ async flush() {
335
+ if (this.#w(), await this.#f, this.#p) throw this.#p;
336
+ }
337
+ onChange(e) {
338
+ if (typeof e != "function") throw TypeError("Invalid terrain sculpt listener; pass a function.");
339
+ return this.#i.add(e), () => this.#i.delete(e);
340
+ }
341
+ onDeviceRestored(e) {
342
+ this.#o = e.gpu ?? void 0, this.#c.clear(), this.#u.clear(), this.#l = void 0, this.#m();
343
+ for (let e of this.#s) this.#o.queue.writeTexture({ texture: e.texture }, e.data, { bytesPerRow: e.columns * 4 }, [e.columns, e.rows]);
344
+ this.#g(), this.#e.invalidate();
345
+ }
346
+ #w() {
347
+ if (this.disposed || !this.#o) throw new t("disposed", "This terrain sculpt was disposed; attach a new TerrainSculpt");
348
+ }
349
+ dispose() {
350
+ if (!this.disposed) {
351
+ this.disposed = !0, this.#d = void 0, this.#a?.sceneOf(this)?.removePlugin(this.name);
352
+ for (let e of this.#u.values()) e.destroy();
353
+ this.#u.clear(), this.#l?.destroy(), this.#i.clear(), this.#n.length = this.#r.length = 0, this.#a = this.#o = this.#l = void 0;
354
+ }
355
+ }
356
+ [Symbol.dispose ?? Symbol()]() {
357
+ this.dispose();
358
+ }
359
+ };
360
+ //#endregion
361
+ export { s as TerrainSculpt };