@margoengine/terrain 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +201 -0
- package/NOTICE +4 -0
- package/README.md +1808 -3
- package/dist/blend.d.ts +70 -0
- package/dist/blend.js +159 -0
- package/dist/colors.d.ts +164 -0
- package/dist/deform.d.ts +103 -0
- package/dist/deform.js +322 -0
- package/dist/displace.d.ts +60 -0
- package/dist/displace.js +254 -0
- package/dist/dunes.d.ts +86 -0
- package/dist/dunes.js +88 -0
- package/dist/errors-fc4i1pSL.js +7 -0
- package/dist/grid.d.ts +11 -0
- package/dist/ground-change-settings.d.ts +29 -0
- package/dist/ground-change-settings.js +69 -0
- package/dist/ground-change.d.ts +227 -0
- package/dist/ground-change.js +1291 -0
- package/dist/ground-model.d.ts +290 -0
- package/dist/hdr-format-DRhzGS7G.js +30 -0
- package/dist/height-grid.d.ts +65 -0
- package/dist/height-grid.js +74 -0
- package/dist/heightfield.d.ts +38 -0
- package/dist/holes.d.ts +37 -0
- package/dist/holes.js +97 -0
- package/dist/imagery.d.ts +109 -0
- package/dist/imagery.js +472 -0
- package/dist/index.d.ts +297 -0
- package/dist/index.js +1 -0
- package/dist/layers-pbr.d.ts +78 -0
- package/dist/layers-pbr.js +128 -0
- package/dist/lighting-layout-CaDtDa5G.js +34 -0
- package/dist/lighting-layout.d.ts +5 -0
- package/dist/mesh-patch-BThCHCeS.js +21 -0
- package/dist/mesh-patch.d.ts +14 -0
- package/dist/noise3-sQdnbz4B.js +11 -0
- package/dist/noise3.d.ts +3 -0
- package/dist/overlays.d.ts +74 -0
- package/dist/overlays.js +297 -0
- package/dist/planet-craters.d.ts +55 -0
- package/dist/planet-recipes.d.ts +75 -0
- package/dist/planet-recipes.js +216 -0
- package/dist/planet.d.ts +139 -0
- package/dist/planet.js +602 -0
- package/dist/query.d.ts +150 -0
- package/dist/query.js +243 -0
- package/dist/relief-lighting.d.ts +46 -0
- package/dist/relief-lighting.js +208 -0
- package/dist/require-webgpu--tUXPsmA.js +7 -0
- package/dist/rock-settings.d.ts +39 -0
- package/dist/rock-settings.js +84 -0
- package/dist/rock-surface.d.ts +111 -0
- package/dist/rock-surface.js +368 -0
- package/dist/rocks.d.ts +258 -0
- package/dist/rocks.js +488 -0
- package/dist/rvt.d.ts +136 -0
- package/dist/rvt.js +518 -0
- package/dist/sculpt.d.ts +103 -0
- package/dist/sculpt.js +361 -0
- package/dist/settings-B9BSdnhD.js +72 -0
- package/dist/settings.d.ts +81 -0
- package/dist/settings.js +152 -0
- package/dist/shader.d.ts +61 -0
- package/dist/shared/settings.d.ts +89 -0
- package/dist/src-C6dtSaAb.js +1155 -0
- package/dist/stream.d.ts +100 -0
- package/dist/stream.js +339 -0
- package/dist/surface-height.d.ts +16 -0
- package/dist/wet-ground.d.ts +82 -0
- package/dist/wet-ground.js +147 -0
- package/package.json +148 -6
|
@@ -0,0 +1,1155 @@
|
|
|
1
|
+
// @margo/core-built 0.1.0
|
|
2
|
+
import {coreRequirement as __margoCoreRequirement,assertCore as __margoAssertCore} from '@margoengine/core/extension';
|
|
3
|
+
const l=(engine,version="0.1.0",source=import.meta.url)=>__margoRuntime(engine,version,source);
|
|
4
|
+
import { t as e } from "./lighting-layout-CaDtDa5G.js";
|
|
5
|
+
import { 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 = new Float32Array(t ** 2 * 2), r = new Uint32Array(e ** 2 * 6), i = new Uint32Array(e ** 2 * 9 / 2);
|
|
18
|
+
for (let t = 0, r = 0; t <= e; t++) for (let i = 0; i <= e; i++) n[r++] = i - e / 2, n[r++] = t - e / 2;
|
|
19
|
+
for (let n = 0, a = 0, o = 0; n < e; n++) for (let s = 0; s < e; s++) {
|
|
20
|
+
let c = n * t + s, l = c + 1, u = c + t, d = u + 1;
|
|
21
|
+
r[a++] = c, r[a++] = u, r[a++] = l, r[a++] = l, r[a++] = u, r[a++] = d, (s < e / 4 || s >= e * 3 / 4 || n < e / 4 || n >= e * 3 / 4) && (i[o++] = c, i[o++] = u, i[o++] = l, i[o++] = l, i[o++] = u, i[o++] = d);
|
|
22
|
+
}
|
|
23
|
+
return {
|
|
24
|
+
vertices: n,
|
|
25
|
+
center: r,
|
|
26
|
+
ring: i
|
|
27
|
+
};
|
|
28
|
+
}
|
|
29
|
+
//#endregion
|
|
30
|
+
//#region ../shared/light-terms.js
|
|
31
|
+
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}\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}\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 let edge=max(abs(grid.x),abs(grid.y));let morph=clamp((edge-frame.grid.w*0.5+2)/2,0.0,1.0);\n let aligned=mix(grid,round(grid*0.5)*2,morph);let inner=clamp((frame.grid.w*0.5-edge)/(frame.grid.w*0.25),0.0,1.0);\n let xz=frame.grid.xy+aligned*frame.grid.z+frame.offset.xy*inner;let position=vec3f(xz.x,height(xz),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 = (e) => e.includes("anchor:vec4f}") ? e : e.replace("heights:vec4f}", "heights:vec4f,anchor:vec4f}").replace(/struct Layer \{([^}]*)\}/, "struct Layer {$1,wrap:vec4f,tone:vec4f}").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;"), w = "\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 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 return vec4f(color,dot(sample,luma)*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}", T = (e) => 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);", E = (e = !1) => `${r}${e ? w : ""}
|
|
32
|
+
fn terrainColor(position:vec3f,normal:vec3f)->vec3f {
|
|
33
|
+
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;" : ""}
|
|
34
|
+
for(var layer=0u;layer<u32(frame.heights.z);layer++){
|
|
35
|
+
let rule=layerRules[layer];let hs=rule.heightSlope;let scale=rule.params.x;let p=position*scale;
|
|
36
|
+
let x=textureSampleGrad(terrainLayers,terrainSampler,p.zy,i32(layer),dx.zy*scale,dy.zy*scale).rgb;
|
|
37
|
+
let y=textureSampleGrad(terrainLayers,terrainSampler,p.xz,i32(layer),dx.xz*scale,dy.xz*scale).rgb;
|
|
38
|
+
let z=textureSampleGrad(terrainLayers,terrainSampler,p.xy,i32(layer),dx.xy*scale,dy.xy*scale).rgb;
|
|
39
|
+
${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;}"}
|
|
40
|
+
let h=rule.params.y;let s=rule.params.z;
|
|
41
|
+
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));
|
|
42
|
+
color+=sample*weight;total+=weight;${e ? "relief+=surface.w*weight;repeat+=scale*weight;" : ""}
|
|
43
|
+
}
|
|
44
|
+
${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);
|
|
45
|
+
}
|
|
46
|
+
@fragment fn fragment(i:Output)->@location(0) vec4f {
|
|
47
|
+
${x}
|
|
48
|
+
${T(e)}let v=normalize(frame.eye.xyz-i.position);let l=frame.light.xyz;let h=(v+l)/max(length(v+l),0.0001);
|
|
49
|
+
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;
|
|
50
|
+
let d=${_};let g=${v};let fresnel=vec3f(0.04)+vec3f(0.96)*pow(1-vh,5.0);
|
|
51
|
+
let direct=((1-fresnel)*base/3.14159265+d*g*fresnel/max(4*nl*nv,0.0001))*nl;
|
|
52
|
+
let linear=direct*frame.radiance.xyz*frame.light.w+base*frame.radiance.w;
|
|
53
|
+
if(frame.heights.w>0.5){return vec4f(linear,1);}
|
|
54
|
+
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);
|
|
55
|
+
}`, D = "\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}", O = (e, t = !1, n = !1) => {
|
|
56
|
+
let r = E(t), i = r.slice(r.indexOf("fn terrainColor("), r.indexOf("@fragment fn fragment(")), a = Math.min(4, Math.max(1, Math.floor(e))), o = `
|
|
57
|
+
${Array.from({ length: a }, (e, t) => t).map((e) => `@group(0) @binding(${6 + e}) var terrainWeights${e}:texture_2d<f32>;`).join("\n")}
|
|
58
|
+
${D}
|
|
59
|
+
fn terrainColor(position:vec3f,normal:vec3f)->vec3f {
|
|
60
|
+
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);
|
|
61
|
+
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);
|
|
62
|
+
var packed=array<vec4f,4>(${[
|
|
63
|
+
0,
|
|
64
|
+
1,
|
|
65
|
+
2,
|
|
66
|
+
3
|
|
67
|
+
].map((e) => e < a ? `textureSampleLevel(terrainWeights${e},terrainSampler,uv,0)` : "vec4f(0)").join(",")});
|
|
68
|
+
var color=vec3f(0);var total=0.0;${t ? "var relief=0.0;var repeat=0.0;" : ""}
|
|
69
|
+
for(var layer=0u;layer<u32(frame.heights.z);layer++){
|
|
70
|
+
let weight=packed[layer/4u][layer%4u];if(weight<=0.0){continue;}
|
|
71
|
+
${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;"}
|
|
72
|
+
}
|
|
73
|
+
${t ? "if(total>0.00001){terrainRelief=relief/total;terrainRepeat=repeat/total;return color/total;}" : "if(total>0.00001){return color/total;}"}
|
|
74
|
+
${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);"}
|
|
75
|
+
}
|
|
76
|
+
${r.replace(i, "")}`;
|
|
77
|
+
return n ? `@group(0) @binding(${6 + a}) var terrainTint:texture_2d<f32>;
|
|
78
|
+
var<private> terrainTintTexel:vec4f;
|
|
79
|
+
fn terrainTinted(c:vec3f,layer:u32)->vec3f {return mix(c,terrainTintTexel.rgb,terrainTintTexel.a*layerRules[layer].params.w);}
|
|
80
|
+
${o.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)")}` : o;
|
|
81
|
+
}, k = "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);";
|
|
82
|
+
function A(e, t, n, r, i, a) {
|
|
83
|
+
let o = e.adapter?.capabilities?.tier;
|
|
84
|
+
if (o === "ldr") return;
|
|
85
|
+
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("o.clip=frame.camera*vec4f(position,1);", k) + `
|
|
86
|
+
@vertex fn seedVertex(@builtin(vertex_index) i:u32)->@builtin(position) vec4f {
|
|
87
|
+
return vec4f(array<vec2f,3>(vec2f(-1,-1),vec2f(3,-1),vec2f(-1,3))[i],0,1);
|
|
88
|
+
}
|
|
89
|
+
@fragment fn seed(@builtin(position) p:vec4f)->@location(0) ${f} {
|
|
90
|
+
let n=vec2f(textureDimensions(heightMap));let q=(p.xy/vec2f(${c},${l})*n-0.5)/max(n-1.0,vec2f(1.0));
|
|
91
|
+
return ${p("height(frame.map.xy+q*frame.map.zw)" + d)};
|
|
92
|
+
}
|
|
93
|
+
@fragment fn sampleSurface(i:Output)->@location(0) ${f} {
|
|
94
|
+
${x}
|
|
95
|
+
return ${p("i.position.y" + d)};
|
|
96
|
+
}`) }), h = e.createPipelineLayout({ bindGroupLayouts: [n] }), g = e.createRenderPipeline({
|
|
97
|
+
layout: h,
|
|
98
|
+
vertex: {
|
|
99
|
+
module: m,
|
|
100
|
+
entryPoint: "seedVertex"
|
|
101
|
+
},
|
|
102
|
+
fragment: {
|
|
103
|
+
module: m,
|
|
104
|
+
entryPoint: "seed",
|
|
105
|
+
targets: [{ format: s }]
|
|
106
|
+
}
|
|
107
|
+
}), _ = e.createRenderPipeline({
|
|
108
|
+
layout: h,
|
|
109
|
+
vertex: {
|
|
110
|
+
module: m,
|
|
111
|
+
entryPoint: "vertex",
|
|
112
|
+
buffers: [{
|
|
113
|
+
arrayStride: 8,
|
|
114
|
+
attributes: [{
|
|
115
|
+
shaderLocation: 0,
|
|
116
|
+
offset: 0,
|
|
117
|
+
format: "float32x2"
|
|
118
|
+
}]
|
|
119
|
+
}]
|
|
120
|
+
},
|
|
121
|
+
fragment: {
|
|
122
|
+
module: m,
|
|
123
|
+
entryPoint: "sampleSurface",
|
|
124
|
+
targets: [{ format: s }]
|
|
125
|
+
}
|
|
126
|
+
}), v = e.createTexture({
|
|
127
|
+
label: "Terrain drawn surface height",
|
|
128
|
+
size: u,
|
|
129
|
+
format: s,
|
|
130
|
+
usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.TEXTURE_BINDING | GPUTextureUsage.COPY_SRC
|
|
131
|
+
}), y = v.createView(), b = -1;
|
|
132
|
+
return {
|
|
133
|
+
texture: v,
|
|
134
|
+
draw(e, t, n, r) {
|
|
135
|
+
if (b === t) return;
|
|
136
|
+
let i = e.beginRenderPass({ colorAttachments: [{
|
|
137
|
+
view: y,
|
|
138
|
+
loadOp: "clear",
|
|
139
|
+
storeOp: "store"
|
|
140
|
+
}] });
|
|
141
|
+
i.setPipeline(g), i.setBindGroup(0, n[0].group), i.draw(3), i.setPipeline(_), i.setVertexBuffer(0, r.vertex);
|
|
142
|
+
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);
|
|
143
|
+
i.end(), b = t;
|
|
144
|
+
}
|
|
145
|
+
};
|
|
146
|
+
}
|
|
147
|
+
//#endregion
|
|
148
|
+
//#region src/colors.ts
|
|
149
|
+
var j = 0, M = [
|
|
150
|
+
.5,
|
|
151
|
+
.42,
|
|
152
|
+
.29
|
|
153
|
+
], N = [[
|
|
154
|
+
.133,
|
|
155
|
+
.263,
|
|
156
|
+
.033
|
|
157
|
+
], [
|
|
158
|
+
.274,
|
|
159
|
+
.342,
|
|
160
|
+
.064
|
|
161
|
+
]], P = [
|
|
162
|
+
.253,
|
|
163
|
+
.223,
|
|
164
|
+
.187
|
|
165
|
+
];
|
|
166
|
+
function F(e, t) {
|
|
167
|
+
let n = 0, r = 50, i = e.geometry?.vertices;
|
|
168
|
+
if (i?.length) {
|
|
169
|
+
n = Infinity, r = -Infinity;
|
|
170
|
+
for (let e = 1; e < i.length; e += 6) i[e] < n && (n = i[e]), i[e] > r && (r = i[e]);
|
|
171
|
+
let t = e.scale.y, a = e.position.y;
|
|
172
|
+
[n, r] = [a + n * t, a + r * t].sort((e, t) => e - t), r > n || (r = n + 1);
|
|
173
|
+
}
|
|
174
|
+
return {
|
|
175
|
+
sand: M,
|
|
176
|
+
meadow: N,
|
|
177
|
+
stone: P,
|
|
178
|
+
shore: [.3, 1.5],
|
|
179
|
+
meadowHeight: [n, r],
|
|
180
|
+
stoneHeight: [r + 1, r + 2],
|
|
181
|
+
stoneNormal: [.75, .85],
|
|
182
|
+
wetHeight: [-.1, .4],
|
|
183
|
+
wetDarkening: .6,
|
|
184
|
+
wetDryTime: 900,
|
|
185
|
+
wetGlossTime: 20,
|
|
186
|
+
...Object.fromEntries(Object.entries(t).filter(([, e]) => e !== void 0))
|
|
187
|
+
};
|
|
188
|
+
}
|
|
189
|
+
function I(e, t) {
|
|
190
|
+
if (typeof t != "object" || !t) throw TypeError("Terrain color options must be an object; pass {} or leave them out for the defaults");
|
|
191
|
+
let n = F(e, t);
|
|
192
|
+
if (n.meadow.length !== 2) throw RangeError("Expected two meadow colors");
|
|
193
|
+
for (let e of [
|
|
194
|
+
n.sand,
|
|
195
|
+
...n.meadow,
|
|
196
|
+
n.stone
|
|
197
|
+
]) 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.");
|
|
198
|
+
for (let e of [
|
|
199
|
+
n.shore,
|
|
200
|
+
n.meadowHeight,
|
|
201
|
+
n.stoneHeight,
|
|
202
|
+
n.stoneNormal,
|
|
203
|
+
n.wetHeight
|
|
204
|
+
]) 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.");
|
|
205
|
+
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.");
|
|
206
|
+
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.");
|
|
207
|
+
let r = n.detail ?? 1;
|
|
208
|
+
if (typeof r != "number" || !(r >= 0 && r <= 1)) throw RangeError("Terrain detail must be a number in 0..1");
|
|
209
|
+
let i = n.wetness;
|
|
210
|
+
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.");
|
|
211
|
+
let a = n.sandSurface ?? {};
|
|
212
|
+
if (a !== !1 && (typeof a != "object" || !a)) throw TypeError("Terrain sandSurface must be an object or false; leave it out for the defaults");
|
|
213
|
+
let o = a === !1 ? void 0 : {
|
|
214
|
+
wind: [1, 0],
|
|
215
|
+
ripple: .1,
|
|
216
|
+
ripples: 1,
|
|
217
|
+
streaks: 1,
|
|
218
|
+
sorting: 1,
|
|
219
|
+
broad: 0,
|
|
220
|
+
...Object.fromEntries(Object.entries(a).filter(([, e]) => e !== void 0))
|
|
221
|
+
};
|
|
222
|
+
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.");
|
|
223
|
+
return {
|
|
224
|
+
options: n,
|
|
225
|
+
detail: r,
|
|
226
|
+
wetness: i,
|
|
227
|
+
sand: o
|
|
228
|
+
};
|
|
229
|
+
}
|
|
230
|
+
var L = 11;
|
|
231
|
+
function R(e, t, n) {
|
|
232
|
+
let r = /* @__PURE__ */ new Float32Array(44), i = e.wetDarkening, a = (e) => W(.6 * t * (e[1] - e[0])), o = n ?? {
|
|
233
|
+
wind: [1, 0],
|
|
234
|
+
ripple: .1,
|
|
235
|
+
ripples: 1,
|
|
236
|
+
streaks: 1,
|
|
237
|
+
sorting: 1,
|
|
238
|
+
broad: 0
|
|
239
|
+
}, s = Math.hypot(o.wind[0], o.wind[1]);
|
|
240
|
+
return r.set([...e.sand, i], 0), r.set([...e.meadow[0], 1 - i], 4), r.set([...e.meadow[1], i < 1 ? W(.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([
|
|
241
|
+
a(e.meadowHeight),
|
|
242
|
+
a(e.shore),
|
|
243
|
+
a(e.stoneHeight),
|
|
244
|
+
a(e.stoneNormal)
|
|
245
|
+
], 28), r.set([
|
|
246
|
+
W(o.wind[0] / s),
|
|
247
|
+
W(o.wind[1] / s),
|
|
248
|
+
W(o.ripple),
|
|
249
|
+
W(o.ripples * t)
|
|
250
|
+
], 32), r.set([
|
|
251
|
+
W(.1 * o.sorting * t),
|
|
252
|
+
W(.07 * o.sorting * t),
|
|
253
|
+
W(.16 * o.streaks * t),
|
|
254
|
+
W(.3 * o.broad * t)
|
|
255
|
+
], 36), r.set([
|
|
256
|
+
W(.14 * o.sorting * t),
|
|
257
|
+
W(o.ripple / 4),
|
|
258
|
+
W(o.ripple / 2)
|
|
259
|
+
], 40), r;
|
|
260
|
+
}
|
|
261
|
+
var z = "let terrainColorFootprint=max(length(dpdx(i.position)),length(dpdy(i.position)));", B = "struct TerrainSurface {color:vec3f,normal:vec3f,rough:f32}\n", V = "\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", H = "\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}";
|
|
262
|
+
function U(e, t = 900, n = 20) {
|
|
263
|
+
let r = Math.exp(-e / t);
|
|
264
|
+
return {
|
|
265
|
+
moisture: r,
|
|
266
|
+
film: Math.exp(-e / n),
|
|
267
|
+
darkening: (1 - Math.exp(-3 * r)) / (1 - Math.exp(-3))
|
|
268
|
+
};
|
|
269
|
+
}
|
|
270
|
+
var W = (e) => Math.round(e * 1e6) / 1e6, G = (e) => String(W(e)), K = class e {coreRequirement=__margoCoreRequirement("0.1.0",import.meta.url);
|
|
271
|
+
constructor(e, t = {}) {
|
|
272
|
+
this.mesh = e, this.name = "terrain:colors:" + ++j, 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 = {
|
|
273
|
+
width: 1,
|
|
274
|
+
height: 1
|
|
275
|
+
}, 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;
|
|
276
|
+
let { options: n, detail: r, wetness: i, sand: a } = I(e, t);
|
|
277
|
+
this.wetness = i, this.given = t, this.dryTime = n.wetDryTime, this.glossTime = n.wetGlossTime, this.look = R(n, r, a);
|
|
278
|
+
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;
|
|
279
|
+
this.sandOn = u;
|
|
280
|
+
let d = u ? `
|
|
281
|
+
let foot=footprint;
|
|
282
|
+
let sw=${o(8, "xy")};let along=dot(p.xz,sw);let across=dot(p.xz,vec2f(-sw.y,sw.x));
|
|
283
|
+
let face=dot(n.xz,sw);let lee=smoothstep(0.25,0.45,face);let stoss=smoothstep(0.03,0.2,-face);
|
|
284
|
+
var sandShade=1.0+${o(9, "x")}*lee-${o(9, "y")}*stoss;
|
|
285
|
+
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));
|
|
286
|
+
var fineStreak=0.0;let sf=1.0-smoothstep(0.13,0.26,foot);
|
|
287
|
+
if(sf>0.0){fineStreak=(terrainNoise(vec2f(along*0.13,across*1.9)+vec2f(3.0,29.0)).x-0.5)*sf;}
|
|
288
|
+
sandShade*=1.0+${o(9, "z")}*(0.65*streak+0.35*fineStreak);
|
|
289
|
+
|
|
290
|
+
sandShade*=1.0+${o(9, "w")}*(terrainNoise(vec2f(along*0.012,across*0.09)+vec2f(23.0,5.0)).x-0.5);
|
|
291
|
+
|
|
292
|
+
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));
|
|
293
|
+
sandShade*=1.0+${o(10, "x")}*lee*flow;
|
|
294
|
+
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))" : ""};
|
|
295
|
+
if(rv>0.0){
|
|
296
|
+
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;
|
|
297
|
+
let t=fract(along/${o(8, "z")}+1.6*w1.x+0.35*w2.x);
|
|
298
|
+
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));
|
|
299
|
+
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));
|
|
300
|
+
sandGrad=vec3f(d.x,0.0,d.y);
|
|
301
|
+
|
|
302
|
+
|
|
303
|
+
sandShade*=1.0-0.2*r*(smoothstep(0.55,0.7,t)*(1.0-smoothstep(0.85,1.0,t))-0.3);
|
|
304
|
+
}` : "";
|
|
305
|
+
this.surfaceCode = `
|
|
306
|
+
fn terrainSurface(p:vec3f,n:vec3f,footprint:f32)->TerrainSurface {
|
|
307
|
+
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;}" : ""}
|
|
308
|
+
let meadow=mix(${o(1, "xyz")},${o(2, "xyz")},${c(o(5, "x"), o(5, "y"), o(7, "x"), "h")});
|
|
309
|
+
let shore=${c(o(4, "x"), o(4, "y"), o(7, "y"), "h")};
|
|
310
|
+
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 ? `
|
|
311
|
+
var rock=large;var grad=vec3f(0.0);
|
|
312
|
+
if(steep>0.004&&fade>0.0){
|
|
313
|
+
let a=n*n;var w=a*a;w/=w.x+w.y+w.z;
|
|
314
|
+
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));
|
|
315
|
+
rock=mix(large,w.x*zy.x+w.y*xz.x+w.z*xy.x-0.5,fade);
|
|
316
|
+
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));
|
|
317
|
+
}
|
|
318
|
+
let grass=0.275+0.35*fine;let stoneT=${l("steep", "grass,0.25+0.5*rock")};
|
|
319
|
+
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;"}
|
|
320
|
+
${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;`}
|
|
321
|
+
s.color=mix(${o(0, "xyz")}${r ? `*(1.0+${G(.2 * r)}*fine)` : ""}${u ? "*sandShade" : ""},mix(meadow,${o(3, "xyz")}${r ? `*(1.0+${G(.6 * r)}*rock)` : ""},stoneT),sandT)*wet${s ? `*(${G(1 - s)}+${G(2 * s)}*(0.65*large+0.35*fine))` : ""};
|
|
322
|
+
s.normal=${r ? `normalize(n-(grad-n*dot(n,grad))*(${G(.15 * r)}*stoneT*sandT)${u ? "-(sandGrad-n*dot(n,sandGrad))" : ""})` : "n"};
|
|
323
|
+
s.rough=select(1.0,0.6+${o(2, "w")}*(glint-${o(0, "w")}),${o(0, "w")}<1.0);return s;
|
|
324
|
+
}
|
|
325
|
+
`, this.wetCode = i ? `
|
|
326
|
+
@group(0) @binding(9) var terrainWater:texture_2d<f32>;
|
|
327
|
+
|
|
328
|
+
fn terrainMoisture(position:vec3f)->f32 {
|
|
329
|
+
if(position.y>=${o(4, "w")}){return 0.0;}
|
|
330
|
+
let uv=(position.xz-vec2f(${i?.origin.join(",")}))/vec2f(${i?.size.join(",")});
|
|
331
|
+
if(any(uv<vec2f(0))||any(uv>vec2f(1))){return 0.0;}
|
|
332
|
+
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);
|
|
333
|
+
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);
|
|
334
|
+
}
|
|
335
|
+
fn terrainWet(position:vec3f)->vec2f {
|
|
336
|
+
if(position.y>=${o(4, "w")}){return vec2f(1.0);}
|
|
337
|
+
let uv=(position.xz-vec2f(${i.origin.join(",")}))/vec2f(${i.size.join(",")});
|
|
338
|
+
if(any(uv<vec2f(0))||any(uv>vec2f(1))){return vec2f(1.0);}
|
|
339
|
+
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);
|
|
340
|
+
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;
|
|
341
|
+
let wet=mix(mix(a,b,t.x),mix(c,d,t.x),t.y);
|
|
342
|
+
let beach=(1.0-smoothstep(${o(4, "z")},${o(4, "w")},position.y))*(1.0-smoothstep(${o(4, "x")},${o(4, "y")},position.y));
|
|
343
|
+
return 1.0-${o(1, "w")}*beach*wet;
|
|
344
|
+
}
|
|
345
|
+
` : "";
|
|
346
|
+
}
|
|
347
|
+
static attach(t, n, r = {}) {__margoAssertCore(t,__margoCoreRequirement("0.1.0",import.meta.url));
|
|
348
|
+
let i = new e(n, r);
|
|
349
|
+
return l(t).use(i), i;
|
|
350
|
+
}
|
|
351
|
+
setup(e) {
|
|
352
|
+
o(e, "TerrainColors");
|
|
353
|
+
let t = u(this.mesh);
|
|
354
|
+
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");
|
|
355
|
+
this.engine = e, this.wetness && (this.dry = e.gpu.createTexture({
|
|
356
|
+
size: [1, 1],
|
|
357
|
+
format: "r32float",
|
|
358
|
+
usage: GPUTextureUsage.TEXTURE_BINDING | GPUTextureUsage.COPY_DST
|
|
359
|
+
}), e.gpu.queue.writeTexture({ texture: this.dry }, /* @__PURE__ */ new Float32Array(1), { bytesPerRow: 4 }, [1, 1]), this.dryEntry = {
|
|
360
|
+
binding: 9,
|
|
361
|
+
resource: this.dry.createView()
|
|
362
|
+
});
|
|
363
|
+
}
|
|
364
|
+
get sandSurfaceOn() {
|
|
365
|
+
return this.sandOn;
|
|
366
|
+
}
|
|
367
|
+
setLook(e) {
|
|
368
|
+
if (typeof e != "object" || !e) throw TypeError("Terrain look must be an object");
|
|
369
|
+
let t = this.given.sandSurface, n = { ...this.given };
|
|
370
|
+
for (let [t, r] of Object.entries(e)) r !== void 0 && t !== "sandSurface" && (r === null ? delete n[t] : n[t] = r);
|
|
371
|
+
if (e.sandSurface !== void 0) {
|
|
372
|
+
if (!this.sandOn) throw TypeError("This TerrainColors was built without a sand surface (sandSurface false or detail 0); it cannot gain one");
|
|
373
|
+
n.sandSurface = {
|
|
374
|
+
...t || {},
|
|
375
|
+
...e.sandSurface
|
|
376
|
+
};
|
|
377
|
+
}
|
|
378
|
+
let r = I(this.mesh, n);
|
|
379
|
+
this.look = R(r.options, r.detail, r.sand), this.dryTime = r.options.wetDryTime, this.glossTime = r.options.wetGlossTime, this.given = n, this.lookDirty = !0;
|
|
380
|
+
}
|
|
381
|
+
patch(e, t) {
|
|
382
|
+
let n = s(e);
|
|
383
|
+
if (!n) return e;
|
|
384
|
+
let { code: r } = n, i = r.indexOf(z), a = i < 0 ? n.at : i + 81, o = "_" + t, l = (`@group(0) @binding(${this.lookBinding}) var<uniform> terrainLook:array<vec4f,${L}>;
|
|
385
|
+
` + this.wetCode.replace("@binding(9)", `@binding(${this.wetBinding})`) + this.surfaceCode).replace(/terrainSurface|terrainWater|terrainWet|terrainMoisture|terrainLook/g, (e) => e + o);
|
|
386
|
+
return (r.includes("struct TerrainSurface ") ? "" : B) + (this.surfaceCode.includes("terrainNoise(") && !r.includes("fn terrainNoise(") ? c : "") + (this.surfaceCode.includes("terrainBlend(") && !r.includes("fn terrainBlend(") ? V : "") + l + r.slice(0, a) + (i < 0 ? z : "") + `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);
|
|
387
|
+
}
|
|
388
|
+
registerPasses(e) {
|
|
389
|
+
e.add({
|
|
390
|
+
name: this.name,
|
|
391
|
+
order: -1,
|
|
392
|
+
execute: (e) => {
|
|
393
|
+
if (e.backend !== "webgpu") return;
|
|
394
|
+
let t = u(this.mesh);
|
|
395
|
+
if (t.check(), this.source !== e.shader) {
|
|
396
|
+
if (this.source = e.shader, this.wetness) for (this.wetBinding = 40; e.bindings.some((e) => e.binding === this.wetBinding);) this.wetBinding++;
|
|
397
|
+
for (this.lookBinding = this.wetness ? this.wetBinding + 1 : 41; e.bindings.some((e) => e.binding === this.lookBinding);) this.lookBinding++;
|
|
398
|
+
this.lookEntry = void 0, this.shader = this.patch(e.shader, t.id);
|
|
399
|
+
}
|
|
400
|
+
if (this.wetness) {
|
|
401
|
+
let t = this.wetness.texture();
|
|
402
|
+
if (t !== void 0) {
|
|
403
|
+
if (!t || t.dimension !== "2d" || t.sampleCount !== 1 || t.depthOrArrayLayers > 1 || ![
|
|
404
|
+
"r32float",
|
|
405
|
+
"rgba32float",
|
|
406
|
+
"rgba16float"
|
|
407
|
+
].includes(t.format) || !(t.usage & GPUTextureUsage.COPY_SRC)) throw TypeError("Terrain wetness needs a copyable water-depth texture");
|
|
408
|
+
(this.wet?.width !== t.width || this.wet?.height !== t.height || this.wet?.format !== t.format) && (this.dropRecord(), this.wet = e.device.createTexture({
|
|
409
|
+
size: [t.width, t.height],
|
|
410
|
+
format: t.format,
|
|
411
|
+
usage: GPUTextureUsage.TEXTURE_BINDING | GPUTextureUsage.COPY_DST
|
|
412
|
+
}), this.record = e.device.createTexture({
|
|
413
|
+
size: [t.width, t.height],
|
|
414
|
+
format: "rgba32float",
|
|
415
|
+
usage: GPUTextureUsage.TEXTURE_BINDING | GPUTextureUsage.COPY_DST
|
|
416
|
+
}), this.recordNext = e.device.createTexture({
|
|
417
|
+
size: [t.width, t.height],
|
|
418
|
+
format: "rgba32float",
|
|
419
|
+
usage: GPUTextureUsage.STORAGE_BINDING | GPUTextureUsage.COPY_SRC
|
|
420
|
+
}), this.dryingBuffer ??= e.device.createBuffer({
|
|
421
|
+
size: 16,
|
|
422
|
+
usage: GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST
|
|
423
|
+
}), this.recordPipeline ??= e.device.createComputePipeline({
|
|
424
|
+
layout: "auto",
|
|
425
|
+
compute: {
|
|
426
|
+
module: e.device.createShaderModule({ code: H }),
|
|
427
|
+
entryPoint: "main"
|
|
428
|
+
}
|
|
429
|
+
}), this.recordGroup = e.device.createBindGroup({
|
|
430
|
+
layout: this.recordPipeline.getBindGroupLayout(0),
|
|
431
|
+
entries: [
|
|
432
|
+
{
|
|
433
|
+
binding: 0,
|
|
434
|
+
resource: this.wet.createView()
|
|
435
|
+
},
|
|
436
|
+
{
|
|
437
|
+
binding: 1,
|
|
438
|
+
resource: this.record.createView()
|
|
439
|
+
},
|
|
440
|
+
{
|
|
441
|
+
binding: 2,
|
|
442
|
+
resource: this.recordNext.createView()
|
|
443
|
+
},
|
|
444
|
+
{
|
|
445
|
+
binding: 3,
|
|
446
|
+
resource: { buffer: this.dryingBuffer }
|
|
447
|
+
}
|
|
448
|
+
]
|
|
449
|
+
}), this.wetEntry = {
|
|
450
|
+
binding: 9,
|
|
451
|
+
resource: this.record.createView()
|
|
452
|
+
}, 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([
|
|
453
|
+
this.elapsed,
|
|
454
|
+
this.dryTime,
|
|
455
|
+
this.glossTime,
|
|
456
|
+
0
|
|
457
|
+
]), this.elapsed = 0, e.device.queue.writeBuffer(this.dryingBuffer, 0, this.drying);
|
|
458
|
+
let n = e.encoder.beginComputePass();
|
|
459
|
+
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);
|
|
460
|
+
}
|
|
461
|
+
let n = t ? this.wetEntry : this.dryEntry;
|
|
462
|
+
n.binding = this.wetBinding, e.bindings.push(n);
|
|
463
|
+
}
|
|
464
|
+
let n = this.engine.gpu;
|
|
465
|
+
this.lookBuffer || (this.lookBuffer = n.createBuffer({
|
|
466
|
+
size: this.look.byteLength,
|
|
467
|
+
usage: GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST
|
|
468
|
+
}), this.lookDirty = !0), this.lookDirty &&= (n.queue.writeBuffer(this.lookBuffer, 0, this.look), !1), this.lookEntry ??= {
|
|
469
|
+
binding: this.lookBinding,
|
|
470
|
+
resource: { buffer: this.lookBuffer }
|
|
471
|
+
}, e.bindings.push(this.lookEntry), e.shader = this.shader;
|
|
472
|
+
}
|
|
473
|
+
});
|
|
474
|
+
}
|
|
475
|
+
onPreUpdate(e) {
|
|
476
|
+
this.elapsed += e;
|
|
477
|
+
}
|
|
478
|
+
dropRecord() {
|
|
479
|
+
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;
|
|
480
|
+
}
|
|
481
|
+
onDeviceRestored(e) {
|
|
482
|
+
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);
|
|
483
|
+
}
|
|
484
|
+
dispose() {
|
|
485
|
+
if (this.disposed) return;
|
|
486
|
+
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;
|
|
487
|
+
let e = this.engine;
|
|
488
|
+
this.engine = void 0, e?.sceneOf(this)?.removePlugin(this.name);
|
|
489
|
+
}
|
|
490
|
+
[Symbol.dispose ?? Symbol()]() {
|
|
491
|
+
this.dispose();
|
|
492
|
+
}
|
|
493
|
+
};
|
|
494
|
+
//#endregion
|
|
495
|
+
//#region src/heightfield.ts
|
|
496
|
+
function q(e, t, n, r) {
|
|
497
|
+
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.");
|
|
498
|
+
}
|
|
499
|
+
function J(e, t, n) {
|
|
500
|
+
let r = e(t, n);
|
|
501
|
+
if (!Number.isFinite(Math.fround(r))) throw RangeError("Terrain height must be finite");
|
|
502
|
+
return r;
|
|
503
|
+
}
|
|
504
|
+
function Y(e, t) {
|
|
505
|
+
let { size: n, resolution: r = 192, origin: i = [-n[0] / 2, -n[1] / 2] } = t;
|
|
506
|
+
q(e, n, r, i);
|
|
507
|
+
let a = p(n[0], n[1], r, r);
|
|
508
|
+
for (let t = 0; t < a.positions.length; t += 3) {
|
|
509
|
+
let r = a.positions[t] + i[0] + n[0] / 2, o = -a.positions[t + 1] + i[1] + n[1] / 2;
|
|
510
|
+
a.positions[t] = r, a.positions[t + 1] = J(e, r, o), a.positions[t + 2] = o;
|
|
511
|
+
}
|
|
512
|
+
return m(a);
|
|
513
|
+
}
|
|
514
|
+
function X(e, t) {
|
|
515
|
+
return h(Y(e, t));
|
|
516
|
+
}
|
|
517
|
+
var Z = 0, Q = class e {coreRequirement=__margoCoreRequirement("0.1.0",import.meta.url);
|
|
518
|
+
constructor(e, t) {
|
|
519
|
+
this.height = e, this.options = t, this.name = "terrain-heightmap:" + ++Z, this.disposed = !1;
|
|
520
|
+
let { size: n, resolution: r = 256, origin: i = [-n[0] / 2, -n[1] / 2] } = t;
|
|
521
|
+
q(e, n, r, i), this.options = {
|
|
522
|
+
size: [n[0], n[1]],
|
|
523
|
+
resolution: r,
|
|
524
|
+
origin: [i[0], i[1]]
|
|
525
|
+
};
|
|
526
|
+
}
|
|
527
|
+
static attach(t, n, r) {__margoAssertCore(t,__margoCoreRequirement("0.1.0",import.meta.url));
|
|
528
|
+
let i = new e(n, r);
|
|
529
|
+
return l(t).use(i), i;
|
|
530
|
+
}
|
|
531
|
+
setup(e) {
|
|
532
|
+
if (this.disposed || !e.gpu) throw new f(this.disposed ? "disposed" : "unsupported", "Terrain heightmap requires WebGPU; attach a new TerrainHeightmap to a WebGPU engine");
|
|
533
|
+
let t = e.gpu, { size: n, resolution: r = 256, origin: i = [-n[0] / 2, -n[1] / 2] } = this.options;
|
|
534
|
+
if (r > t.limits.maxTextureDimension2D) throw RangeError("Heightmap resolution exceeds the GPU texture limit; reduce resolution to the device maxTextureDimension2D or less.");
|
|
535
|
+
let a = new Float32Array(r * r);
|
|
536
|
+
for (let e = 0; e < r; e++) for (let t = 0; t < r; t++) a[e * r + t] = J(this.height, i[0] + (t + .5) / r * n[0], i[1] + (e + .5) / r * n[1]);
|
|
537
|
+
this.engine = e, this.texture = t.createTexture({
|
|
538
|
+
size: [r, r],
|
|
539
|
+
format: "r32float",
|
|
540
|
+
usage: GPUTextureUsage.TEXTURE_BINDING | GPUTextureUsage.COPY_DST
|
|
541
|
+
}), t.queue.writeTexture({ texture: this.texture }, a, { bytesPerRow: r * 4 }, [r, r]);
|
|
542
|
+
}
|
|
543
|
+
onDeviceRestored(e) {
|
|
544
|
+
this.texture?.destroy(), this.texture = void 0, this.setup(e);
|
|
545
|
+
}
|
|
546
|
+
dispose() {
|
|
547
|
+
if (this.disposed) return;
|
|
548
|
+
this.disposed = !0, this.texture?.destroy(), this.texture = void 0;
|
|
549
|
+
let e = this.engine;
|
|
550
|
+
this.engine = void 0, e?.sceneOf(this)?.removePlugin(this.name);
|
|
551
|
+
}
|
|
552
|
+
[Symbol.dispose ?? Symbol()]() {
|
|
553
|
+
this.dispose();
|
|
554
|
+
}
|
|
555
|
+
};
|
|
556
|
+
//#endregion
|
|
557
|
+
//#region src/index.ts
|
|
558
|
+
function $(e, t, n, r, i = new Float64Array(r * 2)) {
|
|
559
|
+
for (let a = 0; a < r; a++) {
|
|
560
|
+
let r = n * 2 ** a;
|
|
561
|
+
i[a * 2] = Math.floor(e[0] / r) * r - t[0], i[a * 2 + 1] = Math.floor(e[2] / r) * r - t[2];
|
|
562
|
+
}
|
|
563
|
+
return i;
|
|
564
|
+
}
|
|
565
|
+
var ee = 0, te = class r {coreRequirement=__margoCoreRequirement("0.1.0",import.meta.url);
|
|
566
|
+
constructor(e) {
|
|
567
|
+
this.options = e, this.name = "terrain:" + ee++, this.shadowVersion = 0, this.disposed = !1, 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.eye = /* @__PURE__ */ new Float64Array(3), this.plan = /* @__PURE__ */ new Float64Array(), this.validate();
|
|
568
|
+
let t = e.clipmapAnchor;
|
|
569
|
+
t && t !== "camera" && (this.anchoredEye = [
|
|
570
|
+
t[0],
|
|
571
|
+
0,
|
|
572
|
+
t[1]
|
|
573
|
+
]);
|
|
574
|
+
let n = e.floatingOrigin;
|
|
575
|
+
n && (this.anchor = [e.origin?.[0] ?? 0, e.origin?.[1] ?? 0], this.shiftValues.set([
|
|
576
|
+
n.origin[0],
|
|
577
|
+
n.origin[1],
|
|
578
|
+
n.origin[2]
|
|
579
|
+
]), this.unfollow = n.onRebase((e, t) => this.shiftValues.set([
|
|
580
|
+
t[0],
|
|
581
|
+
t[1],
|
|
582
|
+
t[2]
|
|
583
|
+
])));
|
|
584
|
+
}
|
|
585
|
+
get shift() {
|
|
586
|
+
return this.shiftValues;
|
|
587
|
+
}
|
|
588
|
+
get surfaceHeightTexture() {
|
|
589
|
+
return this.capturedSurface?.texture;
|
|
590
|
+
}
|
|
591
|
+
static attach(e, t) {__margoAssertCore(e,__margoCoreRequirement("0.1.0",import.meta.url));
|
|
592
|
+
let n = new r(t);
|
|
593
|
+
return l(e).use(n), n;
|
|
594
|
+
}
|
|
595
|
+
validate() {
|
|
596
|
+
let e = this.options;
|
|
597
|
+
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) || !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), cellSize above 0, finite heightScale and heightOffset, and 4 to 16 layers.");
|
|
598
|
+
d(e.origin ?? [0, 0], 2, "Terrain origin"), e.clipmapAnchor !== void 0 && e.clipmapAnchor !== "camera" && d(e.clipmapAnchor, 2, "Terrain clipmap anchor");
|
|
599
|
+
let t = e.floatingOrigin;
|
|
600
|
+
if (t !== void 0 && (typeof t?.onRebase != "function" || t.origin?.length !== 3)) throw TypeError("Invalid terrain floatingOrigin; pass a FloatingOrigin from @margoengine/cameras/origin.");
|
|
601
|
+
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.");
|
|
602
|
+
for (let t of e.layers) {
|
|
603
|
+
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.");
|
|
604
|
+
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).");
|
|
605
|
+
}
|
|
606
|
+
}
|
|
607
|
+
addLighting(e) {
|
|
608
|
+
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.");
|
|
609
|
+
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");
|
|
610
|
+
return this.lighting.add(e), () => this.lighting.delete(e);
|
|
611
|
+
}
|
|
612
|
+
invalidate() {
|
|
613
|
+
this.shadowVersion++;
|
|
614
|
+
}
|
|
615
|
+
get heightmap() {
|
|
616
|
+
return this.textures?.heightmap;
|
|
617
|
+
}
|
|
618
|
+
get weights() {
|
|
619
|
+
return this.textures?.weights;
|
|
620
|
+
}
|
|
621
|
+
get holes() {
|
|
622
|
+
return this.textures?.holes;
|
|
623
|
+
}
|
|
624
|
+
setup(e) {
|
|
625
|
+
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");
|
|
626
|
+
this.engine = e, this.device = e.gpu, this.textures = this.options.textures(this.device);
|
|
627
|
+
let t = this.textures, n = t.weights, r = t.tint, i = t.holes;
|
|
628
|
+
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");
|
|
629
|
+
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");
|
|
630
|
+
for (let e of [
|
|
631
|
+
t.heightmap,
|
|
632
|
+
t.layers,
|
|
633
|
+
...t.normalmap ? [t.normalmap] : [],
|
|
634
|
+
...n ?? [],
|
|
635
|
+
...r ? [r] : [],
|
|
636
|
+
...i ? [i] : []
|
|
637
|
+
]) if (e.dimension !== "2d" || !(e.usage & GPUTextureUsage.TEXTURE_BINDING) || e.sampleCount !== 1) throw TypeError("Terrain textures must be sampled 2D textures");
|
|
638
|
+
if (t.heightmap.depthOrArrayLayers !== 1 || t.normalmap && t.normalmap.depthOrArrayLayers !== 1 || t.layers.depthOrArrayLayers !== this.options.layers.length || ![
|
|
639
|
+
"rgba8unorm",
|
|
640
|
+
"rgba8unorm-srgb",
|
|
641
|
+
"rgba16float"
|
|
642
|
+
].includes(t.layers.format) || ![
|
|
643
|
+
"r32float",
|
|
644
|
+
"rgba16float",
|
|
645
|
+
"rgba8unorm"
|
|
646
|
+
].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)) 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.");
|
|
647
|
+
let a = g(this.options.resolution ?? 64), o = (e, t) => {
|
|
648
|
+
if (e.byteLength > this.device.limits.maxBufferSize) throw RangeError("Terrain grid exceeds the device maxBufferSize; reduce resolution.");
|
|
649
|
+
let n = this.device.createBuffer({
|
|
650
|
+
size: e.byteLength,
|
|
651
|
+
usage: t | GPUBufferUsage.COPY_DST
|
|
652
|
+
});
|
|
653
|
+
try {
|
|
654
|
+
this.device.queue.writeBuffer(n, 0, e);
|
|
655
|
+
} catch (e) {
|
|
656
|
+
throw n.destroy(), e;
|
|
657
|
+
}
|
|
658
|
+
return n;
|
|
659
|
+
};
|
|
660
|
+
this.vertex = o(a.vertices, GPUBufferUsage.VERTEX), this.center = o(a.center, GPUBufferUsage.INDEX), this.ring = o(a.ring, GPUBufferUsage.INDEX), this.centerCount = a.center.length, this.ringCount = a.ring.length, this.rules = o(this.ruleData(), GPUBufferUsage.STORAGE), this.rulesShift.set(this.shiftValues), this.sampler = this.device.createSampler({
|
|
661
|
+
addressModeU: "repeat",
|
|
662
|
+
addressModeV: "repeat",
|
|
663
|
+
magFilter: "linear",
|
|
664
|
+
minFilter: "linear",
|
|
665
|
+
mipmapFilter: "linear"
|
|
666
|
+
});
|
|
667
|
+
let s = GPUShaderStage.VERTEX, c = GPUShaderStage.FRAGMENT;
|
|
668
|
+
this.layout = this.device.createBindGroupLayout({ entries: [
|
|
669
|
+
{
|
|
670
|
+
binding: 0,
|
|
671
|
+
visibility: s | c,
|
|
672
|
+
buffer: { type: "uniform" }
|
|
673
|
+
},
|
|
674
|
+
{
|
|
675
|
+
binding: 1,
|
|
676
|
+
visibility: s | c,
|
|
677
|
+
texture: { sampleType: "unfilterable-float" }
|
|
678
|
+
},
|
|
679
|
+
{
|
|
680
|
+
binding: 2,
|
|
681
|
+
visibility: s | c,
|
|
682
|
+
texture: { sampleType: "unfilterable-float" }
|
|
683
|
+
},
|
|
684
|
+
{
|
|
685
|
+
binding: 3,
|
|
686
|
+
visibility: c,
|
|
687
|
+
texture: { viewDimension: "2d-array" }
|
|
688
|
+
},
|
|
689
|
+
{
|
|
690
|
+
binding: 4,
|
|
691
|
+
visibility: c,
|
|
692
|
+
sampler: { type: "filtering" }
|
|
693
|
+
},
|
|
694
|
+
{
|
|
695
|
+
binding: 5,
|
|
696
|
+
visibility: c,
|
|
697
|
+
buffer: { type: "read-only-storage" }
|
|
698
|
+
},
|
|
699
|
+
...[
|
|
700
|
+
...n ?? [],
|
|
701
|
+
...r ? [r] : [],
|
|
702
|
+
...t.holes ? [t.holes] : []
|
|
703
|
+
].map((e, t) => ({
|
|
704
|
+
binding: 6 + t,
|
|
705
|
+
visibility: c,
|
|
706
|
+
texture: {}
|
|
707
|
+
}))
|
|
708
|
+
] });
|
|
709
|
+
let l = [
|
|
710
|
+
t.heightmap.createView(),
|
|
711
|
+
(t.normalmap ?? t.heightmap).createView(),
|
|
712
|
+
t.layers.createView({ dimension: "2d-array" }),
|
|
713
|
+
this.sampler,
|
|
714
|
+
{ buffer: this.rules },
|
|
715
|
+
...n ? n.map((e) => e.createView()) : [],
|
|
716
|
+
...r ? [r.createView()] : [],
|
|
717
|
+
...t.holes ? [t.holes.createView()] : []
|
|
718
|
+
], u = (e) => this.device.createBindGroup({
|
|
719
|
+
layout: this.layout,
|
|
720
|
+
entries: [{
|
|
721
|
+
binding: 0,
|
|
722
|
+
resource: { buffer: e }
|
|
723
|
+
}, ...l.map((e, t) => ({
|
|
724
|
+
binding: t + 1,
|
|
725
|
+
resource: e
|
|
726
|
+
}))]
|
|
727
|
+
});
|
|
728
|
+
this.ringGroup = u;
|
|
729
|
+
let d = this.options.floatingOrigin ? 48 : 44;
|
|
730
|
+
for (let e = 0; e < (this.options.levels ?? 6); e++) {
|
|
731
|
+
let e = this.device.createBuffer({
|
|
732
|
+
size: d * 4,
|
|
733
|
+
usage: GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST
|
|
734
|
+
}), t = [], n = {
|
|
735
|
+
uniform: e,
|
|
736
|
+
group: void 0,
|
|
737
|
+
values: new Float32Array(d),
|
|
738
|
+
shadowUniforms: t,
|
|
739
|
+
shadowGroups: [],
|
|
740
|
+
shadowValues: new Float32Array(d),
|
|
741
|
+
localUniforms: [],
|
|
742
|
+
localGroups: []
|
|
743
|
+
};
|
|
744
|
+
this.rings.push(n), n.group = u(e);
|
|
745
|
+
for (let e = 0; e < 4; e++) {
|
|
746
|
+
let e = this.device.createBuffer({
|
|
747
|
+
size: d * 4,
|
|
748
|
+
usage: GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST
|
|
749
|
+
});
|
|
750
|
+
t.push(e), n.shadowGroups.push(u(e));
|
|
751
|
+
}
|
|
752
|
+
}
|
|
753
|
+
let p = this.device.createShaderModule({ code: this.clip(y + `@fragment fn outside(i:Output){${x}}`) });
|
|
754
|
+
this.shadowModule = p, this.shadowPipeline = this.device.createRenderPipeline({
|
|
755
|
+
layout: this.device.createPipelineLayout({ bindGroupLayouts: [this.layout] }),
|
|
756
|
+
vertex: {
|
|
757
|
+
module: p,
|
|
758
|
+
entryPoint: "vertex",
|
|
759
|
+
buffers: [{
|
|
760
|
+
arrayStride: 8,
|
|
761
|
+
attributes: [{
|
|
762
|
+
shaderLocation: 0,
|
|
763
|
+
offset: 0,
|
|
764
|
+
format: "float32x2"
|
|
765
|
+
}]
|
|
766
|
+
}]
|
|
767
|
+
},
|
|
768
|
+
fragment: {
|
|
769
|
+
module: p,
|
|
770
|
+
entryPoint: "outside",
|
|
771
|
+
targets: []
|
|
772
|
+
},
|
|
773
|
+
depthStencil: {
|
|
774
|
+
format: "depth32float",
|
|
775
|
+
depthWriteEnabled: !0,
|
|
776
|
+
depthCompare: "less-equal"
|
|
777
|
+
}
|
|
778
|
+
}), this.invalidate();
|
|
779
|
+
}
|
|
780
|
+
ruleData() {
|
|
781
|
+
let e = this.textures.tint, t = !!this.options.floatingOrigin, n = this.shiftValues, r = this.surface() ? 12 : 8, i = r + (t ? 8 : 0), a = new Float32Array(this.options.layers.length * i);
|
|
782
|
+
return this.options.layers.forEach((o, s) => {
|
|
783
|
+
if (a.set([
|
|
784
|
+
o.height[0] - n[1],
|
|
785
|
+
o.height[1] - n[1],
|
|
786
|
+
...o.slope,
|
|
787
|
+
o.scale,
|
|
788
|
+
Math.max(.01, (o.height[1] - o.height[0]) * .05),
|
|
789
|
+
.05,
|
|
790
|
+
+(!!e && !!o.tint),
|
|
791
|
+
...r === 12 ? [
|
|
792
|
+
(o.bump ?? 0) * .5 / o.scale,
|
|
793
|
+
o.macro ?? 0,
|
|
794
|
+
o.scale / 24,
|
|
795
|
+
0
|
|
796
|
+
] : []
|
|
797
|
+
], s * i), !t) return;
|
|
798
|
+
let c = Math.fround(o.scale), l = [
|
|
799
|
+
n[0] - this.anchor[0],
|
|
800
|
+
n[1],
|
|
801
|
+
n[2] - this.anchor[1]
|
|
802
|
+
];
|
|
803
|
+
for (let e = 0; e < 3; e++) {
|
|
804
|
+
let t = Math.floor(l[e] * c / 24), n = t * Math.fround(.302);
|
|
805
|
+
a[s * i + r + e] = l[e] - t * 24 / c, a[s * i + r + 4 + e] = n - Math.floor(n);
|
|
806
|
+
}
|
|
807
|
+
}), a;
|
|
808
|
+
}
|
|
809
|
+
registerPasses(e) {
|
|
810
|
+
e.add({
|
|
811
|
+
name: this.name + ":prepare",
|
|
812
|
+
order: this.options.captureSurfaceHeight ? -11 : -6,
|
|
813
|
+
execute: (e) => {
|
|
814
|
+
e.backend === "webgpu" && this.prepare(e);
|
|
815
|
+
}
|
|
816
|
+
}), e.add({
|
|
817
|
+
name: this.name,
|
|
818
|
+
order: 1,
|
|
819
|
+
execute: (e) => {
|
|
820
|
+
e.backend === "webgpu" && this.drawRings(e);
|
|
821
|
+
}
|
|
822
|
+
});
|
|
823
|
+
}
|
|
824
|
+
prepare(e) {
|
|
825
|
+
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;
|
|
826
|
+
if (f) {
|
|
827
|
+
for (let e = 0; e < 3; e++) this.eye[e] = m[e] + p[e];
|
|
828
|
+
m = this.eye;
|
|
829
|
+
let t = this.rulesShift;
|
|
830
|
+
(t[0] !== p[0] || t[1] !== p[1] || t[2] !== p[2]) && (e.device.queue.writeBuffer(this.rules, 0, this.ruleData()), t.set(p));
|
|
831
|
+
}
|
|
832
|
+
if (this.plan.length !== this.rings.length * 2 && (this.plan = new Float64Array(this.rings.length * 2)), !this.anchoredEye && this.options.clipmapAnchor !== "camera") {
|
|
833
|
+
let t = this.engine?.camera?.position ?? e.camera.position;
|
|
834
|
+
this.anchoredEye = [
|
|
835
|
+
t[0] + p[0],
|
|
836
|
+
0,
|
|
837
|
+
t[2] + p[2]
|
|
838
|
+
];
|
|
839
|
+
}
|
|
840
|
+
let h = $(this.anchoredEye ?? m, p, l, this.rings.length, this.plan), g = 0, _ = 0, v = !1;
|
|
841
|
+
for (let a = 0; a < this.rings.length; a++) {
|
|
842
|
+
let m = this.rings[a].values, y = l * 2 ** a, b = h[a * 2], x = h[a * 2 + 1];
|
|
843
|
+
(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, f && (m[44] = p[0] - this.anchor[0], m[45] = p[2] - this.anchor[1], m[46] = p[1], m[47] = 0), this.upload(e.device.queue, this.rings[a].uniform, m), g = b, _ = x;
|
|
844
|
+
}
|
|
845
|
+
v && this.invalidate(), this.options.captureSurfaceHeight && (this.capturedSurface ??= A(e.device, this.textures.heightmap, this.layout, f ? C(y) : y, (e) => this.clip(e), !!f), this.capturedSurface?.draw(e.encoder, this.shadowVersion, this.rings, {
|
|
846
|
+
vertex: this.vertex,
|
|
847
|
+
center: this.center,
|
|
848
|
+
ring: this.ring,
|
|
849
|
+
centerCount: this.centerCount,
|
|
850
|
+
ringCount: this.ringCount
|
|
851
|
+
}));
|
|
852
|
+
}
|
|
853
|
+
shader() {
|
|
854
|
+
let e = this.base();
|
|
855
|
+
for (let t of this.lighting) e = t.shader(e, 1);
|
|
856
|
+
for (let t of this.lighting) t.finish && (e = t.finish(e, 1));
|
|
857
|
+
return e;
|
|
858
|
+
}
|
|
859
|
+
colorSource() {
|
|
860
|
+
if (!this.disposed && this.layout && this.rings[0]?.group) return {
|
|
861
|
+
code: this.base(),
|
|
862
|
+
layout: this.layout,
|
|
863
|
+
group: this.rings[0].group
|
|
864
|
+
};
|
|
865
|
+
}
|
|
866
|
+
base() {
|
|
867
|
+
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 ? O(this.textures.weights.length, t, !!this.textures.tint) : E(t));
|
|
868
|
+
return this.clip(this.options.floatingOrigin ? C(r) : r);
|
|
869
|
+
}
|
|
870
|
+
clip(e) {
|
|
871
|
+
let t = this.textures;
|
|
872
|
+
return t?.holes ? `@group(0) @binding(${6 + (t.weights?.length ?? 0) + +!!t.tint}) var terrainHoles:texture_2d<f32>;
|
|
873
|
+
${e.split(x).join(x + b)}` : e;
|
|
874
|
+
}
|
|
875
|
+
surface() {
|
|
876
|
+
return this.options.layers.some((e) => (e.bump ?? 0) > 0 || (e.macro ?? 0) > 0);
|
|
877
|
+
}
|
|
878
|
+
drawRings(t) {
|
|
879
|
+
let n = this.shader(), r = t.descriptor.multisample?.count + ":" + t.format + ":" + t.descriptor.depthStencil.format + n, a = this.pipelines.get(r), o = this.lightingEntries;
|
|
880
|
+
o.length = 0;
|
|
881
|
+
for (let e of this.lighting) {
|
|
882
|
+
let t = e.bindings();
|
|
883
|
+
for (let e = 0; e < t.length; e++) o.push(t[e]);
|
|
884
|
+
}
|
|
885
|
+
if (!a) {
|
|
886
|
+
let i = t.device.createShaderModule({ code: n }), s = [this.layout];
|
|
887
|
+
o.length && s.push(t.device.createBindGroupLayout({ entries: e(n, o) })), a = t.device.createRenderPipeline({
|
|
888
|
+
layout: t.device.createPipelineLayout({ bindGroupLayouts: s }),
|
|
889
|
+
vertex: {
|
|
890
|
+
module: i,
|
|
891
|
+
entryPoint: "vertex",
|
|
892
|
+
buffers: [{
|
|
893
|
+
arrayStride: 8,
|
|
894
|
+
attributes: [{
|
|
895
|
+
shaderLocation: 0,
|
|
896
|
+
offset: 0,
|
|
897
|
+
format: "float32x2"
|
|
898
|
+
}]
|
|
899
|
+
}]
|
|
900
|
+
},
|
|
901
|
+
fragment: {
|
|
902
|
+
module: i,
|
|
903
|
+
entryPoint: "fragment",
|
|
904
|
+
targets: [{ format: t.format }]
|
|
905
|
+
},
|
|
906
|
+
multisample: t.descriptor.multisample,
|
|
907
|
+
depthStencil: {
|
|
908
|
+
format: t.descriptor.depthStencil.format,
|
|
909
|
+
depthWriteEnabled: !0,
|
|
910
|
+
depthCompare: "greater-equal"
|
|
911
|
+
}
|
|
912
|
+
}), this.pipelines.set(r, a);
|
|
913
|
+
}
|
|
914
|
+
let s = t.encoder.beginRenderPass({
|
|
915
|
+
colorAttachments: [{
|
|
916
|
+
view: t.color,
|
|
917
|
+
loadOp: "load",
|
|
918
|
+
storeOp: "store"
|
|
919
|
+
}],
|
|
920
|
+
depthStencilAttachment: {
|
|
921
|
+
view: t.depth,
|
|
922
|
+
depthLoadOp: "load",
|
|
923
|
+
depthStoreOp: "store",
|
|
924
|
+
...t.descriptor.depthStencil.format.includes("stencil") ? {
|
|
925
|
+
stencilLoadOp: "load",
|
|
926
|
+
stencilStoreOp: "store"
|
|
927
|
+
} : {}
|
|
928
|
+
}
|
|
929
|
+
});
|
|
930
|
+
i(s, t), s.setPipeline(a), o.length && s.setBindGroup(1, this.lightingGroup(t.device, a, o)), s.setVertexBuffer(0, this.vertex);
|
|
931
|
+
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++;
|
|
932
|
+
s.end();
|
|
933
|
+
}
|
|
934
|
+
setCapture(e) {
|
|
935
|
+
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.");
|
|
936
|
+
return this.capture = e, () => {
|
|
937
|
+
this.capture === e && (this.capture = void 0);
|
|
938
|
+
};
|
|
939
|
+
}
|
|
940
|
+
onDispose(e) {
|
|
941
|
+
if (typeof e != "function") throw TypeError("Terrain onDispose needs a function");
|
|
942
|
+
return this.disposers.add(e), () => this.disposers.delete(e);
|
|
943
|
+
}
|
|
944
|
+
draw(n, r, i, a) {
|
|
945
|
+
let o = this.capture;
|
|
946
|
+
if (r !== "capture" || !o || this.disposed || !this.rings.length) return;
|
|
947
|
+
let s = this.shader(), c = o.declarations(s), l = c + "\0" + s, u = this.captureCode.get(l);
|
|
948
|
+
if (u === void 0) {
|
|
949
|
+
let e = "@fragment fn fragment(i:Output)->@location(0) vec4f {";
|
|
950
|
+
if (s.split(e).length !== 2) throw t("unsupported", "Terrain capture needs the terrain fragment entry point once; a lighting effect changed it");
|
|
951
|
+
u = c + s.replace(e, "fn margoShade(i:Output)->vec4f {") + `\n@fragment fn capture(i:Output)->MargoSSR {${x}${this.textures?.holes ? b : ""}${T(this.surface())}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);
|
|
952
|
+
}
|
|
953
|
+
let d = this.lightingEntries;
|
|
954
|
+
d.length = 0;
|
|
955
|
+
for (let e of this.lighting) {
|
|
956
|
+
let t = e.bindings();
|
|
957
|
+
for (let e = 0; e < t.length; e++) d.push(t[e]);
|
|
958
|
+
}
|
|
959
|
+
let f = "capture:" + o.targets.map((e) => e.format).join(",") + ":" + n.descriptor.multisample?.count + ":" + n.descriptor.depthStencil.format + u, p = this.pipelines.get(f);
|
|
960
|
+
if (!p) {
|
|
961
|
+
let t = n.device.createShaderModule({ code: u }), r = [this.layout];
|
|
962
|
+
d.length && r.push(n.device.createBindGroupLayout({ entries: e(u, d) })), p = n.device.createRenderPipeline({
|
|
963
|
+
layout: n.device.createPipelineLayout({ bindGroupLayouts: r }),
|
|
964
|
+
vertex: {
|
|
965
|
+
module: t,
|
|
966
|
+
entryPoint: "vertex",
|
|
967
|
+
buffers: [{
|
|
968
|
+
arrayStride: 8,
|
|
969
|
+
attributes: [{
|
|
970
|
+
shaderLocation: 0,
|
|
971
|
+
offset: 0,
|
|
972
|
+
format: "float32x2"
|
|
973
|
+
}]
|
|
974
|
+
}]
|
|
975
|
+
},
|
|
976
|
+
fragment: {
|
|
977
|
+
module: t,
|
|
978
|
+
entryPoint: "capture",
|
|
979
|
+
targets: o.targets
|
|
980
|
+
},
|
|
981
|
+
multisample: n.descriptor.multisample,
|
|
982
|
+
depthStencil: {
|
|
983
|
+
format: n.descriptor.depthStencil.format,
|
|
984
|
+
depthWriteEnabled: !0,
|
|
985
|
+
depthCompare: "greater-equal"
|
|
986
|
+
}
|
|
987
|
+
}), this.pipelines.set(f, p);
|
|
988
|
+
}
|
|
989
|
+
let m = o.begin();
|
|
990
|
+
m.setPipeline(p), d.length && m.setBindGroup(1, this.lightingGroup(n.device, p, d)), m.setVertexBuffer(0, this.vertex);
|
|
991
|
+
for (let e = 0; e < this.rings.length; e++) m.setBindGroup(0, this.rings[e].group), m.setIndexBuffer(e ? this.ring : this.center, "uint32"), m.drawIndexed(e ? this.ringCount : this.centerCount);
|
|
992
|
+
}
|
|
993
|
+
lightingGroup(e, t, n) {
|
|
994
|
+
let r = this.lightingGroups.get(t);
|
|
995
|
+
if (r?.device === e && r.entries.length === n.length && n.every((e, t) => {
|
|
996
|
+
let n = r.entries[t], i = e.resource, a = n.resource;
|
|
997
|
+
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);
|
|
998
|
+
})) return r.group;
|
|
999
|
+
let i = n.map(({ binding: e, resource: t }) => ({
|
|
1000
|
+
binding: e,
|
|
1001
|
+
resource: "buffer" in t ? {
|
|
1002
|
+
buffer: t.buffer,
|
|
1003
|
+
offset: t.offset,
|
|
1004
|
+
size: t.size
|
|
1005
|
+
} : t
|
|
1006
|
+
})), a = e.createBindGroup({
|
|
1007
|
+
layout: t.getBindGroupLayout(1),
|
|
1008
|
+
entries: n
|
|
1009
|
+
});
|
|
1010
|
+
return this.lightingGroups.set(t, {
|
|
1011
|
+
device: e,
|
|
1012
|
+
entries: i,
|
|
1013
|
+
group: a
|
|
1014
|
+
}), a;
|
|
1015
|
+
}
|
|
1016
|
+
drawOccluder({ pass: e, samples: t }) {
|
|
1017
|
+
if (!this.disposed && this.device) {
|
|
1018
|
+
if (this.occluder?.samples !== t) {
|
|
1019
|
+
let e = this.device.createShaderModule({ code: this.clip(y + `@fragment fn outside(i:Output){${x}}`) });
|
|
1020
|
+
this.occluder = {
|
|
1021
|
+
samples: t,
|
|
1022
|
+
pipeline: this.device.createRenderPipeline({
|
|
1023
|
+
layout: this.device.createPipelineLayout({ bindGroupLayouts: [this.layout] }),
|
|
1024
|
+
vertex: {
|
|
1025
|
+
module: e,
|
|
1026
|
+
entryPoint: "vertex",
|
|
1027
|
+
buffers: [{
|
|
1028
|
+
arrayStride: 8,
|
|
1029
|
+
attributes: [{
|
|
1030
|
+
shaderLocation: 0,
|
|
1031
|
+
offset: 0,
|
|
1032
|
+
format: "float32x2"
|
|
1033
|
+
}]
|
|
1034
|
+
}]
|
|
1035
|
+
},
|
|
1036
|
+
fragment: {
|
|
1037
|
+
module: e,
|
|
1038
|
+
entryPoint: "outside",
|
|
1039
|
+
targets: []
|
|
1040
|
+
},
|
|
1041
|
+
multisample: { count: t },
|
|
1042
|
+
depthStencil: {
|
|
1043
|
+
format: "depth32float",
|
|
1044
|
+
depthWriteEnabled: !0,
|
|
1045
|
+
depthCompare: "greater-equal"
|
|
1046
|
+
}
|
|
1047
|
+
})
|
|
1048
|
+
};
|
|
1049
|
+
}
|
|
1050
|
+
e.setPipeline(this.occluder.pipeline), e.setVertexBuffer(0, this.vertex);
|
|
1051
|
+
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);
|
|
1052
|
+
}
|
|
1053
|
+
}
|
|
1054
|
+
drawShadow({ context: e, pass: t, matrix: n, cascade: r }) {
|
|
1055
|
+
if (!this.disposed) {
|
|
1056
|
+
t.setPipeline(this.shadowPipeline), t.setVertexBuffer(0, this.vertex);
|
|
1057
|
+
for (let i = 0; i < this.rings.length; i++) {
|
|
1058
|
+
let a = this.rings[i];
|
|
1059
|
+
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);
|
|
1060
|
+
}
|
|
1061
|
+
}
|
|
1062
|
+
}
|
|
1063
|
+
drawLocalShadow({ context: e, pass: t, matrix: n, layer: r }) {
|
|
1064
|
+
if (this.disposed || !this.shadowModule || !this.ringGroup) return;
|
|
1065
|
+
if (!Number.isInteger(r) || r < 0) throw RangeError("Invalid local shadow layer; pass the integer layer index LocalShadows gives");
|
|
1066
|
+
let i = e.device, a = this.shadowModule;
|
|
1067
|
+
this.localShadowPipeline ??= i.createRenderPipeline({
|
|
1068
|
+
layout: i.createPipelineLayout({ bindGroupLayouts: [this.layout] }),
|
|
1069
|
+
vertex: {
|
|
1070
|
+
module: a,
|
|
1071
|
+
entryPoint: "vertex",
|
|
1072
|
+
buffers: [{
|
|
1073
|
+
arrayStride: 8,
|
|
1074
|
+
attributes: [{
|
|
1075
|
+
shaderLocation: 0,
|
|
1076
|
+
offset: 0,
|
|
1077
|
+
format: "float32x2"
|
|
1078
|
+
}]
|
|
1079
|
+
}]
|
|
1080
|
+
},
|
|
1081
|
+
fragment: {
|
|
1082
|
+
module: a,
|
|
1083
|
+
entryPoint: "outside",
|
|
1084
|
+
targets: []
|
|
1085
|
+
},
|
|
1086
|
+
depthStencil: {
|
|
1087
|
+
format: "depth32float",
|
|
1088
|
+
depthWriteEnabled: !0,
|
|
1089
|
+
depthCompare: "greater"
|
|
1090
|
+
}
|
|
1091
|
+
}), t.setPipeline(this.localShadowPipeline), t.setVertexBuffer(0, this.vertex);
|
|
1092
|
+
for (let e = 0; e < this.rings.length; e++) {
|
|
1093
|
+
let a = this.rings[e], o = a.localUniforms[r];
|
|
1094
|
+
o || (o = a.localUniforms[r] = i.createBuffer({
|
|
1095
|
+
size: a.values.length * 4,
|
|
1096
|
+
usage: GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST
|
|
1097
|
+
}), a.localGroups[r] = this.ringGroup(o)), a.shadowValues.set(a.values), a.shadowValues.set(n), this.upload(i.queue, o, a.shadowValues), t.setBindGroup(0, a.localGroups[r]), t.setIndexBuffer(e ? this.ring : this.center, "uint32"), t.drawIndexed(e ? this.ringCount : this.centerCount);
|
|
1098
|
+
}
|
|
1099
|
+
}
|
|
1100
|
+
upload(e, t, n) {
|
|
1101
|
+
let r = this.bitViews.get(n);
|
|
1102
|
+
r || this.bitViews.set(n, r = new Uint32Array(n.buffer, n.byteOffset, n.length));
|
|
1103
|
+
let i = this.sent.get(t);
|
|
1104
|
+
if (i) {
|
|
1105
|
+
let e = !0;
|
|
1106
|
+
for (let t = 0; t < r.length; t++) if (r[t] !== i[t]) {
|
|
1107
|
+
e = !1;
|
|
1108
|
+
break;
|
|
1109
|
+
}
|
|
1110
|
+
if (e) return;
|
|
1111
|
+
} else this.sent.set(t, i = new Uint32Array(r.length));
|
|
1112
|
+
i.set(r), e.writeBuffer(t, 0, n);
|
|
1113
|
+
}
|
|
1114
|
+
release() {
|
|
1115
|
+
this.capturedSurface?.texture.destroy(), this.capturedSurface = void 0;
|
|
1116
|
+
for (let e of new Set(this.textures ? [
|
|
1117
|
+
this.textures.heightmap,
|
|
1118
|
+
this.textures.normalmap,
|
|
1119
|
+
this.textures.layers,
|
|
1120
|
+
...this.textures.weights ?? [],
|
|
1121
|
+
this.textures.tint,
|
|
1122
|
+
this.textures.holes
|
|
1123
|
+
] : [])) e?.destroy();
|
|
1124
|
+
for (let e of [
|
|
1125
|
+
this.vertex,
|
|
1126
|
+
this.center,
|
|
1127
|
+
this.ring,
|
|
1128
|
+
this.rules
|
|
1129
|
+
]) e?.destroy();
|
|
1130
|
+
for (let e of this.rings) for (let t of [
|
|
1131
|
+
e.uniform,
|
|
1132
|
+
...e.shadowUniforms,
|
|
1133
|
+
...e.localUniforms
|
|
1134
|
+
]) t?.destroy();
|
|
1135
|
+
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.shadowPipeline = this.localShadowPipeline = this.shadowModule = this.ringGroup = void 0, this.layout = void 0, this.sampler = void 0;
|
|
1136
|
+
}
|
|
1137
|
+
onDeviceRestored(e) {
|
|
1138
|
+
this.release(), this.setup(e);
|
|
1139
|
+
}
|
|
1140
|
+
dispose() {
|
|
1141
|
+
if (this.disposed) return;
|
|
1142
|
+
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;
|
|
1143
|
+
let e = [...this.disposers];
|
|
1144
|
+
this.disposers.clear();
|
|
1145
|
+
for (let t of e) t();
|
|
1146
|
+
}
|
|
1147
|
+
[Symbol.dispose ?? Symbol()]() {
|
|
1148
|
+
this.dispose();
|
|
1149
|
+
}
|
|
1150
|
+
destroy() {
|
|
1151
|
+
this.dispose();
|
|
1152
|
+
}
|
|
1153
|
+
};
|
|
1154
|
+
//#endregion
|
|
1155
|
+
export { Y as a, g as c, X as i, $ as n, K as o, Q as r, U as s, te as t };
|