@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,1366 @@
1
+ // @margo/core-built 1.0.0
2
+ import {coreRequirement as __margoCoreRequirement,assertCore as __margoAssertCore} from '@margoengine/core/extension';
3
+ const l=(engine,version="1.0.0",source=import.meta.url)=>__margoRuntime(engine,version,source);
4
+ import { t as e } from "./lighting-layout-CaDtDa5G.js";
5
+ import { t } from "./errors-fc4i1pSL.js";
6
+ import { n, o as r, r as i, t as a } from "./hdr-format-DRhzGS7G.js";
7
+ import { t as o } from "./require-webgpu--tUXPsmA.js";
8
+ import { n as s, t as c } from "./mesh-patch-BThCHCeS.js";
9
+ import { engineRuntime as __margoRuntime, meshRuntime as u } from "@margoengine/core/extension";
10
+ import { finiteVector as d } from "@margoengine/math/validate";
11
+ import { MargoError as f } from "@margoengine/math/errors";
12
+ import { planeGeometry as p } from "@margoengine/geometry/primitives";
13
+ import { computeVertexNormals as m, toGeometry as h } from "@margoengine/geometry/utils";
14
+ //#region src/grid.ts
15
+ function g(e) {
16
+ if (!Number.isInteger(e) || e < 8 || e > 256 || e % 4) throw RangeError("Clipmap resolution must be a multiple of four in 8..256");
17
+ let t = e + 1, n = t ** 2, r = new Float32Array((n + e ** 2) * 2), i = new Uint32Array(e ** 2 * 12), a = new Uint32Array(e ** 2 * 9);
18
+ for (let t = 0, n = 0; t <= e; t++) for (let i = 0; i <= e; i++) r[n++] = i - e / 2, r[n++] = t - e / 2;
19
+ for (let t = 0, i = n * 2; t < e; t++) for (let n = 0; n < e; n++) r[i++] = n + .5 - e / 2, r[i++] = t + .5 - e / 2;
20
+ for (let r = 0, o = 0, s = 0; r < e; r++) for (let c = 0; c < e; c++) {
21
+ let l = r * t + c, u = l + 1, d = l + t, f = d + 1, p = n + r * e + c, m = [
22
+ l,
23
+ d,
24
+ p,
25
+ d,
26
+ f,
27
+ p,
28
+ f,
29
+ u,
30
+ p,
31
+ u,
32
+ l,
33
+ p
34
+ ];
35
+ i.set(m, o), o += 12, (c < e / 4 || c >= e * 3 / 4 || r < e / 4 || r >= e * 3 / 4) && (a.set(m, s), s += 12);
36
+ }
37
+ return {
38
+ vertices: r,
39
+ center: i,
40
+ ring: a
41
+ };
42
+ }
43
+ //#endregion
44
+ //#region ../shared/light-terms.js
45
+ var _ = "a2/(3.14159265*pow(max(dot(cross(n,h),cross(n,h)),step(nh,0.0))+a2*nh*nh,2.0))", v = "2*nl*nv/max(nl*sqrt(a2+(1-a2)*nv*nv)+nv*sqrt(a2+(1-a2)*nl*nl),1e-30)", y = "\nstruct Frame {camera:mat4x4f,eye:vec4f,light:vec4f,radiance:vec4f,grid:vec4f,offset:vec4f,map:vec4f,heights:vec4f,ambient:vec4f}\nstruct Layer {heightSlope:vec4f,params:vec4f}\n@group(0) @binding(0) var<uniform> frame:Frame;\n@group(0) @binding(1) var heightMap:texture_2d<f32>;\n@group(0) @binding(2) var normalMap:texture_2d<f32>;\n@group(0) @binding(3) var terrainLayers:texture_2d_array<f32>;\n@group(0) @binding(4) var terrainSampler:sampler;\n@group(0) @binding(5) var<storage,read> layerRules:array<Layer>;\nfn height(position:vec2f)->f32 {\n let dimensions=vec2i(textureDimensions(heightMap));let uv=clamp((position-frame.map.xy)/frame.map.zw,vec2f(0),vec2f(1));let pixel=uv*vec2f(dimensions-vec2i(1));let lo=vec2i(floor(pixel));let hi=min(lo+vec2i(1),dimensions-vec2i(1));let t=fract(pixel);\n let a=mix(textureLoad(heightMap,lo,0).r,textureLoad(heightMap,vec2i(hi.x,lo.y),0).r,t.x);let b=mix(textureLoad(heightMap,vec2i(lo.x,hi.y),0).r,textureLoad(heightMap,hi,0).r,t.x);\n return mix(a,b,t.y)*frame.heights.x+frame.heights.y;\n}\nfn terrainCatmull(t:f32)->vec4f {let t2=t*t;let t3=t2*t;return vec4f(-0.5*t3+t2-0.5*t,1.5*t3-2.5*t2+1.0,-1.5*t3+2.0*t2+0.5*t,0.5*t3-0.5*t2);}\nfn terrainCubic(position:vec2f)->f32 {\n let dimensions=vec2i(textureDimensions(heightMap));let uv=clamp((position-frame.map.xy)/frame.map.zw,vec2f(0),vec2f(1));let pixel=uv*vec2f(dimensions-vec2i(1));let lo=vec2i(floor(pixel));\n let wx=terrainCatmull(fract(pixel.x));let wy=terrainCatmull(fract(pixel.y));var h=0.0;\n for(var j=0;j<4;j++){for(var k=0;k<4;k++){h+=wx[k]*wy[j]*textureLoad(heightMap,clamp(lo+vec2i(k-1,j-1),vec2i(0),dimensions-vec2i(1)),0).r;}}\n return h*frame.heights.x+frame.heights.y;\n}\nfn terrainMorph(g:vec2f)->vec3f {\n let edge=max(abs(g.x),abs(g.y));let morph=clamp((edge-frame.grid.w*0.5+2)/2,0.0,1.0);\n return vec3f(mix(g,round(g*0.5)*2,morph),select(0.0,1.0,edge<=frame.grid.w*0.25));\n}\nfn terrainMorphXZ(m:vec3f)->vec2f {return frame.grid.xy+m.xy*frame.grid.z+frame.offset.xy*m.z;}\nstruct Output {@builtin(position) @invariant clip:vec4f,@location(0) position:vec3f,@location(1) normal:vec3f,@location(2) color:vec3f,@location(3) material:vec4f}\n@vertex fn vertex(@location(0) grid:vec2f)->Output {\n var m=terrainMorph(grid);var lift=0.0;let centre=fract(grid.x)!=0.0;\n if(centre){\n let a=terrainMorph(grid-vec2f(0.5));let b=terrainMorph(grid+vec2f(0.5,-0.5));let c=terrainMorph(grid+vec2f(-0.5,0.5));let d=terrainMorph(grid+vec2f(0.5));\n let ad=(height(terrainMorphXZ(a))+height(terrainMorphXZ(d)))*0.5;let bc=(height(terrainMorphXZ(b))+height(terrainMorphXZ(c)))*0.5;\n let r=terrainCubic(terrainMorphXZ((a+b+c+d)*0.25));let along=abs(r-ad)<abs(r-bc);\n m=select((b+c)*0.5,(a+d)*0.5,along);lift=select(bc,ad,along);\n }\n let aligned=m.xy;let inner=m.z;\n let xz=frame.grid.xy+aligned*frame.grid.z+frame.offset.xy*inner;let position=vec3f(xz.x,select(height(xz),lift,centre),xz.y);\n let step=frame.map.zw/max(vec2f(textureDimensions(heightMap))-1,vec2f(1));\n var normal=normalize(vec3f((height(xz-vec2f(step.x,0))-height(xz+vec2f(step.x,0)))/(2*step.x),1,(height(xz-vec2f(0,step.y))-height(xz+vec2f(0,step.y)))/(2*step.y)));\n if(frame.offset.w>0.5){let dimensions=vec2i(textureDimensions(normalMap));let uv=clamp((xz-frame.map.xy)/frame.map.zw,vec2f(0),vec2f(1));let sampled=textureLoad(normalMap,min(vec2i(uv*vec2f(dimensions)),dimensions-vec2i(1)),0).xyz*2-1;if(dot(sampled,sampled)>0.00001){normal=normalize(sampled);}}\n var o:Output;o.position=position;o.clip=frame.camera*vec4f(position,1);o.normal=normal;o.color=vec3f(1);o.material=vec4f(0.9,0,1,1);return o;\n}\n", b = "{let hd=vec2i(textureDimensions(terrainHoles));if(textureLoad(terrainHoles,clamp(vec2i(floor((i.position.xz-frame.map.xy)/frame.map.zw*vec2f(hd))),vec2i(0),hd-vec2i(1)),0).r<0.5){discard;}}", x = "if(any(i.position.xz<frame.map.xy)||any(i.position.xz>frame.map.xy+frame.map.zw)){discard;}", S = (e) => e.replace("struct Layer {heightSlope:vec4f,params:vec4f}", "struct Layer {heightSlope:vec4f,params:vec4f,surface:vec4f}"), C = "o.clip=frame.camera*vec4f(position,1);", w = "let terrainE=frame.view.xy+aligned*frame.grid.z+frame.offset.xy*inner;o.eye=vec3f(terrainE.x,position.y-frame.view.z,terrainE.y);o.clip=frame.camera*vec4f(o.eye,0)+frame.column;", T = (e) => e.includes("anchor:vec4f,view:vec4f") ? e : e.replace("ambient:vec4f}", "ambient:vec4f,anchor:vec4f,view:vec4f,column:vec4f}").replace(/struct Layer \{([^}]*)\}/, "struct Layer {$1,wrap:vec4f,tone:vec4f,eyeWrap:vec4f,eyeTone:vec4f}").replace("@location(3) material:vec4f}", "@location(3) material:vec4f,@location(12) eye:vec3f}").replace(C, w).replace("fn terrainRockP(p:vec3f)->vec3f {return p;}", "fn terrainRockP(p:vec3f)->vec3f {return p+vec3f(frame.anchor.x,frame.anchor.z,frame.anchor.y);}").replace("fn terrainPatchXZ(p:vec3f)->vec2f {return p.xz;}", "fn terrainPatchXZ(p:vec3f)->vec2f {return p.xz+frame.anchor.xy;}").split("let p=position*scale;").join("let p=(position+layerRules[layer].wrap.xyz)*scale;").replace("let p=position*m;let q=position*m*0.302;", "let p=(position+layerRules[layer].wrap.xyz)*layerRules[layer].params.x/24.0;let q=p*0.302+layerRules[layer].tone.xyz;"), E = "@fragment fn fragment(i:Output)->@location(0) vec4f {", D = "terrainEyeOn=true;terrainEyeAt=i.eye;terrainEyeLocal=i.position;", O = (e) => e.includes("var<private> terrainEyeOn:bool;") || !e.includes("eye:vec3f}") ? e : "var<private> terrainEyeOn:bool;var<private> terrainEyeAt:vec3f;var<private> terrainEyeLocal:vec3f;\nfn terrainTexAt(p:vec3f)->vec3f {return select(p,terrainEyeAt+(p-terrainEyeLocal),terrainEyeOn);}\nfn terrainTexPoint(p:vec3f,l:u32)->vec3f {return terrainTexAt(p)+select(layerRules[l].wrap.xyz,layerRules[l].eyeWrap.xyz,terrainEyeOn);}\nfn terrainToneOf(l:u32)->vec3f {return select(layerRules[l].tone.xyz,layerRules[l].eyeTone.xyz,terrainEyeOn);}\n" + e.replace(E, E + D).replace(/\(position\+layerRules\[layer\]\.wrap\.xyz\)/g, "terrainTexPoint(position,layer)").replace(/layerRules\[layer\]\.tone\.xyz/g, "terrainToneOf(layer)").replace(/(dpd[xy](Fine)?)\(position\)/g, "$1(terrainTexAt(position))"), k = "\nvar<private> terrainRelief:f32;var<private> terrainRepeat:f32;\nfn terrainMacro(p:vec2f,q:vec2f,dx:vec2f,dy:vec2f,m:f32,layer:u32,top:f32,norm:f32)->f32 {\n let luma=vec3f(0.2126,0.7152,0.0722);let w=dot(textureSampleLevel(terrainLayers,terrainSampler,q,i32(layer),max(top-3.0,0.0)).rgb,luma)*norm;\n let k=w*16.0;let i=floor(k);let t=smoothstep(0.2,0.8,k-i);\n let a=textureSampleGrad(terrainLayers,terrainSampler,p+sin(vec2f(3,7)*i),i32(layer),dx*m,dy*m).rgb;\n let b=textureSampleGrad(terrainLayers,terrainSampler,p+sin(vec2f(3,7)*(i+1.0)),i32(layer),dx*m,dy*m).rgb;\n return dot(mix(a,b,t),luma)*norm*w;\n}\nfn terrainReliefTap(p:vec2f,layer:u32,level:u32,size:i32)->f32 {\n let st=p*f32(size)-0.5;let i=floor(st);let f=st-i;let r=vec2f(1.0)-f;\n let a=r*r*r/6.0;let b=(3.0*f*f*f-6.0*f*f+4.0)/6.0;let d=f*f*f/6.0;let c=vec2f(1.0)-a-b-d;\n let wx=vec4f(a.x,b.x,c.x,d.x);let wy=vec4f(a.y,b.y,c.y,d.y);let first=vec2i(i)-1;var h=0.0;\n for(var y=0;y<4;y++){for(var x=0;x<4;x++){\n let t=((first+vec2i(x,y))%size+size)%size;\n h+=wx[x]*wy[y]*dot(textureLoad(terrainLayers,t,i32(layer),level).rgb,vec3f(0.2126,0.7152,0.0722));\n }}\n return h;\n}\nfn terrainReliefLuma(position:vec3f,projection:vec3f,layer:u32)->f32 {\n let scale=layerRules[layer].params.x;let p=position*scale;let texels=textureDimensions(terrainLayers).x;\n let level=u32(clamp(floor(log2(f32(texels)/128.0)),0.0,f32(textureNumLevels(terrainLayers)-1u)));let size=i32(texels>>level);\n var h=0.0;var total=0.0;\n if(projection.x>0.01){h+=projection.x*terrainReliefTap(p.zy,layer,level,size);total+=projection.x;}\n if(projection.y>0.01){h+=projection.y*terrainReliefTap(p.xz,layer,level,size);total+=projection.y;}\n if(projection.z>0.01){h+=projection.z*terrainReliefTap(p.xy,layer,level,size);total+=projection.z;}\n return h/max(total,0.00001);\n}\nfn terrainReliefTint(h:f32,layer:u32)->f32 {return h;}\nfn terrainSurface(sample:vec3f,position:vec3f,projection:vec3f,dx:vec3f,dy:vec3f,layer:u32)->vec4f {\n let s=layerRules[layer].surface;let luma=vec3f(0.2126,0.7152,0.0722);var color=sample;\n if(s.y>0.0){\n let top=f32(textureNumLevels(terrainLayers)-1u);let norm=1.0/max(dot(textureSampleLevel(terrainLayers,terrainSampler,vec2f(0.5),i32(layer),top).rgb,luma),0.0001);\n let m=s.z;let p=position*m;let q=position*m*0.302;var tone=0.0;\n if(projection.x>0.01){tone+=projection.x*terrainMacro(p.zy,q.yz,dx.zy,dy.zy,m,layer,top,norm);}\n if(projection.y>0.01){tone+=projection.y*terrainMacro(p.xz,q.zx,dx.xz,dy.xz,m,layer,top,norm);}\n if(projection.z>0.01){tone+=projection.z*terrainMacro(p.xy,q.yx,dx.xy,dy.xy,m,layer,top,norm);}\n color*=max(1.0-s.y+s.y*tone,0.0);\n }\n var h=dot(sample,luma);\n if(s.x>0.0){\n let near=1.0-smoothstep(1.0/128.0,1.0/64.0,layerRules[layer].params.x*max(length(dx),length(dy)));\n if(near>0.0){h=mix(h,terrainReliefTint(terrainReliefLuma(position,projection,layer),layer),near);}\n }\n return vec4f(color,h*s.x);\n}\nfn terrainBump(position:vec3f,normal:vec3f)->vec3f {\n let px=dpdxFine(position);let py=dpdyFine(position);let ax=1.0/max(length(px),1e-20);let ay=1.0/max(length(py),1e-20);\n let dx=px*ax;let dy=py*ay;let r1=cross(dy,normal);let r2=cross(normal,dx);let det=dot(dx,r1);\n let g=sign(det)*(dpdxFine(terrainRelief)*ax*r1+dpdyFine(terrainRelief)*ay*r2)*min(1.0,1.0/max(64.0*terrainRepeat*max(length(px),length(py)),1e-20));\n let bumped=abs(det)*normal-g*min(1.0,min(1.0,4.0*abs(det))*abs(det)/max(length(g),1e-20));\n return select(normal,normalize(bumped),dot(bumped,bumped)>0.0);\n}", A = (e, t = !1) => t ? e ? "let terrainN=terrainRock(i.position,normalize(i.normal));let base=terrainColor(i.position,normalize(i.normal))*terrainRockShade;let n=terrainBump(i.position,terrainN);" : "let n=terrainRock(i.position,normalize(i.normal));let base=terrainColor(i.position,normalize(i.normal))*terrainRockShade;" : e ? "let terrainN=normalize(i.normal);let base=terrainColor(i.position,terrainN);let n=terrainBump(i.position,terrainN);" : "let n=normalize(i.normal);let base=terrainColor(i.position,n);", j = (e) => {
46
+ let t = Math.fround(e).toPrecision(9);
47
+ return t.includes(".") || t.includes("e") ? t : t + ".0";
48
+ }, ee = (e) => {
49
+ let t = e.map >= 0;
50
+ return `
51
+ ${t ? `@group(0) @binding(${e.map}) var terrainStructure:texture_2d<f32>;` : ""}
52
+ var<private> terrainRockShade:f32=1.0;var<private> terrainRockLoose:f32=0.0;
53
+ fn terrainRockP(p:vec3f)->vec3f {return p;}
54
+ fn terrainRockHash(c:vec3i)->vec3f {
55
+ var v=bitcast<vec3u>(c)*1664525u+1013904223u;
56
+ v.x+=v.y*v.z;v.y+=v.z*v.x;v.z+=v.x*v.y;v^=v>>vec3u(16u);v.x+=v.y*v.z;v.y+=v.z*v.x;v.z+=v.x*v.y;
57
+ return vec3f(v>>vec3u(8u))/16777216.0;
58
+ }
59
+ fn terrainRockNoise(p:vec2f,seed:i32)->f32 {
60
+ let i=floor(p);let f=p-i;let u=f*f*f*(f*(f*6.0-15.0)+10.0);let c=vec2i(i);
61
+ return mix(mix(terrainRockHash(vec3i(c,seed)).x,terrainRockHash(vec3i(c+vec2i(1,0),seed)).x,u.x),mix(terrainRockHash(vec3i(c+vec2i(0,1),seed)).x,terrainRockHash(vec3i(c+vec2i(1,1),seed)).x,u.x),u.y);
62
+ }
63
+ fn terrainRockFacets(p:vec3f,normal:vec3f,size:f32,fp:f32,steep:f32,weight:f32,seed:vec3i)->vec3f {
64
+ let q=p*vec3f(1.0,0.42,1.0)/size;let base=vec3i(floor(q));var d1=1e9;var d2=1e9;var id=vec3i(0);var id2=vec3i(0);
65
+ for(var j=0;j<27;j++){
66
+ let cell=base+vec3i(j%3-1,(j/3)%3-1,j/9-1);let d=distance(q,vec3f(cell)+terrainRockHash(cell+seed));
67
+ if(d<d1){d2=d1;id2=id;d1=d;id=cell+seed;}else if(d<d2){d2=d;id2=cell+seed;}
68
+ }
69
+ let r=fp/size;let near=steep*weight*mix(1.0,0.3,smoothstep(0.006,0.04,r))*(1.0-smoothstep(0.12,0.4,r));
70
+ let own=0.5+0.5*smoothstep(0.0,0.14+2.0*r,d2-d1);
71
+ let tilt=mix(terrainRockHash(id2+vec3i(17,-31,7)),terrainRockHash(id+vec3i(17,-31,7)),own)*2.0-1.0;
72
+ let joint=mix(1.0,0.82+0.18*smoothstep(0.0,max(0.05,2.0*r),d2-d1),1.0-smoothstep(0.006,0.04,r));
73
+ let tone=mix(terrainRockHash(id2).y,terrainRockHash(id).y,own);
74
+ terrainRockShade*=mix(1.0,joint*(1.0+${j(e.tone)}*(tone-0.5)),near);
75
+ return normalize(normal+${j(e.relief)}*near*(tilt-normal*dot(tilt,normal)));
76
+ }
77
+ fn terrainRock(position:vec3f,normal:vec3f)->vec3f {
78
+ terrainRockShade=1.0;terrainRockLoose=0.0;
79
+ let p=terrainRockP(position);let fp=max(max(length(dpdx(position)),length(dpdy(position))),0.0001);
80
+ let steep=smoothstep(${j(e.slope[0])},${j(e.slope[1])},degrees(acos(clamp(normal.y,0.0,1.0))));
81
+ var m=normal/max(normal.y,0.05);
82
+ ${t ? ` let sd=vec2f(textureDimensions(terrainStructure));let e=frame.map.zw/sd;
83
+ let uv=clamp((position.xz-frame.map.xy)/frame.map.zw,vec2f(0.5)/sd,vec2f(1)-vec2f(0.5)/sd);
84
+ let c=textureSampleLevel(terrainStructure,terrainSampler,uv,0);let ex=vec2f(1.0/sd.x,0);let ez=vec2f(0,1.0/sd.y);
85
+ let gx=(textureSampleLevel(terrainStructure,terrainSampler,uv+ex,0).r-textureSampleLevel(terrainStructure,terrainSampler,uv-ex,0).r)/(2.0*e.x);
86
+ let gz=(textureSampleLevel(terrainStructure,terrainSampler,uv+ez,0).r-textureSampleLevel(terrainStructure,terrainSampler,uv-ez,0).r)/(2.0*e.y);
87
+ let depth=${j(e.gullies)}*mix(0.3,1.0,steep)*(1.0-smoothstep(0.25,0.6,fp/max(e.x,e.y)));
88
+ m.x+=depth*gx;m.z+=depth*gz;
89
+ terrainRockShade*=1.0-0.7*${j(e.tone)}*c.r*mix(0.4,1.0,steep);
90
+ terrainRockLoose=max(0.85*c.g,0.5*smoothstep(0.7,1.0,c.r)*(1.0-steep));
91
+ ` : ""}${e.strata > 0 ? ` let s=(p.y-dot(vec2f(${j(e.dip[0])},${j(e.dip[1])}),p.xz))/${j(e.strata)}+1.6*(terrainRockNoise(p.xz/${j(e.strata * 9)},7)-0.5)+0.35*(terrainRockNoise(p.xz/${j(e.strata * 2.3)},8)-0.5);
92
+ let ws=fwidth(s);let fade=1.0-smoothstep(0.1,0.3,ws);let bed=floor(s);let f=s-bed;let w=clamp(ws,0.03,0.12);
93
+ let keep=smoothstep(0.32,0.62,terrainRockNoise(p.xz/${j(e.strata * 4.5)}+vec2f(bed*17.13,bed*-9.71),9));
94
+ let bench=smoothstep(${j(.7)}-w,${j(.7)}+w,f)*(1.0-smoothstep(1.0-w,1.0,f));
95
+ let k=${j(e.ledges)}*steep*fade*keep;let factor=mix(1.0,mix(${j(1.3214285714285716)},${j(.25)},bench),k);
96
+ m.x*=factor;m.z*=factor;
97
+ terrainRockLoose=max(terrainRockLoose,bench*k*0.7);
98
+ terrainRockShade*=1.0+${j(e.tone)}*0.6*(terrainRockHash(vec3i(i32(bed),3,5)).x-0.5)*steep*(1.0-smoothstep(0.3,1.0,ws));
99
+ ` : ""}${e.undulation > 0 ? ` let flat=1.0-steep;var lift=0.0;
100
+ for(var oc=0;oc<3;oc++){
101
+ let l=select(select(8.0,20.0,oc==1),48.0,oc==0);let a=${j(e.undulation)}*select(select(0.2,0.45,oc==1),1.0,oc==0);
102
+ let k=flat*(1.0-smoothstep(0.05,0.25,fp/l));let q=p.xz/l;let i=floor(q);let f=q-i;let c=vec2i(i);
103
+ let u=f*f*f*(f*(f*6.0-15.0)+10.0);let du=30.0*f*f*(f*(f-2.0)+1.0);
104
+ let h00=terrainRockHash(vec3i(c,61+oc)).x;let h10=terrainRockHash(vec3i(c+vec2i(1,0),61+oc)).x;
105
+ let h01=terrainRockHash(vec3i(c+vec2i(0,1),61+oc)).x;let h11=terrainRockHash(vec3i(c+vec2i(1,1),61+oc)).x;
106
+ let h=mix(mix(h00,h10,u.x),mix(h01,h11,u.x),u.y);
107
+ let g=vec2f(du.x*mix(h10-h00,h11-h01,u.y),du.y*mix(h01-h00,h11-h10,u.x))*a/l;
108
+ m.x-=k*g.x;m.z-=k*g.y;lift+=k*(h-0.5)*a/${j(e.undulation)};
109
+ }
110
+ terrainRockShade*=1.0+0.12*lift;
111
+ ` : ""} var n=normalize(m);
112
+ ${e.facets > 0 ? ` n=terrainRockFacets(p,n,${j(e.facets * 4.1)},fp,steep,0.7,vec3i(41,7,-13));
113
+ n=terrainRockFacets(p,n,${j(e.facets)},fp,steep,1.0,vec3i(0));
114
+ ` : ""} return n;
115
+ }${e.debris >= 0 ? `
116
+ fn terrainRockDebris(packed:ptr<function,array<vec4f,4>>) {
117
+ let k=clamp(terrainRockLoose,0.0,1.0);var sum=0.0;
118
+ for(var layer=0u;layer<u32(frame.heights.z);layer++){sum+=(*packed)[layer/4u][layer%4u];(*packed)[layer/4u][layer%4u]*=1.0-k;}
119
+ (*packed)[${e.debris >> 2}u][${e.debris & 3}u]+=k*sum;
120
+ }` : ""}`;
121
+ }, M = (e = !1, t) => `${r}${e ? k : ""}${t ? ee(t) : ""}
122
+ fn terrainColor(position:vec3f,normal:vec3f)->vec3f {
123
+ let slope=1-clamp(normal.y,0.0,1.0);let axes=pow(abs(normal),vec3f(8));let projection=axes/max(axes.x+axes.y+axes.z,0.00001);let dx=dpdx(position);let dy=dpdy(position);var color=vec3f(0);var total=0.0;var fallback=vec3f(0);${e ? "var relief=0.0;var fallbackRelief=0.0;var repeat=0.0;" : ""}
124
+ for(var layer=0u;layer<u32(frame.heights.z);layer++){
125
+ let rule=layerRules[layer];let hs=rule.heightSlope;let scale=rule.params.x;let p=position*scale;
126
+ let x=textureSampleGrad(terrainLayers,terrainSampler,p.zy,i32(layer),dx.zy*scale,dy.zy*scale).rgb;
127
+ let y=textureSampleGrad(terrainLayers,terrainSampler,p.xz,i32(layer),dx.xz*scale,dy.xz*scale).rgb;
128
+ let z=textureSampleGrad(terrainLayers,terrainSampler,p.xy,i32(layer),dx.xy*scale,dy.xy*scale).rgb;
129
+ ${e ? "let surface=terrainSurface(x*projection.x+y*projection.y+z*projection.z,position,projection,dx,dy,layer);let sample=surface.rgb;if(layer==0){fallback=sample;fallbackRelief=surface.w;terrainRepeat=scale;}" : "let sample=x*projection.x+y*projection.y+z*projection.z;if(layer==0){fallback=sample;}"}
130
+ let h=rule.params.y;let s=rule.params.z;
131
+ let weight=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));
132
+ color+=sample*weight;total+=weight;${e ? "relief+=surface.w*weight;repeat+=scale*weight;" : ""}
133
+ }
134
+ ${e ? "terrainRelief=select(fallbackRelief,relief/max(total,0.00001),total>0.00001);if(total>0.00001){terrainRepeat=repeat/total;}" : ""}return select(fallback,color/max(total,0.00001),total>0.00001);
135
+ }
136
+ @fragment fn fragment(i:Output)->@location(0) vec4f {
137
+ ${x}
138
+ ${A(e, !!t)}let v=normalize(frame.eye.xyz-i.position);let l=frame.light.xyz;let h=(v+l)/max(length(v+l),0.0001);
139
+ let nl=clamp(dot(n,l),0.0,1.0);let nv=clamp(dot(n,v),0.0001,1.0);let nh=clamp(dot(n,h),0.0,1.0);let vh=clamp(dot(v,h),0.0,1.0);let a=i.material.x*i.material.x;let a2=a*a;
140
+ let d=${_};let g=${v};let fresnel=vec3f(0.04)+vec3f(0.96)*pow(1-vh,5.0);
141
+ let direct=((1-fresnel)*base/3.14159265+d*g*fresnel/max(4*nl*nv,0.0001))*nl;
142
+ let linear=direct*frame.radiance.xyz*frame.light.w+base*frame.radiance.w*frame.ambient.rgb;
143
+ if(frame.heights.w>0.5){return vec4f(linear,1);}
144
+ let mapped=pbrNeutral(max(linear,vec3f(0)));return vec4f(select(mapped*12.92,1.055*pow(mapped,vec3f(1.0/2.4))-0.055,mapped>=vec3f(0.0031308)),1);
145
+ }`, N = "\nfn terrainLayerSample(position:vec3f,projection:vec3f,dx:vec3f,dy:vec3f,layer:u32)->vec3f {\n let scale=layerRules[layer].params.x;let p=position*scale;\n let x=textureSampleGrad(terrainLayers,terrainSampler,p.zy,i32(layer),dx.zy*scale,dy.zy*scale).rgb;\n let y=textureSampleGrad(terrainLayers,terrainSampler,p.xz,i32(layer),dx.xz*scale,dy.xz*scale).rgb;\n let z=textureSampleGrad(terrainLayers,terrainSampler,p.xy,i32(layer),dx.xy*scale,dy.xy*scale).rgb;\n return x*projection.x+y*projection.y+z*projection.z;\n}", P = ({ size: e, contrast: t, warp: n, terraces: r }) => `
146
+ var<private> terrainPatchWeights:array<f32,16>;
147
+ fn terrainPatchXZ(p:vec3f)->vec2f {return p.xz;}
148
+ fn terrainPatchHash(c:vec2f,layer:u32)->f32 {
149
+ var v=vec3u(bitcast<u32>(i32(c.x)),bitcast<u32>(i32(c.y)),layer)*1664525u+1013904223u;
150
+ v.x+=v.y*v.z;v.y+=v.z*v.x;v.z+=v.x*v.y;v^=v>>vec3u(16u);v.x+=v.y*v.z;v.y+=v.z*v.x;v.z+=v.x*v.y;
151
+ return f32(v.x>>8u)/16777216.0;
152
+ }
153
+ fn terrainPatchNoise(p:vec2f,layer:u32)->f32 {
154
+ let i=floor(p);let f=p-i;let u=f*f*f*(f*(f*6.0-15.0)+10.0);
155
+ return mix(mix(terrainPatchHash(i,layer),terrainPatchHash(i+vec2f(1,0),layer),u.x),mix(terrainPatchHash(i+vec2f(0,1),layer),terrainPatchHash(i+vec2f(1,1),layer),u.x),u.y);
156
+ }
157
+ fn terrainPatch(xz:vec2f,layer:u32,footprint:f32)->f32 {
158
+ var p=xz*${(1 / e).toPrecision(9)};var cell=${e.toPrecision(9)};var amp=0.5;var sum=0.0;var norm=0.0;
159
+ for(var k=0u;k<3u;k++){let fade=1.0-smoothstep(0.25,0.5,footprint/cell);sum+=amp*mix(0.5,terrainPatchNoise(p,layer*3u+k),fade);norm+=amp;p=p*2.03+vec2f(19.1,7.3);cell/=2.03;amp*=0.5;}${n > 0 ? `
160
+ let broad=1.0-smoothstep(0.25,0.5,footprint/${(e * 3.3).toPrecision(9)});sum+=0.75*mix(0.5,terrainPatchNoise(xz*${(1 / (e * 3.3)).toPrecision(9)}+vec2f(3.7,8.1),layer*3u+48u),broad);norm+=0.75;` : ""}
161
+ return sum/norm;
162
+ }
163
+ fn terrainPatchBlend(packed:ptr<function,array<vec4f,4>>,position:vec2f,height:f32,up:f32,footprint:f32) {
164
+ var xz=position;${n > 0 ? `
165
+ let wp=position*${(1 / (e * 2.6)).toPrecision(9)};
166
+ xz+=${(n * e * 2.2).toPrecision(9)}*(vec2f(terrainPatchNoise(wp,61u),terrainPatchNoise(wp+vec2f(5.2,1.3),62u))-0.5);` : ""}${r > 0 ? `
167
+ let phase=height*${(1 / r).toPrecision(9)}+1.3*terrainPatchNoise(position*${(1 / (r * 7)).toPrecision(9)},63u);
168
+ let tilt=degrees(acos(clamp(up,0.0,1.0)));
169
+ let bands=${(.22 * t).toPrecision(9)}*(1.0-smoothstep(0.12,0.35,fwidth(phase)))*smoothstep(8.0,14.0,tilt)*(1.0-smoothstep(30.0,38.0,tilt))*smoothstep(0.42,0.68,terrainPatchNoise(position*${(1 / (r * 14)).toPrecision(9)},64u));` : ""}
170
+ var top=-1.0;var plain=0.0;
171
+ for(var layer=0u;layer<u32(frame.heights.z);layer++){
172
+ let w=(*packed)[layer/4u][layer%4u];terrainPatchWeights[layer]=-1.0;if(w<=0.0){continue;}
173
+ let t=w+${t.toPrecision(9)}*terrainPatch(xz,layer,footprint)${r > 0 ? "+bands*sin(6.2831853*phase+f32(layer)*2.1)" : ""};terrainPatchWeights[layer]=t;top=max(top,t);plain+=w;
174
+ }
175
+ let line=top-${(.05 * t).toPrecision(9)};var sum=0.0;
176
+ for(var layer=0u;layer<u32(frame.heights.z);layer++){let b=max(terrainPatchWeights[layer]-line,0.0);terrainPatchWeights[layer]=b;sum+=b;}
177
+ let near=1.0-smoothstep(0.3,0.8,footprint*${(1 / e).toPrecision(9)});
178
+ for(var layer=0u;layer<u32(frame.heights.z);layer++){
179
+ terrainPatchWeights[layer]=mix((*packed)[layer/4u][layer%4u]/max(plain,0.00001),terrainPatchWeights[layer]/max(sum,0.00001),near);
180
+ }
181
+ }`, F = (e, t = !1, n = !1, r, i) => {
182
+ let a = M(t, i), o = a.slice(a.indexOf("fn terrainColor("), a.indexOf("@fragment fn fragment(")), s = Math.min(4, Math.max(1, Math.floor(e))), c = `
183
+ ${Array.from({ length: s }, (e, t) => t).map((e) => `@group(0) @binding(${6 + e}) var terrainWeights${e}:texture_2d<f32>;`).join("\n")}
184
+ ${N}${r ? P(r) : ""}
185
+ fn terrainColor(position:vec3f,normal:vec3f)->vec3f {
186
+ let axes=pow(abs(normal),vec3f(8));let projection=axes/max(axes.x+axes.y+axes.z,0.00001);let dx=dpdx(position);let dy=dpdy(position);
187
+ 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);
188
+ var packed=array<vec4f,4>(${[
189
+ 0,
190
+ 1,
191
+ 2,
192
+ 3
193
+ ].map((e) => e < s ? `textureSampleLevel(terrainWeights${e},terrainSampler,uv,0)` : "vec4f(0)").join(",")});
194
+ ${i && i.debris >= 0 ? "terrainRockDebris(&packed);" : ""}${r ? "terrainPatchBlend(&packed,terrainPatchXZ(position),position.y,normal.y,max(length(dx),length(dy)));" : ""}var color=vec3f(0);var total=0.0;${t ? "var relief=0.0;var repeat=0.0;" : ""}
195
+ for(var layer=0u;layer<u32(frame.heights.z);layer++){
196
+ ${r ? "let weight=terrainPatchWeights[layer];" : "let weight=packed[layer/4u][layer%4u];"}if(weight<=0.0){continue;}
197
+ ${t ? "let surface=terrainSurface(terrainLayerSample(position,projection,dx,dy,layer),position,projection,dx,dy,layer);color+=surface.rgb*weight;relief+=surface.w*weight;repeat+=layerRules[layer].params.x*weight;total+=weight;" : "color+=terrainLayerSample(position,projection,dx,dy,layer)*weight;total+=weight;"}
198
+ }
199
+ ${t ? "if(total>0.00001){terrainRelief=relief/total;terrainRepeat=repeat/total;return color/total;}" : "if(total>0.00001){return color/total;}"}
200
+ ${t ? "let surface=terrainSurface(terrainLayerSample(position,projection,dx,dy,0u),position,projection,dx,dy,0u);terrainRelief=surface.w;terrainRepeat=layerRules[0].params.x;return surface.rgb;" : "return terrainLayerSample(position,projection,dx,dy,0u);"}
201
+ }
202
+ ${a.replace(o, "")}`;
203
+ return n ? `@group(0) @binding(${6 + s}) var terrainTint:texture_2d<f32>;
204
+ var<private> terrainTintTexel:vec4f;
205
+ fn terrainTinted(c:vec3f,layer:u32)->vec3f {return mix(c,terrainTintTexel.rgb,terrainTintTexel.a*layerRules[layer].params.w);}
206
+ ${c.replace("var packed=", "let td=vec2f(textureDimensions(terrainTint));terrainTintTexel=textureSampleLevel(terrainTint,terrainSampler,clamp((position.xz-frame.map.xy)/frame.map.zw,vec2f(0.5)/td,vec2f(1)-vec2f(0.5)/td),0);var packed=").replace(/terrainLayerSample\(position,projection,dx,dy,(layer|0u)\)/g, "terrainTinted($&,$1)").replace("fn terrainReliefTint(h:f32,layer:u32)->f32 {return h;}", "fn terrainReliefTint(h:f32,layer:u32)->f32 {return mix(h,dot(terrainTintTexel.rgb,vec3f(0.2126,0.7152,0.0722)),terrainTintTexel.a*layerRules[layer].params.w);}")}` : c;
207
+ }, I = "let n=vec2f(textureDimensions(heightMap));let uv=((position.xz-frame.map.xy)/frame.map.zw*(n-1.0)+0.5)/n;o.clip=vec4f(uv.x*2.0-1.0,1.0-2.0*uv.y,0.0,1.0);";
208
+ function te(e, t, n, r, i, a) {
209
+ let o = e.adapter?.capabilities?.tier;
210
+ if (o === "ldr") return;
211
+ let s = o === "half-float" ? "rgba16float" : "r32float", c = Math.min(2049, t.width), l = Math.min(2049, t.height), u = [c, l], d = a ? "+frame.anchor.z" : "", f = s === "rgba16float" ? "vec4f" : "f32", p = (e) => f === "vec4f" ? `vec4f(${e},0.0,0.0,1.0)` : e, m = e.createShaderModule({ code: i(r.replace(a ? w : C, I) + `
212
+ @vertex fn seedVertex(@builtin(vertex_index) i:u32)->@builtin(position) vec4f {
213
+ return vec4f(array<vec2f,3>(vec2f(-1,-1),vec2f(3,-1),vec2f(-1,3))[i],0,1);
214
+ }
215
+ @fragment fn seed(@builtin(position) p:vec4f)->@location(0) ${f} {
216
+ let n=vec2f(textureDimensions(heightMap));let q=(p.xy/vec2f(${c},${l})*n-0.5)/max(n-1.0,vec2f(1.0));
217
+ return ${p("height(frame.map.xy+q*frame.map.zw)" + d)};
218
+ }
219
+ @fragment fn sampleSurface(i:Output)->@location(0) ${f} {
220
+ ${x}
221
+ return ${p("i.position.y" + d)};
222
+ }`) }), h = e.createPipelineLayout({ bindGroupLayouts: [n] }), g = e.createRenderPipeline({
223
+ layout: h,
224
+ vertex: {
225
+ module: m,
226
+ entryPoint: "seedVertex"
227
+ },
228
+ fragment: {
229
+ module: m,
230
+ entryPoint: "seed",
231
+ targets: [{ format: s }]
232
+ }
233
+ }), _ = e.createRenderPipeline({
234
+ layout: h,
235
+ vertex: {
236
+ module: m,
237
+ entryPoint: "vertex",
238
+ buffers: [{
239
+ arrayStride: 8,
240
+ attributes: [{
241
+ shaderLocation: 0,
242
+ offset: 0,
243
+ format: "float32x2"
244
+ }]
245
+ }]
246
+ },
247
+ fragment: {
248
+ module: m,
249
+ entryPoint: "sampleSurface",
250
+ targets: [{ format: s }]
251
+ }
252
+ }), v = e.createTexture({
253
+ label: "Terrain drawn surface height",
254
+ size: u,
255
+ format: s,
256
+ usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.TEXTURE_BINDING | GPUTextureUsage.COPY_SRC
257
+ }), y = v.createView(), b = -1;
258
+ return {
259
+ texture: v,
260
+ draw(e, t, n, r) {
261
+ if (b === t) return;
262
+ let i = e.beginRenderPass({ colorAttachments: [{
263
+ view: y,
264
+ loadOp: "clear",
265
+ storeOp: "store"
266
+ }] });
267
+ i.setPipeline(g), i.setBindGroup(0, n[0].group), i.draw(3), i.setPipeline(_), i.setVertexBuffer(0, r.vertex);
268
+ for (let e = n.length - 1; e >= 0; e--) i.setBindGroup(0, n[e].group), i.setIndexBuffer(e ? r.ring : r.center, "uint32"), i.drawIndexed(e ? r.ringCount : r.centerCount);
269
+ i.end(), b = t;
270
+ }
271
+ };
272
+ }
273
+ //#endregion
274
+ //#region src/colors.ts
275
+ var ne = 0, L = [
276
+ .5,
277
+ .42,
278
+ .29
279
+ ], re = [[
280
+ .133,
281
+ .263,
282
+ .033
283
+ ], [
284
+ .274,
285
+ .342,
286
+ .064
287
+ ]], ie = [
288
+ .253,
289
+ .223,
290
+ .187
291
+ ], ae = Object.freeze([
292
+ L[0],
293
+ L[1],
294
+ L[2]
295
+ ]);
296
+ function R(e, t) {
297
+ let n = 0, r = 50, i = e.geometry?.vertices;
298
+ if (i?.length) {
299
+ n = Infinity, r = -Infinity;
300
+ for (let e = 1; e < i.length; e += 6) i[e] < n && (n = i[e]), i[e] > r && (r = i[e]);
301
+ let t = e.scale.y, a = e.position.y;
302
+ [n, r] = [a + n * t, a + r * t].sort((e, t) => e - t), r > n || (r = n + 1);
303
+ }
304
+ return {
305
+ sand: L,
306
+ meadow: re,
307
+ stone: ie,
308
+ shore: [.3, 1.5],
309
+ meadowHeight: [n, r],
310
+ stoneHeight: [r + 1, r + 2],
311
+ stoneNormal: [.75, .85],
312
+ wetHeight: [-.1, .4],
313
+ wetDarkening: .6,
314
+ wetDryTime: 900,
315
+ wetGlossTime: 20,
316
+ ...Object.fromEntries(Object.entries(t).filter(([, e]) => e !== void 0))
317
+ };
318
+ }
319
+ function z(e, t) {
320
+ if (typeof t != "object" || !t) throw TypeError("Terrain color options must be an object; pass {} or leave them out for the defaults");
321
+ let n = R(e, t);
322
+ if (n.meadow.length !== 2) throw RangeError("Expected two meadow colors");
323
+ for (let e of [
324
+ n.sand,
325
+ ...n.meadow,
326
+ n.stone
327
+ ]) if (e.length !== 3 || e.some((e) => !Number.isFinite(e) || e < 0 || e > 1)) throw RangeError("Invalid terrain color; use [r, g, b] with each channel between 0 and 1.");
328
+ for (let e of [
329
+ n.shore,
330
+ n.meadowHeight,
331
+ n.stoneHeight,
332
+ n.stoneNormal,
333
+ n.wetHeight
334
+ ]) if (e.length !== 2 || !e.every((e) => Number.isFinite(Math.fround(e))) || e[0] >= e[1]) throw RangeError("Invalid terrain color range; use [min, max] with finite numbers and min below max.");
335
+ if (n.stoneNormal[0] < 0 || n.stoneNormal[1] > 1 || !Number.isFinite(n.wetDarkening) || n.wetDarkening < 0 || n.wetDarkening > 1 || !Number.isFinite(n.variation ?? 0) || (n.variation ?? 0) < 0 || (n.variation ?? 0) > 1) throw RangeError("Invalid terrain wetness or variation; stoneNormal must stay within 0..1, wetDarkening and variation must be between 0 and 1.");
336
+ if (!(n.wetDryTime >= 1 && n.wetDryTime <= 604800) || !(n.wetGlossTime >= .1 && n.wetGlossTime <= 3600)) throw RangeError("Invalid terrain drying; wetDryTime must be 1 to 604,800 s and wetGlossTime 0.1 to 3,600 s.");
337
+ let r = n.detail ?? 1;
338
+ if (typeof r != "number" || !(r >= 0 && r <= 1)) throw RangeError("Terrain detail must be a number in 0..1");
339
+ let i = n.wetness;
340
+ if (i !== void 0 && (!i || typeof i.texture != "function" || !Array.isArray(i.origin) || !Array.isArray(i.size) || i.origin.length !== 2 || i.size.length !== 2 || !i.origin.every((e) => Number.isFinite(Math.fround(e))) || !i.size.every((e) => Number.isFinite(Math.fround(e)) && e > 0))) throw RangeError("Invalid terrain wetness map; give a texture function, a finite [x, z] origin and a positive finite [width, depth] size.");
341
+ let a = n.sandSurface ?? {};
342
+ if (a !== !1 && (typeof a != "object" || !a)) throw TypeError("Terrain sandSurface must be an object or false; leave it out for the defaults");
343
+ let o = a === !1 ? void 0 : {
344
+ wind: [1, 0],
345
+ ripple: .1,
346
+ ripples: 1,
347
+ streaks: 1,
348
+ sorting: 1,
349
+ broad: 0,
350
+ ...Object.fromEntries(Object.entries(a).filter(([, e]) => e !== void 0))
351
+ };
352
+ if (o && (!Array.isArray(o.wind) || o.wind.length !== 2 || !o.wind.every(Number.isFinite) || !(Math.hypot(o.wind[0], o.wind[1]) > 1e-6) || !(o.ripple >= .02 && o.ripple <= 1) || !(o.ripples >= 0 && o.ripples <= 2) || !(o.streaks >= 0 && o.streaks <= 1) || !(o.sorting >= 0 && o.sorting <= 1) || !(o.broad >= 0 && o.broad <= 1))) throw RangeError("Invalid terrain sandSurface; pass wind as a non-zero finite [x, z], ripple 0.02 to 1 m, ripples 0 to 2, streaks, sorting and broad 0 to 1.");
353
+ return {
354
+ options: n,
355
+ detail: r,
356
+ wetness: i,
357
+ sand: o
358
+ };
359
+ }
360
+ var B = 11;
361
+ function V(e, t, n) {
362
+ let r = /* @__PURE__ */ new Float32Array(44), i = e.wetDarkening, a = (e) => q(.6 * t * (e[1] - e[0])), o = n ?? {
363
+ wind: [1, 0],
364
+ ripple: .1,
365
+ ripples: 1,
366
+ streaks: 1,
367
+ sorting: 1,
368
+ broad: 0
369
+ }, s = Math.hypot(o.wind[0], o.wind[1]);
370
+ return r.set([...e.sand, i], 0), r.set([...e.meadow[0], 1 - i], 4), r.set([...e.meadow[1], i < 1 ? q(.4 / (1 - i)) : 0], 8), r.set(e.stone, 12), r.set([...e.shore, ...e.wetHeight], 16), r.set([...e.meadowHeight, ...e.stoneHeight], 20), r.set(e.stoneNormal, 24), r.set([
371
+ a(e.meadowHeight),
372
+ a(e.shore),
373
+ a(e.stoneHeight),
374
+ a(e.stoneNormal)
375
+ ], 28), r.set([
376
+ q(o.wind[0] / s),
377
+ q(o.wind[1] / s),
378
+ q(o.ripple),
379
+ q(o.ripples * t)
380
+ ], 32), r.set([
381
+ q(.1 * o.sorting * t),
382
+ q(.07 * o.sorting * t),
383
+ q(.16 * o.streaks * t),
384
+ q(.3 * o.broad * t)
385
+ ], 36), r.set([
386
+ q(.14 * o.sorting * t),
387
+ q(o.ripple / 4),
388
+ q(o.ripple / 2)
389
+ ], 40), r;
390
+ }
391
+ var H = "let terrainColorFootprint=max(length(dpdx(i.position)),length(dpdy(i.position)));", U = "struct TerrainSurface {color:vec3f,normal:vec3f,rough:f32}\n", W = "\nfn terrainBlend(t:f32,ha:f32,hb:f32)->f32 {\n let a=ha+1.0-t;let b=hb+t;let m=max(a,b)-0.2;let x=max(a-m,0.0);let y=max(b-m,0.0);return y/(x+y);\n}\n", G = "\n@group(0) @binding(0) var depth:texture_2d<f32>;\n@group(0) @binding(1) var before:texture_2d<f32>;\n@group(0) @binding(2) var after:texture_storage_2d<rgba32float,write>;\n@group(0) @binding(3) var<uniform> drying:vec4f;\n@compute @workgroup_size(8,8) fn main(@builtin(global_invocation_id) id:vec3u){\n let size=vec2i(textureDimensions(after));let p=vec2i(id.xy);if(any(p>=size)){return;}\n let now=smoothstep(0.001,0.025,textureLoad(depth,p,0).r);let w=textureLoad(before,p,0);\n let m=max(now,w.x*exp(-drying.x/drying.y));let f=max(now,w.y*exp(-drying.x/drying.z));\n textureStore(after,p,vec4f(m,f,(1.0-exp(-3.0*m))/(1.0-exp(-3.0)),0.0));\n}";
392
+ function K(e, t = 900, n = 20) {
393
+ let r = Math.exp(-e / t);
394
+ return {
395
+ moisture: r,
396
+ film: Math.exp(-e / n),
397
+ darkening: (1 - Math.exp(-3 * r)) / (1 - Math.exp(-3))
398
+ };
399
+ }
400
+ var q = (e) => Math.round(e * 1e6) / 1e6, J = (e) => String(q(e)), oe = class e {coreRequirement=__margoCoreRequirement("1.0.0",import.meta.url);
401
+ constructor(e, t = {}) {
402
+ this.mesh = e, this.name = "terrain:colors:" + ++ne, this.source = "", this.shader = "", this.disposed = !1, this.wetBinding = 40, this.lookBinding = 41, this.lookDirty = !0, this.wetSource = { texture: void 0 }, this.wetTarget = { texture: void 0 }, this.wetSize = {
403
+ width: 1,
404
+ height: 1
405
+ }, this.drying = /* @__PURE__ */ new Float32Array(4), this.recordSource = { texture: void 0 }, this.recordTarget = { texture: void 0 }, this.elapsed = 0, this.dryTime = 900, this.glossTime = 20;
406
+ let { options: n, detail: r, wetness: i, sand: a } = z(e, t);
407
+ this.wetness = i, this.given = t, this.dryTime = n.wetDryTime, this.glossTime = n.wetGlossTime, this.look = V(n, r, a);
408
+ let o = (e, t) => `terrainLook[${e}].${t}`, s = n.variation ?? 0, c = (e, t, n, i) => `smoothstep(${e},${t},${i}${r ? `+large*${n}` : ""})`, l = (e, t) => r === 1 ? `terrainBlend(${e},${t})` : `mix(${e},terrainBlend(${e},${t}),${r})`, u = !!a && r > 0;
409
+ this.sandOn = u;
410
+ let d = u ? `
411
+ let foot=footprint;
412
+ let sw=${o(8, "xy")};let along=dot(p.xz,sw);let across=dot(p.xz,vec2f(-sw.y,sw.x));
413
+ let face=dot(n.xz,sw);let lee=smoothstep(0.25,0.45,face);let stoss=smoothstep(0.03,0.2,-face);
414
+ var sandShade=1.0+${o(9, "x")}*lee-${o(9, "y")}*stoss;
415
+ let streak=(terrainNoise(vec2f(along*0.045,across*0.55)+vec2f(13.0,7.0)).x-0.5)*(1.0-smoothstep(0.45,0.9,foot));
416
+ var fineStreak=0.0;let sf=1.0-smoothstep(0.13,0.26,foot);
417
+ if(sf>0.0){fineStreak=(terrainNoise(vec2f(along*0.13,across*1.9)+vec2f(3.0,29.0)).x-0.5)*sf;}
418
+ sandShade*=1.0+${o(9, "z")}*(0.65*streak+0.35*fineStreak);
419
+
420
+ sandShade*=1.0+${o(9, "w")}*(terrainNoise(vec2f(along*0.012,across*0.09)+vec2f(23.0,5.0)).x-0.5);
421
+
422
+ let flow=(terrainNoise(vec2f(along*0.12,across*1.1)+vec2f(41.0,17.0)).x-0.5)*(1.0-smoothstep(0.25,0.5,foot));
423
+ sandShade*=1.0+${o(10, "x")}*lee*flow;
424
+ var sandGrad=vec3f(0.0);let rv=${o(8, "w")}*(1.0-smoothstep(${o(10, "y")},${o(10, "z")},foot))*(1.0-lee)*(1.0-sandT)${i ? "*(1.0-terrainMoisture(p))" : ""};
425
+ if(rv>0.0){
426
+ let w1=terrainNoise(p.xz*0.9);let w2=terrainNoise(p.xz*3.3+vec2f(7.0,3.0));let amp=terrainNoise(p.xz*1.7+vec2f(5.0,11.0)).x;
427
+ let t=fract(along/${o(8, "z")}+1.6*w1.x+0.35*w2.x);
428
+ let up=smoothstep(0.0,0.06,t)*(1.0-smoothstep(0.69,0.75,t));let down=smoothstep(0.75,0.81,t)*(1.0-smoothstep(0.94,1.0,t));
429
+ let r=rv*(0.4+0.6*amp);let d=r*(0.0966*up-0.351*down)*(sw+${o(8, "z")}*(1.44*w1.yz+1.155*w2.yz));
430
+ sandGrad=vec3f(d.x,0.0,d.y);
431
+
432
+
433
+ sandShade*=1.0-0.2*r*(smoothstep(0.55,0.7,t)*(1.0-smoothstep(0.85,1.0,t))-0.3);
434
+ }` : "";
435
+ this.surfaceCode = `
436
+ fn terrainSurface(p:vec3f,n:vec3f,footprint:f32)->TerrainSurface {
437
+ var s:TerrainSurface;let h=p.y;${s || r ? "let fade=1.0-smoothstep(20.0,60.0,distance(frame.eye.xyz,p));\n let large=terrainNoise(p.xz*0.07).x-0.5;var fine=0.0;\n if(fade>0.0){fine=(terrainNoise(mat2x2f(0.61566,0.78801,-0.78801,0.61566)*p.xz*0.9).x-0.5)*fade;}" : ""}
438
+ let meadow=mix(${o(1, "xyz")},${o(2, "xyz")},${c(o(5, "x"), o(5, "y"), o(7, "x"), "h")});
439
+ let shore=${c(o(4, "x"), o(4, "y"), o(7, "y"), "h")};
440
+ let steep=max(${c(o(5, "z"), o(5, "w"), o(7, "z"), "h")},1.0-${c(o(6, "x"), o(6, "y"), o(7, "w"), "n.y")});${r ? `
441
+ var rock=large;var grad=vec3f(0.0);
442
+ if(steep>0.004&&fade>0.0){
443
+ let a=n*n;var w=a*a;w/=w.x+w.y+w.z;
444
+ let zy=terrainNoise(vec2f(p.z*0.35,p.y*1.4)+vec2f(17.0,0.0));let xz=terrainNoise(p.xz*0.6);let xy=terrainNoise(vec2f(p.x*0.35,p.y*1.4)+vec2f(0.0,29.0));
445
+ rock=mix(large,w.x*zy.x+w.y*xz.x+w.z*xy.x-0.5,fade);
446
+ grad=fade*(w.x*vec3f(0.0,zy.z*1.4,zy.y*0.35)+w.y*vec3f(xz.y*0.6,0.0,xz.z*0.6)+w.z*vec3f(xy.y*0.35,xy.z*1.4,0.0));
447
+ }
448
+ let grass=0.275+0.35*fine;let stoneT=${l("steep", "grass,0.25+0.5*rock")};
449
+ let sandT=${l("shore", "0.15-0.3*fine,mix(grass,0.25+0.5*rock,stoneT)")};${d}` : "\n let stoneT=steep;let sandT=shore;"}
450
+ ${i ? "let wr=terrainWet(p);let wet=wr.x;let glint=wr.y;" : `let wet=mix(${o(0, "w")},1.0,smoothstep(${o(4, "z")},${o(4, "w")},h));let glint=wet;`}
451
+ s.color=mix(${o(0, "xyz")}${r ? `*(1.0+${J(.2 * r)}*fine)` : ""}${u ? "*sandShade" : ""},mix(meadow,${o(3, "xyz")}${r ? `*(1.0+${J(.6 * r)}*rock)` : ""},stoneT),sandT)*wet${s ? `*(${J(1 - s)}+${J(2 * s)}*(0.65*large+0.35*fine))` : ""};
452
+ s.normal=${r ? `normalize(n-(grad-n*dot(n,grad))*(${J(.15 * r)}*stoneT*sandT)${u ? "-(sandGrad-n*dot(n,sandGrad))" : ""})` : "n"};
453
+ s.rough=select(1.0,0.6+${o(2, "w")}*(glint-${o(0, "w")}),${o(0, "w")}<1.0);return s;
454
+ }
455
+ `, this.wetCode = i ? `
456
+ @group(0) @binding(9) var terrainWater:texture_2d<f32>;
457
+
458
+ fn terrainMoisture(position:vec3f)->f32 {
459
+ if(position.y>=${o(4, "w")}){return 0.0;}
460
+ let uv=(position.xz-vec2f(${i?.origin.join(",")}))/vec2f(${i?.size.join(",")});
461
+ if(any(uv<vec2f(0))||any(uv>vec2f(1))){return 0.0;}
462
+ let size=vec2i(textureDimensions(terrainWater));let pixel=clamp(uv*vec2f(size)-0.5,vec2f(0),vec2f(size-1));let lo=vec2i(floor(pixel));let hi=min(lo+1,size-1);let t=fract(pixel);
463
+ return mix(mix(textureLoad(terrainWater,lo,0).x,textureLoad(terrainWater,vec2i(hi.x,lo.y),0).x,t.x),mix(textureLoad(terrainWater,vec2i(lo.x,hi.y),0).x,textureLoad(terrainWater,hi,0).x,t.x),t.y);
464
+ }
465
+ fn terrainWet(position:vec3f)->vec2f {
466
+ if(position.y>=${o(4, "w")}){return vec2f(1.0);}
467
+ let uv=(position.xz-vec2f(${i.origin.join(",")}))/vec2f(${i.size.join(",")});
468
+ if(any(uv<vec2f(0))||any(uv>vec2f(1))){return vec2f(1.0);}
469
+ let size=vec2i(textureDimensions(terrainWater));let pixel=clamp(uv*vec2f(size)-0.5,vec2f(0),vec2f(size-1));let lo=vec2i(floor(pixel));let hi=min(lo+1,size-1);let t=fract(pixel);
470
+ let a=textureLoad(terrainWater,lo,0).zy;let b=textureLoad(terrainWater,vec2i(hi.x,lo.y),0).zy;let c=textureLoad(terrainWater,vec2i(lo.x,hi.y),0).zy;let d=textureLoad(terrainWater,hi,0).zy;
471
+ let wet=mix(mix(a,b,t.x),mix(c,d,t.x),t.y);
472
+ let beach=(1.0-smoothstep(${o(4, "z")},${o(4, "w")},position.y))*(1.0-smoothstep(${o(4, "x")},${o(4, "y")},position.y));
473
+ return 1.0-${o(1, "w")}*beach*wet;
474
+ }
475
+ ` : "";
476
+ }
477
+ static attach(t, n, r = {}) {__margoAssertCore(t,__margoCoreRequirement("1.0.0",import.meta.url));
478
+ let i = new e(n, r);
479
+ return l(t).use(i), i;
480
+ }
481
+ setup(e) {
482
+ o(e, "TerrainColors");
483
+ let t = u(this.mesh);
484
+ if (t.check(), this.engine || this.disposed || t.engine !== e) throw new f("attached", "Terrain color mesh belongs to another engine or is already attached; attach one TerrainColors per mesh, to the mesh's engine");
485
+ this.engine = e, this.wetness && (this.dry = e.gpu.createTexture({
486
+ size: [1, 1],
487
+ format: "r32float",
488
+ usage: GPUTextureUsage.TEXTURE_BINDING | GPUTextureUsage.COPY_DST
489
+ }), e.gpu.queue.writeTexture({ texture: this.dry }, /* @__PURE__ */ new Float32Array(1), { bytesPerRow: 4 }, [1, 1]), this.dryEntry = {
490
+ binding: 9,
491
+ resource: this.dry.createView()
492
+ });
493
+ }
494
+ get sandSurfaceOn() {
495
+ return this.sandOn;
496
+ }
497
+ setLook(e) {
498
+ if (typeof e != "object" || !e) throw TypeError("Terrain look must be an object");
499
+ let t = this.given.sandSurface, n = { ...this.given };
500
+ for (let [t, r] of Object.entries(e)) r !== void 0 && t !== "sandSurface" && (r === null ? delete n[t] : n[t] = r);
501
+ if (e.sandSurface !== void 0) {
502
+ if (!this.sandOn) throw TypeError("This TerrainColors was built without a sand surface (sandSurface false or detail 0); it cannot gain one");
503
+ n.sandSurface = {
504
+ ...t || {},
505
+ ...e.sandSurface
506
+ };
507
+ }
508
+ let r = z(this.mesh, n);
509
+ this.look = V(r.options, r.detail, r.sand), this.dryTime = r.options.wetDryTime, this.glossTime = r.options.wetGlossTime, this.given = n, this.lookDirty = !0;
510
+ }
511
+ patch(e, t) {
512
+ let n = s(e);
513
+ if (!n) return e;
514
+ let { code: r } = n, i = r.indexOf(H), a = i < 0 ? n.at : i + 81, o = "_" + t, l = (`@group(0) @binding(${this.lookBinding}) var<uniform> terrainLook:array<vec4f,${B}>;
515
+ ` + this.wetCode.replace("@binding(9)", `@binding(${this.wetBinding})`) + this.surfaceCode).replace(/terrainSurface|terrainWater|terrainWet|terrainMoisture|terrainLook/g, (e) => e + o);
516
+ return (r.includes("struct TerrainSurface ") ? "" : U) + (this.surfaceCode.includes("terrainNoise(") && !r.includes("fn terrainNoise(") ? c : "") + (this.surfaceCode.includes("terrainBlend(") && !r.includes("fn terrainBlend(") ? W : "") + l + r.slice(0, a) + (i < 0 ? H : "") + `if(i.terrainId==${t + 1}.0){let s=terrainSurface${o}(i.position,n,terrainColorFootprint);i.color=s.color;i.material.x*=s.rough;n=s.normal;}` + r.slice(a);
517
+ }
518
+ registerPasses(e) {
519
+ e.add({
520
+ name: this.name,
521
+ order: -1,
522
+ execute: (e) => {
523
+ if (e.backend !== "webgpu") return;
524
+ let t = u(this.mesh);
525
+ if (t.check(), this.source !== e.shader) {
526
+ if (this.source = e.shader, this.wetness) for (this.wetBinding = 40; e.bindings.some((e) => e.binding === this.wetBinding);) this.wetBinding++;
527
+ for (this.lookBinding = this.wetness ? this.wetBinding + 1 : 41; e.bindings.some((e) => e.binding === this.lookBinding);) this.lookBinding++;
528
+ this.lookEntry = void 0, this.shader = this.patch(e.shader, t.id);
529
+ }
530
+ if (this.wetness) {
531
+ let t = this.wetness.texture();
532
+ if (t !== void 0) {
533
+ if (!t || t.dimension !== "2d" || t.sampleCount !== 1 || t.depthOrArrayLayers > 1 || ![
534
+ "r32float",
535
+ "rgba32float",
536
+ "rgba16float"
537
+ ].includes(t.format) || !(t.usage & GPUTextureUsage.COPY_SRC)) throw TypeError("Terrain wetness needs a copyable water-depth texture");
538
+ (this.wet?.width !== t.width || this.wet?.height !== t.height || this.wet?.format !== t.format) && (this.dropRecord(), this.wet = e.device.createTexture({
539
+ size: [t.width, t.height],
540
+ format: t.format,
541
+ usage: GPUTextureUsage.TEXTURE_BINDING | GPUTextureUsage.COPY_DST
542
+ }), this.record = e.device.createTexture({
543
+ size: [t.width, t.height],
544
+ format: "rgba32float",
545
+ usage: GPUTextureUsage.TEXTURE_BINDING | GPUTextureUsage.COPY_DST
546
+ }), this.recordNext = e.device.createTexture({
547
+ size: [t.width, t.height],
548
+ format: "rgba32float",
549
+ usage: GPUTextureUsage.STORAGE_BINDING | GPUTextureUsage.COPY_SRC
550
+ }), this.dryingBuffer ??= e.device.createBuffer({
551
+ size: 16,
552
+ usage: GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST
553
+ }), this.recordPipeline ??= e.device.createComputePipeline({
554
+ layout: "auto",
555
+ compute: {
556
+ module: e.device.createShaderModule({ code: G }),
557
+ entryPoint: "main"
558
+ }
559
+ }), this.recordGroup = e.device.createBindGroup({
560
+ layout: this.recordPipeline.getBindGroupLayout(0),
561
+ entries: [
562
+ {
563
+ binding: 0,
564
+ resource: this.wet.createView()
565
+ },
566
+ {
567
+ binding: 1,
568
+ resource: this.record.createView()
569
+ },
570
+ {
571
+ binding: 2,
572
+ resource: this.recordNext.createView()
573
+ },
574
+ {
575
+ binding: 3,
576
+ resource: { buffer: this.dryingBuffer }
577
+ }
578
+ ]
579
+ }), this.wetEntry = {
580
+ binding: 9,
581
+ resource: this.record.createView()
582
+ }, this.wetTarget.texture = this.wet, this.recordSource.texture = this.recordNext, this.recordTarget.texture = this.record, this.wetSize.width = t.width, this.wetSize.height = t.height), this.wetSource.texture = t, e.encoder.copyTextureToTexture(this.wetSource, this.wetTarget, this.wetSize), this.drying.set([
583
+ this.elapsed,
584
+ this.dryTime,
585
+ this.glossTime,
586
+ 0
587
+ ]), this.elapsed = 0, e.device.queue.writeBuffer(this.dryingBuffer, 0, this.drying);
588
+ let n = e.encoder.beginComputePass();
589
+ n.setPipeline(this.recordPipeline), n.setBindGroup(0, this.recordGroup), n.dispatchWorkgroups(Math.ceil(t.width / 8), Math.ceil(t.height / 8)), n.end(), e.encoder.copyTextureToTexture(this.recordSource, this.recordTarget, this.wetSize);
590
+ }
591
+ let n = t ? this.wetEntry : this.dryEntry;
592
+ n.binding = this.wetBinding, e.bindings.push(n);
593
+ }
594
+ let n = this.engine.gpu;
595
+ this.lookBuffer || (this.lookBuffer = n.createBuffer({
596
+ size: this.look.byteLength,
597
+ usage: GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST
598
+ }), this.lookDirty = !0), this.lookDirty &&= (n.queue.writeBuffer(this.lookBuffer, 0, this.look), !1), this.lookEntry ??= {
599
+ binding: this.lookBinding,
600
+ resource: { buffer: this.lookBuffer }
601
+ }, e.bindings.push(this.lookEntry), e.shader = this.shader;
602
+ }
603
+ });
604
+ }
605
+ onPreUpdate(e) {
606
+ this.elapsed += e;
607
+ }
608
+ dropRecord() {
609
+ this.wet?.destroy(), this.record?.destroy(), this.recordNext?.destroy(), this.wet = this.record = this.recordNext = void 0, this.recordGroup = void 0, this.recordSource.texture = this.recordTarget.texture = void 0;
610
+ }
611
+ onDeviceRestored(e) {
612
+ this.dry?.destroy(), this.dropRecord(), this.dryingBuffer?.destroy(), this.dryingBuffer = this.recordPipeline = void 0, this.dry = void 0, this.dryEntry = this.wetEntry = void 0, this.wetSource.texture = this.wetTarget.texture = void 0, this.lookBuffer?.destroy(), this.lookBuffer = void 0, this.lookEntry = void 0, this.lookDirty = !0, this.engine = void 0, this.setup(e);
613
+ }
614
+ dispose() {
615
+ if (this.disposed) return;
616
+ this.disposed = !0, this.dry?.destroy(), this.dropRecord(), this.dryingBuffer?.destroy(), this.dryingBuffer = this.recordPipeline = void 0, this.dry = void 0, this.dryEntry = this.wetEntry = void 0, this.wetSource.texture = this.wetTarget.texture = void 0, this.lookBuffer?.destroy(), this.lookBuffer = void 0, this.lookEntry = void 0;
617
+ let e = this.engine;
618
+ this.engine = void 0, e?.sceneOf(this)?.removePlugin(this.name);
619
+ }
620
+ [Symbol.dispose ?? Symbol()]() {
621
+ this.dispose();
622
+ }
623
+ };
624
+ //#endregion
625
+ //#region src/heightfield.ts
626
+ function Y(e, t, n, r) {
627
+ if (typeof e != "function" || t.length !== 2 || !Number.isFinite(t[0]) || !Number.isFinite(t[1]) || t[0] <= 0 || t[1] <= 0 || t[0] > 1e5 || t[1] > 1e5 || r.length !== 2 || !Number.isFinite(Math.fround(r[0])) || !Number.isFinite(Math.fround(r[1])) || !Number.isInteger(n) || n < 1 || n > 1024) throw RangeError("Invalid terrain heightfield; pass a height function, a size of 1..100000 per axis, a finite origin and an integer resolution from 1 to 1024.");
628
+ }
629
+ function X(e, t, n) {
630
+ let r = e(t, n);
631
+ if (!Number.isFinite(Math.fround(r))) throw RangeError("Terrain height must be finite");
632
+ return r;
633
+ }
634
+ function Z(e, t) {
635
+ let { size: n, resolution: r = 192, origin: i = [-n[0] / 2, -n[1] / 2] } = t;
636
+ Y(e, n, r, i);
637
+ let a = p(n[0], n[1], r, r);
638
+ for (let t = 0; t < a.positions.length; t += 3) {
639
+ let r = a.positions[t] + i[0] + n[0] / 2, o = -a.positions[t + 1] + i[1] + n[1] / 2;
640
+ a.positions[t] = r, a.positions[t + 1] = X(e, r, o), a.positions[t + 2] = o;
641
+ }
642
+ return m(a);
643
+ }
644
+ function se(e, t) {
645
+ return h(Z(e, t));
646
+ }
647
+ var ce = 0, le = class e {coreRequirement=__margoCoreRequirement("1.0.0",import.meta.url);
648
+ constructor(e, t) {
649
+ this.height = e, this.options = t, this.name = "terrain-heightmap:" + ++ce, this.disposed = !1;
650
+ let { size: n, resolution: r = 256, origin: i = [-n[0] / 2, -n[1] / 2] } = t;
651
+ Y(e, n, r, i), this.options = {
652
+ size: [n[0], n[1]],
653
+ resolution: r,
654
+ origin: [i[0], i[1]]
655
+ };
656
+ }
657
+ static attach(t, n, r) {__margoAssertCore(t,__margoCoreRequirement("1.0.0",import.meta.url));
658
+ let i = new e(n, r);
659
+ return l(t).use(i), i;
660
+ }
661
+ setup(e) {
662
+ if (this.disposed || !e.gpu) throw new f(this.disposed ? "disposed" : "unsupported", "Terrain heightmap requires WebGPU; attach a new TerrainHeightmap to a WebGPU engine");
663
+ let t = e.gpu, { size: n, resolution: r = 256, origin: i = [-n[0] / 2, -n[1] / 2] } = this.options;
664
+ if (r > t.limits.maxTextureDimension2D) throw RangeError("Heightmap resolution exceeds the GPU texture limit; reduce resolution to the device maxTextureDimension2D or less.");
665
+ let a = new Float32Array(r * r);
666
+ for (let e = 0; e < r; e++) for (let t = 0; t < r; t++) a[e * r + t] = X(this.height, i[0] + (t + .5) / r * n[0], i[1] + (e + .5) / r * n[1]);
667
+ this.engine = e, this.texture = t.createTexture({
668
+ size: [r, r],
669
+ format: "r32float",
670
+ usage: GPUTextureUsage.TEXTURE_BINDING | GPUTextureUsage.COPY_DST
671
+ }), t.queue.writeTexture({ texture: this.texture }, a, { bytesPerRow: r * 4 }, [r, r]);
672
+ }
673
+ onDeviceRestored(e) {
674
+ this.texture?.destroy(), this.texture = void 0, this.setup(e);
675
+ }
676
+ dispose() {
677
+ if (this.disposed) return;
678
+ this.disposed = !0, this.texture?.destroy(), this.texture = void 0;
679
+ let e = this.engine;
680
+ this.engine = void 0, e?.sceneOf(this)?.removePlugin(this.name);
681
+ }
682
+ [Symbol.dispose ?? Symbol()]() {
683
+ this.dispose();
684
+ }
685
+ };
686
+ //#endregion
687
+ //#region src/index.ts
688
+ function ue(e, t) {
689
+ if (typeof e != "object" || !e) return !1;
690
+ let n = (e, t, n) => e === void 0 || e >= t && e <= n, r = (e) => e === void 0 || e === 0 || e >= .5 && e <= 500, i = e.slope ?? [28, 44], a = e.dip ?? [0, 0];
691
+ return Array.isArray(i) && i.length === 2 && i[0] >= 0 && i[0] < i[1] && i[1] <= 90 && Array.isArray(a) && a.length === 2 && a.every((e) => e >= -4 && e <= 4) && r(e.strata) && r(e.facets) && n(e.ledges, 0, 1) && n(e.relief, 0, 1) && n(e.tone, 0, 1) && n(e.gullies, 0, 100) && n(e.undulation, 0, 10) && (e.debris === void 0 || Number.isInteger(e.debris) && e.debris >= 0 && e.debris < t);
692
+ }
693
+ function Q(e, t, n, r, i = new Float64Array(r * 2)) {
694
+ for (let a = 0; a < r; a++) {
695
+ let r = n * 2 ** a;
696
+ i[a * 2] = Math.floor(e[0] / r) * r - t[0], i[a * 2 + 1] = Math.floor(e[2] / r) * r - t[2];
697
+ }
698
+ return i;
699
+ }
700
+ function $(e, t, n) {
701
+ for (let r = 0; r < 4; r++) e[56 + r] = t[12 + r] + t[r] * n[0] + t[4 + r] * n[1] + t[8 + r] * n[2];
702
+ }
703
+ var de = 0, fe = class r {coreRequirement=__margoCoreRequirement("1.0.0",import.meta.url);
704
+ constructor(e) {
705
+ this.options = e, this.name = "terrain:" + de++, this.shadowVersion = 0, this.disposed = !1, this.localShadowPipelines = [], this.rings = [], this.sent = /* @__PURE__ */ new WeakMap(), this.bitViews = /* @__PURE__ */ new WeakMap(), this.pipelines = /* @__PURE__ */ new Map(), this.lightingGroups = /* @__PURE__ */ new Map(), this.lighting = /* @__PURE__ */ new Set(), this.lightingEntries = [], this.centerCount = 0, this.ringCount = 0, this.captureCode = /* @__PURE__ */ new Map(), this.disposers = /* @__PURE__ */ new Set(), this.shiftValues = /* @__PURE__ */ new Float64Array(3), this.rulesShift = /* @__PURE__ */ new Float64Array(3), this.rulesEye = new Float64Array([
706
+ NaN,
707
+ NaN,
708
+ NaN
709
+ ]), this.eyeLocal = /* @__PURE__ */ new Float64Array(3), this.eye = /* @__PURE__ */ new Float64Array(3), this.plan = /* @__PURE__ */ new Float64Array(), this.validate();
710
+ let t = e.clipmapAnchor;
711
+ t && t !== "camera" && (this.anchoredEye = [
712
+ t[0],
713
+ 0,
714
+ t[1]
715
+ ]);
716
+ let n = e.floatingOrigin;
717
+ n && (this.anchor = [e.origin?.[0] ?? 0, e.origin?.[1] ?? 0], this.shiftValues.set([
718
+ n.origin[0],
719
+ n.origin[1],
720
+ n.origin[2]
721
+ ]), this.unfollow = n.onRebase((e, t) => this.shiftValues.set([
722
+ t[0],
723
+ t[1],
724
+ t[2]
725
+ ])));
726
+ }
727
+ get shift() {
728
+ return this.shiftValues;
729
+ }
730
+ get surfaceHeightTexture() {
731
+ return this.capturedSurface?.texture;
732
+ }
733
+ static attach(e, t) {__margoAssertCore(e,__margoCoreRequirement("1.0.0",import.meta.url));
734
+ let n = new r(t);
735
+ return l(e).use(n), n;
736
+ }
737
+ validate() {
738
+ let e = this.options;
739
+ if (typeof e.textures != "function" || !Number.isInteger(e.resolution ?? 64) || (e.resolution ?? 64) < 8 || (e.resolution ?? 64) > 256 || (e.resolution ?? 64) % 4 || !Number.isInteger(e.levels ?? 6) || (e.levels ?? 6) < 1 || (e.levels ?? 6) > 12 || e.roughness !== void 0 && !(e.roughness >= 0 && e.roughness <= 1) || e.patches !== void 0 && (typeof e.patches != "object" || e.patches === null || !((e.patches.size ?? 14) >= .5 && (e.patches.size ?? 14) <= 1e4) || !((e.patches.contrast ?? .6) > 0 && (e.patches.contrast ?? .6) <= 1) || !((e.patches.warp ?? 0) >= 0 && (e.patches.warp ?? 0) <= 1) || !(e.patches.terraces === void 0 || e.patches.terraces === 0 || e.patches.terraces >= .5 && e.patches.terraces <= 1e3)) || e.rock !== void 0 && !ue(e.rock, e.layers?.length ?? 0) || !Number.isFinite(Math.fround(e.cellSize ?? 1)) || (e.cellSize ?? 1) <= 0 || !Number.isFinite(Math.fround(e.heightScale ?? 100)) || !Number.isFinite(Math.fround(e.heightOffset ?? 0)) || !Array.isArray(e.layers) || e.layers.length < 4 || e.layers.length > 16) throw RangeError("Invalid terrain options; check textures, resolution (multiple of 4, 8..256), levels (1..12), roughness (0..1), patches (size 0.5..10000 m, contrast above 0 to 1, warp 0..1, terraces 0 or 0.5..1000 m), rock (slope 0 <= start < full <= 90, strata and facets 0 or 0.5..500 m, ledges, relief and tone 0..1, dip -4..4, gullies 0..100 m, undulation 0..10 m, debris a layer index), cellSize above 0, finite heightScale and heightOffset, and 4 to 16 layers.");
740
+ d(e.origin ?? [0, 0], 2, "Terrain origin"), e.clipmapAnchor !== void 0 && e.clipmapAnchor !== "camera" && d(e.clipmapAnchor, 2, "Terrain clipmap anchor");
741
+ let t = e.floatingOrigin;
742
+ if (t !== void 0 && (typeof t?.onRebase != "function" || t.origin?.length !== 3)) throw TypeError("Invalid terrain floatingOrigin; pass a FloatingOrigin from @margoengine/cameras/origin.");
743
+ if (t && d(t.origin, 3, "Terrain floatingOrigin origin"), d(e.size, 2, "Terrain size"), e.size.some((e) => e <= 0)) throw RangeError("Invalid terrain size; give a [width, depth] with both above 0.");
744
+ for (let t of e.layers) {
745
+ if (d(t.height, 2, "Layer height"), d(t.slope, 2, "Layer slope"), t.height[0] >= t.height[1] || t.slope[0] < 0 || t.slope[1] > 1 || t.slope[0] >= t.slope[1] || !Number.isFinite(Math.fround(t.scale)) || t.scale <= 0) throw RangeError("Invalid terrain layer; height must rise, slope must rise within 0..1 and scale must be above 0.");
746
+ if (![t.bump ?? 0, t.macro ?? 0].every((e) => typeof e == "number" && e >= 0 && e <= 1)) throw RangeError("Invalid terrain layer bump or macro; give each a number from 0 to 1 (default 0).");
747
+ }
748
+ }
749
+ addLighting(e) {
750
+ if (this.disposed || !e || typeof e.shader != "function" || typeof e.bindings != "function") throw TypeError("Invalid terrain lighting; pass a live Terrain an effect with shader() and bindings() functions.");
751
+ if (e.owner && this.engine && e.owner !== this.engine) throw new f("attached", "Terrain lighting belongs to another engine; use objects created by the same engine");
752
+ return this.lighting.add(e), () => this.lighting.delete(e);
753
+ }
754
+ invalidate() {
755
+ this.shadowVersion++;
756
+ }
757
+ get heightmap() {
758
+ return this.textures?.heightmap;
759
+ }
760
+ get weights() {
761
+ return this.textures?.weights;
762
+ }
763
+ get holes() {
764
+ return this.textures?.holes;
765
+ }
766
+ setup(e) {
767
+ if (this.disposed || !e.gpu) throw new f(this.disposed ? "disposed" : "unsupported", "Terrain requires WebGPU and a live module; attach a new Terrain to a WebGPU engine; see https://margoengine.com/errors#webgpu");
768
+ this.engine = e, this.device = e.gpu, this.textures = this.options.textures(this.device);
769
+ let t = this.textures, n = t.weights, r = t.tint, i = t.holes, a = t.structure;
770
+ if (r !== void 0 && (!n || !["rgba8unorm", "rgba8unorm-srgb"].includes(r?.format) || r.depthOrArrayLayers !== 1)) throw TypeError("Terrain tint must be one rgba8unorm or rgba8unorm-srgb 2D texture, given with weights");
771
+ if (n !== void 0 && (!Array.isArray(n) || n.length < 2 || n.length > 4 || n.length * 4 < this.options.layers.length)) throw TypeError("Terrain weights must be 2 to 4 rgba8unorm 2D textures, one per 4 layers; pass the same texture twice for 4 layers");
772
+ for (let e of [
773
+ t.heightmap,
774
+ t.layers,
775
+ ...t.normalmap ? [t.normalmap] : [],
776
+ ...n ?? [],
777
+ ...r ? [r] : [],
778
+ ...i ? [i] : [],
779
+ ...a ? [a] : []
780
+ ]) if (e.dimension !== "2d" || !(e.usage & GPUTextureUsage.TEXTURE_BINDING) || e.sampleCount !== 1) throw TypeError("Terrain textures must be sampled 2D textures");
781
+ if (t.heightmap.depthOrArrayLayers !== 1 || t.normalmap && t.normalmap.depthOrArrayLayers !== 1 || t.layers.depthOrArrayLayers !== this.options.layers.length || ![
782
+ "rgba8unorm",
783
+ "rgba8unorm-srgb",
784
+ "rgba16float"
785
+ ].includes(t.layers.format) || ![
786
+ "r32float",
787
+ "rgba16float",
788
+ "rgba8unorm"
789
+ ].includes(t.heightmap.format) || t.normalmap && !["rgba8unorm", "rgba16float"].includes(t.normalmap.format) || n && n.some((e) => e.format !== "rgba8unorm" || e.depthOrArrayLayers !== 1) || i && (!["r8unorm", "rgba8unorm"].includes(i.format) || i.depthOrArrayLayers !== 1) || a && (a.format !== "rgba8unorm" || a.depthOrArrayLayers !== 1)) throw TypeError("Invalid terrain texture format or layer count; use a layers array texture with one layer per terrain layer and a supported heightmap format.");
790
+ let o = g(this.options.resolution ?? 64), s = (e, t) => {
791
+ if (e.byteLength > this.device.limits.maxBufferSize) throw RangeError("Terrain grid exceeds the device maxBufferSize; reduce resolution.");
792
+ let n = this.device.createBuffer({
793
+ size: e.byteLength,
794
+ usage: t | GPUBufferUsage.COPY_DST
795
+ });
796
+ try {
797
+ this.device.queue.writeBuffer(n, 0, e);
798
+ } catch (e) {
799
+ throw n.destroy(), e;
800
+ }
801
+ return n;
802
+ };
803
+ this.vertex = s(o.vertices, GPUBufferUsage.VERTEX), this.center = s(o.center, GPUBufferUsage.INDEX), this.ring = s(o.ring, GPUBufferUsage.INDEX), this.centerCount = o.center.length, this.ringCount = o.ring.length, this.rules = s(this.ruleData(), GPUBufferUsage.STORAGE), this.rulesShift.set(this.shiftValues), this.sampler = this.device.createSampler({
804
+ addressModeU: "repeat",
805
+ addressModeV: "repeat",
806
+ magFilter: "linear",
807
+ minFilter: "linear",
808
+ mipmapFilter: "linear",
809
+ maxAnisotropy: 16
810
+ });
811
+ let c = GPUShaderStage.VERTEX, l = GPUShaderStage.FRAGMENT;
812
+ this.layout = this.device.createBindGroupLayout({ entries: [
813
+ ...t.source?.entries(this.sourceBinding()) ?? [],
814
+ {
815
+ binding: 0,
816
+ visibility: c | l,
817
+ buffer: { type: "uniform" }
818
+ },
819
+ {
820
+ binding: 1,
821
+ visibility: c | l,
822
+ texture: { sampleType: "unfilterable-float" }
823
+ },
824
+ {
825
+ binding: 2,
826
+ visibility: c | l,
827
+ texture: { sampleType: "unfilterable-float" }
828
+ },
829
+ {
830
+ binding: 3,
831
+ visibility: l,
832
+ texture: { viewDimension: "2d-array" }
833
+ },
834
+ {
835
+ binding: 4,
836
+ visibility: l,
837
+ sampler: { type: "filtering" }
838
+ },
839
+ {
840
+ binding: 5,
841
+ visibility: l,
842
+ buffer: { type: "read-only-storage" }
843
+ },
844
+ ...[
845
+ ...n ?? [],
846
+ ...r ? [r] : [],
847
+ ...t.holes ? [t.holes] : [],
848
+ ...a ? [a] : []
849
+ ].map((e, t) => ({
850
+ binding: 6 + t,
851
+ visibility: l,
852
+ texture: {}
853
+ }))
854
+ ] });
855
+ let u = [
856
+ t.heightmap.createView(),
857
+ (t.normalmap ?? t.heightmap).createView(),
858
+ t.layers.createView({ dimension: "2d-array" }),
859
+ this.sampler,
860
+ { buffer: this.rules },
861
+ ...n ? n.map((e) => e.createView()) : [],
862
+ ...r ? [r.createView()] : [],
863
+ ...t.holes ? [t.holes.createView()] : [],
864
+ ...a ? [a.createView()] : [],
865
+ ...t.source?.resources() ?? []
866
+ ], d = (e) => this.device.createBindGroup({
867
+ layout: this.layout,
868
+ entries: [{
869
+ binding: 0,
870
+ resource: { buffer: e }
871
+ }, ...u.map((e, t) => ({
872
+ binding: t + 1,
873
+ resource: e
874
+ }))]
875
+ });
876
+ this.ringGroup = d;
877
+ let p = this.options.floatingOrigin ? 60 : 48;
878
+ for (let e = 0; e < (this.options.levels ?? 6); e++) {
879
+ let e = this.device.createBuffer({
880
+ size: p * 4,
881
+ usage: GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST
882
+ }), t = [], n = {
883
+ uniform: e,
884
+ group: void 0,
885
+ values: new Float32Array(p),
886
+ shadowUniforms: t,
887
+ shadowGroups: [],
888
+ shadowValues: new Float32Array(p),
889
+ localUniforms: [],
890
+ localGroups: [],
891
+ captureUniforms: [],
892
+ captureGroups: []
893
+ };
894
+ this.rings.push(n), n.group = d(e);
895
+ for (let e = 0; e < 4; e++) {
896
+ let e = this.device.createBuffer({
897
+ size: p * 4,
898
+ usage: GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST
899
+ });
900
+ t.push(e), n.shadowGroups.push(d(e));
901
+ }
902
+ }
903
+ let m = this.device.createShaderModule({ code: this.clip(y + `@fragment fn outside(i:Output){${x}}`) });
904
+ this.shadowModule = m, this.shadowPipeline = this.device.createRenderPipeline({
905
+ layout: this.device.createPipelineLayout({ bindGroupLayouts: [this.layout] }),
906
+ vertex: {
907
+ module: m,
908
+ entryPoint: "vertex",
909
+ buffers: [{
910
+ arrayStride: 8,
911
+ attributes: [{
912
+ shaderLocation: 0,
913
+ offset: 0,
914
+ format: "float32x2"
915
+ }]
916
+ }]
917
+ },
918
+ fragment: {
919
+ module: m,
920
+ entryPoint: "outside",
921
+ targets: []
922
+ },
923
+ depthStencil: {
924
+ format: "depth32float",
925
+ depthWriteEnabled: !0,
926
+ depthCompare: "less-equal"
927
+ }
928
+ }), this.invalidate();
929
+ }
930
+ ruleData() {
931
+ let e = this.textures.tint, t = !!this.options.floatingOrigin, n = this.shiftValues, r = this.surface() ? 12 : 8, i = r + (t ? 16 : 0), a = new Float32Array(this.options.layers.length * i);
932
+ return this.options.layers.forEach((o, s) => {
933
+ if (a.set([
934
+ o.height[0] - n[1],
935
+ o.height[1] - n[1],
936
+ ...o.slope,
937
+ o.scale,
938
+ Math.max(.01, (o.height[1] - o.height[0]) * .05),
939
+ .05,
940
+ +(!!e && !!o.tint),
941
+ ...r === 12 ? [
942
+ (o.bump ?? 0) * .5 / o.scale,
943
+ o.macro ?? 0,
944
+ o.scale / 24,
945
+ 0
946
+ ] : []
947
+ ], s * i), !t) return;
948
+ let c = Math.fround(o.scale), l = this.eye, u = [
949
+ n[0] - this.anchor[0],
950
+ n[1],
951
+ n[2] - this.anchor[1]
952
+ ], d = [
953
+ l[0] - this.anchor[0],
954
+ l[1],
955
+ l[2] - this.anchor[1]
956
+ ];
957
+ for (let [e, t] of [[u, r], [d, r + 8]]) for (let n = 0; n < 3; n++) {
958
+ let r = Math.floor(e[n] * c / 24), o = r * Math.fround(.302);
959
+ a[s * i + t + n] = e[n] - r * 24 / c, a[s * i + t + 4 + n] = o - Math.floor(o);
960
+ }
961
+ }), a;
962
+ }
963
+ registerPasses(e) {
964
+ e.add({
965
+ name: this.name + ":prepare",
966
+ order: this.options.captureSurfaceHeight ? -11 : -6,
967
+ execute: (e) => {
968
+ e.backend === "webgpu" && this.prepare(e);
969
+ }
970
+ }), e.add({
971
+ name: this.name,
972
+ order: 1,
973
+ execute: (e) => {
974
+ e.backend === "webgpu" && this.drawRings(e);
975
+ }
976
+ });
977
+ }
978
+ prepare(e) {
979
+ let t = this.options.origin, r = this.options.size, i = this.options.resolution ?? 64, o = this.options.heightScale ?? 100, s = this.options.heightOffset ?? 0, c = this.options.layers.length, l = this.options.cellSize ?? 1, u = +a(e.format), d = +!!this.textures.normalmap, f = this.options.floatingOrigin, p = this.shiftValues, m = e.camera.position;
980
+ if (f) {
981
+ for (let e = 0; e < 3; e++) this.eyeLocal[e] = m[e], this.eye[e] = m[e] + p[e];
982
+ m = this.eye;
983
+ let t = this.rulesShift, n = this.rulesEye, r = this.eye;
984
+ (t[0] !== p[0] || t[1] !== p[1] || t[2] !== p[2] || n[0] !== r[0] || n[1] !== r[1] || n[2] !== r[2]) && (e.device.queue.writeBuffer(this.rules, 0, this.ruleData()), t.set(p), n.set(r));
985
+ }
986
+ if (this.plan.length !== this.rings.length * 2 && (this.plan = new Float64Array(this.rings.length * 2)), !this.anchoredEye && this.options.clipmapAnchor !== "camera") {
987
+ let t = this.engine?.camera?.position ?? e.camera.position;
988
+ this.anchoredEye = [
989
+ t[0] + p[0],
990
+ 0,
991
+ t[2] + p[2]
992
+ ];
993
+ }
994
+ let h = Q(this.anchoredEye ?? m, p, l, this.rings.length, this.plan), g = 0, _ = 0, v = !1;
995
+ for (let a = 0; a < this.rings.length; a++) {
996
+ let m = this.rings[a].values, y = l * 2 ** a, b = h[a * 2], x = h[a * 2 + 1];
997
+ (m[28] !== Math.fround(b) || m[29] !== Math.fround(x)) && (v = !0), m.set(e.camera.matrix), m.set(e.camera.position, 16), n(m, 20, this.engine.lighting.direction), m.set(this.engine.lighting.radiance, 24), m[28] = b, m[29] = x, m[30] = y, m[31] = i, m[32] = a ? g - b : 0, m[33] = a ? _ - x : 0, m[34] = a, m[35] = d, m[36] = (t?.[0] ?? 0) - p[0], m[37] = (t?.[1] ?? 0) - p[2], m[38] = r[0], m[39] = r[1], m[40] = o, m[41] = s - p[1], m[42] = c, m[43] = u;
998
+ let S = this.engine.lighting.ambient;
999
+ if (m[44] = S?.[0] ?? 1, m[45] = S?.[1] ?? 1, m[46] = S?.[2] ?? 1, m[47] = 0, f) {
1000
+ m[48] = p[0] - this.anchor[0], m[49] = p[2] - this.anchor[1], m[50] = p[1], m[51] = 0;
1001
+ let t = this.eyeLocal;
1002
+ m[52] = b - t[0], m[53] = x - t[2], m[54] = t[1], m[55] = 0, $(m, e.camera.matrix, t);
1003
+ }
1004
+ this.upload(e.device.queue, this.rings[a].uniform, m), g = b, _ = x;
1005
+ }
1006
+ v && this.invalidate(), this.options.captureSurfaceHeight && (this.capturedSurface ??= te(e.device, this.textures.heightmap, this.layout, f ? T(y) : y, (e) => this.clip(e), !!f), this.capturedSurface?.draw(e.encoder, this.shadowVersion, this.rings, {
1007
+ vertex: this.vertex,
1008
+ center: this.center,
1009
+ ring: this.ring,
1010
+ centerCount: this.centerCount,
1011
+ ringCount: this.ringCount
1012
+ }));
1013
+ }
1014
+ shader() {
1015
+ let e = this.base();
1016
+ for (let t of this.lighting) e = t.shader(e, 1);
1017
+ for (let t of this.lighting) t.finish && (e = t.finish(e, 1));
1018
+ return this.options.floatingOrigin ? O(e) : e;
1019
+ }
1020
+ colorSource() {
1021
+ if (!this.disposed && this.layout && this.rings[0]?.group) return {
1022
+ code: this.base(),
1023
+ layout: this.layout,
1024
+ group: this.rings[0].group
1025
+ };
1026
+ }
1027
+ base() {
1028
+ let e = this.options.roughness, t = this.surface(), n = e === void 0 ? y : y.replace("o.material=vec4f(0.9,0,1,1)", `o.material=vec4f(${e},0,1,1)`), r = (t ? S(n) : n) + (this.textures?.weights ? F(this.textures.weights.length, t, !!this.textures.tint, this.options.patches ? {
1029
+ size: this.options.patches.size ?? 14,
1030
+ contrast: this.options.patches.contrast ?? .6,
1031
+ warp: this.options.patches.warp ?? 0,
1032
+ terraces: this.options.patches.terraces ?? 0
1033
+ } : void 0, this.rockShader()) : M(t, this.rockShader()));
1034
+ return this.clip(this.options.floatingOrigin ? T(r) : r);
1035
+ }
1036
+ clip(e) {
1037
+ let t = this.textures;
1038
+ return t?.holes && (e = `@group(0) @binding(${this.holesBinding()}) var terrainHoles:texture_2d<f32>;
1039
+ ${e.split(x).join(x + b)}`), t?.source ? t.source.shader(e, this.sourceBinding()) : e;
1040
+ }
1041
+ holesBinding() {
1042
+ let e = this.textures;
1043
+ return 6 + (e.weights?.length ?? 0) + +!!e.tint;
1044
+ }
1045
+ sourceBinding() {
1046
+ let e = this.textures;
1047
+ return this.holesBinding() + +!!e.holes + +!!e.structure;
1048
+ }
1049
+ rockShader() {
1050
+ let e = this.options.rock;
1051
+ if (e) return {
1052
+ slope: e.slope ?? [28, 44],
1053
+ strata: e.strata ?? 9,
1054
+ ledges: e.ledges ?? .6,
1055
+ dip: e.dip ?? [0, 0],
1056
+ facets: e.facets ?? 18,
1057
+ relief: e.relief ?? .45,
1058
+ gullies: e.gullies ?? 6,
1059
+ undulation: e.undulation ?? 0,
1060
+ tone: e.tone ?? .35,
1061
+ debris: this.textures?.weights && e.debris !== void 0 ? e.debris : -1,
1062
+ map: this.textures?.structure ? this.sourceBinding() - 1 : -1
1063
+ };
1064
+ }
1065
+ surface() {
1066
+ return this.options.layers.some((e) => (e.bump ?? 0) > 0 || (e.macro ?? 0) > 0);
1067
+ }
1068
+ drawRings(t) {
1069
+ let n = this.shader(), r = t.descriptor.multisample?.count + ":" + t.format + ":" + t.descriptor.depthStencil.format + n, a = this.pipelines.get(r), o = this.lightingEntries;
1070
+ o.length = 0;
1071
+ for (let e of this.lighting) {
1072
+ let t = e.bindings();
1073
+ for (let e = 0; e < t.length; e++) o.push(t[e]);
1074
+ }
1075
+ if (!a) {
1076
+ let i = t.device.createShaderModule({ code: n }), s = [this.layout];
1077
+ o.length && s.push(t.device.createBindGroupLayout({ entries: e(n, o) })), a = t.device.createRenderPipeline({
1078
+ layout: t.device.createPipelineLayout({ bindGroupLayouts: s }),
1079
+ vertex: {
1080
+ module: i,
1081
+ entryPoint: "vertex",
1082
+ buffers: [{
1083
+ arrayStride: 8,
1084
+ attributes: [{
1085
+ shaderLocation: 0,
1086
+ offset: 0,
1087
+ format: "float32x2"
1088
+ }]
1089
+ }]
1090
+ },
1091
+ fragment: {
1092
+ module: i,
1093
+ entryPoint: "fragment",
1094
+ targets: [{ format: t.format }]
1095
+ },
1096
+ multisample: t.descriptor.multisample,
1097
+ depthStencil: {
1098
+ format: t.descriptor.depthStencil.format,
1099
+ depthWriteEnabled: !0,
1100
+ depthCompare: "greater-equal"
1101
+ }
1102
+ }), this.pipelines.set(r, a);
1103
+ }
1104
+ let s = t.encoder.beginRenderPass({
1105
+ colorAttachments: [{
1106
+ view: t.color,
1107
+ loadOp: "load",
1108
+ storeOp: "store"
1109
+ }],
1110
+ depthStencilAttachment: {
1111
+ view: t.depth,
1112
+ depthLoadOp: "load",
1113
+ depthStoreOp: "store",
1114
+ ...t.descriptor.depthStencil.format.includes("stencil") ? {
1115
+ stencilLoadOp: "load",
1116
+ stencilStoreOp: "store"
1117
+ } : {}
1118
+ }
1119
+ });
1120
+ i(s, t), s.setPipeline(a), o.length && s.setBindGroup(1, this.lightingGroup(t.device, a, o)), s.setVertexBuffer(0, this.vertex);
1121
+ for (let e = 0; e < this.rings.length; e++) s.setBindGroup(0, this.rings[e].group), s.setIndexBuffer(e ? this.ring : this.center, "uint32"), s.drawIndexed(e ? this.ringCount : this.centerCount), this.engine.stats.drawCalls++;
1122
+ s.end();
1123
+ }
1124
+ setCapture(e) {
1125
+ if (this.disposed || !e || typeof e.declarations != "function" || typeof e.begin != "function" || !Array.isArray(e.targets)) throw TypeError("Invalid terrain capture hook; pass an object with declarations() and begin() functions and a targets array to a live Terrain.");
1126
+ return this.capture = e, () => {
1127
+ this.capture === e && (this.capture = void 0);
1128
+ };
1129
+ }
1130
+ onDispose(e) {
1131
+ if (typeof e != "function") throw TypeError("Terrain onDispose needs a function");
1132
+ return this.disposers.add(e), () => this.disposers.delete(e);
1133
+ }
1134
+ draw(n, r, i, a) {
1135
+ let o = this.capture;
1136
+ if (r !== "capture" || !o || this.disposed || !this.rings.length) return;
1137
+ let s = this.shader(), c = o.declarations(s), l = c + "\0" + s, u = this.captureCode.get(l);
1138
+ if (u === void 0) {
1139
+ let e = "@fragment fn fragment(i:Output)->@location(0) vec4f {";
1140
+ if (s.split(e).length !== 2) throw t("unsupported", "Terrain capture needs the terrain fragment entry point once; a lighting effect changed it");
1141
+ let n = x + (this.textures?.holes ? b : ""), r = this.textures?.source;
1142
+ u = c + s.replace(e, "fn margoShade(i:Output)->vec4f {") + `\n@fragment fn capture(i:Output)->MargoSSR {${this.options.floatingOrigin ? D : ""}${r ? r.shader(n, this.sourceBinding()) : n}${A(this.surface(), !!this.options.rock)}let v=normalize(frame.eye.xyz-i.position);${c.includes("var<private> margoPosition:") ? "margoPosition=i.position;" : ""}return margoSSR(n,v,base,i.material.y,i.material.x);}\n`, this.captureCode.size >= 16 && this.captureCode.clear(), this.captureCode.set(l, u);
1143
+ }
1144
+ let d = this.lightingEntries;
1145
+ d.length = 0;
1146
+ for (let e of this.lighting) {
1147
+ let t = e.bindings();
1148
+ for (let e = 0; e < t.length; e++) d.push(t[e]);
1149
+ }
1150
+ let f = "capture:" + o.targets.map((e) => e.format).join(",") + ":" + n.descriptor.multisample?.count + ":" + n.descriptor.depthStencil.format + u, p = this.pipelines.get(f);
1151
+ if (!p) {
1152
+ let t = n.device.createShaderModule({ code: u }), r = [this.layout];
1153
+ d.length && r.push(n.device.createBindGroupLayout({ entries: e(u, d) })), p = n.device.createRenderPipeline({
1154
+ layout: n.device.createPipelineLayout({ bindGroupLayouts: r }),
1155
+ vertex: {
1156
+ module: t,
1157
+ entryPoint: "vertex",
1158
+ buffers: [{
1159
+ arrayStride: 8,
1160
+ attributes: [{
1161
+ shaderLocation: 0,
1162
+ offset: 0,
1163
+ format: "float32x2"
1164
+ }]
1165
+ }]
1166
+ },
1167
+ fragment: {
1168
+ module: t,
1169
+ entryPoint: "capture",
1170
+ targets: o.targets
1171
+ },
1172
+ multisample: n.descriptor.multisample,
1173
+ depthStencil: {
1174
+ format: n.descriptor.depthStencil.format,
1175
+ depthWriteEnabled: !0,
1176
+ depthCompare: "greater-equal"
1177
+ }
1178
+ }), this.pipelines.set(f, p);
1179
+ }
1180
+ let m = o.begin();
1181
+ m.setPipeline(p), d.length && m.setBindGroup(1, this.lightingGroup(n.device, p, d)), m.setVertexBuffer(0, this.vertex);
1182
+ let h = this.otherCamera(n.camera), g = n.view?.index ?? 0;
1183
+ for (let e = 0; e < this.rings.length; e++) {
1184
+ let t = this.rings[e], r = t.group;
1185
+ if (h) {
1186
+ let e = t.captureUniforms[g];
1187
+ e || (e = t.captureUniforms[g] = n.device.createBuffer({
1188
+ size: t.values.length * 4,
1189
+ usage: GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST
1190
+ }), t.captureGroups[g] = this.ringGroup(e)), t.shadowValues.set(t.values), t.shadowValues.set(n.camera.matrix), t.shadowValues.set(n.camera.position, 16), this.options.floatingOrigin && $(t.shadowValues, n.camera.matrix, this.eyeLocal), this.upload(n.device.queue, e, t.shadowValues), r = t.captureGroups[g];
1191
+ }
1192
+ m.setBindGroup(0, r), m.setIndexBuffer(e ? this.ring : this.center, "uint32"), m.drawIndexed(e ? this.ringCount : this.centerCount);
1193
+ }
1194
+ }
1195
+ otherCamera(e) {
1196
+ let t = this.rings[0].values, n = e.matrix, r = e.position;
1197
+ for (let e = 0; e < 16; e++) if (t[e] !== Math.fround(n[e])) return !0;
1198
+ for (let e = 0; e < 3; e++) if (t[16 + e] !== Math.fround(r[e])) return !0;
1199
+ return !1;
1200
+ }
1201
+ lightingGroup(e, t, n) {
1202
+ let r = this.lightingGroups.get(t);
1203
+ if (r?.device === e && r.entries.length === n.length && n.every((e, t) => {
1204
+ let n = r.entries[t], i = e.resource, a = n.resource;
1205
+ return e.binding === n.binding && (i === a || "buffer" in i && "buffer" in a && i.buffer === a.buffer && i.offset === a.offset && i.size === a.size);
1206
+ })) return r.group;
1207
+ let i = n.map(({ binding: e, resource: t }) => ({
1208
+ binding: e,
1209
+ resource: "buffer" in t ? {
1210
+ buffer: t.buffer,
1211
+ offset: t.offset,
1212
+ size: t.size
1213
+ } : t
1214
+ })), a = e.createBindGroup({
1215
+ layout: t.getBindGroupLayout(1),
1216
+ entries: n
1217
+ });
1218
+ return this.lightingGroups.set(t, {
1219
+ device: e,
1220
+ entries: i,
1221
+ group: a
1222
+ }), a;
1223
+ }
1224
+ drawOccluder({ pass: e, samples: t }) {
1225
+ if (!this.disposed && this.device) {
1226
+ if (this.occluder?.samples !== t) {
1227
+ let e = this.device.createShaderModule({ code: this.clip(y + `@fragment fn outside(i:Output){${x}}`) });
1228
+ this.occluder = {
1229
+ samples: t,
1230
+ pipeline: this.device.createRenderPipeline({
1231
+ layout: this.device.createPipelineLayout({ bindGroupLayouts: [this.layout] }),
1232
+ vertex: {
1233
+ module: e,
1234
+ entryPoint: "vertex",
1235
+ buffers: [{
1236
+ arrayStride: 8,
1237
+ attributes: [{
1238
+ shaderLocation: 0,
1239
+ offset: 0,
1240
+ format: "float32x2"
1241
+ }]
1242
+ }]
1243
+ },
1244
+ fragment: {
1245
+ module: e,
1246
+ entryPoint: "outside",
1247
+ targets: []
1248
+ },
1249
+ multisample: { count: t },
1250
+ depthStencil: {
1251
+ format: "depth32float",
1252
+ depthWriteEnabled: !0,
1253
+ depthCompare: "greater-equal"
1254
+ }
1255
+ })
1256
+ };
1257
+ }
1258
+ e.setPipeline(this.occluder.pipeline), e.setVertexBuffer(0, this.vertex);
1259
+ for (let t = 0; t < this.rings.length; t++) e.setBindGroup(0, this.rings[t].group), e.setIndexBuffer(t ? this.ring : this.center, "uint32"), e.drawIndexed(t ? this.ringCount : this.centerCount);
1260
+ }
1261
+ }
1262
+ drawShadow({ context: e, pass: t, matrix: n, cascade: r }) {
1263
+ if (!this.disposed) {
1264
+ t.setPipeline(this.shadowPipeline), t.setVertexBuffer(0, this.vertex);
1265
+ for (let i = 0; i < this.rings.length; i++) {
1266
+ let a = this.rings[i];
1267
+ a.shadowValues.set(a.values), a.shadowValues.set(n), this.upload(e.device.queue, a.shadowUniforms[r], a.shadowValues), t.setBindGroup(0, a.shadowGroups[r]), t.setIndexBuffer(i ? this.ring : this.center, "uint32"), t.drawIndexed(i ? this.ringCount : this.centerCount);
1268
+ }
1269
+ }
1270
+ }
1271
+ drawLocalShadow({ context: e, pass: t, matrix: n, layer: r, depthCompare: i = "greater" }) {
1272
+ if (this.disposed || !this.shadowModule || !this.ringGroup) return;
1273
+ if (!Number.isInteger(r) || r < 0) throw RangeError("Invalid local shadow layer; pass the integer layer index LocalShadows gives");
1274
+ if (i !== "greater" && i !== "less-equal") throw RangeError("Invalid local shadow depthCompare; pass 'greater' or 'less-equal'");
1275
+ let a = e.device, o = this.shadowModule, s = i === "less-equal", c = r * 2 + +!!s, l = this.localShadowPipelines[+!!s] ??= a.createRenderPipeline({
1276
+ layout: a.createPipelineLayout({ bindGroupLayouts: [this.layout] }),
1277
+ vertex: {
1278
+ module: o,
1279
+ entryPoint: "vertex",
1280
+ buffers: [{
1281
+ arrayStride: 8,
1282
+ attributes: [{
1283
+ shaderLocation: 0,
1284
+ offset: 0,
1285
+ format: "float32x2"
1286
+ }]
1287
+ }]
1288
+ },
1289
+ fragment: {
1290
+ module: o,
1291
+ entryPoint: "outside",
1292
+ targets: []
1293
+ },
1294
+ depthStencil: {
1295
+ format: "depth32float",
1296
+ depthWriteEnabled: !0,
1297
+ depthCompare: i
1298
+ }
1299
+ });
1300
+ t.setPipeline(l), t.setVertexBuffer(0, this.vertex);
1301
+ for (let e = 0; e < this.rings.length; e++) {
1302
+ let r = this.rings[e], i = r.localUniforms[c];
1303
+ i || (i = r.localUniforms[c] = a.createBuffer({
1304
+ size: r.values.length * 4,
1305
+ usage: GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST
1306
+ }), r.localGroups[c] = this.ringGroup(i)), r.shadowValues.set(r.values), r.shadowValues.set(n), this.upload(a.queue, i, r.shadowValues), t.setBindGroup(0, r.localGroups[c]), t.setIndexBuffer(e ? this.ring : this.center, "uint32"), t.drawIndexed(e ? this.ringCount : this.centerCount);
1307
+ }
1308
+ }
1309
+ upload(e, t, n) {
1310
+ let r = this.bitViews.get(n);
1311
+ r || this.bitViews.set(n, r = new Uint32Array(n.buffer, n.byteOffset, n.length));
1312
+ let i = this.sent.get(t);
1313
+ if (i) {
1314
+ let e = !0;
1315
+ for (let t = 0; t < r.length; t++) if (r[t] !== i[t]) {
1316
+ e = !1;
1317
+ break;
1318
+ }
1319
+ if (e) return;
1320
+ } else this.sent.set(t, i = new Uint32Array(r.length));
1321
+ i.set(r), e.writeBuffer(t, 0, n);
1322
+ }
1323
+ release() {
1324
+ this.capturedSurface?.texture.destroy(), this.capturedSurface = void 0;
1325
+ for (let e of new Set(this.textures ? [
1326
+ this.textures.heightmap,
1327
+ this.textures.normalmap,
1328
+ this.textures.layers,
1329
+ ...this.textures.weights ?? [],
1330
+ this.textures.tint,
1331
+ this.textures.holes,
1332
+ this.textures.structure
1333
+ ] : [])) e?.destroy();
1334
+ for (let e of [
1335
+ this.vertex,
1336
+ this.center,
1337
+ this.ring,
1338
+ this.rules
1339
+ ]) e?.destroy();
1340
+ for (let e of this.rings) for (let t of [
1341
+ e.uniform,
1342
+ ...e.shadowUniforms,
1343
+ ...e.localUniforms,
1344
+ ...e.captureUniforms
1345
+ ]) t?.destroy();
1346
+ this.textures = void 0, this.vertex = this.center = this.ring = this.rules = void 0, this.rings = [], this.pipelines.clear(), this.occluder = void 0, this.lightingGroups.clear(), this.localShadowPipelines = [], this.shadowPipeline = this.shadowModule = this.ringGroup = void 0, this.layout = void 0, this.sampler = void 0;
1347
+ }
1348
+ onDeviceRestored(e) {
1349
+ this.release(), this.setup(e);
1350
+ }
1351
+ dispose() {
1352
+ if (this.disposed) return;
1353
+ this.disposed = !0, this.engine?.sceneOf(this)?.removePlugin(this.name), this.release(), this.unfollow?.(), this.unfollow = void 0, this.lighting.clear(), this.capture = void 0, this.captureCode.clear(), this.engine = this.device = void 0;
1354
+ let e = [...this.disposers];
1355
+ this.disposers.clear();
1356
+ for (let t of e) t();
1357
+ }
1358
+ [Symbol.dispose ?? Symbol()]() {
1359
+ this.dispose();
1360
+ }
1361
+ destroy() {
1362
+ this.dispose();
1363
+ }
1364
+ };
1365
+ //#endregion
1366
+ export { Z as a, K as c, se as i, g as l, Q as n, ae as o, le as r, oe as s, fe as t };