@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
@@ -0,0 +1,254 @@
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/displace.ts
7
+ var n = 108, r = 160, i = .02, a = 4, o = "@fragment fn fragment(i:Output)->@location(0) vec4f {return terrainPbrShade(i);}", s = "let dx=dpdx(position);let dy=dpdy(position);", c = "let direct=(", l = `
8
+ @group(GROUP) @binding(109) var terrainDisplaceMax:texture_2d_array<f32>;
9
+ var<private> terrainDisplaceO:array<vec2f,16>;
10
+ fn terrainDisplaceRelief(xz:vec2f)->f32 {
11
+ var sum=0.0;var total=0.0;
12
+ for(var layer=0u;layer<u32(frame.heights.z);layer++){
13
+ let w=terrainDisplaceW[layer];if(w<=0.0){continue;}
14
+ let a=textureSampleLevel(terrainPbrSurfaces,terrainSampler,xz*layerRules[layer].params.x,i32(layer),0.0).a;
15
+ let b=w*exp2(terrainPbrRules[layer].w*(a-1.0));sum+=b*a;total+=b;
16
+ }
17
+ return sum/max(total,0.00001);
18
+ }
19
+ fn terrainDisplaceBound(lo:vec2f,hi:vec2f,reference:f32,top:i32)->f32 {
20
+ var m=0.0;
21
+ for(var layer=0u;layer<u32(frame.heights.z);layer++){
22
+ if(terrainDisplaceW[layer]<=0.0){continue;}
23
+ let r=layerRules[layer].params.x/reference;let a=terrainDisplaceO[layer]+lo*r+0.001;let b=terrainDisplaceO[layer]+hi*r-0.001;
24
+ let level=clamp(i32(ceil(log2(max(max(b.x-a.x,b.y-a.y),1.0)))),0,top);
25
+ let c=exp2(f32(level));let n=vec2i(textureDimensions(terrainDisplaceMax,level));
26
+ let c0=vec2i(floor(a/c));let c1=vec2i(floor(b/c));
27
+ for(var y=c0.y;y<=c1.y;y++){for(var x=c0.x;x<=c1.x;x++){
28
+ m=max(m,textureLoad(terrainDisplaceMax,((vec2i(x,y)%n)+n)%n,i32(layer),level).r);
29
+ }}
30
+ }
31
+ return m;
32
+ }
33
+ fn terrainDisplaceSun(p:vec3f,normal:vec3f,depth:f32)->f32 {
34
+ let l=frame.light.xyz;let up=dot(l,normal);let t=l-normal*up;let run=length(t.xz);
35
+ if(up<=0.0||run<0.0001){return 1.0;}
36
+ let dir=t.xz/run;let side=f32(textureDimensions(terrainDisplaceMax).x);let top=i32(textureNumLevels(terrainDisplaceMax))-1;
37
+ var reference=0.0;var first=0u;var root=0.0;
38
+ for(var layer=0u;layer<u32(frame.heights.z);layer++){
39
+ if(terrainDisplaceW[layer]<=0.0){continue;}
40
+ let s=layerRules[layer].params.x;if(s>reference){reference=s;first=layer;}
41
+ terrainDisplaceO[layer]=fract(p.xz*s)*side-0.5;
42
+ root=max(root,textureLoad(terrainDisplaceMax,vec2i(0),i32(layer),top).r);
43
+ }
44
+ if(reference<=0.0){return 1.0;}
45
+
46
+ let k=reference*side;let rise=up/run/(depth*k);let margin=${i}/(depth*k);let o=terrainDisplaceO[first];
47
+ let h0=terrainDisplaceRelief(p.xz);
48
+ var level=0;var tau=0.0;var lowest=${i};
49
+ for(var i=0;i<${r};i++){
50
+ let ray=h0+rise*tau;if(ray>=root){break;}
51
+ let w=o+dir*tau;let c=exp2(f32(level));let cell=floor((w+dir*0.001)/c)*c;
52
+ let across=select((select(cell,cell+c,dir>vec2f(0.0))-w)/dir,vec2f(1e9),abs(dir)<vec2f(0.000001));
53
+ let exit=tau+max(min(across.x,across.y),0.001);
54
+ if(ray-terrainDisplaceBound(cell-o,cell+c-o,reference,top)>=margin*exit){tau=exit;level=min(level+1,top);continue;}
55
+ if(level>0){level--;continue;}
56
+ for(var j=1;j<=2;j++){
57
+ let at=mix(tau,exit,0.5*f32(j));
58
+ if(at>=0.25){lowest=min(lowest,(h0+rise*at-terrainDisplaceRelief(p.xz+dir*(at/k)))*depth*k/at);}
59
+ }
60
+ if(lowest<=-${i}){break;}
61
+ tau=exit;
62
+ }
63
+ return smoothstep(-${i},${i},lowest);
64
+ }
65
+
66
+
67
+
68
+
69
+
70
+
71
+ fn terrainDisplaceSunArea(p:vec3f,normal:vec3f,depth:f32)->f32 {
72
+ var reference=0.0;
73
+ for(var layer=0u;layer<u32(frame.heights.z);layer++){if(terrainDisplaceW[layer]>0.0){reference=max(reference,layerRules[layer].params.x);}}
74
+ let ax=terrainDisplaceDx.xz;let ay=terrainDisplaceDy.xz;
75
+ let n=clamp(round(max(length(ax),length(ay))*reference*f32(textureDimensions(terrainDisplaceMax).x)),1.0,${a}.0);
76
+ if(n<=1.0){return terrainDisplaceSun(p,normal,depth);}
77
+ var sum=0.0;
78
+ for(var y=0.0;y<n;y+=1.0){for(var x=0.0;x<n;x+=1.0){
79
+ let o=ax*((x+0.5)/n-0.5)+ay*((y+0.5)/n-0.5);sum+=terrainDisplaceSun(p+vec3f(o.x,0.0,o.y),normal,depth);
80
+ }}
81
+ return sum/(n*n);
82
+ }`, u = (e, t, r) => `
83
+ @group(${e}) @binding(${n}) var<uniform> terrainDisplaceRules:array<vec4f,17>;
84
+ var<private> terrainDisplaced:bool;var<private> terrainDisplaceDx:vec3f;var<private> terrainDisplaceDy:vec3f;
85
+ var<private> terrainDisplaceShadow:f32=1.0;var<private> terrainDisplaceW:array<f32,16>;var<private> terrainDisplaceLift:vec3f;
86
+
87
+
88
+
89
+ fn terrainDisplaceShadowPoint(p:vec3f)->vec3f {return select(p,terrainDisplaceLift,terrainDisplaced);}
90
+ fn terrainDisplaceWeights(position:vec3f,normal:vec3f)->f32 {
91
+ var total=0.0;var depth=0.0;let count=u32(frame.heights.z);${t ? `
92
+ let d=vec2f(textureDimensions(terrainWeights0));let uv=clamp((position.xz-frame.map.xy)/frame.map.zw,vec2f(0.5)/d,vec2f(1)-vec2f(0.5)/d);
93
+ let packed=array<vec4f,4>(${[
94
+ 0,
95
+ 1,
96
+ 2,
97
+ 3
98
+ ].map((e) => e < t ? `textureSampleLevel(terrainWeights${e},terrainSampler,uv,0)` : "vec4f(0)").join(",")});
99
+ for(var layer=0u;layer<count;layer++){let w=packed[layer/4u][layer%4u];terrainDisplaceW[layer]=w;total+=w;depth+=w*terrainDisplaceRules[layer].x;}` : "\n let slope=1-clamp(normal.y,0.0,1.0);\n for(var layer=0u;layer<count;layer++){\n let rule=layerRules[layer];let hs=rule.heightSlope;let h=rule.params.y;let s=rule.params.z;\n let w=smoothstep(hs.x-h,hs.x+h,position.y)*(1-smoothstep(hs.y-h,hs.y+h,position.y))*smoothstep(hs.z-s,hs.z+s,slope)*(1-smoothstep(hs.w-s,hs.w+s,slope));\n terrainDisplaceW[layer]=w;total+=w;depth+=w*terrainDisplaceRules[layer].x;\n }"}
100
+ if(total<=0.00001){for(var layer=0u;layer<count;layer++){terrainDisplaceW[layer]=0.0;}terrainDisplaceW[0]=1.0;return terrainDisplaceRules[0].x;}
101
+ return depth/total;
102
+ }
103
+ fn terrainDisplaceHeight(xz:vec2f)->f32 {
104
+ var sum=0.0;var total=0.0;
105
+ for(var layer=0u;layer<u32(frame.heights.z);layer++){
106
+ let w=terrainDisplaceW[layer];if(w<=0.0){continue;}
107
+ let s=layerRules[layer].params.x;
108
+ let a=textureSampleGrad(terrainPbrSurfaces,terrainSampler,xz*s,i32(layer),terrainDisplaceDx.xz*s,terrainDisplaceDy.xz*s).a;
109
+ let b=w*exp2(terrainPbrRules[layer].w*(a-1.0));sum+=b*a;total+=b;
110
+ }
111
+ return sum/max(total,0.00001);
112
+ }${r ? l.replace("GROUP", String(e)) : ""}
113
+ fn terrainDisplace(position:vec3f,normal:vec3f)->vec3f {
114
+ terrainDisplaceDx=dpdx(position);terrainDisplaceDy=dpdy(position);
115
+ let settings=terrainDisplaceRules[16];let v=frame.eye.xyz-position;let far=length(v);
116
+ if(far>=settings.x||normal.y<0.55){return position;}
117
+ let depth=terrainDisplaceWeights(position,normal)*(1.0-smoothstep(0.75*settings.x,settings.x,far))*smoothstep(0.55,0.85,normal.y);
118
+ if(depth<=0.0){return position;}
119
+ let e=v/far;let facing=max(dot(e,normal),0.2);let ray=-e/facing;
120
+ let steps=max(round(mix(settings.y,settings.y*0.25,facing)),2.0);let dd=depth/steps;
121
+ var d0=0.0;var f0=-depth*(1.0-terrainDisplaceHeight(position.xz));var d1=0.0;var f1=f0;
122
+ for(var k=1.0;k<=steps;k+=1.0){
123
+ d1=dd*k;f1=d1-depth*(1.0-terrainDisplaceHeight((position+ray*d1).xz));
124
+ if(f1>=0.0){break;}
125
+ d0=d1;f0=f1;
126
+ }
127
+ var hit=d1;if(f1>=0.0&&f1>f0){hit=d0+(d1-d0)*(-f0)/(f1-f0);}
128
+ let p=position+ray*hit;terrainDisplaced=true;
129
+ let l=frame.light.xyz;terrainDisplaceLift=p+l*max(dot(position-p,normal),0.0)/max(dot(l,normal),0.05);${r ? "terrainDisplaceShadow=terrainDisplaceSunArea(p,normal,depth);" : ""}
130
+ return p;
131
+ }`, d = (e) => `
132
+ @group(0) @binding(0) var relief:texture_2d_array<f32>;
133
+ @group(0) @binding(1) var maxima:texture_storage_2d_array<r32float,write>;
134
+ @compute @workgroup_size(8,8) fn main(@builtin(global_invocation_id) id:vec3u) {
135
+ let n=textureDimensions(maxima);if(id.x>=n.x||id.y>=n.y){return;}
136
+ let m=vec2i(textureDimensions(relief));var h=0.0;
137
+ for(var y=0;y<2;y++){for(var x=0;x<2;x++){
138
+ h=max(h,textureLoad(relief,(vec2i(id.xy)*${e ? 1 : 2}+vec2i(x,y))%m,i32(id.z),0).${e ? "a" : "r"});
139
+ }}
140
+ textureStore(maxima,vec2i(id.xy),i32(id.z),vec4f(h));
141
+ }`, f = 0, p = class r {coreRequirement=__margoCoreRequirement("1.0.0",import.meta.url);
142
+ #e;
143
+ #t;
144
+ #n;
145
+ #r;
146
+ #i;
147
+ constructor(e, t, n) {
148
+ this.terrain = e, this.materials = t, this.options = n, this.name = "terrain-displace:" + f++, this.disposed = !1, this.#n = [], this.#i = /* @__PURE__ */ new Map();
149
+ let r = e?.options?.layers?.length;
150
+ if (!r || typeof e.addLighting != "function") throw TypeError("Invalid terrain displacement; pass a Terrain");
151
+ if (typeof t?.bindings != "function" || !("surface" in t)) throw TypeError("Invalid terrain displacement; pass the TerrainMaterials attached to the terrain");
152
+ let i = n ?? {}, a = i.layers ?? [], o = (e) => typeof e == "number" && e >= 0 && e <= 1;
153
+ if (!o(i.depth ?? .05) || !Array.isArray(a) || a.length > r || !a.every((e) => o(e?.depth ?? 0)) || !((i.distance ?? 30) > 0 && Number.isFinite(i.distance ?? 30)) || !Number.isInteger(i.steps ?? 24) || (i.steps ?? 24) < 4 || (i.steps ?? 24) > 64 || typeof (i.shadows ?? !0) != "boolean") throw RangeError("Invalid terrain displacement; give depth 0..1, at most one layers entry per terrain layer with depth 0..1, distance above 0, steps 4..64 and shadows true or false.");
154
+ }
155
+ static attach(t, n, i, a = {}) {__margoAssertCore(t,__margoCoreRequirement("1.0.0",import.meta.url));
156
+ let o = new r(n, i, a);
157
+ return e(t).use(o), o;
158
+ }
159
+ setup(e) {
160
+ if (this.disposed || !e.gpu) throw new t(this.disposed ? "disposed" : "unsupported", "Terrain displacement requires WebGPU and a live module; attach a new one to a WebGPU engine");
161
+ this.owner = e;
162
+ let r = this.options, i = e.gpu, a = /* @__PURE__ */ new Float32Array(68);
163
+ for (let e = 0; e < 16; e++) a[e * 4] = r.layers?.[e]?.depth ?? r.depth ?? .05;
164
+ a.set([
165
+ r.distance ?? 30,
166
+ r.steps ?? 24,
167
+ +(r.shadows ?? !0),
168
+ 0
169
+ ], 64), this.#e = i.createBuffer({
170
+ size: a.byteLength,
171
+ usage: 72
172
+ }), i.queue.writeBuffer(this.#e, 0, a), this.#n = [{
173
+ binding: n,
174
+ resource: { buffer: this.#e }
175
+ }], (r.shadows ?? !0) && (this.#t = this.#a(i), this.#n.push({
176
+ binding: 109,
177
+ resource: this.#t.createView({ dimension: "2d-array" })
178
+ })), this.#r ??= this.terrain.addLighting(this);
179
+ }
180
+ #a(e) {
181
+ let n = this.materials.surface, r = n?.width ?? 0;
182
+ if (!n) throw new t("unsupported", "Terrain displacement needs live TerrainMaterials; attach TerrainMaterials first");
183
+ if (n.height !== r || r < 1 || r & r - 1) throw new t("unsupported", "Terrain displacement shadows need square, power-of-two surface maps; resize them or pass shadows: false");
184
+ let i = Math.log2(r) + 1, a = n.depthOrArrayLayers, o = e.createTexture({
185
+ size: [
186
+ r,
187
+ r,
188
+ a
189
+ ],
190
+ format: "r32float",
191
+ mipLevelCount: i,
192
+ usage: 12
193
+ }), s = [!0, !1].map((t) => e.createComputePipeline({
194
+ layout: "auto",
195
+ compute: {
196
+ module: e.createShaderModule({ code: d(t) }),
197
+ entryPoint: "main"
198
+ }
199
+ })), c = e.createCommandEncoder(), l = c.beginComputePass();
200
+ for (let t = 0; t < i; t++) {
201
+ let i = s[+!!t], c = Math.ceil((r >> t) / 8);
202
+ l.setPipeline(i), l.setBindGroup(0, e.createBindGroup({
203
+ layout: i.getBindGroupLayout(0),
204
+ entries: [{
205
+ binding: 0,
206
+ resource: (t ? o : n).createView({
207
+ dimension: "2d-array",
208
+ baseMipLevel: Math.max(t - 1, 0),
209
+ mipLevelCount: 1
210
+ })
211
+ }, {
212
+ binding: 1,
213
+ resource: o.createView({
214
+ dimension: "2d-array",
215
+ baseMipLevel: t,
216
+ mipLevelCount: 1
217
+ })
218
+ }]
219
+ })), l.dispatchWorkgroups(c, c, a);
220
+ }
221
+ return l.end(), e.queue.submit([c.finish()]), o;
222
+ }
223
+ bindings() {
224
+ return this.#n;
225
+ }
226
+ shader(e, n) {
227
+ let r = n + e, i = this.#i.get(r);
228
+ if (i) return i;
229
+ if (!e.includes("terrainPbrSurfaces") || [
230
+ o,
231
+ s,
232
+ c
233
+ ].some((t) => e.split(t).length !== 2)) throw new t("unsupported", "Terrain displacement needs the terrain lit shader with TerrainMaterials; attach TerrainMaterials first");
234
+ let a = [...e.matchAll(/var terrainWeights(\d):texture_2d<f32>;/g)].length, l = u(n, a, this.options.shadows ?? !0), d = (e.includes("wrap:vec4f") ? l.replace("fract(p.xz*s)", "fract((p.xz+layerRules[layer].wrap.xz)*s)").replace("xz*s,i32(layer)", "(xz+layerRules[layer].wrap.xz)*s,i32(layer)").replace("xz*layerRules[layer].params.x,i32(layer)", "(xz+layerRules[layer].wrap.xz)*layerRules[layer].params.x,i32(layer)") : l) + e.replace(o, "@fragment fn fragment(i:Output)->@location(0) vec4f {var j=i;j.position=terrainDisplace(i.position,normalize(i.normal));return terrainPbrShade(j);}").replace(s, "var dx=dpdx(position);var dy=dpdy(position);if(terrainDisplaced){dx=terrainDisplaceDx;dy=terrainDisplaceDy;}").replace(c, "let direct=terrainDisplaceShadow*(");
235
+ return this.#i.size >= 16 && this.#i.clear(), this.#i.set(r, d), d;
236
+ }
237
+ finish(e) {
238
+ return e.includes("fn terrainDisplaceShadowPoint") ? e.replace(/shadowLit\(([^,()]+),i\.position,/g, "shadowLit($1,terrainDisplaceShadowPoint(i.position),") : e;
239
+ }
240
+ onDeviceRestored(e) {
241
+ this.#o(), this.setup(e);
242
+ }
243
+ #o() {
244
+ this.#e?.destroy(), this.#t?.destroy(), this.#e = this.#t = void 0, this.#n = [];
245
+ }
246
+ dispose() {
247
+ this.disposed || (this.disposed = !0, this.#r?.(), this.#r = void 0, this.owner?.sceneOf(this)?.removePlugin(this.name), this.#o(), this.#i.clear(), this.owner = void 0);
248
+ }
249
+ [Symbol.dispose ?? Symbol()]() {
250
+ this.dispose();
251
+ }
252
+ };
253
+ //#endregion
254
+ export { p as TerrainDisplacement };
@@ -0,0 +1,86 @@
1
+ /** Dune kinds: ridges across the wind where sand is plentiful, isolated crescents where it is scarce (Werner 1995). */
2
+ export type DuneType = 'transverse' | 'barchan';
3
+ /** Options for {@link duneField}. Lengths in metres, angles in degrees. */
4
+ export interface DuneFieldOptions {
5
+ /** Cells along x and z (the grid has `width * depth` heights, row by row along x). */
6
+ readonly width: number;
7
+ readonly depth: number;
8
+ /** Metres between neighbouring heights. Default 1. */
9
+ readonly cellSize?: number;
10
+ /** World x and z of the first height. Default 0, 0. */
11
+ readonly origin?: readonly [number, number];
12
+ /** Direction the wind blows toward, degrees from +x toward +z. Default 90 (toward +z). */
13
+ readonly wind?: number;
14
+ readonly type?: DuneType;
15
+ /** Crest height in metres. Default 4. */
16
+ readonly height?: number;
17
+ /** Crest-to-crest spacing along the wind (transverse) or mean distance between dunes (barchan). Default 70. */
18
+ readonly spacing?: number;
19
+ /** Steepest windward slope in degrees, 3 to 20. Default 12 (Sauermann et al. 2001). */
20
+ readonly stoss?: number;
21
+ /** Slip face slope, the angle of repose of dry sand, 25 to 36 degrees. Default 32 (Bagnold 1941). */
22
+ readonly lee?: number;
23
+ /** How much crests wander and vary, 0 to 1. Default 0.35. */
24
+ readonly irregularity?: number;
25
+ /** Seed of the crest noise. Default 1. */
26
+ readonly seed?: number;
27
+ /** Metres over which each brink is rounded (see {@link duneProfile}). Default 0, a sharp brink. */
28
+ readonly round?: number;
29
+ /** Heights to build the dunes on (metres, the grid's layout); default flat 0. */
30
+ readonly base?: Float32Array;
31
+ /** Share of dune height per world point, 0 to 1 (no dunes where 0, as on wet sand). Default 1 everywhere. */
32
+ readonly amount?: (x: number, z: number) => number;
33
+ }
34
+ /**
35
+ * Height of one dune profile `p` metres downwind of its windward toe: a half cosine up the stoss side (steepest slope
36
+ * `tanStoss` at its middle, level at the crest), then the slip face at `tanLee` down to the floor, its toe rounded over
37
+ * `toe` metres. `round` (metres, default 0) rounds the brink over that length, as on old dunes whose crest the wind
38
+ * has blunted: a parabola level where it leaves the stoss side and meeting the slip face at its slope. 0 outside.
39
+ */
40
+ export declare function duneProfile(p: number, height: number, tanStoss: number, tanLee: number, toe?: number, round?: number): number;
41
+ /** Lengths of a dune of `height`: windward side, slip face and their sum, in metres. */
42
+ export declare function duneLengths(height: number, stoss?: number, lee?: number): {
43
+ stoss: number;
44
+ lee: number;
45
+ total: number;
46
+ };
47
+ /**
48
+ * A height field of wind-built dunes, row by row along x (`width` heights a row, `depth` rows), added to `base`.
49
+ * Transverse: ridges across the wind every `spacing` metres with wandering, varying crests; a ridge that would not fit
50
+ * its spacing at full height is lowered so its windward side and slip face fit. Barchan: crescents one per `spacing`
51
+ * cell with horns pointing downwind, width about 11 heights (Hersen et al. 2002).
52
+ * @throws RangeError for a bad size, an angle outside its range or a height of 0 or less.
53
+ */
54
+ export declare function duneField(options: DuneFieldOptions): Float32Array;
55
+ /**
56
+ * One barchan of crest height `height` centred (crest) at u = 0, v = 0: a stoss side rising along the wind, a slip face
57
+ * at `tanLee` whose brink curves downwind toward the horns, and horns trailing downwind at the sides. Width about 11
58
+ * heights, as Hersen et al. 2002 measured.
59
+ */
60
+ export declare function barchan(u: number, v: number, height: number, tanStoss: number, tanLee: number, round?: number): number;
61
+ /** Options for {@link duneHill}. Lengths in metres, angles in degrees. */
62
+ export interface DuneHillOptions {
63
+ /** World x and z of the crest. */
64
+ readonly crest: readonly [number, number];
65
+ /** Crest height above the floor. */
66
+ readonly height: number;
67
+ /** Direction the wind blows toward, degrees from +x toward +z, as {@link DuneFieldOptions.wind}. Default 90. */
68
+ readonly wind?: number;
69
+ /** Half the hill's width across the wind; the crest falls off to its ends as a raised cosine. Default 5 heights. */
70
+ readonly halfWidth?: number;
71
+ /** Steepest windward slope, 3 to 20 degrees. Default 12. */
72
+ readonly stoss?: number;
73
+ /** Slip face slope, 20 to 36 degrees (a lower value for an old face that has slumped and settled). Default 30. */
74
+ readonly lee?: number;
75
+ /** Metres over which the brink is rounded. Default a third of the height. */
76
+ readonly round?: number;
77
+ }
78
+ /**
79
+ * Height at world (x, z) of one big isolated dune: a long windward side, a rounded crest and a steeper lee face, its
80
+ * crest falling off to the ends across the wind. The shape the hills of a coastal dune field take when the wind comes
81
+ * mostly from one side (Bagnold 1941; Sauermann, Kroy and Herrmann 2001); add it to a {@link duneField} or real heights.
82
+ * @throws RangeError for a height of 0 or less or an angle outside its range.
83
+ */
84
+ export declare function duneHill(x: number, z: number, options: DuneHillOptions): number;
85
+ /** Steepest slope in degrees of a height grid around cell (i, j), from central differences. */
86
+ export declare function slopeAt(heights: Float32Array, width: number, i: number, j: number, cellSize?: number): number;
package/dist/dunes.js ADDED
@@ -0,0 +1,88 @@
1
+ //#region src/dunes.ts
2
+ var e = (e, t) => {
3
+ let n = Math.imul(e ^ Math.imul(t, 2654435761), 2246822507);
4
+ return n ^= n >>> 13, n = Math.imul(n, 3266489909), n ^= n >>> 16, (n >>> 0) / 4294967296;
5
+ };
6
+ function t(t, n) {
7
+ let r = Math.floor(t), i = t - r, a = i * i * (3 - 2 * i);
8
+ return (e(r, n) * (1 - a) + e(r + 1, n) * a) * 2 - 1;
9
+ }
10
+ function n(t, n, r) {
11
+ let i = Math.floor(t), a = Math.floor(n), o = t - i, s = n - a, c = o * o * (3 - 2 * o), l = s * s * (3 - 2 * s), u = (t, n) => e(Math.imul(t, 73856093) ^ Math.imul(n, 19349663), r), d = u(i, a) * (1 - c) + u(i + 1, a) * c, f = u(i, a + 1) * (1 - c) + u(i + 1, a + 1) * c;
12
+ return (d * (1 - l) + f * l) * 2 - 1;
13
+ }
14
+ function r(e, t, n, r, i = .6, a = 0) {
15
+ if (t <= 0 || e <= 0) return 0;
16
+ let o = t * Math.PI / (2 * n), s = Math.max(0, Math.min(a / 2, o / 2, t / r / 2)), c = o - s, l = (e) => t * (1 - Math.cos(Math.PI * e / o)) / 2;
17
+ if (e <= c) return l(e);
18
+ let u = l(c), d = s > 0 ? t * Math.PI / (2 * o) * Math.sin(Math.PI * c / o) : 0, f = s > 0 ? (d + r) / (4 * s) : 0, p = u + s * (d - r);
19
+ if (e < o + s) return u + d * (e - c) - f * (e - c) ** 2;
20
+ let m = p - (e - o - s) * r, h = i * r / 2;
21
+ if (m >= h) return m;
22
+ let g = h - m;
23
+ return g >= 2 * h ? 0 : (2 * h - g) * (2 * h - g) / (4 * h);
24
+ }
25
+ function i(e, t = 12, n = 32) {
26
+ let r = e * Math.PI / (2 * Math.tan(t * Math.PI / 180)), i = e / Math.tan(n * Math.PI / 180);
27
+ return {
28
+ stoss: r,
29
+ lee: i,
30
+ total: r + i
31
+ };
32
+ }
33
+ function a(a) {
34
+ let { width: s, depth: c } = a, l = a.cellSize ?? 1, [u, d] = a.origin ?? [0, 0], f = a.type ?? "transverse", p = a.height ?? 4, m = a.spacing ?? 70, h = a.stoss ?? 12, g = a.lee ?? 32, _ = a.irregularity ?? .35, v = a.seed ?? 1, y = a.round ?? 0;
35
+ if (!(y >= 0)) throw RangeError("duneField: round is out of range; pass 0 or more metres.");
36
+ if (!Number.isInteger(s) || !Number.isInteger(c) || s < 2 || c < 2 || s * c > 1 << 26) throw RangeError("duneField: width and depth are wrong; pass integers of 2 or more (at most 67,108,864 heights).");
37
+ if (!(l > 0) || !(p > 0) || !(m > 0)) throw RangeError("duneField: cellSize, height and spacing must be above 0.");
38
+ if (!(h >= 3 && h <= 20)) throw RangeError("duneField: stoss is out of range; pass a windward slope of 3 to 20 degrees.");
39
+ if (!(g >= 25 && g <= 36)) throw RangeError("duneField: lee is out of range; pass an angle of repose of 25 to 36 degrees.");
40
+ if (!(_ >= 0 && _ <= 1)) throw RangeError("duneField: irregularity is out of range; pass 0 to 1.");
41
+ if (f !== "transverse" && f !== "barchan") throw RangeError("duneField: unknown type; pass 'transverse' or 'barchan'.");
42
+ if (a.base && a.base.length !== s * c) throw RangeError("duneField: base must hold width * depth heights.");
43
+ let b = a.base ? Float32Array.from(a.base) : new Float32Array(s * c), x = (a.wind ?? 90) * Math.PI / 180, S = [Math.cos(x), Math.sin(x)], C = [-S[1], S[0]], w = Math.tan(h * Math.PI / 180), T = Math.tan(g * Math.PI / 180);
44
+ for (let x = 0; x < c; x++) for (let c = 0; c < s; c++) {
45
+ let E = u + c * l, D = d + x * l, O = E * S[0] + D * S[1], k = E * C[0] + D * C[1], A = a.amount ? Math.min(1, Math.max(0, a.amount(E, D))) : 1;
46
+ if (A <= 0) continue;
47
+ let j = 0;
48
+ if (f === "transverse") {
49
+ let e = Math.floor(O / m);
50
+ for (let n = e - 1; n <= e + 1; n++) {
51
+ let e = _ * .25 * m * t(k / (2.5 * m) + n * 7.31, v), a = p * (1 + _ * .6 * t(k / (1.7 * m) + n * 3.77, v + 1)), o = Math.min(a, m / i(1, h, g).total), { stoss: s } = i(o, h, g), c = n * m + e - s;
52
+ j = Math.max(j, r(O - c, o, w, T, .6, y));
53
+ }
54
+ } else {
55
+ let t = Math.floor(O / m), n = Math.floor(k / m);
56
+ for (let r = t - 1; r <= t + 1; r++) for (let t = n - 1; t <= n + 1; t++) {
57
+ let n = Math.imul(r, 92837111) ^ Math.imul(t, 689287499);
58
+ if (e(n, v + 2) < .35 * _) continue;
59
+ let i = p * (1 + _ * .5 * (e(n, v + 3) * 2 - 1)), a = (r + .5 + _ * .3 * (e(n, v + 4) - .5)) * m, s = (t + .5 + _ * .3 * (e(n, v + 5) - .5)) * m;
60
+ j = Math.max(j, o(O - a, k - s, i, w, T, y));
61
+ }
62
+ }
63
+ j += p * .06 * _ * n(E / (.3 * m), D / (.3 * m), v + 9), b[x * s + c] += Math.max(0, j) * A;
64
+ }
65
+ return b;
66
+ }
67
+ function o(e, t, n, i, a, o = 0) {
68
+ let s = 5.5 * n, c = t / s;
69
+ if (Math.abs(c) >= 1) return 0;
70
+ let l = n * (1 - c * c) ** 1.5, u = 1.2 * n * c * c * (s / n) * .5, d = r(e - u + l * Math.PI / (2 * i), l, i, a, .6, o), f = 1 - Math.min(1, Math.abs(Math.abs(c) - .72) / .22), p = n * .3 * f * f * (3 - 2 * f);
71
+ return p > 0 && e > u && (d = Math.max(d, p * Math.max(0, 1 - (e - u) / (4 * n)))), d;
72
+ }
73
+ function s(e, t, n) {
74
+ let i = n.height, a = n.stoss ?? 12, o = n.lee ?? 30, s = n.halfWidth ?? 5 * i;
75
+ if (!(i > 0) || !(s > 0)) throw RangeError("duneHill: height and halfWidth must be above 0; pass metres.");
76
+ if (!(a >= 3 && a <= 20)) throw RangeError("duneHill: stoss is out of range; pass 3 to 20 degrees.");
77
+ if (!(o >= 20 && o <= 36)) throw RangeError("duneHill: lee is out of range; pass 20 to 36 degrees.");
78
+ let c = (n.wind ?? 90) * Math.PI / 180, l = e - n.crest[0], u = t - n.crest[1], d = l * Math.cos(c) + u * Math.sin(c), f = -l * Math.sin(c) + u * Math.cos(c), p = Math.min(1, Math.abs(f) / s), m = i * (1 + Math.cos(Math.PI * p)) / 2;
79
+ if (m <= 0) return 0;
80
+ let h = Math.tan(a * Math.PI / 180);
81
+ return r(d + m * Math.PI / (2 * h), m, h, Math.tan(o * Math.PI / 180), .6, (n.round ?? i / 3) * m / i);
82
+ }
83
+ function c(e, t, n, r, i = 1) {
84
+ let a = e.length / t, o = (n, r) => e[Math.min(a - 1, Math.max(0, r)) * t + Math.min(t - 1, Math.max(0, n))], s = (o(n + 1, r) - o(n - 1, r)) / (2 * i), c = (o(n, r + 1) - o(n, r - 1)) / (2 * i);
85
+ return Math.atan(Math.hypot(s, c)) * 180 / Math.PI;
86
+ }
87
+ //#endregion
88
+ export { o as barchan, a as duneField, s as duneHill, i as duneLengths, r as duneProfile, c as slopeAt };
@@ -0,0 +1,182 @@
1
+ import { type GridFill, type GridHeightField } from './height-grid.js';
2
+ /** One decoded raster page: `openTIFF(bytes).read(0)` from `@margoengine/decoders/tiff` has this shape. */
3
+ export interface ElevationRaster {
4
+ /** Samples across. */
5
+ readonly width: number;
6
+ /** Samples down. */
7
+ readonly height: number;
8
+ /** Interleaved samples, row 0 first (a Float32Array of a float GeoTIFF, an Int16Array of SRTM, any numbers). */
9
+ readonly samples: ArrayLike<number>;
10
+ /** Samples per pixel (bands, interleaved). Default 1. */
11
+ readonly samplesPerPixel?: number;
12
+ }
13
+ /** Where the raster lies: `readGeoTIFF(page)` from `@margoengine/decoders/geotiff` has this shape. */
14
+ export interface ElevationGeoreference {
15
+ /** Raster (i, j) to longitude and latitude: lon = a i + b j + c, lat = d i + e j + f. */
16
+ readonly transform: readonly [number, number, number, number, number, number] | null;
17
+ /** `'area'` (sample at the cell centre) or `'point'` (sample at the raster point). */
18
+ readonly raster: 'area' | 'point';
19
+ /** A sample value that means no data, or null. */
20
+ readonly noData: number | null;
21
+ /** The coordinate system; only `'geographic'` (degrees) is read. */
22
+ readonly crs: {
23
+ readonly model: string;
24
+ readonly epsg: number | null;
25
+ readonly citation: string | null;
26
+ };
27
+ /** Unit of the samples, null when the file does not say (then metres are assumed). */
28
+ readonly verticalUnits: 'metre' | 'foot' | 'us-foot' | null;
29
+ }
30
+ /** A latitude and longitude box, degrees (north positive, east positive). */
31
+ export interface GeoWindow {
32
+ readonly south: number;
33
+ readonly west: number;
34
+ readonly north: number;
35
+ readonly east: number;
36
+ }
37
+ /** Options of {@link readElevation}. */
38
+ export interface ElevationOptions {
39
+ /** Keeps only the samples whose cells meet this box (plus one ring, so a lookup reaches its edge). Default the whole raster. */
40
+ readonly window?: GeoWindow;
41
+ /** Which band of a multi-band raster. Default 0. */
42
+ readonly band?: number;
43
+ /**
44
+ * The vertical datum the heights are measured from, as text. A GeoTIFF rarely says; name it from the data's own
45
+ * description (for example `'Lake Superior Low Water Datum, 183.2 m IGLD 1985'` for the NOAA NCEI Great Lakes grids).
46
+ * Default `'unknown'`.
47
+ */
48
+ readonly datum?: string;
49
+ /**
50
+ * Multiplies every sample to give metres up: -1 for a file of positive depths. Default 1, or 0.3048 for feet and
51
+ * 1200 / 3937 for US survey feet when the file's VerticalUnits says so.
52
+ */
53
+ readonly scale?: number;
54
+ }
55
+ /** A cropped elevation grid in geographic coordinates. */
56
+ export interface Elevation {
57
+ /** Samples across (west to east). */
58
+ readonly width: number;
59
+ /** Samples down (north to south). */
60
+ readonly height: number;
61
+ /** Heights in metres up from {@link Elevation.datum}, row 0 the north row; NaN where the data has none. */
62
+ readonly heights: Float32Array;
63
+ /** Longitude of the first column's samples and latitude of the first row's, degrees. */
64
+ readonly west: number;
65
+ readonly north: number;
66
+ /** Degrees between neighbouring samples, along a row (east) and down a column (south), both positive. */
67
+ readonly step: readonly [number, number];
68
+ /** Longitude of the last column's samples and latitude of the last row's, degrees. */
69
+ readonly east: number;
70
+ readonly south: number;
71
+ /** The vertical datum, as given. */
72
+ readonly datum: string;
73
+ /** The horizontal datum: the file's EPSG code and name. */
74
+ readonly crs: {
75
+ readonly epsg: number | null;
76
+ readonly citation: string | null;
77
+ };
78
+ /** Samples with no data. */
79
+ readonly missing: number;
80
+ /** Lowest and highest valid height, metres. */
81
+ readonly min: number;
82
+ readonly max: number;
83
+ /** Bilinear height at a latitude and longitude, metres; NaN outside the samples or next to a missing one. */
84
+ at(lat: number, lon: number): number;
85
+ }
86
+ /**
87
+ * Crops a georeferenced raster band to a latitude and longitude window and names its vertical datum.
88
+ * @example
89
+ * import { openTIFF } from '@margoengine/decoders/tiff';
90
+ * import { readGeoTIFF } from '@margoengine/decoders/geotiff';
91
+ * const page = openTIFF(bytes).read(0);
92
+ * const lake = readElevation(page, readGeoTIFF(page), {
93
+ * window: { south: 46.9, west: -86.0, north: 47.5, east: -85.0 },
94
+ * datum: 'Lake Superior Low Water Datum, 183.2 m IGLD 1985',
95
+ * });
96
+ * lake.at(46.9983, -85.11); // metres below the datum are negative
97
+ * @throws RangeError for a raster that is not georeferenced in latitude and longitude, is rotated, has the wrong
98
+ * number of samples, or a window that misses it.
99
+ */
100
+ export declare function readElevation(raster: ElevationRaster, georeference: ElevationGeoreference, options?: ElevationOptions): Elevation;
101
+ /** An ellipsoid: semi-major axis `a`, metres, and flattening `f`. */
102
+ export interface Ellipsoid {
103
+ readonly a: number;
104
+ readonly f: number;
105
+ }
106
+ /** GRS 80 (Moritz 1980), the ellipsoid of NAD 83 (EPSG:4269). */
107
+ export declare const GRS80: Ellipsoid;
108
+ /** WGS 84 (NIMA TR8350.2), the ellipsoid of GPS (EPSG:4326). Within 0.1 mm of GRS 80. */
109
+ export declare const WGS84: Ellipsoid;
110
+ /** A site on the earth: latitude and longitude, degrees, and height above the ellipsoid, metres. */
111
+ export interface Site {
112
+ readonly lat: number;
113
+ readonly lon: number;
114
+ readonly height?: number;
115
+ }
116
+ /** A local tangent plane at a site, in metres: x east, y up, z south (north is -z), the site at the origin. */
117
+ export interface LocalFrame {
118
+ readonly site: Required<Site>;
119
+ readonly ellipsoid: Ellipsoid;
120
+ /** World [x, y, z] metres of a latitude, longitude and ellipsoid height. */
121
+ toLocal(lat: number, lon: number, height?: number): [number, number, number];
122
+ /** [lat, lon, height] of world (x, y, z) metres; `y` defaults to 0 (a point on the plane). */
123
+ toGeographic(x: number, z: number, y?: number): [number, number, number];
124
+ }
125
+ /**
126
+ * The local east, north, up frame at a site (Hofmann-Wellenhof et al. 2008, section 8.2.2), turned to the engine's axes:
127
+ * x east, y up, z south. Exact on the ellipsoid in both directions (Bowring's 1976 inverse, iterated to below 0.1 mm).
128
+ * @example
129
+ * const frame = localFrame({ lat: 46.9983, lon: -85.11 });
130
+ * frame.toLocal(47.0073, -85.11); // about [0, -0.08, -1000]: 1 km north, 8 cm below the plane by the curve
131
+ * @throws RangeError for a latitude outside -90 to 90, a non-finite longitude or height, or a bad ellipsoid.
132
+ */
133
+ export declare function localFrame(site: Site, ellipsoid?: Ellipsoid): LocalFrame;
134
+ /** Options of {@link elevationField}. */
135
+ export interface ElevationFieldOptions {
136
+ /** The site at the world origin, or a frame from {@link localFrame}. */
137
+ readonly site: Site | LocalFrame;
138
+ /**
139
+ * World [x, z] extent of the grid, metres. Default the largest box the elevation covers whose centre is the site's
140
+ * (so the world origin is the site), a whole number of `spacing` each side, so the site is a texel.
141
+ */
142
+ readonly size?: readonly [number, number];
143
+ /** World x and z of the grid's minimum corner. Default `-size / 2` (the site at the centre). */
144
+ readonly origin?: readonly [number, number];
145
+ /** Metres between texels of the resampled grid. Default the source's own spacing north to south at the site. */
146
+ readonly spacing?: number;
147
+ /** How a missing sample is filled, as `gridHeightField`'s `fill`. Default `'nearest'`. */
148
+ readonly fill?: GridFill;
149
+ /**
150
+ * `false` (default): y is the height above the datum, so a level water surface at the datum stays flat at y = 0 across
151
+ * the whole window. `true`: y is the tangent plane's up, so the ground falls away by about d^2 / 2R (70 m at 30 km).
152
+ */
153
+ readonly curvature?: boolean;
154
+ /**
155
+ * Relief finer than the source cells, metres added to each resampled texel at its world (x, z): the engine's own
156
+ * procedural detail, never surveyed data. The result's `detailed` is true when it is given. Default none.
157
+ */
158
+ readonly detail?: (x: number, z: number) => number;
159
+ }
160
+ /** A height function in local metres resampled from an {@link Elevation}. */
161
+ export interface ElevationField extends GridHeightField {
162
+ /** The frame its world coordinates are in. */
163
+ readonly frame: LocalFrame;
164
+ /** The vertical datum heights are measured from (`'tangent plane'` when `curvature` is true). */
165
+ readonly datum: string;
166
+ /** Metres between the source samples (east, south) at the site: the finest surveyed relief the field holds. */
167
+ readonly surveyed: readonly [number, number];
168
+ /** Metres between the resampled texels. */
169
+ readonly spacing: number;
170
+ /** Whether procedural `detail` was added (relief below `surveyed` is then not survey data). */
171
+ readonly detailed: boolean;
172
+ }
173
+ /**
174
+ * Resamples an elevation onto a site's local tangent plane: a height function `(x, z) => y` in metres for `Terrain`,
175
+ * `heightfield`, `TerrainQuery` or the physics `TerrainBed` (its `elevations`), x east and z south of the site.
176
+ * @example
177
+ * const bed = elevationField(lake, { site: { lat: 46.9983, lon: -85.11 }, spacing: 90 });
178
+ * bed(0, 0); // the depth at the site, metres below the datum
179
+ * @throws RangeError for a size or origin the elevation does not cover sensibly, a spacing that is not positive, or more
180
+ * than 67,108,864 texels.
181
+ */
182
+ export declare function elevationField(elevation: Elevation, options: ElevationFieldOptions): ElevationField;