@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
package/dist/query.d.ts
ADDED
|
@@ -0,0 +1,150 @@
|
|
|
1
|
+
import type { EngineKernel } from '@margoengine/core';
|
|
2
|
+
import type { MutableVec3, Vec3 } from '@margoengine/math';
|
|
3
|
+
/** Where the heights lie and how they scale: the fields of the same name in `TerrainOptions`, so `terrain.options` fits. */
|
|
4
|
+
export interface TerrainQueryOptions {
|
|
5
|
+
/** World XZ of the heightmap's minimum corner (its first texel). Default [0, 0]. */
|
|
6
|
+
readonly origin?: readonly [number, number];
|
|
7
|
+
/** World XZ extent the heightmap covers, each above 0 (its last texel sits at `origin + size`). */
|
|
8
|
+
readonly size: readonly [number, number];
|
|
9
|
+
/** World Y per height sample unit. Default 100. */
|
|
10
|
+
readonly heightScale?: number;
|
|
11
|
+
/** World Y added to every height. Default 0. */
|
|
12
|
+
readonly heightOffset?: number;
|
|
13
|
+
/**
|
|
14
|
+
* Hole cells to skip, as the terrain drops them (`TerrainTextures.holes`): a `TerrainHoles` from
|
|
15
|
+
* `@margoengine/terrain/holes` fits. Read live, so later cuts apply without a refresh. Default none.
|
|
16
|
+
*/
|
|
17
|
+
readonly holes?: TerrainHoleMask;
|
|
18
|
+
}
|
|
19
|
+
/** A hole mask over the heightmap's bounds: `columns * rows` bytes, row by row along +Z, 0 for a hole. */
|
|
20
|
+
export interface TerrainHoleMask {
|
|
21
|
+
readonly mask: Uint8Array;
|
|
22
|
+
readonly columns: number;
|
|
23
|
+
readonly rows: number;
|
|
24
|
+
}
|
|
25
|
+
/** A ray's first hit on the terrain. Its shape is `@margoengine/animator`'s `GroundHit`, so it plants feet as it is. */
|
|
26
|
+
export interface TerrainHit {
|
|
27
|
+
/** World distance from the ray's origin. */
|
|
28
|
+
distance: number;
|
|
29
|
+
/** World point of the hit. */
|
|
30
|
+
position: MutableVec3;
|
|
31
|
+
/** Unit shading normal there, as the terrain's vertex shader works it out (see `TerrainQuery.normal`). */
|
|
32
|
+
normal: MutableVec3;
|
|
33
|
+
}
|
|
34
|
+
/** Settings of {@link TerrainQuery.read}. */
|
|
35
|
+
export interface TerrainReadOptions {
|
|
36
|
+
/** Stops the wait for the GPU read; the promise then rejects with the signal's reason. */
|
|
37
|
+
readonly signal?: AbortSignal;
|
|
38
|
+
}
|
|
39
|
+
/** What {@link TerrainQuery.read} needs of a `Terrain`: its options and its heightmap texture. */
|
|
40
|
+
export interface TerrainHeightSource {
|
|
41
|
+
readonly options: TerrainQueryOptions;
|
|
42
|
+
readonly heightmap: GPUTexture | undefined;
|
|
43
|
+
}
|
|
44
|
+
/** Settings of {@link TerrainQuery.triangles}. */
|
|
45
|
+
export interface TerrainTrianglesOptions {
|
|
46
|
+
/**
|
|
47
|
+
* Samples between neighbouring vertices each way, an integer 1 or more. Default 1: one vertex per height sample, so
|
|
48
|
+
* every vertex lies on the surface `height` answers. A larger step thins the mesh; the last row and column of the
|
|
49
|
+
* region are always kept, so the mesh still reaches the region's edges.
|
|
50
|
+
*/
|
|
51
|
+
readonly step?: number;
|
|
52
|
+
/**
|
|
53
|
+
* World XZ rectangle to cover, widened to whole cells and clipped to the heightmap. Default the whole heightmap.
|
|
54
|
+
*/
|
|
55
|
+
readonly region?: {
|
|
56
|
+
readonly min: readonly [number, number];
|
|
57
|
+
readonly max: readonly [number, number];
|
|
58
|
+
};
|
|
59
|
+
}
|
|
60
|
+
/** A triangle mesh of the terrain in world space, from {@link TerrainQuery.triangles}. */
|
|
61
|
+
export interface TerrainTriangles {
|
|
62
|
+
/** World positions, xyz per vertex. */
|
|
63
|
+
readonly positions: Float32Array;
|
|
64
|
+
/** Unit shading normals, xyz per vertex, as `TerrainQuery.normal` gives them. */
|
|
65
|
+
readonly normals: Float32Array;
|
|
66
|
+
/** Three vertex indices per triangle, counter-clockwise seen from above (+Y). Empty when every cell is a hole. */
|
|
67
|
+
readonly indices: Uint32Array;
|
|
68
|
+
}
|
|
69
|
+
/**
|
|
70
|
+
* Height, normal and first-hit ray queries on a terrain's heights, for picking, foot placement and game logic. Answers
|
|
71
|
+
* the surface `Terrain` samples in its vertex shader; the clipmap draws it as triangles at its own cell spacing, so a
|
|
72
|
+
* drawn point lies within that triangulation's error of the answer. Holds the heights it is given (no copy) and a
|
|
73
|
+
* min-max tree of two thirds of their count in floats; call `refresh` after changing heights in place. CPU only, no allocation
|
|
74
|
+
* per query when an `out` is passed.
|
|
75
|
+
* @throws RangeError when the grid or the options are out of range.
|
|
76
|
+
*/
|
|
77
|
+
export declare class TerrainQuery {
|
|
78
|
+
/** Height samples, row by row (`columns` per row), in heightmap units: world Y is `sample * heightScale + heightOffset`. */
|
|
79
|
+
readonly heights: Float32Array;
|
|
80
|
+
readonly columns: number;
|
|
81
|
+
readonly rows: number;
|
|
82
|
+
private readonly ox;
|
|
83
|
+
private readonly oz;
|
|
84
|
+
private readonly sx;
|
|
85
|
+
private readonly sz;
|
|
86
|
+
/** World size of one cell (texel spacing). */
|
|
87
|
+
private readonly dx;
|
|
88
|
+
private readonly dz;
|
|
89
|
+
private readonly scale;
|
|
90
|
+
private readonly offset;
|
|
91
|
+
private readonly holes?;
|
|
92
|
+
/** Min-max levels from 1 up; level l's node (i, j) covers cells [i << l, (i + 1) << l) each way, [min, max] pairs. */
|
|
93
|
+
private readonly levels;
|
|
94
|
+
private readonly widths;
|
|
95
|
+
private readonly stack;
|
|
96
|
+
private readonly order;
|
|
97
|
+
/**
|
|
98
|
+
* @param heights `columns * rows` finite samples, row by row from the `origin` corner along +X, rows along +Z, the
|
|
99
|
+
* layout `queue.writeTexture` uploads to the heightmap.
|
|
100
|
+
*/
|
|
101
|
+
constructor(heights: Float32Array, columns: number, rows: number, options: TerrainQueryOptions);
|
|
102
|
+
/**
|
|
103
|
+
* Reads a live terrain's heightmap back from the GPU into a new query, once (later edits to the texture need a new
|
|
104
|
+
* read or `refresh` on your own copy). The heightmap needs `GPUTextureUsage.COPY_SRC`; `r32float`, `rgba16float` and
|
|
105
|
+
* `rgba8unorm` (R channel, 0..1) are read as the shader reads them.
|
|
106
|
+
* @throws MargoError `'state'` when the terrain has no heightmap yet (attach it first) or it lacks COPY_SRC.
|
|
107
|
+
*/
|
|
108
|
+
static read(engine: EngineKernel, terrain: TerrainHeightSource, { signal }?: TerrainReadOptions): Promise<TerrainQuery>;
|
|
109
|
+
/**
|
|
110
|
+
* Rebuilds the min-max tree over a rectangle of samples after you changed `heights` in place (the whole grid by
|
|
111
|
+
* default). Costs about the rectangle's sample count.
|
|
112
|
+
* @throws RangeError when a sample is not finite.
|
|
113
|
+
*/
|
|
114
|
+
refresh(x?: number, z?: number, width?: number, depth?: number): void;
|
|
115
|
+
/** World height at world (x, z), or undefined outside the heightmap's rectangle (where the terrain draws nothing). */
|
|
116
|
+
height(x: number, z: number): number | undefined;
|
|
117
|
+
/**
|
|
118
|
+
* Unit shading normal at world (x, z), as the vertex shader works it out without a normal map: central differences
|
|
119
|
+
* of the height one texel either way (heights clamped at the edges). Undefined outside the heightmap's rectangle.
|
|
120
|
+
*/
|
|
121
|
+
normal(x: number, z: number, out?: MutableVec3): MutableVec3 | undefined;
|
|
122
|
+
/**
|
|
123
|
+
* The terrain as a world-space triangle mesh, for a path tracer, a collider or an export: vertices on the height
|
|
124
|
+
* samples (every `step`-th each way), two triangles per cell, normals as `normal` works them out. A cell whose centre
|
|
125
|
+
* lies in a hole is left out, so the cut follows the mesh's cells (with `step` 1, the heightmap's own cells). The
|
|
126
|
+
* drawn clipmap triangulates at its own cell spacing; at a step of 1 this mesh holds the surface's exact samples.
|
|
127
|
+
*
|
|
128
|
+
* ```ts
|
|
129
|
+
* const { positions, normals, indices } = query.triangles({ step: 2, region: { min: [-50, -50], max: [50, 50] } });
|
|
130
|
+
* ```
|
|
131
|
+
* @throws RangeError for a step that is not an integer 1 or more, a region that is not finite or misses the
|
|
132
|
+
* heightmap, or a mesh of more than 16,777,216 vertices (pass a larger step or a smaller region).
|
|
133
|
+
*/
|
|
134
|
+
triangles({ step, region }?: TerrainTrianglesOptions): TerrainTriangles;
|
|
135
|
+
/** The shading normal at world (x, z) inside the rectangle, without the bounds and hole checks of `normal`. */
|
|
136
|
+
private slope;
|
|
137
|
+
/**
|
|
138
|
+
* The first point where a ray from world `origin` along `direction` (any length above 0) meets the terrain within
|
|
139
|
+
* `maxDistance`, from above or below, or null. Inside the heightmap's rectangle only. Pass `out` to reuse a hit.
|
|
140
|
+
* `(origin, direction) => query.raycast(origin, direction)` is a `FootIK` raycast as it is.
|
|
141
|
+
* @throws TypeError when the origin or direction is not finite or the direction has no length.
|
|
142
|
+
*/
|
|
143
|
+
raycast(origin: Vec3, direction: Vec3, maxDistance?: number, out?: TerrainHit): TerrainHit | null;
|
|
144
|
+
/** Smallest t in [t0, t1] where the ray meets cell (cx, cz)'s bilinear patch, or undefined. */
|
|
145
|
+
private patch;
|
|
146
|
+
/** Whether world (x, z) is in a hole cell of `holes` (the cell the terrain's fragment test reads there). */
|
|
147
|
+
private hole;
|
|
148
|
+
/** Bilinear world height at (x, z), clamped to the heightmap like the shader's `height`. */
|
|
149
|
+
private sample;
|
|
150
|
+
}
|
package/dist/query.js
ADDED
|
@@ -0,0 +1,243 @@
|
|
|
1
|
+
import { t as e } from "./errors-fc4i1pSL.js";
|
|
2
|
+
//#region ../shared/map-read.js
|
|
3
|
+
function t(e, t) {
|
|
4
|
+
return new Promise((n, r) => {
|
|
5
|
+
let i = () => r(t.reason);
|
|
6
|
+
t?.addEventListener("abort", i, { once: !0 }), e.mapAsync(GPUMapMode.READ).then(() => {
|
|
7
|
+
t?.removeEventListener("abort", i), n();
|
|
8
|
+
}, (e) => {
|
|
9
|
+
t?.removeEventListener("abort", i), r(e);
|
|
10
|
+
});
|
|
11
|
+
});
|
|
12
|
+
}
|
|
13
|
+
//#endregion
|
|
14
|
+
//#region src/query.ts
|
|
15
|
+
var n = 16384, r = 2 ** 24, i = class i {
|
|
16
|
+
constructor(e, t, r, i) {
|
|
17
|
+
if (this.levels = [], this.widths = [], this.order = /* @__PURE__ */ new Float64Array(8), !(e instanceof Float32Array) || ![t, r].every((e) => Number.isInteger(e) && e >= 2 && e <= n) || e.length !== t * r) throw RangeError(`Invalid terrain query grid; pass a Float32Array of columns * rows samples, each count an integer 2..${n}.`);
|
|
18
|
+
let a = i?.origin ?? [0, 0], o = i?.size;
|
|
19
|
+
if (this.scale = i?.heightScale ?? 100, this.offset = i?.heightOffset ?? 0, !o || ![
|
|
20
|
+
a[0],
|
|
21
|
+
a[1],
|
|
22
|
+
o[0],
|
|
23
|
+
o[1],
|
|
24
|
+
this.scale,
|
|
25
|
+
this.offset
|
|
26
|
+
].every(Number.isFinite) || !(o[0] > 0 && o[1] > 0)) throw RangeError("Invalid terrain query options; give a size above 0 each way and a finite origin, heightScale and heightOffset.");
|
|
27
|
+
let s = i?.holes;
|
|
28
|
+
if (s !== void 0 && (!(s?.mask instanceof Uint8Array) || !Number.isInteger(s.columns) || !Number.isInteger(s.rows) || s.columns < 1 || s.rows < 1 || s.mask.length !== s.columns * s.rows)) throw RangeError("Invalid terrain query holes; pass a mask of columns * rows bytes (a TerrainHoles fits).");
|
|
29
|
+
this.holes = s, this.heights = e, this.columns = t, this.rows = r, [this.ox, this.oz] = a, [this.sx, this.sz] = o, this.dx = o[0] / (t - 1), this.dz = o[1] / (r - 1);
|
|
30
|
+
let c = t - 1, l = r - 1;
|
|
31
|
+
for (; c > 1 || l > 1;) c = Math.ceil(c / 2), l = Math.ceil(l / 2), this.widths.push(c), this.levels.push(new Float32Array(c * l * 2));
|
|
32
|
+
this.stack = new Int32Array(3 * (3 * (this.levels.length + 1) + 4)), this.refresh();
|
|
33
|
+
}
|
|
34
|
+
static async read(n, r, { signal: o } = {}) {
|
|
35
|
+
o?.throwIfAborted();
|
|
36
|
+
let s = n.gpu, c = r?.heightmap;
|
|
37
|
+
if (!s || !c || !(c.usage & GPUTextureUsage.COPY_SRC)) throw e("state", "TerrainQuery.read needs an attached WebGPU Terrain whose heightmap has GPUTextureUsage.COPY_SRC; add it in your textures factory or pass the heights to new TerrainQuery");
|
|
38
|
+
let l = {
|
|
39
|
+
r32float: 4,
|
|
40
|
+
rgba16float: 8,
|
|
41
|
+
rgba8unorm: 4
|
|
42
|
+
}[c.format];
|
|
43
|
+
if (!l) throw TypeError("Unsupported heightmap format for TerrainQuery.read; use r32float, rgba16float or rgba8unorm, or pass the heights to new TerrainQuery");
|
|
44
|
+
let u = c.width, d = c.height, f = Math.ceil(u * l / 256) * 256, p = s.createBuffer({
|
|
45
|
+
size: f * d,
|
|
46
|
+
usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ
|
|
47
|
+
});
|
|
48
|
+
try {
|
|
49
|
+
let e = s.createCommandEncoder();
|
|
50
|
+
e.copyTextureToBuffer({ texture: c }, {
|
|
51
|
+
buffer: p,
|
|
52
|
+
bytesPerRow: f,
|
|
53
|
+
rowsPerImage: d
|
|
54
|
+
}, [u, d]), s.queue.submit([e.finish()]), await t(p, o);
|
|
55
|
+
let n = new DataView(p.getMappedRange()), m = new Float32Array(u * d);
|
|
56
|
+
for (let e = 0; e < d; e++) for (let t = 0; t < u; t++) {
|
|
57
|
+
let r = e * f + t * l;
|
|
58
|
+
m[e * u + t] = l === 8 ? a(n.getUint16(r, !0)) : c.format === "r32float" ? n.getFloat32(r, !0) : n.getUint8(r) / 255;
|
|
59
|
+
}
|
|
60
|
+
return p.unmap(), new i(m, u, d, r.options);
|
|
61
|
+
} finally {
|
|
62
|
+
p.destroy();
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
refresh(e = 0, t = 0, n = this.columns - e, r = this.rows - t) {
|
|
66
|
+
let i = this.columns, a = i - 1, o = this.rows - 1, s = Math.max(0, Math.floor(e) - 1), c = Math.max(0, Math.floor(t) - 1), l = Math.min(a - 1, Math.ceil(e + n) - 1), u = Math.min(o - 1, Math.ceil(t + r) - 1), d = this.heights;
|
|
67
|
+
if (!(l < s || u < c)) {
|
|
68
|
+
for (let a = Math.max(0, Math.floor(t)); a < Math.min(this.rows, Math.ceil(t + r)); a++) for (let t = Math.max(0, Math.floor(e)); t < Math.min(i, Math.ceil(e + n)); t++) if (!Number.isFinite(d[a * i + t])) throw RangeError(`Terrain query height at (${t}, ${a}) is not finite; write finite heights before refresh`);
|
|
69
|
+
for (let e = 0; e < this.levels.length; e++) {
|
|
70
|
+
let t = this.levels[e], n = this.widths[e], r = t.length / 2 / n, f = s >> e + 1, p = c >> e + 1, m = Math.min(n - 1, l >> e + 1), h = Math.min(r - 1, u >> e + 1);
|
|
71
|
+
for (let r = p; r <= h; r++) for (let s = f; s <= m; s++) {
|
|
72
|
+
let c = Infinity, l = -Infinity;
|
|
73
|
+
if (e === 0) for (let e = 2 * r; e <= Math.min(2 * r + 2, o); e++) for (let t = 2 * s; t <= Math.min(2 * s + 2, a); t++) {
|
|
74
|
+
let n = d[e * i + t];
|
|
75
|
+
n < c && (c = n), n > l && (l = n);
|
|
76
|
+
}
|
|
77
|
+
else {
|
|
78
|
+
let t = this.levels[e - 1], n = this.widths[e - 1], i = t.length / 2 / n;
|
|
79
|
+
for (let e = 2 * r; e < Math.min(2 * r + 2, i); e++) for (let r = 2 * s; r < Math.min(2 * s + 2, n); r++) {
|
|
80
|
+
let i = (e * n + r) * 2;
|
|
81
|
+
t[i] < c && (c = t[i]), t[i + 1] > l && (l = t[i + 1]);
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
t[(r * n + s) * 2] = c, t[(r * n + s) * 2 + 1] = l;
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
height(e, t) {
|
|
90
|
+
if (e >= this.ox && e <= this.ox + this.sx && t >= this.oz && t <= this.oz + this.sz && !this.hole(e, t)) return this.sample(e, t);
|
|
91
|
+
}
|
|
92
|
+
normal(e, t, n = [
|
|
93
|
+
0,
|
|
94
|
+
0,
|
|
95
|
+
0
|
|
96
|
+
]) {
|
|
97
|
+
if (e >= this.ox && e <= this.ox + this.sx && t >= this.oz && t <= this.oz + this.sz && !this.hole(e, t)) return this.slope(e, t, n);
|
|
98
|
+
}
|
|
99
|
+
triangles({ step: e = 1, region: t } = {}) {
|
|
100
|
+
if (!Number.isInteger(e) || e < 1) throw RangeError(`Invalid terrain triangles step ${e}; pass an integer 1 or more`);
|
|
101
|
+
let n = 0, i = this.columns - 1, a = 0, o = this.rows - 1;
|
|
102
|
+
if (t !== void 0) {
|
|
103
|
+
let e = t?.min, r = t?.max;
|
|
104
|
+
if (!e || !r || ![
|
|
105
|
+
e[0],
|
|
106
|
+
e[1],
|
|
107
|
+
r[0],
|
|
108
|
+
r[1]
|
|
109
|
+
].every(Number.isFinite) || !(r[0] > e[0] && r[1] > e[1])) throw RangeError("Invalid terrain triangles region; pass finite min and max corners with max above min");
|
|
110
|
+
if (n = Math.max(n, Math.floor((e[0] - this.ox) / this.dx)), i = Math.min(i, Math.ceil((r[0] - this.ox) / this.dx)), a = Math.max(a, Math.floor((e[1] - this.oz) / this.dz)), o = Math.min(o, Math.ceil((r[1] - this.oz) / this.dz)), i <= n || o <= a) throw RangeError("Invalid terrain triangles region; it does not overlap the heightmap by a cell");
|
|
111
|
+
}
|
|
112
|
+
let s = (t, n) => {
|
|
113
|
+
let r = [];
|
|
114
|
+
for (let i = t; i < n; i += e) r.push(i);
|
|
115
|
+
return r.push(n), r;
|
|
116
|
+
}, c = s(n, i), l = s(a, o), u = c.length, d = u * l.length;
|
|
117
|
+
if (d > r) throw RangeError(`Terrain triangles would hold ${d} vertices, above ${r}; pass a larger step or a smaller region`);
|
|
118
|
+
let f = new Float32Array(d * 3), p = new Float32Array(d * 3), m = [
|
|
119
|
+
0,
|
|
120
|
+
0,
|
|
121
|
+
0
|
|
122
|
+
], h = this.columns;
|
|
123
|
+
for (let e = 0; e < l.length; e++) for (let t = 0; t < u; t++) {
|
|
124
|
+
let n = (e * u + t) * 3, r = this.ox + c[t] * this.dx, i = this.oz + l[e] * this.dz;
|
|
125
|
+
f[n] = r, f[n + 1] = this.heights[l[e] * h + c[t]] * this.scale + this.offset, f[n + 2] = i, this.slope(r, i, m), p[n] = m[0], p[n + 1] = m[1], p[n + 2] = m[2];
|
|
126
|
+
}
|
|
127
|
+
let g = new Uint32Array((u - 1) * (l.length - 1) * 6), _ = 0;
|
|
128
|
+
for (let e = 0; e + 1 < l.length; e++) for (let t = 0; t + 1 < u; t++) {
|
|
129
|
+
if (this.hole(this.ox + (c[t] + c[t + 1]) / 2 * this.dx, this.oz + (l[e] + l[e + 1]) / 2 * this.dz)) continue;
|
|
130
|
+
let n = e * u + t, r = n + 1, i = n + u, a = i + 1;
|
|
131
|
+
g[_++] = n, g[_++] = i, g[_++] = r, g[_++] = r, g[_++] = i, g[_++] = a;
|
|
132
|
+
}
|
|
133
|
+
return {
|
|
134
|
+
positions: f,
|
|
135
|
+
normals: p,
|
|
136
|
+
indices: _ === g.length ? g : g.slice(0, _)
|
|
137
|
+
};
|
|
138
|
+
}
|
|
139
|
+
slope(e, t, n) {
|
|
140
|
+
let r = (this.sample(e - this.dx, t) - this.sample(e + this.dx, t)) / (2 * this.dx), i = (this.sample(e, t - this.dz) - this.sample(e, t + this.dz)) / (2 * this.dz), a = Math.hypot(r, 1, i);
|
|
141
|
+
return n[0] = r / a, n[1] = 1 / a, n[2] = i / a, n;
|
|
142
|
+
}
|
|
143
|
+
raycast(e, t, n = Infinity, r) {
|
|
144
|
+
let i = Math.hypot(t?.[0], t?.[1], t?.[2]);
|
|
145
|
+
if (!(i > 0 && Number.isFinite(i)) || ![
|
|
146
|
+
e?.[0],
|
|
147
|
+
e?.[1],
|
|
148
|
+
e?.[2]
|
|
149
|
+
].every(Number.isFinite)) throw TypeError("Invalid terrain raycast; pass a finite origin and a finite direction of length above 0");
|
|
150
|
+
if (!(n >= 0)) return null;
|
|
151
|
+
let a = e[0], o = e[1], s = e[2], c = t[0] / i, l = t[1] / i, u = t[2] / i, d = 1 / c, f = 1 / u, p = 1 / l, m = this.columns - 1, h = this.rows - 1, g = this.stack, _ = this.levels.length, v = this.order, y = 0;
|
|
152
|
+
for (g[y++] = _, g[y++] = 0, g[y++] = 0; y > 0;) {
|
|
153
|
+
let e = g[--y], t = g[--y], i = g[--y], _ = t << i, b = e << i, x = Math.min(t + 1 << i, m), S = Math.min(e + 1 << i, h), C, w;
|
|
154
|
+
if (i === 0) {
|
|
155
|
+
let e = this.columns, t = this.heights, n = t[b * e + _], r = t[b * e + _ + 1], i = t[(b + 1) * e + _], a = t[(b + 1) * e + _ + 1];
|
|
156
|
+
C = Math.min(n, r, i, a), w = Math.max(n, r, i, a);
|
|
157
|
+
} else {
|
|
158
|
+
let n = this.levels[i - 1], r = (e * this.widths[i - 1] + t) * 2;
|
|
159
|
+
C = n[r], w = n[r + 1];
|
|
160
|
+
}
|
|
161
|
+
let T = this.scale >= 0 ? C * this.scale + this.offset : w * this.scale + this.offset, E = this.scale >= 0 ? w * this.scale + this.offset : C * this.scale + this.offset, D = 0, O = n, k = this.ox + _ * this.dx, A = this.ox + x * this.dx, j = this.oz + b * this.dz, M = this.oz + S * this.dz;
|
|
162
|
+
if (c !== 0) {
|
|
163
|
+
let e = (k - a) * d, t = (A - a) * d;
|
|
164
|
+
D = Math.max(D, Math.min(e, t)), O = Math.min(O, Math.max(e, t));
|
|
165
|
+
} else if (a < k || a > A) continue;
|
|
166
|
+
if (u !== 0) {
|
|
167
|
+
let e = (j - s) * f, t = (M - s) * f;
|
|
168
|
+
D = Math.max(D, Math.min(e, t)), O = Math.min(O, Math.max(e, t));
|
|
169
|
+
} else if (s < j || s > M) continue;
|
|
170
|
+
if (l !== 0) {
|
|
171
|
+
let e = (T - o) * p, t = (E - o) * p;
|
|
172
|
+
D = Math.max(D, Math.min(e, t)), O = Math.min(O, Math.max(e, t));
|
|
173
|
+
} else if (o < T || o > E) continue;
|
|
174
|
+
if (D > O) continue;
|
|
175
|
+
if (i === 0) {
|
|
176
|
+
let e = this.patch(_, b, a, o, s, c, l, u, D, O);
|
|
177
|
+
if (e === void 0) continue;
|
|
178
|
+
let t = a + c * e, n = s + u * e;
|
|
179
|
+
if (this.hole(t, n)) continue;
|
|
180
|
+
let i = r ?? {
|
|
181
|
+
distance: 0,
|
|
182
|
+
position: [
|
|
183
|
+
0,
|
|
184
|
+
0,
|
|
185
|
+
0
|
|
186
|
+
],
|
|
187
|
+
normal: [
|
|
188
|
+
0,
|
|
189
|
+
0,
|
|
190
|
+
0
|
|
191
|
+
]
|
|
192
|
+
};
|
|
193
|
+
i.distance = e, i.position[0] = t, i.position[1] = o + l * e, i.position[2] = n;
|
|
194
|
+
let d = Math.min(Math.max(t, this.ox), this.ox + this.sx), f = Math.min(Math.max(n, this.oz), this.oz + this.sz);
|
|
195
|
+
return this.normal(d, f, i.normal), i;
|
|
196
|
+
}
|
|
197
|
+
let N = 0;
|
|
198
|
+
for (let n = 0; n < 2; n++) for (let r = 0; r < 2; r++) {
|
|
199
|
+
let o = 2 * t + r, l = 2 * e + n, p = 1 << i - 1;
|
|
200
|
+
if (o * p >= m || l * p >= h) continue;
|
|
201
|
+
let g = this.ox + o * p * this.dx, _ = this.ox + Math.min((o + 1) * p, m) * this.dx, y = this.oz + l * p * this.dz, b = this.oz + Math.min((l + 1) * p, h) * this.dz, x = 0;
|
|
202
|
+
c !== 0 && (x = Math.max(x, Math.min((g - a) * d, (_ - a) * d))), u !== 0 && (x = Math.max(x, Math.min((y - s) * f, (b - s) * f)));
|
|
203
|
+
let S = N++;
|
|
204
|
+
for (; S > 0 && v[(S - 1) * 2] < x;) v[S * 2] = v[(S - 1) * 2], v[S * 2 + 1] = v[(S - 1) * 2 + 1], S--;
|
|
205
|
+
v[S * 2] = x, v[S * 2 + 1] = n * 2 + r;
|
|
206
|
+
}
|
|
207
|
+
for (let n = 0; n < N; n++) {
|
|
208
|
+
let r = v[n * 2 + 1];
|
|
209
|
+
g[y++] = i - 1, g[y++] = 2 * t + (r & 1), g[y++] = 2 * e + (r >> 1);
|
|
210
|
+
}
|
|
211
|
+
}
|
|
212
|
+
return null;
|
|
213
|
+
}
|
|
214
|
+
patch(e, t, n, r, i, a, o, s, c, l) {
|
|
215
|
+
let u = this.columns, d = this.heights, f = this.scale, p = this.offset, m = d[t * u + e] * f + p, h = d[t * u + e + 1] * f + p, g = d[(t + 1) * u + e] * f + p, _ = d[(t + 1) * u + e + 1] * f + p, v = (n + a * c - (this.ox + e * this.dx)) / this.dx, y = (i + s * c - (this.oz + t * this.dz)) / this.dz, b = a / this.dx, x = s / this.dz, S = h - m, C = g - m, w = m - h - g + _, T = -w * b * x, E = o - (S * b + C * x + w * (v * x + y * b)), D = r + o * c - (m + S * v + C * y + w * v * y), O = l - c, k = 1e-9 * Math.max(1, O);
|
|
216
|
+
if (Math.abs(D) <= 1e-12 * Math.max(1, Math.abs(m), Math.abs(r))) return c;
|
|
217
|
+
let A;
|
|
218
|
+
if (T === 0 || Math.abs(T) * O <= 1e-12 * Math.abs(E)) E !== 0 && (A = -D / E);
|
|
219
|
+
else {
|
|
220
|
+
let e = E * E - 4 * T * D;
|
|
221
|
+
if (e < 0) return;
|
|
222
|
+
let t = -.5 * (E + (E >= 0 ? 1 : -1) * Math.sqrt(e)), n = t / T, r = t === 0 ? n : D / t, i = Math.min(n, r), a = Math.max(n, r);
|
|
223
|
+
A = i >= -k ? i : a;
|
|
224
|
+
}
|
|
225
|
+
if (!(A === void 0 || A < -k || A > O + k)) return c + Math.min(Math.max(A, 0), O);
|
|
226
|
+
}
|
|
227
|
+
hole(e, t) {
|
|
228
|
+
let n = this.holes;
|
|
229
|
+
if (!n) return !1;
|
|
230
|
+
let r = Math.min(Math.max(Math.floor((e - this.ox) / this.sx * n.columns), 0), n.columns - 1), i = Math.min(Math.max(Math.floor((t - this.oz) / this.sz * n.rows), 0), n.rows - 1);
|
|
231
|
+
return n.mask[i * n.columns + r] < 128;
|
|
232
|
+
}
|
|
233
|
+
sample(e, t) {
|
|
234
|
+
let n = this.columns, r = Math.min(Math.max((e - this.ox) / this.sx, 0), 1) * (n - 1), i = Math.min(Math.max((t - this.oz) / this.sz, 0), 1) * (this.rows - 1), a = Math.floor(r), o = Math.floor(i), s = Math.min(a + 1, n - 1), c = Math.min(o + 1, this.rows - 1), l = r - a, u = i - o, d = this.heights, f = d[o * n + a] + (d[o * n + s] - d[o * n + a]) * l;
|
|
235
|
+
return (f + (d[c * n + a] + (d[c * n + s] - d[c * n + a]) * l - f) * u) * this.scale + this.offset;
|
|
236
|
+
}
|
|
237
|
+
};
|
|
238
|
+
function a(e) {
|
|
239
|
+
let t = e >> 10 & 31, n = e & 1023, r = e & 32768 ? -1 : 1;
|
|
240
|
+
return t === 0 ? r * n * 2 ** -24 : t === 31 ? n ? NaN : r * Infinity : r * (1 + n / 1024) * 2 ** (t - 15);
|
|
241
|
+
}
|
|
242
|
+
//#endregion
|
|
243
|
+
export { i as TerrainQuery };
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
/// <reference lib="esnext.disposable" preserve="true" />
|
|
2
|
+
import type { EngineKernel } from '@margoengine/core';
|
|
3
|
+
import { type Engine, type EnginePlugin } from '@margoengine/core/extension';
|
|
4
|
+
import type { Terrain, TerrainLighting } from './index.js';
|
|
5
|
+
/** World-space controls for directional shadows and the projected sky-view factor of a heightfield. */
|
|
6
|
+
export interface TerrainReliefLightingOptions {
|
|
7
|
+
/** Direction toward the light (Y up). Default [-0.6, 0.45, -0.65], or the engine light for the terrain plugin. */
|
|
8
|
+
direction?: readonly [number, number, number];
|
|
9
|
+
/** Horizontal search radius in world units. Default a quarter of the shorter side. */
|
|
10
|
+
radius?: number;
|
|
11
|
+
/** Sky-view azimuth samples, 4 to 32. Default 12. */
|
|
12
|
+
rays?: number;
|
|
13
|
+
/** Maximum samples on a ray, 8 to 256. Default 48. */
|
|
14
|
+
steps?: number;
|
|
15
|
+
/** Angular half-width of the sun's soft horizon, in degrees, above zero and up to 10. Default 0.75. */
|
|
16
|
+
softness?: number;
|
|
17
|
+
/** World units per input texel value, finite. Default 1 or the Terrain's height scale. */
|
|
18
|
+
heightScale?: number;
|
|
19
|
+
}
|
|
20
|
+
/**
|
|
21
|
+
* Enqueues a WebGPU terrain lighting bake from an existing sampled height texture.
|
|
22
|
+
* R is direct-light visibility, G is projected diffuse sky visibility. Both are 0–1, with texels at the original
|
|
23
|
+
* height sample positions. The caller owns the returned rgba16float texture and must destroy it when finished.
|
|
24
|
+
*/
|
|
25
|
+
export declare function bakeTerrainReliefLighting(device: GPUDevice, heightmap: GPUTexture, size: readonly [number, number], options?: TerrainReliefLightingOptions): GPUTexture;
|
|
26
|
+
/** WGSL for sampling the bake at a corner-aligned heightfield uv, with one bilinear fetch. */
|
|
27
|
+
export declare const terrainReliefLightingWGSL = "\n\nfn terrainReliefUv(uv:vec2f,size:vec2f)->vec2f{\n return (clamp(uv,vec2f(0),vec2f(1))*(size-1.0)+0.5)/size;\n}\nfn terrainReliefLight(map:texture_2d<f32>, mapSampler:sampler, uv:vec2f)->vec2f{\n let uvMap=terrainReliefUv(uv,vec2f(textureDimensions(map)));\n return textureSampleLevel(map,mapSampler,uvMap,0.0).rg;\n}";
|
|
28
|
+
/** Adds geometric sun and sky shading to a clipmap Terrain, including terrain outside the camera view. */
|
|
29
|
+
export declare class TerrainReliefLighting implements EnginePlugin, TerrainLighting, Disposable {
|
|
30
|
+
#private;
|
|
31
|
+
private readonly terrain;
|
|
32
|
+
readonly name: string;
|
|
33
|
+
owner?: Engine;
|
|
34
|
+
disposed: boolean;
|
|
35
|
+
constructor(terrain: Terrain, options?: TerrainReliefLightingOptions);
|
|
36
|
+
/** Attach after Terrain and before disposal of its heightmap. Works with layer and local relief materials. */
|
|
37
|
+
static attach(engine: EngineKernel, terrain: Terrain, options?: TerrainReliefLightingOptions): TerrainReliefLighting;
|
|
38
|
+
setup(engine: Engine): void;
|
|
39
|
+
/** Rebuild after height edits or a sun change. Options are merged with the last successful settings. */
|
|
40
|
+
rebake(options?: TerrainReliefLightingOptions): void;
|
|
41
|
+
shader(source: string, group: number): string;
|
|
42
|
+
bindings(): GPUBindGroupEntry[];
|
|
43
|
+
onDeviceRestored(engine: Engine): void;
|
|
44
|
+
dispose(): void;
|
|
45
|
+
[Symbol.dispose](): void;
|
|
46
|
+
}
|
|
@@ -0,0 +1,208 @@
|
|
|
1
|
+
// @margo/core-built 0.1.0
|
|
2
|
+
import {coreRequirement as __margoCoreRequirement,assertCore as __margoAssertCore} from '@margoengine/core/extension';
|
|
3
|
+
const e=(engine,version="0.1.0",source=import.meta.url)=>__margoRuntime(engine,version,source);
|
|
4
|
+
import { engineRuntime as __margoRuntime } from "@margoengine/core/extension";
|
|
5
|
+
import { MargoError as t } from "@margoengine/math/errors";
|
|
6
|
+
//#region src/relief-lighting.ts
|
|
7
|
+
var n = 4, r = 64, i = 120, a = 121, o = /* @__PURE__ */ new Set([
|
|
8
|
+
"r32float",
|
|
9
|
+
"rgba16float",
|
|
10
|
+
"rgba8unorm"
|
|
11
|
+
]);
|
|
12
|
+
function s(e, t, r) {
|
|
13
|
+
if (!e || e.dimension !== "2d" || e.depthOrArrayLayers !== 1 || e.sampleCount !== 1 || e.width < 2 || e.height < 2 || !(e.usage & n) || !o.has(e.format)) throw TypeError("Terrain relief needs a sampled r32float, rgba16float or rgba8unorm 2D heightmap at least 2×2.");
|
|
14
|
+
let i = (e) => Number.isFinite(Math.fround(e)) && Math.fround(e) > 0;
|
|
15
|
+
if (t.length !== 2 || !t.every(i)) throw RangeError("Terrain relief size needs two positive finite world lengths.");
|
|
16
|
+
let a = r.direction ?? [
|
|
17
|
+
-.6,
|
|
18
|
+
.45,
|
|
19
|
+
-.65
|
|
20
|
+
], s = Math.hypot(...a), c = r.radius ?? Math.min(...t) / 4, l = r.rays ?? 12, u = r.steps ?? 48, d = r.softness ?? .75, f = r.heightScale ?? 1;
|
|
21
|
+
if (a.length !== 3 || !i(s) || !i(c) || !Number.isInteger(l) || l < 4 || l > 32 || !Number.isInteger(u) || u < 8 || u > 256 || !i(d) || d > 10 || !Number.isFinite(Math.fround(f))) throw RangeError("Terrain relief needs a nonzero direction, positive radius, 4–32 rays, 8–256 steps, softness in (0, 10] degrees and a finite heightScale.");
|
|
22
|
+
return new Float32Array([
|
|
23
|
+
...t,
|
|
24
|
+
c,
|
|
25
|
+
f,
|
|
26
|
+
a[0] / s,
|
|
27
|
+
a[1] / s,
|
|
28
|
+
a[2] / s,
|
|
29
|
+
d * Math.PI / 180,
|
|
30
|
+
l,
|
|
31
|
+
u,
|
|
32
|
+
0,
|
|
33
|
+
0
|
|
34
|
+
]);
|
|
35
|
+
}
|
|
36
|
+
var c = "\nstruct ReliefBake { map:vec4f, light:vec4f, limits:vec4f }\n@group(0) @binding(0) var reliefHeight:texture_2d<f32>;\n@group(0) @binding(1) var reliefOut:texture_storage_2d<rgba16float,write>;\n@group(0) @binding(2) var<uniform> bake:ReliefBake;\nfn heightAt(p:vec2f, edge:vec2i)->f32 {\n let lo=vec2i(floor(p));let hi=min(lo+1,edge);let w=fract(p);\n let a=textureLoad(reliefHeight,lo,0).r;\n let b=textureLoad(reliefHeight,vec2i(hi.x,lo.y),0).r;\n let c=textureLoad(reliefHeight,vec2i(lo.x,hi.y),0).r;\n let d=textureLoad(reliefHeight,hi,0).r;\n return mix(mix(a,b,w.x),mix(c,d,w.x),w.y);\n}\nfn horizon(p:vec2f, direction:vec2f, edge:vec2i, spacing:vec2f, originHeight:f32)->f32 {\n let motion=direction/spacing;\n let stride=1.0/max(abs(motion.x),abs(motion.y));\n let count=u32(bake.limits.y);\n let fine=min(1.0,bake.map.z/(f32(count)*stride))*stride;\n let tail=max(0.0,bake.map.z-f32(count)*fine);\n var slope=0.0;\n for(var k=1u;k<=count;k++){\n let f=f32(k)/f32(count);\n let distance=f32(k)*fine+tail*f*f;\n let sample=p+distance*motion;\n if(any(sample<vec2f(0.0))||any(sample>vec2f(edge))){break;}\n let rise=(heightAt(sample,edge)-originHeight)*bake.map.w;\n slope=max(slope,rise/distance);\n }\n return slope;\n}\n@compute @workgroup_size(8,8)\nfn main(@builtin(global_invocation_id) id:vec3u){\n let size=textureDimensions(reliefHeight);\n if(any(id.xy>=size)){return;}\n let ij=vec2i(id.xy);\n let p=vec2f(ij);let edge=vec2i(size)-1;\n let spacing=bake.map.xy/vec2f(edge);\n let start=textureLoad(reliefHeight,ij,0).r;\n let rays=u32(bake.limits.x);\n var sky=0.0;\n for(var i=0u;i<rays;i++){\n let azimuth=6.28318530718*f32(i)/f32(rays);\n let h=horizon(p,vec2f(cos(azimuth),sin(azimuth)),edge,spacing,start);\n sky+=1.0/(1.0+h*h);\n }\n let sun=bake.light.xyz;\n let run=length(sun.xz);let elevation=atan2(sun.y,run);\n var lip=0.0;\n if(run>0.000001&&elevation> -bake.light.w){\n lip=atan(horizon(p,sun.xz/run,edge,spacing,start));\n }\n let direct=smoothstep(lip-bake.light.w,lip+bake.light.w,elevation);\n textureStore(reliefOut,ij,vec4f(direct,sky/f32(rays),0.0,1.0));\n}", l = /* @__PURE__ */ new WeakMap(), u = /* @__PURE__ */ new WeakMap();
|
|
37
|
+
function d(e, t, n, i = {}) {
|
|
38
|
+
let a = s(t, n, i), o = u.get(e), d = l.get(e);
|
|
39
|
+
(!o || !d) && (d = e.createBindGroupLayout({ entries: [
|
|
40
|
+
{
|
|
41
|
+
binding: 0,
|
|
42
|
+
visibility: 4,
|
|
43
|
+
texture: { sampleType: "unfilterable-float" }
|
|
44
|
+
},
|
|
45
|
+
{
|
|
46
|
+
binding: 1,
|
|
47
|
+
visibility: 4,
|
|
48
|
+
storageTexture: {
|
|
49
|
+
format: "rgba16float",
|
|
50
|
+
access: "write-only"
|
|
51
|
+
}
|
|
52
|
+
},
|
|
53
|
+
{
|
|
54
|
+
binding: 2,
|
|
55
|
+
visibility: 4,
|
|
56
|
+
buffer: { type: "uniform" }
|
|
57
|
+
}
|
|
58
|
+
] }), o = e.createComputePipeline({
|
|
59
|
+
layout: e.createPipelineLayout({ bindGroupLayouts: [d] }),
|
|
60
|
+
compute: {
|
|
61
|
+
module: e.createShaderModule({ code: c }),
|
|
62
|
+
entryPoint: "main"
|
|
63
|
+
}
|
|
64
|
+
}), l.set(e, d), u.set(e, o));
|
|
65
|
+
let f = e.createTexture({
|
|
66
|
+
label: "Terrain relief light",
|
|
67
|
+
size: [t.width, t.height],
|
|
68
|
+
format: "rgba16float",
|
|
69
|
+
usage: 13
|
|
70
|
+
}), p = e.createBuffer({
|
|
71
|
+
size: a.byteLength,
|
|
72
|
+
usage: r,
|
|
73
|
+
mappedAtCreation: !0
|
|
74
|
+
});
|
|
75
|
+
try {
|
|
76
|
+
new Float32Array(p.getMappedRange()).set(a), p.unmap();
|
|
77
|
+
let n = e.createBindGroup({
|
|
78
|
+
layout: d,
|
|
79
|
+
entries: [
|
|
80
|
+
{
|
|
81
|
+
binding: 0,
|
|
82
|
+
resource: t.createView({
|
|
83
|
+
dimension: "2d",
|
|
84
|
+
baseMipLevel: 0,
|
|
85
|
+
mipLevelCount: 1
|
|
86
|
+
})
|
|
87
|
+
},
|
|
88
|
+
{
|
|
89
|
+
binding: 1,
|
|
90
|
+
resource: f.createView()
|
|
91
|
+
},
|
|
92
|
+
{
|
|
93
|
+
binding: 2,
|
|
94
|
+
resource: { buffer: p }
|
|
95
|
+
}
|
|
96
|
+
]
|
|
97
|
+
}), r = e.createCommandEncoder(), i = r.beginComputePass();
|
|
98
|
+
i.setPipeline(o), i.setBindGroup(0, n), i.dispatchWorkgroups(Math.ceil(t.width / 8), Math.ceil(t.height / 8)), i.end(), e.queue.submit([r.finish()]);
|
|
99
|
+
} catch (e) {
|
|
100
|
+
throw f.destroy(), p.destroy(), e;
|
|
101
|
+
}
|
|
102
|
+
let m = () => p.destroy();
|
|
103
|
+
return e.queue.onSubmittedWorkDone().then(m, m), f;
|
|
104
|
+
}
|
|
105
|
+
var f = "\nfn terrainReliefUv(uv:vec2f,size:vec2f)->vec2f{\n return (clamp(uv,vec2f(0),vec2f(1))*(size-1.0)+0.5)/size;\n}", p = `
|
|
106
|
+
${f}
|
|
107
|
+
fn terrainReliefLight(map:texture_2d<f32>, mapSampler:sampler, uv:vec2f)->vec2f{
|
|
108
|
+
let uvMap=terrainReliefUv(uv,vec2f(textureDimensions(map)));
|
|
109
|
+
return textureSampleLevel(map,mapSampler,uvMap,0.0).rg;
|
|
110
|
+
}`, m = 0, h = class n {coreRequirement=__margoCoreRequirement("0.1.0",import.meta.url);
|
|
111
|
+
#e;
|
|
112
|
+
#t;
|
|
113
|
+
#n;
|
|
114
|
+
#r;
|
|
115
|
+
#i;
|
|
116
|
+
#a;
|
|
117
|
+
constructor(e, t = {}) {
|
|
118
|
+
if (this.terrain = e, this.name = "terrain-relief-lighting:" + m++, this.disposed = !1, this.#i = [], this.#a = /* @__PURE__ */ new Map(), !e || typeof e.addLighting != "function") throw TypeError("Terrain relief lighting needs a live clipmap Terrain.");
|
|
119
|
+
this.#n = this.#o(t);
|
|
120
|
+
}
|
|
121
|
+
static attach(t, r, i = {}) {__margoAssertCore(t,__margoCoreRequirement("0.1.0",import.meta.url));
|
|
122
|
+
let a = new n(r, i);
|
|
123
|
+
return e(t).use(a), a;
|
|
124
|
+
}
|
|
125
|
+
setup(e) {
|
|
126
|
+
if (this.disposed || !e.gpu) throw new t(this.disposed ? "disposed" : "unsupported", "Terrain relief lighting needs a live WebGPU engine.");
|
|
127
|
+
let n = e.gpu.createSampler({
|
|
128
|
+
minFilter: "linear",
|
|
129
|
+
magFilter: "linear"
|
|
130
|
+
}), r = this.#s(e, this.#n);
|
|
131
|
+
try {
|
|
132
|
+
this.owner = e, this.#r ??= this.terrain.addLighting(this);
|
|
133
|
+
} catch (e) {
|
|
134
|
+
throw this.owner = void 0, r.destroy(), e;
|
|
135
|
+
}
|
|
136
|
+
this.#t = n, this.#c(r);
|
|
137
|
+
}
|
|
138
|
+
#o(e) {
|
|
139
|
+
return {
|
|
140
|
+
...e,
|
|
141
|
+
direction: e.direction ? [...e.direction] : void 0
|
|
142
|
+
};
|
|
143
|
+
}
|
|
144
|
+
#s(e, n) {
|
|
145
|
+
if (!this.terrain.heightmap) throw new t("state", "Attach the clipmap Terrain before its relief lighting.");
|
|
146
|
+
let { direction: r } = e.lighting;
|
|
147
|
+
return d(e.gpu, this.terrain.heightmap, this.terrain.options.size, {
|
|
148
|
+
...n,
|
|
149
|
+
direction: n.direction ?? [
|
|
150
|
+
r[0],
|
|
151
|
+
r[1],
|
|
152
|
+
r[2]
|
|
153
|
+
],
|
|
154
|
+
heightScale: n.heightScale ?? this.terrain.options.heightScale ?? 100
|
|
155
|
+
});
|
|
156
|
+
}
|
|
157
|
+
#c(e) {
|
|
158
|
+
let t = this.#e;
|
|
159
|
+
if (this.#e = e, this.#i = [{
|
|
160
|
+
binding: i,
|
|
161
|
+
resource: e.createView()
|
|
162
|
+
}, {
|
|
163
|
+
binding: a,
|
|
164
|
+
resource: this.#t
|
|
165
|
+
}], t) {
|
|
166
|
+
let e = () => t.destroy();
|
|
167
|
+
this.owner.gpu.queue.onSubmittedWorkDone().then(e, e);
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
rebake(e = {}) {
|
|
171
|
+
if (this.disposed || !this.owner) throw new t(this.disposed ? "disposed" : "state", "Attach live Terrain relief lighting before rebaking.");
|
|
172
|
+
let n = this.#o({
|
|
173
|
+
...this.#n,
|
|
174
|
+
...e
|
|
175
|
+
});
|
|
176
|
+
this.#c(this.#s(this.owner, n)), this.#n = n;
|
|
177
|
+
}
|
|
178
|
+
shader(e, n) {
|
|
179
|
+
let r = n + e, o = this.#a.get(r);
|
|
180
|
+
if (o) return o;
|
|
181
|
+
let s = /let direct=[^;]+;/g, c = "+base*frame.radiance.w";
|
|
182
|
+
if ([...e.matchAll(s)].length !== 1 || e.split(c).length !== 2) throw new t("unsupported", "Terrain relief lighting needs the terrain lit shader and its sun and sky terms.");
|
|
183
|
+
let l = `
|
|
184
|
+
@group(${n}) @binding(${i}) var terrainReliefMap:texture_2d<f32>;
|
|
185
|
+
@group(${n}) @binding(${a}) var terrainReliefSampler:sampler;
|
|
186
|
+
${f}
|
|
187
|
+
fn terrainReliefApplied(uv:vec2f)->vec2f{
|
|
188
|
+
let uvMap=terrainReliefUv(uv,vec2f(textureDimensions(terrainReliefMap)));
|
|
189
|
+
return textureSampleLevel(terrainReliefMap,terrainReliefSampler,uvMap,0.0).rg;
|
|
190
|
+
}
|
|
191
|
+
` + e.replace(s, (e) => "let terrainLight=terrainReliefApplied((i.position.xz-frame.map.xy)/frame.map.zw);" + e.slice(0, -1) + "*terrainLight.x;").replace(c, c + "*terrainLight.y");
|
|
192
|
+
return this.#a.size >= 16 && this.#a.clear(), this.#a.set(r, l), l;
|
|
193
|
+
}
|
|
194
|
+
bindings() {
|
|
195
|
+
return this.#i;
|
|
196
|
+
}
|
|
197
|
+
onDeviceRestored(e) {
|
|
198
|
+
this.#e?.destroy(), this.#e = void 0, this.setup(e);
|
|
199
|
+
}
|
|
200
|
+
dispose() {
|
|
201
|
+
this.disposed || (this.disposed = !0, this.#r?.(), this.#r = void 0, this.owner?.sceneOf(this)?.removePlugin(this.name), this.#e?.destroy(), this.#e = void 0, this.#t = void 0, this.#i = [], this.#a.clear(), this.owner = void 0);
|
|
202
|
+
}
|
|
203
|
+
[Symbol.dispose]() {
|
|
204
|
+
this.dispose();
|
|
205
|
+
}
|
|
206
|
+
};
|
|
207
|
+
//#endregion
|
|
208
|
+
export { h as TerrainReliefLighting, d as bakeTerrainReliefLighting, p as terrainReliefLightingWGSL };
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import { MargoError as e } from "@margoengine/math/errors";
|
|
2
|
+
//#region ../shared/require-webgpu.js
|
|
3
|
+
function t(t, n) {
|
|
4
|
+
if (t.backend === "webgl2" || !t.gpu) throw new e("unsupported", `${n} needs WebGPU; see https://margoengine.com/errors#webgpu`);
|
|
5
|
+
}
|
|
6
|
+
//#endregion
|
|
7
|
+
export { t };
|