@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.
Files changed (71) hide show
  1. package/LICENSE +201 -0
  2. package/NOTICE +4 -0
  3. package/README.md +1808 -3
  4. package/dist/blend.d.ts +70 -0
  5. package/dist/blend.js +159 -0
  6. package/dist/colors.d.ts +164 -0
  7. package/dist/deform.d.ts +103 -0
  8. package/dist/deform.js +322 -0
  9. package/dist/displace.d.ts +60 -0
  10. package/dist/displace.js +254 -0
  11. package/dist/dunes.d.ts +86 -0
  12. package/dist/dunes.js +88 -0
  13. package/dist/errors-fc4i1pSL.js +7 -0
  14. package/dist/grid.d.ts +11 -0
  15. package/dist/ground-change-settings.d.ts +29 -0
  16. package/dist/ground-change-settings.js +69 -0
  17. package/dist/ground-change.d.ts +227 -0
  18. package/dist/ground-change.js +1291 -0
  19. package/dist/ground-model.d.ts +290 -0
  20. package/dist/hdr-format-DRhzGS7G.js +30 -0
  21. package/dist/height-grid.d.ts +65 -0
  22. package/dist/height-grid.js +74 -0
  23. package/dist/heightfield.d.ts +38 -0
  24. package/dist/holes.d.ts +37 -0
  25. package/dist/holes.js +97 -0
  26. package/dist/imagery.d.ts +109 -0
  27. package/dist/imagery.js +472 -0
  28. package/dist/index.d.ts +297 -0
  29. package/dist/index.js +1 -0
  30. package/dist/layers-pbr.d.ts +78 -0
  31. package/dist/layers-pbr.js +128 -0
  32. package/dist/lighting-layout-CaDtDa5G.js +34 -0
  33. package/dist/lighting-layout.d.ts +5 -0
  34. package/dist/mesh-patch-BThCHCeS.js +21 -0
  35. package/dist/mesh-patch.d.ts +14 -0
  36. package/dist/noise3-sQdnbz4B.js +11 -0
  37. package/dist/noise3.d.ts +3 -0
  38. package/dist/overlays.d.ts +74 -0
  39. package/dist/overlays.js +297 -0
  40. package/dist/planet-craters.d.ts +55 -0
  41. package/dist/planet-recipes.d.ts +75 -0
  42. package/dist/planet-recipes.js +216 -0
  43. package/dist/planet.d.ts +139 -0
  44. package/dist/planet.js +602 -0
  45. package/dist/query.d.ts +150 -0
  46. package/dist/query.js +243 -0
  47. package/dist/relief-lighting.d.ts +46 -0
  48. package/dist/relief-lighting.js +208 -0
  49. package/dist/require-webgpu--tUXPsmA.js +7 -0
  50. package/dist/rock-settings.d.ts +39 -0
  51. package/dist/rock-settings.js +84 -0
  52. package/dist/rock-surface.d.ts +111 -0
  53. package/dist/rock-surface.js +368 -0
  54. package/dist/rocks.d.ts +258 -0
  55. package/dist/rocks.js +488 -0
  56. package/dist/rvt.d.ts +136 -0
  57. package/dist/rvt.js +518 -0
  58. package/dist/sculpt.d.ts +103 -0
  59. package/dist/sculpt.js +361 -0
  60. package/dist/settings-B9BSdnhD.js +72 -0
  61. package/dist/settings.d.ts +81 -0
  62. package/dist/settings.js +152 -0
  63. package/dist/shader.d.ts +61 -0
  64. package/dist/shared/settings.d.ts +89 -0
  65. package/dist/src-C6dtSaAb.js +1155 -0
  66. package/dist/stream.d.ts +100 -0
  67. package/dist/stream.js +339 -0
  68. package/dist/surface-height.d.ts +16 -0
  69. package/dist/wet-ground.d.ts +82 -0
  70. package/dist/wet-ground.js +147 -0
  71. package/package.json +148 -6
@@ -0,0 +1,297 @@
1
+ /// <reference lib="esnext.disposable" preserve="true" />
2
+ import type { EngineKernel } from '@margoengine/core';
3
+ import { type Engine, type EnginePlugin, type FrameGraph, type PassContext } from '@margoengine/core/extension';
4
+ export { clipmapGrid } from './grid.js';
5
+ export { TerrainColors, wetSandAfter, type SandSurface, type TerrainColorOptions, type TerrainLook, type TerrainLookUpdate, } from './colors.js';
6
+ export { heightfield, heightfieldGeometry, TerrainHeightmap, type HeightField, type HeightfieldOptions, } from './heightfield.js';
7
+ type TerrainPassContext = Extract<PassContext, {
8
+ backend: 'webgpu';
9
+ }>;
10
+ /** The textures `TerrainOptions.textures` returns; Terrain owns and destroys them. All sampled, single-sample 2D. */
11
+ export interface TerrainTextures {
12
+ /** Heights in the R channel: `r32float`, `rgba16float` or `rgba8unorm`, one layer. */
13
+ heightmap: GPUTexture;
14
+ /** Optional XYZ normals encoded 0..1: `rgba8unorm` or `rgba16float`. Default: from neighbouring heights. */
15
+ normalmap?: GPUTexture;
16
+ /** Layer colours, one array layer per `TerrainLayer`: `rgba8unorm-srgb`, `rgba8unorm` or `rgba16float`. */
17
+ layers: GPUTexture;
18
+ /**
19
+ * Optional painted layer weights over the heightmap's bounds, 2 to 4 `rgba8unorm` 2D textures, enough for the layers
20
+ * (4 per texture, up to 16): layer i's weight is channel i % 4 of texture i / 4 (pass the same texture twice for 4
21
+ * layers). When present they replace the height and slope rules (each rule's `scale` still sets its texture repeat),
22
+ * as `@margoengine/biomes/view` uses for biome ground layers; a layer whose weight is 0 at a pixel skips its texture
23
+ * samples there. Without them the terrain shader and bindings are unchanged. Default: none.
24
+ */
25
+ weights?: readonly GPUTexture[];
26
+ /**
27
+ * Optional tint over the heightmap's bounds, with `weights` only: one `rgba8unorm` or `rgba8unorm-srgb` 2D texture of
28
+ * any size, sampled bilinearly. Each layer with `tint: true` has its colour mixed toward the texel's RGB by its A:
29
+ * `mix(layer, tint.rgb, tint.a)`, in linear light (an `-srgb` texture holds sRGB colours). Layers without `tint` are
30
+ * drawn as they are. `@margoengine/biomes/view` draws seasons through it. Without it the shader and bindings are
31
+ * unchanged. Default: none.
32
+ */
33
+ tint?: GPUTexture;
34
+ /**
35
+ * Optional holes over the heightmap's bounds: one `r8unorm` or `rgba8unorm` 2D texture of any size, a texel per
36
+ * cell (texel (u, v) covers cell (u, v) of the bounds split into its width by height); where its R is below 0.5 the
37
+ * terrain draws nothing, in its colour, SSR capture, shadow and occluder passes alike. `TerrainHoles`
38
+ * (`@margoengine/terrain/holes`) makes and edits one. Without it the shaders and bindings are unchanged. Default: none.
39
+ */
40
+ holes?: GPUTexture;
41
+ }
42
+ /** A splat rule: where layer i's texture shows. Rules blend smoothly around their bounds; layer 0 is the fallback. */
43
+ export interface TerrainLayer {
44
+ /** World Y range [min, max), min < max. */
45
+ height: readonly [number, number];
46
+ /** Slope range (1 - normal.y), 0 <= min < max <= 1. */
47
+ slope: readonly [number, number];
48
+ /** Texture repeats per world unit, > 0. */
49
+ scale: number;
50
+ /**
51
+ * Relief from the layer's own texture, 0 to 1: its luma becomes a height of up to `bump` halves of one texture repeat
52
+ * (2 m at scale 0.25), and the shading normal follows that height's slope (derivative bump mapping, Mikkelsen 2010).
53
+ * No extra texture samples; the mips flatten it with distance, and its slope falls once a pixel covers over 1/64 of a
54
+ * repeat on the ground. Default 0 (no bump).
55
+ */
56
+ bump?: number;
57
+ /**
58
+ * Large-scale variation, 0 to 1: the same layer at 1/24 of `scale` (96 m at 0.25) scales the colour by
59
+ * `1 - macro + macro * luma / meanLuma`, so far slopes keep a pattern where the fine texture has averaged to its mean.
60
+ * A smooth sample about 318 m wide picks that repeat's offset, so it draws no grid. The mean comes from the layer's
61
+ * top mip: give the layers texture a full mip chain.
62
+ * Default 0 (no macro sample).
63
+ */
64
+ macro?: number;
65
+ /** Whether the layer takes `TerrainTextures.tint` (plant cover, not rock). Ignored without a tint. Default false. */
66
+ tint?: boolean;
67
+ }
68
+ /**
69
+ * What `TerrainOptions.floatingOrigin` takes: the float64 world point at local zero and its rebase event. A
70
+ * `FloatingOrigin` from `@margoengine/cameras/origin` fits as is.
71
+ */
72
+ export interface TerrainOrigin {
73
+ /** Float64 world position of local [0, 0, 0]. */
74
+ readonly origin: ArrayLike<number>;
75
+ /** Calls `listener` after each rebase with the new origin second; returns an unsubscribe. */
76
+ onRebase(listener: (shift: ArrayLike<number>, origin: ArrayLike<number>) => void): () => void;
77
+ }
78
+ /**
79
+ * The ring corners of a clipmap: for each level i, the eye's float64 world XZ snapped down to the level's spacing
80
+ * (`cell * 2^i`), less `shift` (the world point at local zero), as [x0, z0, x1, z1, ...]. Snapping the world point keeps
81
+ * the lattice, and so the vertices and the LOD, the same wherever the origin sits; only the small local result reaches
82
+ * float32. Exported for the tests.
83
+ */
84
+ export declare function planRings(eye: ArrayLike<number>, shift: ArrayLike<number>, cell: number, levels: number, out?: Float64Array<ArrayBuffer>): Float64Array;
85
+ /** Clipmap terrain settings, fixed at construction. Invalid values throw RangeError. */
86
+ export interface TerrainOptions {
87
+ /** Creates the textures, at attach and again after device restoration (recreate them from retained data). */
88
+ textures: (device: GPUDevice) => TerrainTextures;
89
+ /** 4 to 16 splat rules, one per `layers` texture layer. */
90
+ layers: readonly TerrainLayer[];
91
+ /** World XZ of the heightmap's minimum corner. Default [0, 0]. */
92
+ origin?: readonly [number, number];
93
+ /** World XZ extent the heightmap covers, each > 0. */
94
+ size: readonly [number, number];
95
+ /** World Y per height sample unit. Default 100. */
96
+ heightScale?: number;
97
+ /** World Y added to every height. Default 0. */
98
+ heightOffset?: number;
99
+ /** Finest grid spacing in world units, > 0; doubles per level. Default 1. */
100
+ cellSize?: number;
101
+ /** Cells per ring side, a multiple of 4 from 8 to 256. Default 64. */
102
+ resolution?: number;
103
+ /** Clipmap rings, 1-12. Default 6. */
104
+ levels?: number;
105
+ /** World XZ centre for the rings. Defaults to the main camera's initial world XZ and stays fixed. Use `'camera'`
106
+ * for an unbounded route that needs to select a moving window on the world lattice. */
107
+ readonly clipmapAnchor?: readonly [number, number] | 'camera';
108
+ /** Rasterize the drawn clipmap heights before vegetation placement. Default false. */
109
+ readonly captureSurfaceHeight?: boolean;
110
+ /** Surface roughness (GGX, 0-1), for the sun's highlight and screen-space reflections (`ssr.add(terrain)`). Default
111
+ * 0.9; leaving it out keeps the shader as it was. */
112
+ roughness?: number;
113
+ /**
114
+ * A floating origin (`FloatingOrigin` from `@margoengine/cameras/origin`) for terrain far from world zero: the camera
115
+ * is local to it and the terrain plans its rings, layer texture phases and cache windows in float64 world space, then
116
+ * sends the GPU only small local numbers. A terrain 10,000 km out then draws the same vertices, levels and texels as
117
+ * at zero, and a rebase moves nothing on screen. `origin`, `size` and every CPU call (`TerrainQuery`, holes, decals,
118
+ * overlays, sculpt) stay in world coordinates. Default: none (the shaders, uniforms and rules stay as they were).
119
+ */
120
+ floatingOrigin?: TerrainOrigin;
121
+ }
122
+ /** What `setCapture` takes: `@margoengine/post` SSR's material capture hook (its `SSRCapture`), declared here so terrain
123
+ * does not import post. */
124
+ export interface TerrainCapture {
125
+ /** Module-scope WGSL for the lit shader `code`: `struct MargoSSR` and `fn margoSSR(n,v,base,metal,rough)->MargoSSR`. */
126
+ declarations(code: string): string;
127
+ /** Colour targets of the capture pass, in `MargoSSR` location order. */
128
+ readonly targets: readonly GPUColorTargetState[];
129
+ /** This frame's capture pass: these targets and a depth attachment of the context's format; ended by the owner. */
130
+ begin(): GPURenderPassEncoder;
131
+ }
132
+ /**
133
+ * A lighting effect patched into the terrain shader, such as shadows or clustered lights (`terrain.addLighting`).
134
+ * Its bindings live in group 1.
135
+ */
136
+ export interface TerrainLighting {
137
+ /** The engine the effect belongs to; a different engine is rejected. */
138
+ readonly owner?: Engine;
139
+ /** Returns `source` with the effect's WGSL added, using bind group `group`. */
140
+ shader(source: string, group: number): string;
141
+ /** The group-1 entries the patched shader reads, asked every frame. */
142
+ bindings(): GPUBindGroupEntry[];
143
+ /**
144
+ * Optional: runs on the whole lit shader after every effect's `shader`, in the same order, so an effect can adjust
145
+ * what effects attached after it added (displacement moves their sun shadow lookups). Returns the shader.
146
+ */
147
+ finish?(source: string, group: number): string;
148
+ }
149
+ /**
150
+ * Geometry-clipmap terrain: concentric rings that follow the camera, heights sampled from a texture in the vertex
151
+ * shader, 4 to 16 slope/height texture layers with triplanar cliffs, GGX sun lighting. Works with `Shadows` and
152
+ * `Clustered` (`shadows.add(terrain)`, `clustered.add(terrain)`). `Terrain.attach(engine, options)`; WebGPU only.
153
+ * @throws RangeError from the constructor when an option is out of range.
154
+ * @throws TypeError when the textures have the wrong dimension, format, usage or layer count.
155
+ * @throws MargoError `'unsupported'` on a WebGL engine, `'disposed'` after `dispose()`, `'attached'` when a lighting
156
+ * effect belongs to another engine.
157
+ */
158
+ export declare class Terrain implements EnginePlugin {
159
+ readonly options: TerrainOptions;
160
+ readonly name: string;
161
+ shadowVersion: number;
162
+ disposed: boolean;
163
+ private engine?;
164
+ private device?;
165
+ private textures?;
166
+ private vertex?;
167
+ private center?;
168
+ private ring?;
169
+ private rules?;
170
+ private sampler?;
171
+ private layout?;
172
+ private shadowPipeline?;
173
+ /** Reversed-depth variant of the shadow pipeline for local light maps, built on first use. */
174
+ private localShadowPipeline?;
175
+ private shadowModule?;
176
+ private ringGroup?;
177
+ private occluder?;
178
+ private rings;
179
+ /** The bits each uniform buffer last received, so an unchanged frame uploads nothing. Buffers made anew start empty. */
180
+ private readonly sent;
181
+ private readonly bitViews;
182
+ private pipelines;
183
+ private lightingGroups;
184
+ private lighting;
185
+ /** Bind-group entries for the current draw. Lighting providers may return fresh wrappers; the group cache compares them. */
186
+ private readonly lightingEntries;
187
+ private centerCount;
188
+ private ringCount;
189
+ private capture?;
190
+ private captureCode;
191
+ private readonly disposers;
192
+ /** The float64 world point at local zero (zeros without `floatingOrigin`); `shift` reads it. */
193
+ private readonly shiftValues;
194
+ /** The shift the layer rules were last written with, and the scratch eye and ring plan of `prepare`. */
195
+ private readonly rulesShift;
196
+ private readonly eye;
197
+ private anchoredEye?;
198
+ private capturedSurface?;
199
+ private plan;
200
+ private unfollow?;
201
+ /**
202
+ * With `floatingOrigin`, `options.origin` as it was at construction (a stream moves its array): local + `Frame.anchor`
203
+ * is world XZ less this, the coordinate cache surfaces, overlays and imagery draw in. Undefined without the option.
204
+ */
205
+ readonly anchor?: readonly [number, number];
206
+ constructor(options: TerrainOptions);
207
+ /**
208
+ * The float64 world point at local zero: the floating origin's, or zeros without `floatingOrigin`. Every terrain entry
209
+ * reads it per frame and compares it with the last one to see a rebase. Read only.
210
+ */
211
+ get shift(): ArrayLike<number>;
212
+ /** World heights of the rendered triangles, with the heightmap's UVs. Available after the first captured frame. */
213
+ get surfaceHeightTexture(): GPUTexture | undefined;
214
+ static attach(instance: EngineKernel, options: TerrainOptions): Terrain;
215
+ private validate;
216
+ addLighting(effect: TerrainLighting): () => void;
217
+ invalidate(): void;
218
+ /**
219
+ * The heightmap texture the `textures` factory returned, while attached (undefined before and after disposal; a new
220
+ * one after device restoration). Terrain owns it. `TerrainQuery.read` (`@margoengine/terrain/query`) reads it back.
221
+ */
222
+ get heightmap(): GPUTexture | undefined;
223
+ /** The painted weight textures the factory returned (as given, a texture may repeat), while attached; else undefined. */
224
+ get weights(): readonly GPUTexture[] | undefined;
225
+ /** The holes texture the factory returned, while attached; else undefined. `TerrainHoles.upload` writes into it. */
226
+ get holes(): GPUTexture | undefined;
227
+ setup(engine: Engine): void;
228
+ /**
229
+ * The layer rules: 8 floats a layer; 12 with `bump` or `macro` (surfaceStruct: bump metres per unit of luma, macro,
230
+ * macro scale); with `floatingOrigin` 8 more (originShader: `wrap` and `tone` per axis) and the height bounds less the
231
+ * shift's Y, as positions reach the shader local.
232
+ */
233
+ private ruleData;
234
+ registerPasses(graph: FrameGraph): void;
235
+ private prepare;
236
+ /** The lit shader: terrain's own (with `roughness`, when given) through every lighting effect. */
237
+ private shader;
238
+ /**
239
+ * The terrain's own shader, with its edge and hole tests and no lighting effect, with the bind group layout and the
240
+ * finest ring's group 0 it draws with, while attached: what `@margoengine/terrain/rvt` bakes the ground colour from.
241
+ */
242
+ colorSource(): {
243
+ code: string;
244
+ layout: GPUBindGroupLayout;
245
+ group: GPUBindGroup;
246
+ } | undefined;
247
+ /** The terrain's own shader (with `roughness`, when given) and its edge and hole tests, before any effect. */
248
+ private base;
249
+ /** With `TerrainTextures.holes`: declares the mask after the weights and tint and adds its test to the edge test. */
250
+ private clip;
251
+ /** Whether any layer sets `bump` or `macro`; without, the shader and rules are what they were before both. */
252
+ private surface;
253
+ private drawRings;
254
+ /**
255
+ * Lets a capture hook (`@margoengine/post` SSR: `ssr.add(terrain)`) draw the terrain's material with
256
+ * `draw(c, 'capture', ...)`: its normal, layer colour and roughness through the hook's `margoSSR`, depth tested
257
+ * (greater-equal) and written. Returns a remover. Without a hook the terrain draws exactly as before.
258
+ */
259
+ setCapture(hook: TerrainCapture): () => void;
260
+ /** Calls `callback` once when the terrain is disposed; returns a remover. */
261
+ onDispose(callback: () => void): () => void;
262
+ /** `mode` 'capture': draws the terrain into the capture hook's pass (`setCapture`); `color` and `depth` are unused (the
263
+ * hook's pass has its own). Does nothing without a hook or after disposal. */
264
+ draw(c: TerrainPassContext, mode: 'capture', color?: GPUTextureView, depth?: GPUTextureView): void;
265
+ private lightingGroup;
266
+ /**
267
+ * Draws the terrain's depth with the frame's camera into an occluder pass of @margoengine/culling
268
+ * (`parts.addOccluder(terrain)`): the rings the main pass draws, on the same uniforms.
269
+ */
270
+ drawOccluder({ pass, samples }: {
271
+ pass: GPURenderPassEncoder;
272
+ samples: number;
273
+ }): void;
274
+ drawShadow({ context, pass, matrix, cascade, }: {
275
+ context: TerrainPassContext;
276
+ pass: GPURenderPassEncoder;
277
+ matrix: Float32Array;
278
+ cascade: number;
279
+ }): void;
280
+ /**
281
+ * Casts the terrain into a point, spot, directional or area light's map of clustered `LocalShadows` (pass the
282
+ * terrain to `LocalShadows.add`). Reversed depth (`greater`), one uniform set per ring and layer, made on first use.
283
+ */
284
+ drawLocalShadow({ context, pass, matrix, layer, }: {
285
+ context: TerrainPassContext;
286
+ pass: GPURenderPassEncoder;
287
+ matrix: Float32Array;
288
+ layer: number;
289
+ }): void;
290
+ /** Writes `values` to `buffer` unless the buffer already holds exactly these bits (compared bit for bit, so -0 and NaN count). */
291
+ private upload;
292
+ private release;
293
+ onDeviceRestored(engine: Engine): void;
294
+ dispose(): void;
295
+ [Symbol.dispose]: () => void;
296
+ destroy(): void;
297
+ }
package/dist/index.js ADDED
@@ -0,0 +1 @@
1
+ export { t as Terrain, o as TerrainColors, r as TerrainHeightmap, c as clipmapGrid, i as heightfield, a as heightfieldGeometry, n as planRings, s as wetSandAfter } from "./src-C6dtSaAb.js";
@@ -0,0 +1,78 @@
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
+ /** One layer's material settings, in the order of `TerrainOptions.layers`. Every field has a default. */
6
+ export interface TerrainLayerMaterial {
7
+ /** How strongly the normal map tilts the shading normal, 0 to 2. Default 1 (as authored). */
8
+ normal?: number;
9
+ /** How much of the map's ambient occlusion applies, 0 to 1. Default 1. */
10
+ occlusion?: number;
11
+ /** Multiplies the map's roughness, 0 to 2 (the result is clamped to 0.02 to 1). Default 1. */
12
+ roughness?: number;
13
+ }
14
+ /** The textures `TerrainMaterialOptions.textures` returns; the materials own and destroy them. */
15
+ export interface TerrainMaterialTextures {
16
+ /**
17
+ * Tangent-space normal maps, one array layer per terrain layer, XYZ encoded 0..1 with +Y up (the OpenGL convention,
18
+ * Poly Haven's `nor_gl`): `rgba8unorm` or `rgba16float`, the size of the layers' colour texture.
19
+ */
20
+ normals: GPUTexture;
21
+ /**
22
+ * Surface maps, one array layer per terrain layer: R ambient occlusion, G roughness (glTF's ORM order; Poly Haven's
23
+ * `arm`), B unused, A height 0..1 (Poly Haven's `disp`): `rgba8unorm` or `rgba16float`.
24
+ */
25
+ surface: GPUTexture;
26
+ }
27
+ /** Settings of {@link TerrainMaterials.attach}. Invalid values throw RangeError. */
28
+ export interface TerrainMaterialOptions {
29
+ /** Creates the textures, at attachment and again after device restoration (recreate them from retained data). */
30
+ textures: (device: GPUDevice) => TerrainMaterialTextures;
31
+ /** One entry per terrain layer, or fewer (the rest take the defaults). Default: all defaults. */
32
+ layers?: readonly TerrainLayerMaterial[];
33
+ /**
34
+ * Height blending where layers' weights overlap, 0 to 1: 0 crossfades by weight as the terrain does; 1 lets the
35
+ * higher surface win almost outright (weights scaled by 2^(8 (height - 1))). Default 0.5.
36
+ */
37
+ heightBlend?: number;
38
+ }
39
+ /**
40
+ * Full PBR layer materials for a `Terrain`: per layer normal, ambient occlusion, roughness and height maps, triplanar
41
+ * like the layer colours, with height blending between layers. `TerrainMaterials.attach(engine, terrain, options)`;
42
+ * WebGPU only. Works with painted weights, `bump` and `macro`, shadows and clustered lights (they read its normal and
43
+ * roughness); SSR's capture keeps the terrain's own normal and roughness.
44
+ * @throws RangeError when an option is out of range.
45
+ * @throws TypeError when the textures have the wrong dimension, format, usage or layer count.
46
+ * @throws MargoError `'unsupported'` when the terrain's shader lacks the lines it patches, `'disposed'` after dispose.
47
+ */
48
+ export declare class TerrainMaterials implements EnginePlugin, TerrainLighting {
49
+ private readonly terrain;
50
+ readonly options: TerrainMaterialOptions;
51
+ readonly name: string;
52
+ disposed: boolean;
53
+ owner?: Engine;
54
+ private device?;
55
+ private textures?;
56
+ private rules?;
57
+ private entries;
58
+ private remove?;
59
+ private readonly cache;
60
+ private constructor();
61
+ /** Attaches materials to `terrain`, which must already be attached to `engine`. Returns them; `dispose()` removes them. */
62
+ static attach(engine: EngineKernel, terrain: Terrain, options: TerrainMaterialOptions): TerrainMaterials;
63
+ setup(engine: Engine): void;
64
+ /**
65
+ * The surface maps texture the `textures` factory returned, while attached (undefined before and after disposal; a
66
+ * new one after device restoration). The materials own it. `TerrainDisplacement` (`@margoengine/terrain/displace`)
67
+ * reads its height channel.
68
+ */
69
+ get surface(): GPUTexture | undefined;
70
+ /** The group-1 entries the patched shader reads. */
71
+ bindings(): GPUBindGroupEntry[];
72
+ /** The terrain's lit shader with the layer materials patched in (bindings in `group`). */
73
+ shader(source: string, group: number): string;
74
+ onDeviceRestored(engine: Engine): void;
75
+ private release;
76
+ dispose(): void;
77
+ [Symbol.dispose]: () => void;
78
+ }
@@ -0,0 +1,128 @@
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/layers-pbr.ts
7
+ var n = 90, r = 0, i = class i {coreRequirement=__margoCoreRequirement("0.1.0",import.meta.url);
8
+ constructor(e, t) {
9
+ this.terrain = e, this.options = t, this.name = "terrain-materials:" + r++, this.disposed = !1, this.entries = [], this.cache = /* @__PURE__ */ new Map();
10
+ let n = e?.options?.layers?.length;
11
+ if (!n || typeof t?.textures != "function") throw TypeError("Invalid terrain materials; pass a Terrain and options with a textures factory");
12
+ let i = t.heightBlend ?? .5, a = t.layers ?? [];
13
+ if (!(i >= 0 && i <= 1) || !Array.isArray(a) || a.length > n || !a.every((e) => (e.normal ?? 1) >= 0 && (e.normal ?? 1) <= 2 && (e.occlusion ?? 1) >= 0 && (e.occlusion ?? 1) <= 1 && (e.roughness ?? 1) >= 0 && (e.roughness ?? 1) <= 2)) throw RangeError("Invalid terrain materials; give heightBlend 0..1 and at most one entry per terrain layer with normal 0..2, occlusion 0..1 and roughness 0..2.");
14
+ }
15
+ static attach(t, n, r) {__margoAssertCore(t,__margoCoreRequirement("0.1.0",import.meta.url));
16
+ let a = new i(n, r);
17
+ return e(t).use(a), a;
18
+ }
19
+ setup(e) {
20
+ if (this.disposed || !e.gpu) throw new t(this.disposed ? "disposed" : "unsupported", "Terrain materials require WebGPU and a live module; attach new TerrainMaterials to a WebGPU engine");
21
+ this.owner = e, this.device = e.gpu;
22
+ let r = this.textures = this.options.textures(this.device), i = this.terrain.options.layers.length;
23
+ for (let e of [r?.normals, r?.surface]) if (!e || e.dimension !== "2d" || !(e.usage & GPUTextureUsage.TEXTURE_BINDING) || e.sampleCount !== 1 || e.depthOrArrayLayers !== i || !["rgba8unorm", "rgba16float"].includes(e.format)) throw TypeError(`Invalid terrain material textures; return normals and surface as rgba8unorm or rgba16float 2D arrays with ${i} layers, one per terrain layer`);
24
+ let a = /* @__PURE__ */ new Float32Array(64), o = 8 * (this.options.heightBlend ?? .5);
25
+ for (let e = 0; e < i; e++) {
26
+ let t = this.options.layers?.[e] ?? {};
27
+ a.set([
28
+ t.normal ?? 1,
29
+ t.occlusion ?? 1,
30
+ t.roughness ?? 1,
31
+ o
32
+ ], e * 4);
33
+ }
34
+ this.rules = this.device.createBuffer({
35
+ size: 256,
36
+ usage: GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST
37
+ }), this.device.queue.writeBuffer(this.rules, 0, a), this.entries = [
38
+ {
39
+ binding: n,
40
+ resource: r.normals.createView({ dimension: "2d-array" })
41
+ },
42
+ {
43
+ binding: 91,
44
+ resource: r.surface.createView({ dimension: "2d-array" })
45
+ },
46
+ {
47
+ binding: 92,
48
+ resource: { buffer: this.rules }
49
+ }
50
+ ], this.remove ??= this.terrain.addLighting(this);
51
+ }
52
+ get surface() {
53
+ return this.textures?.surface;
54
+ }
55
+ bindings() {
56
+ return this.entries;
57
+ }
58
+ shader(e, n) {
59
+ let r = n + e, i = this.cache.get(r);
60
+ if (i) return i;
61
+ let a = "@fragment fn fragment(i:Output)->@location(0) vec4f {", s = "let n=normalize(i.normal);let base=terrainColor(i.position,n);", c = "let n=terrainBump(i.position,terrainN);", l = "let weight=smoothstep(", u = "let weight=packed[layer/4u][layer%4u];if(weight<=0.0){continue;}", d = "+base*frame.radiance.w";
62
+ if ([
63
+ a,
64
+ d,
65
+ "total+=weight;"
66
+ ].some((t) => e.split(t).length !== 2) || e.includes(s) === e.includes(c) || e.includes(l) === e.includes(u)) throw new t("unsupported", "Terrain materials need the terrain's own lit shader; attach them before any effect that replaces it");
67
+ let f = "i.material.x=terrainPbrRoughness(i.material.x);", p = o(n), m = (e.includes("wrap:vec4f") ? p.split("position*s,").join("(position+layerRules[layer].wrap.xyz)*s,") : p) + e.replace(a, "fn terrainPbrShade(terrainIn:Output)->vec4f {var i=terrainIn;").replace(s, `let terrainN0=normalize(i.normal);let base=terrainColor(i.position,terrainN0);let n=terrainPbrNormal(terrainN0);${f}`).replace(c, `let n=terrainPbrNormal(terrainBump(i.position,terrainN));${f}`).replace(l, "let weight=terrainPbrHeight(position,projection,dx,dy,layer)*smoothstep(").replace(u, "let painted=packed[layer/4u][layer%4u];if(painted<=0.0){continue;}let weight=painted*terrainPbrHeight(position,projection,dx,dy,layer);").replace("total+=weight;", "total+=weight;terrainPbrLayer(position,projection,dx,dy,layer,weight);").replace(d, d + "*terrainPbrOcclusion()");
68
+ return m += `\n${a}return terrainPbrShade(i);}\n`, this.cache.size >= 16 && this.cache.clear(), this.cache.set(r, m), m;
69
+ }
70
+ onDeviceRestored(e) {
71
+ this.release(), this.setup(e);
72
+ }
73
+ release() {
74
+ this.textures?.normals.destroy(), this.textures?.surface.destroy(), this.rules?.destroy(), this.textures = this.rules = void 0, this.entries = [];
75
+ }
76
+ dispose() {
77
+ this.disposed || (this.disposed = !0, this.remove?.(), this.remove = void 0, this.owner?.sceneOf(this)?.removePlugin(this.name), this.release(), this.cache.clear(), this.owner = this.device = void 0);
78
+ }
79
+ [Symbol.dispose ?? Symbol()]() {
80
+ this.dispose();
81
+ }
82
+ }, a = (e, t) => `
83
+ fn ${t}(p:vec3f,q:vec3f,dx:vec3f,dy:vec3f,s:f32,layer:u32)->array<vec4f,3> {
84
+ var r=array<vec4f,3>(vec4f(0),vec4f(0),vec4f(0));
85
+ if(q.x>0.0){r[0]=textureSampleGrad(${e},terrainSampler,p.zy,i32(layer),dx.zy*s,dy.zy*s);}
86
+ if(q.y>0.0){r[1]=textureSampleGrad(${e},terrainSampler,p.xz,i32(layer),dx.xz*s,dy.xz*s);}
87
+ if(q.z>0.0){r[2]=textureSampleGrad(${e},terrainSampler,p.xy,i32(layer),dx.xy*s,dy.xy*s);}
88
+ return r;
89
+ }`, o = (e) => `
90
+ @group(${e}) @binding(${n}) var terrainPbrNormals:texture_2d_array<f32>;
91
+ @group(${e}) @binding(91) var terrainPbrSurfaces:texture_2d_array<f32>;
92
+ @group(${e}) @binding(92) var<uniform> terrainPbrRules:array<vec4f,16>;
93
+ var<private> terrainPbrGradient:vec4f;var<private> terrainPbrSurface:vec3f;var<private> terrainPbrLast:vec4f;
94
+ ${a("terrainPbrNormals", "terrainPbrTriN")}${a("terrainPbrSurfaces", "terrainPbrTriS")}
95
+ fn terrainPbrHeight(position:vec3f,projection:vec3f,dx:vec3f,dy:vec3f,layer:u32)->f32 {
96
+ let s=layerRules[layer].params.x;let t=terrainPbrTriS(position*s,projection,dx,dy,s,layer);
97
+ terrainPbrLast=t[0]*projection.x+t[1]*projection.y+t[2]*projection.z;
98
+ return exp2(terrainPbrRules[layer].w*(terrainPbrLast.a-1.0));
99
+ }
100
+ fn terrainPbrLayer(position:vec3f,projection:vec3f,dx:vec3f,dy:vec3f,layer:u32,weight:f32) {
101
+ if(weight<=0.0){return;}
102
+ let r=terrainPbrRules[layer];let s=layerRules[layer].params.x;
103
+ let t=terrainPbrTriN(position*s,projection,dx,dy,s,layer);
104
+
105
+
106
+ var g=vec3f(0);
107
+ if(projection.x>0.0){let m=t[0].xyz*2.0-1.0;let d=vec2f(-m.x,m.y)/max(m.z,0.05);g+=projection.x*vec3f(0.0,d.y,d.x);}
108
+ if(projection.y>0.0){let m=t[1].xyz*2.0-1.0;let d=vec2f(-m.x,m.y)/max(m.z,0.05);g+=projection.y*vec3f(d.x,0.0,d.y);}
109
+ if(projection.z>0.0){let m=t[2].xyz*2.0-1.0;let d=vec2f(-m.x,m.y)/max(m.z,0.05);g+=projection.z*vec3f(d.x,d.y,0.0);}
110
+ terrainPbrGradient+=vec4f(g*r.x*weight,weight);
111
+ terrainPbrSurface+=vec3f(mix(1.0,terrainPbrLast.r,r.y),terrainPbrLast.g*r.z,0.0)*weight;
112
+ }
113
+ fn terrainPbrNormal(n:vec3f)->vec3f {
114
+ if(terrainPbrGradient.w<=0.00001){return n;}
115
+ let g=terrainPbrGradient.xyz/terrainPbrGradient.w;let surface=g-dot(g,n)*n;let tilted=n-surface;
116
+ return select(n,normalize(tilted),dot(tilted,tilted)>0.0);
117
+ }
118
+ fn terrainPbrRoughness(fallback:f32)->f32 {
119
+ if(terrainPbrGradient.w<=0.00001){return fallback;}
120
+ return clamp(terrainPbrSurface.y/terrainPbrGradient.w,0.02,1.0);
121
+ }
122
+ fn terrainPbrOcclusion()->f32 {
123
+ if(terrainPbrGradient.w<=0.00001){return 1.0;}
124
+ return terrainPbrSurface.x/terrainPbrGradient.w;
125
+ }
126
+ `;
127
+ //#endregion
128
+ export { i as TerrainMaterials };
@@ -0,0 +1,34 @@
1
+ //#region src/lighting-layout.ts
2
+ var e = /@group\((\d+)\)\s*@binding\((\d+)\)\s*var(?:<([^>]*)>)?\s+(\w+)\s*:\s*([^;]+);/g, t = /^texture_(2d_array|2d|3d|cube_array|cube)<(f32|i32|u32)>$/, n = /^texture_depth_(2d_array|2d|cube_array|cube)$/, r = (e) => e.replace("_", "-");
3
+ function i(e, i, a, o) {
4
+ if (i === "uniform") return { buffer: { type: "uniform" } };
5
+ if (i.startsWith("storage")) return { buffer: { type: i.includes("read_write") ? "storage" : "read-only-storage" } };
6
+ if (o === "sampler_comparison") return { sampler: { type: "comparison" } };
7
+ if (o === "sampler") return { sampler: { type: "filtering" } };
8
+ let s = n.exec(o);
9
+ if (s) return { texture: {
10
+ sampleType: "depth",
11
+ viewDimension: r(s[1])
12
+ } };
13
+ let c = t.exec(o);
14
+ if (!c) throw TypeError(`Terrain lighting declares ${a} as ${o}, which a lighting group cannot hold; declare a sampled texture, sampler or buffer`);
15
+ let l = new RegExp(String.raw`textureSample\w*\(\s*${a}\b`).test(e);
16
+ return { texture: {
17
+ sampleType: c[2] === "f32" ? l ? "float" : "unfilterable-float" : c[2] === "u32" ? "uint" : "sint",
18
+ viewDimension: r(c[1])
19
+ } };
20
+ }
21
+ function a(t, n, r = 1) {
22
+ let a = /* @__PURE__ */ new Map();
23
+ for (let [, n, o, s = "", c, l] of t.matchAll(e)) +n === r && a.set(+o, i(t, s.replace(/\s/g, ""), c, l.trim()));
24
+ return n.flatMap(({ binding: e }) => {
25
+ let t = a.get(e);
26
+ return t ? [{
27
+ binding: e,
28
+ visibility: GPUShaderStage.FRAGMENT,
29
+ ...t
30
+ }] : [];
31
+ });
32
+ }
33
+ //#endregion
34
+ export { a as t };
@@ -0,0 +1,5 @@
1
+ /**
2
+ * The layout entries of `entries`, each as `code` declares it at `group` (default 1). One it does not declare has no entry, so
3
+ * WebGPU's `createBindGroup` names it as a validation error.
4
+ */
5
+ export declare function lightingLayout(code: string, entries: readonly GPUBindGroupEntry[], group?: number): GPUBindGroupLayoutEntry[];
@@ -0,0 +1,21 @@
1
+ //#region src/mesh-patch.ts
2
+ var e = "let terrainSource=i;let terrainNormal=n;{var i=terrainSource;var n=terrainNormal;", t = "\nfn terrainHash(seed:u32)->u32 {\n var h=seed;h^=h>>16u;h*=0x7feb352du;h^=h>>15u;h*=0x846ca68bu;h^=h>>16u;return h;\n}\n\n\n\nfn terrainNoise(p:vec2f)->vec3f {\n let base=floor(p);let c=bitcast<vec2u>(vec2i(base));let t=p-base;\n let row0=terrainHash(c.y);let row1=terrainHash(c.y+1u);\n let v00=f32(terrainHash(c.x+row0)>>8u)*5.9604645e-8;let v10=f32(terrainHash(c.x+1u+row0)>>8u)*5.9604645e-8;\n let v01=f32(terrainHash(c.x+row1)>>8u)*5.9604645e-8;let v11=f32(terrainHash(c.x+1u+row1)>>8u)*5.9604645e-8;\n let s=t*t*(3.0-2.0*t);let ds=6.0*t*(1.0-t);\n let low=mix(v00,v10,s.x);let high=mix(v01,v11,s.x);\n let slopeX=ds.x*mix(v10-v00,v11-v01,s.y);\n return vec3f(mix(low,high,s.y),slopeX,ds.y*(high-low));\n}\n", n = (e) => Math.max(-1, ...[...e.matchAll(/@location\((\d+)\)/g)].map((e) => Number(e[1]))) + 1;
3
+ function r(t) {
4
+ let r = t;
5
+ if (r.includes("terrainId:f32") || (r = r.replace(/struct Output \{[^}]+\}/, (e) => e.replace("}", `,@location(${n(e)}) @interpolate(flat) terrainId:f32 }`)).replace("o.color=i.color.rgb;", "o.terrainId=i.factors.w+1.0;o.color=i.color.rgb;")), !r.includes("terrainId:f32") || !r.includes("o.terrainId=")) return;
6
+ let i = r.indexOf(e);
7
+ if (i < 0) {
8
+ if (i = r.indexOf("let n=normalize(i.normal)*select(-1.0,1.0,facing);"), i < 0) return;
9
+ i += 50;
10
+ let t = i;
11
+ for (let e = 1; t < r.length; t++) if (r[t] === "{") e++;
12
+ else if (r[t] === "}" && --e === 0) break;
13
+ r = r.slice(0, i) + e + r.slice(i, t) + "}" + r.slice(t);
14
+ }
15
+ return {
16
+ code: r,
17
+ at: i + 81
18
+ };
19
+ }
20
+ //#endregion
21
+ export { r as n, t };
@@ -0,0 +1,14 @@
1
+ export declare const normalLine = "let n=normalize(i.normal)*select(-1.0,1.0,facing);";
2
+ export declare const block = "let terrainSource=i;let terrainNormal=n;{var i=terrainSource;var n=terrainNormal;";
3
+ export declare const noiseCode = "\nfn terrainHash(seed:u32)->u32 {\n var h=seed;h^=h>>16u;h*=0x7feb352du;h^=h>>15u;h*=0x846ca68bu;h^=h>>16u;return h;\n}\n\n\n\nfn terrainNoise(p:vec2f)->vec3f {\n let base=floor(p);let c=bitcast<vec2u>(vec2i(base));let t=p-base;\n let row0=terrainHash(c.y);let row1=terrainHash(c.y+1u);\n let v00=f32(terrainHash(c.x+row0)>>8u)*5.9604645e-8;let v10=f32(terrainHash(c.x+1u+row0)>>8u)*5.9604645e-8;\n let v01=f32(terrainHash(c.x+row1)>>8u)*5.9604645e-8;let v11=f32(terrainHash(c.x+1u+row1)>>8u)*5.9604645e-8;\n let s=t*t*(3.0-2.0*t);let ds=6.0*t*(1.0-t);\n let low=mix(v00,v10,s.x);let high=mix(v01,v11,s.x);\n let slopeX=ds.x*mix(v10-v00,v11-v01,s.y);\n return vec3f(mix(low,high,s.y),slopeX,ds.y*(high-low));\n}\n";
4
+ /** The first @location a struct does not use: patches that add varyings to a shared struct must not collide. */
5
+ export declare const freeLocation: (struct: string) => number;
6
+ /**
7
+ * Core's standard shader with the flat mesh-ID varying (`i.terrainId`, the mesh id plus 1) and the per-pixel block,
8
+ * each added once, and the index just inside the block where a patch puts its per-mesh code. Undefined when the
9
+ * source is not core's standard shader (the patches then leave it as it is, like core's other optional patches).
10
+ */
11
+ export declare function openMeshBlock(source: string): {
12
+ code: string;
13
+ at: number;
14
+ } | undefined;
@@ -0,0 +1,11 @@
1
+ //#region src/noise3.ts
2
+ function e(e, t, n, r) {
3
+ let i = Math.imul(e, 2376512323) ^ Math.imul(t, 3625334849) ^ Math.imul(n, 3407524639) ^ r;
4
+ return i ^= i >>> 16, i = Math.imul(i, 2146121005), i ^= i >>> 15, i = Math.imul(i, 2221713035), i ^= i >>> 16, (i >>> 0) / 2147483647.5 - 1;
5
+ }
6
+ function t(t, n, r, i) {
7
+ let a = Math.floor(t), o = Math.floor(n), s = Math.floor(r), c = t - a, l = n - o, u = r - s, d = c * c * c * (c * (c * 6 - 15) + 10), f = l * l * l * (l * (l * 6 - 15) + 10), p = u * u * u * (u * (u * 6 - 15) + 10), m = Math.imul(i, 374761393), h = e(a, o, s, m), g = e(a + 1, o, s, m), _ = e(a, o + 1, s, m), v = e(a + 1, o + 1, s, m), y = e(a, o, s + 1, m), b = e(a + 1, o, s + 1, m), x = e(a, o + 1, s + 1, m), S = e(a + 1, o + 1, s + 1, m), C = h + (g - h) * d + (_ + (v - _) * d - h - (g - h) * d) * f;
8
+ return C + (y + (b - y) * d + (x + (S - x) * d - y - (b - y) * d) * f - C) * p;
9
+ }
10
+ //#endregion
11
+ export { t as n, e as t };
@@ -0,0 +1,3 @@
1
+ export declare function hash(x: number, y: number, z: number, seed: number): number;
2
+ /** Trilinear value noise with quintic fades, -1..1. */
3
+ export declare function valueNoise(x: number, y: number, z: number, seed: number): number;