Skip to content

A fast 2D and 3D game engine — TypeScript SDK, C++/WebAssembly core, visual editor. Ship one project to web, desktop, WeChat MiniGames, playable ads, and native Android / iOS.

feat(terrain): each terrain layer says how it meets the others, and the terrain's paint and bounds can be asked

yhh9a717d54f17e
diff --git a/desktop b/desktop
index 5aa40fd78..3a07b5b63 160000
--- a/desktop
+++ b/desktop
@@ -1 +1 @@
-Subproject commit 5aa40fd786a19d8964080ad9f84cb46c12576cf2
+Subproject commit 3a07b5b6386d94fc7892a6c76be8f769423c4d06
diff --git a/docs/astro/src/content/docs/graphics/terrain.mdx b/docs/astro/src/content/docs/graphics/terrain.mdx
index 5e2eb2c73..f2d64ec35 100644
--- a/docs/astro/src/content/docs/graphics/terrain.mdx
+++ b/docs/astro/src/content/docs/graphics/terrain.mdx
@@ -75,6 +75,7 @@ paint all eight.
| `tint` | Multiplies the albedo. |
| `roughness` | The roughness where there is no mask. |
| `normalStrength` | How strongly the normal map bends the light: 1 as drawn, 0 flat. |
+| `heightBlend` | Optional. How much this layer's own height decides where it meets another: 0 blends by the paint alone (grass into sand), 1 by the layers' heights (stones standing through grass). Where several layers meet, each counts by how much of it is there. Absent, it is the material's `u_heightBlend`. |
The ground is drawn by the **Terrain Layers** shader (`builtin:terrain-layers`). Every layer is read by world position without repeat
near the eye, with a wider tile mixed in far off; where layers meet, the one whose mask stands higher shows (stones through grass, sand
diff --git a/docs/astro/src/content/docs/zh-cn/graphics/terrain.mdx b/docs/astro/src/content/docs/zh-cn/graphics/terrain.mdx
index d0372fc5f..561c94727 100644
--- a/docs/astro/src/content/docs/zh-cn/graphics/terrain.mdx
+++ b/docs/astro/src/content/docs/zh-cn/graphics/terrain.mdx
@@ -57,6 +57,7 @@ description: 一个 Terrain 组件,用高度图或噪声生成地面,可以是
| `tint` | 与颜色相乘。 |
| `roughness` | 没有遮罩贴图时的粗糙度。 |
| `normalStrength` | 法线贴图的强度:1 为原样,0 为平坦。 |
+| `heightBlend` | 可选。这一层自己的高度在与别的层相交处起多大作用:0 只按涂色混合(草到沙),1 按各层高度混合(石头从草里露出)。多层相遇时,每层按它在此处所占的比例计入。缺省则用材质的 `u_heightBlend`。 |
地面由 **Terrain Layers** 着色器(`builtin:terrain-layers`)绘制。每一层按世界位置铺设,近处去除重复,远处混入更大的平铺;层与层交界处遮罩高度更高的一层显露(草间露出石头、石缝里填着沙);坡面上同时从侧面投影,悬崖不会被拉伸。法线贴图和遮罩的遮蔽、粗糙度参与光照。材质控制效果:`u_sharpness`、`u_heightBlend`、`u_blendNoise`、`u_antiTile`、`u_farScale`、`u_macroVariation`、`u_triplanarFrom`(多陡开始读侧面)和 `u_wetLevel`/`u_wetBand`,含义同下文 Terrain 着色器。
diff --git a/sdk/src/terrain/layers.ts b/sdk/src/terrain/layers.ts
index d71148269..33a68d689 100644
--- a/sdk/src/terrain/layers.ts
+++ b/sdk/src/terrain/layers.ts
@@ -30,6 +30,11 @@ export interface TerrainLayerDef {
roughness: number;
/** How strongly the normal map bends the light: 1 as drawn, 0 flat. */
normalStrength: number;
+ /**
+ * How much the layer's own height decides where it meets another, 0 to 1: 0 blends by the paint alone (a smooth edge, for grass into sand),
+ * 1 by the layers' heights (stones standing through grass). Absent, it is the material's `u_heightBlend`.
+ */
+ heightBlend?: number;
}
const DEFAULTS: TerrainLayerDef = { tile: 4, tint: [1, 1, 1], roughness: 0.9, normalStrength: 1 };
@@ -59,6 +64,7 @@ export function parseTerrainLayer(json: unknown, file = 'terrain layer'): Terrai
tint: tint as [number, number, number],
roughness: num('roughness', DEFAULTS.roughness, 0, 1),
normalStrength: num('normalStrength', DEFAULTS.normalStrength, 0, 4),
+ ...(o.heightBlend === undefined ? {} : { heightBlend: num('heightBlend', 0, 0, 1) }),
};
}
@@ -84,7 +90,7 @@ export interface LayerImage { width: number; height: number; pixels: Uint8Array
export interface LayerSource { def: TerrainLayerDef; albedo: LayerImage | null; normal: LayerImage | null; mask: LayerImage | null }
/** The layers packed: one image a layer in each of the three arrays, all `size` by `size`. */
-export interface PackedLayers { size: number; albedo: Uint8Array[]; normal: Uint8Array[]; mask: Uint8Array[]; tiles: number[] }
+export interface PackedLayers { size: number; albedo: Uint8Array[]; normal: Uint8Array[]; mask: Uint8Array[]; tiles: number[]; heightBlends: number[] }
/** `image` resampled (bilinear, wrapping, as the layer tiles) to `size` by `size`. */
function resample(image: LayerImage, size: number): Uint8Array {
@@ -151,5 +157,6 @@ export function packLayers(layers: readonly LayerSource[], maxSize = 1024): Pack
mask.push(made);
}
}
- return { size, albedo, normal, mask, tiles: layers.map((l) => l.def.tile) };
+ // A layer with no height blend of its own is -1: the shader reads the material's.
+ return { size, albedo, normal, mask, tiles: layers.map((l) => l.def.tile), heightBlends: layers.map((l) => l.def.heightBlend ?? -1) };
}
diff --git a/sdk/src/terrain/terrainPlugin.ts b/sdk/src/terrain/terrainPlugin.ts
index 650f13c72..1c8a630ea 100644
--- a/sdk/src/terrain/terrainPlugin.ts
+++ b/sdk/src/terrain/terrainPlugin.ts
@@ -264,6 +264,57 @@ export class Terrains {
return null;
}
+ /**
+ * The weights of the terrain's layers at (x, z), as the ground is painted there (four, or as many as it has layers), or null where no terrain is:
+ * what a world's rules read as the fields `paint.<layer>`.
+ */
+ paintAt(x: number, z: number): readonly number[] | null {
+ const world = this.app_?.world;
+ if (!world) return null;
+ for (const [entity, built] of this.built_) {
+ const source = built.source, surface = built.surface;
+ if (!source || !surface || !world.valid(entity)) continue;
+ const t = world.tryGet(entity, Transform) as TransformData | null;
+ if (!t) continue;
+ const lx = x - t.worldPosition.x, lz = z - t.worldPosition.z;
+ const h = surface.height(lx, lz), n = surface.normal(lx, lz);
+ if (h === null || !n) continue;
+ return source.paint(lx, lz, h, n[1]);
+ }
+ return null;
+ }
+
+ /**
+ * The world rectangle the terrains cover, `[minX, minZ, maxX, maxZ]`, or null where it has no end (a terrain of infinite extent) or there is none:
+ * what a layer of chunks laid over the ground is held to, so it does not count a radius of empty world.
+ */
+ areaBounds(): [number, number, number, number] | null {
+ const world = this.app_?.world;
+ if (!world) return null;
+ let out: [number, number, number, number] | null = null;
+ for (const [entity, built] of this.built_) {
+ if (!world.valid(entity)) continue;
+ if (built.data.extent !== TerrainExtent.Area) return null;
+ const t = world.tryGet(entity, Transform) as TransformData | null;
+ if (!t) continue;
+ const r: [number, number, number, number] = [
+ t.worldPosition.x - built.data.sizeX / 2, t.worldPosition.z - built.data.sizeZ / 2,
+ t.worldPosition.x + built.data.sizeX / 2, t.worldPosition.z + built.data.sizeZ / 2,
+ ];
+ out = out ? [Math.min(out[0], r[0]), Math.min(out[1], r[1]), Math.max(out[2], r[2]), Math.max(out[3], r[3])] : r;
+ }
+ return out;
+ }
+
+ /** The names of the terrain's layers, in the order `paintAt` weighs them: the layer files' names, or grass, dirt, snow and rock without any. */
+ layerNames(): string[] {
+ for (const built of this.built_.values()) {
+ const layers = built.data.layers ?? [];
+ if (layers.length > 0) return layers.map((ref, i) => (ref.split('/').pop() ?? '').replace(/\.[^.]*$/, '') || `layer${i}`);
+ }
+ return ['grass', 'dirt', 'snow', 'rock'];
+ }
+
/** The world height of the ground at (x, z) as it was made, under every modifier laid over it: what a plot is levelled from. */
heightBeneathAt(x: number, z: number): number | null {
const world = this.app_?.world;
@@ -740,6 +791,9 @@ export class TerrainPlugin implements Plugin {
const t = (i: number): number => packed.tiles[i] ?? 4;
set('u_tiles0', { x: t(0), y: t(1), z: t(2), w: t(3) });
set('u_tiles1', { x: t(4), y: t(5), z: t(6), w: t(7) });
+ const hb = (i: number): number => packed.heightBlends[i] ?? -1;
+ set('u_heightBlends0', { x: hb(0), y: hb(1), z: hb(2), w: hb(3) });
+ set('u_heightBlends1', { x: hb(4), y: hb(5), z: hb(6), w: hb(7) });
} catch (e) {
log.error('terrain', 'packing the terrain layers failed', e);
} finally {
diff --git a/sdk/src/terrain/terrainShader.ts b/sdk/src/terrain/terrainShader.ts
index 3a2b0c13b..312729475 100644
--- a/sdk/src/terrain/terrainShader.ts
+++ b/sdk/src/terrain/terrainShader.ts
@@ -486,6 +486,9 @@ const TERRAIN_LAYERS = `#pragma shader "Terrain Layers"
#pragma param u_layerCount float default(0) range(0,8) ui(slider)
#pragma param u_tiles0 vec4 default(4,4,4,4)
#pragma param u_tiles1 vec4 default(4,4,4,4)
+// Each layer's own height blend (below zero: the material's u_heightBlend), written by the Terrain from the layer files.
+#pragma param u_heightBlends0 vec4 default(-1,-1,-1,-1)
+#pragma param u_heightBlends1 vec4 default(-1,-1,-1,-1)
// How much a layer with more weight takes over from the others at the seam: 1 is a plain blend, higher a harder edge.
#pragma param u_sharpness float default(1.6) range(1,8) ui(slider)
// How much the seams follow the layers' heights (their masks' blue): rock shows through the gaps in the grass before the grass gives
@@ -558,6 +561,7 @@ vec2 tnHash2(vec2 p) {
return fract(sin(vec2(dot(p, vec2(127.1, 311.7)), dot(p, vec2(269.5, 183.3)))) * 43758.5453);
}
float tnTile(int i) { return i < 4 ? u_tiles0[i] : u_tiles1[i - 4]; }
+float tnHeightBlend(int i) { float b = i < 4 ? u_heightBlends0[i] : u_heightBlends1[i - 4]; return b < 0.0 ? u_heightBlend : b; }
// One layer read at uv (in repeats) on one plane: its albedo, its tangent normal's slope (x, y) and its mask, from the gradients given.
struct TnTap { vec3 albedo; vec2 slope; vec3 mask; };
@@ -627,8 +631,13 @@ void main() {
float sum = 0.0;
for (int i = 0; i < 8; i++) {
float raw = i < 4 ? paintA[i] : paintB[i - 4];
- // Each layer's say wanders by slow noise of its own, so where two meet the edge is ragged, not the paint's gradient.
- float wander = tnNoise(P.xz / (tnTile(i) * 2.3) + float(i) * 11.0 + 3.0);
+ // Each layer's say wanders by noise of its own, so where two meet the edge is ragged, not the paint's gradient. Three octaves: the slow one
+ // moves where the edge runs, the two finer break it up at the size of a paint texel and below, where a sharpened bilinear paint
+ // would otherwise follow the texel grid in steps.
+ float tileSize = tnTile(i);
+ float wander = tnNoise(P.xz / (tileSize * 2.3) + float(i) * 11.0 + 3.0) * 0.5
+ + tnNoise(P.xz / (tileSize * 0.45) + float(i) * 7.0 + 17.0) * 0.3
+ + tnNoise(P.xz / (tileSize * 0.11) + float(i) * 5.0 + 29.0) * 0.2;
w[i] = i < count ? max(raw, 0.0) * mix(1.0, 0.35 + 1.3 * wander, u_blendNoise) : 0.0;
sum += w[i];
}
@@ -685,9 +694,13 @@ void main() {
float hsum = 0.0;
float hw[8];
for (int i = 0; i < 8; i++) { hw[i] = w[i] > 1e-3 ? max(mask[i].b + w[i] * 1.5 - (top - 0.35), 0.0) : 0.0; hsum += hw[i]; }
+ // How much height decides here: each layer's own say, weighted by how much of that layer is here, so grass into sand blends by the paint and stones
+ // standing through grass by their heights, with no one number for the whole ground.
+ float byHeight = 0.0;
+ for (int i = 0; i < 8; i++) byHeight += w[i] * tnHeightBlend(i);
vec3 colour = vec3(0.0), slope = vec3(0.0), surface = vec3(0.0);
for (int i = 0; i < 8; i++) {
- float k = mix(w[i], hw[i] / max(hsum, 1e-4), u_heightBlend);
+ float k = mix(w[i], hw[i] / max(hsum, 1e-4), byHeight);
colour += albedo[i] * k; slope += bend[i] * k; surface += mask[i] * k;
}
float broad = tnNoise(P.xz / (scale * 7.3)) * 0.6 + tnNoise(P.xz / (scale * 29.0) + 5.0) * 0.4;
@@ -728,6 +741,12 @@ fn tnTile(i : i32) -> f32 {
if (i < 4) { return mc.u_tiles0[i]; }
return mc.u_tiles1[i - 4];
}
+fn tnHeightBlend(i : i32) -> f32 {
+ var b = 0.0;
+ if (i < 4) { b = mc.u_heightBlends0[i]; } else { b = mc.u_heightBlends1[i - 4]; }
+ if (b < 0.0) { return mc.u_heightBlend; }
+ return b;
+}
struct TnTap { albedo : vec3f, slope : vec2f, mask : vec3f };
fn tnPlain(uv : vec2f, layer : i32, gx : vec2f, gy : vec2f) -> TnTap {
var t : TnTap;
@@ -817,7 +836,11 @@ fn packNormal(n : vec3f) -> vec2f {
for (var i = 0; i < 8; i = i + 1) {
var raw = 0.0;
if (i < 4) { raw = paintA[i]; } else { raw = paintB[i - 4]; }
- let wander = tnNoise(P.xz / (tnTile(i) * 2.3) + vec2f(f32(i) * 11.0 + 3.0));
+ // Three octaves: the slow one moves where the edge runs, the two finer break it up at the size of a paint texel and below.
+ let tileSize = tnTile(i);
+ let wander = tnNoise(P.xz / (tileSize * 2.3) + vec2f(f32(i) * 11.0 + 3.0)) * 0.5
+ + tnNoise(P.xz / (tileSize * 0.45) + vec2f(f32(i) * 7.0 + 17.0)) * 0.3
+ + tnNoise(P.xz / (tileSize * 0.11) + vec2f(f32(i) * 5.0 + 29.0)) * 0.2;
w[i] = 0.0;
if (i < count) { w[i] = max(raw, 0.0) * mix(1.0, 0.35 + 1.3 * wander, mc.u_blendNoise); }
sum = sum + w[i];
@@ -881,11 +904,14 @@ fn packNormal(n : vec3f) -> vec2f {
if (w[i] > 1e-3) { hw[i] = max(mask[i].b + w[i] * 1.5 - (top - 0.35), 0.0); }
hsum = hsum + hw[i];
}
+ // How much height decides here: each layer's own say, weighted by how much of that layer is here.
+ var byHeight = 0.0;
+ for (var i = 0; i < 8; i = i + 1) { byHeight = byHeight + w[i] * tnHeightBlend(i); }
var colour = vec3f(0.0);
var slope = vec3f(0.0);
var surface = vec3f(0.0);
for (var i = 0; i < 8; i = i + 1) {
- let k = mix(w[i], hw[i] / max(hsum, 1e-4), mc.u_heightBlend);
+ let k = mix(w[i], hw[i] / max(hsum, 1e-4), byHeight);
colour = colour + albedo[i] * k;
slope = slope + bend[i] * k;
surface = surface + mask[i] * k;
diff --git a/sdk/tests/terrain-layers.test.ts b/sdk/tests/terrain-layers.test.ts
index c1685fcc3..9aed923c7 100644
--- a/sdk/tests/terrain-layers.test.ts
+++ b/sdk/tests/terrain-layers.test.ts
@@ -17,6 +17,12 @@ describe('a terrain layer file', () => {
expect(l).toMatchObject({ albedo: 'assets/grass.png', normal: undefined, mask: undefined, tile: 3, tint: [1, 1, 1], roughness: 0.9, normalStrength: 1 });
});
+ it('keeps a height blend of its own only when it names one', () => {
+ expect(parseTerrainLayer({ tile: 3 }).heightBlend).toBeUndefined();
+ expect(parseTerrainLayer({ tile: 3, heightBlend: 0.15 }).heightBlend).toBe(0.15);
+ expect(() => parseTerrainLayer({ heightBlend: 2 }, 'g.esterrainlayer')).toThrow(/g\.esterrainlayer\.heightBlend/);
+ });
+
it('says which field it cannot take', () => {
expect(() => parseTerrainLayer({ tile: -1 }, 'g.esterrainlayer')).toThrow(/g\.esterrainlayer\.tile/);
expect(() => parseTerrainLayer({ tint: [1, 1] })).toThrow(/tint/);
@@ -36,6 +42,10 @@ describe('packing layers', () => {
expect(packed.albedo).toHaveLength(2);
expect(packed.albedo[0]!.length).toBe(64 * 64 * 4);
expect(packed.tiles).toEqual([2, 8]);
+ // A layer with no height blend of its own is -1, which the shader reads as the material's.
+ expect(packed.heightBlends).toEqual([-1, -1]);
+ const own = packLayers([{ def: parseTerrainLayer({ heightBlend: 0.2 }), albedo: null, normal: null, mask: null }, { def: rock, albedo: null, normal: null, mask: null }]);
+ expect(own.heightBlends).toEqual([0.2, -1]);
expect(packLayers([{ def: grass, albedo: solid(4096, [0, 0, 0, 255]), normal: null, mask: null }], 512).size).toBe(512);
});