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.
TypeScript 2d-game-engine3d3d-game-engineandroidcppecsgame-editorgame-enginegamedeviostypescriptwebassemblywebglwebgpuwechat-minigame
feat(terrain): a planet's ground is drawn with the layers' textures
yhh33813dc466fc
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex a99b871e0..1f0c60673 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -16,6 +16,7 @@ published separately; it ships inside the editor.### Added+- **A planet's ground has the layers' textures.** `Planet.layers` names up to four `.esterrainlayer` files, as on a flat terrain: each layer's albedo and normal map are read on the planes of the world's axes by how much the ground faces them, with a wider read mixed in far off so the repeat is lost. Without layers the ground is still the four colours.- **A planet's ground collides.** `Planet` takes `collision`, `collisionDistance`, `collisionLayer` and `friction` as flat terrain does: the finest nodes round every moving 3D body and character are built as collision geometry from the same samples the ground is drawn from, one chunk layer to each face of the cube.- **Height Fog by height above a planet.** `heightFog` takes `u_planetRadius` and the planet's centre (`u_planetX/Y/Z`): with a radius above 0 the fog thins with the height above the ground's sphere and not with world Y, so a round world is hazy at its horizon and clear from orbit.diff --git a/docs/astro/src/content/docs/graphics/terrain.mdx b/docs/astro/src/content/docs/graphics/terrain.mdxindex 3bcf6b331..5d583d5ef 100644--- a/docs/astro/src/content/docs/graphics/terrain.mdx+++ b/docs/astro/src/content/docs/graphics/terrain.mdx@@ -282,7 +282,7 @@ registerPlanetProvider({});```-The ground collides: the finest nodes within `collisionDistance` of every moving 3D body and character are built as collision geometry from the same samples the ground is drawn from (`collision`, `collisionDistance`, `collisionLayer`, `friction`, as on a flat terrain). A planet's transform is a position only: a turned or scaled planet's collision stands where it would be unturned. The layers' textures, the sea, a sky that follows the horizon round and gravity toward the centre are not in it yet; a body falls along the world's one gravity, so toward the centre only at the top of the planet.+The ground collides: the finest nodes within `collisionDistance` of every moving 3D body and character are built as collision geometry from the same samples the ground is drawn from (`collision`, `collisionDistance`, `collisionLayer`, `friction`, as on a flat terrain). A planet's transform is a position only: a turned or scaled planet's collision stands where it would be unturned. `layers` names up to four `.esterrainlayer` files, as on a flat terrain; each is read on the planes of the world's axes by how much the ground faces them, with a wider read mixed in far off so the repeat is lost. Without layers the ground is the four colours. The sea, a sky that follows the horizon round and gravity toward the centre are not in it yet; a body falls along the world's one gravity, so toward the centre only at the top of the planet.## Limitsdiff --git a/docs/astro/src/content/docs/zh-cn/graphics/terrain.mdx b/docs/astro/src/content/docs/zh-cn/graphics/terrain.mdxindex 935ad4094..b2e61d6dc 100644--- a/docs/astro/src/content/docs/zh-cn/graphics/terrain.mdx+++ b/docs/astro/src/content/docs/zh-cn/graphics/terrain.mdx@@ -193,7 +193,7 @@ registerTerrainProvider(planet);星球的提供器回答的是**方向**,不是位置:它拿到从星球中心出发的单位方向和它们所在的半径,给出每个方向上高出半径的高度,如果上色,再给出四个图层权重。球面没有 x 和 z,所以生成器读三维噪声,没有接缝也没有极点。-地面有碰撞:每个运动的 3D 刚体和角色在 `collisionDistance` 内的最细节点,会用画地面的同一批采样建成碰撞几何(`collision`、`collisionDistance`、`collisionLayer`、`friction`,和平面地形一样)。星球的变换只有位置:旋转或缩放过的星球,碰撞仍站在没旋转时的位置。图层贴图、海、跟着地平线转的天空和指向球心的重力还没有;物体沿世界唯一的重力下落,所以只有在星球顶部才是朝向球心。+地面有碰撞:每个运动的 3D 刚体和角色在 `collisionDistance` 内的最细节点,会用画地面的同一批采样建成碰撞几何(`collision`、`collisionDistance`、`collisionLayer`、`friction`,和平面地形一样)。星球的变换只有位置:旋转或缩放过的星球,碰撞仍站在没旋转时的位置。`layers` 可以写最多四个 `.esterrainlayer` 文件,和平面地形一样;每层按地面朝向世界坐标轴的程度,在三个投影面上取样,远处混入更宽的一次取样,看不出重复。不写图层时地面就是四种颜色。海、跟着地平线转的天空和指向球心的重力还没有;物体沿世界唯一的重力下落,所以只有在星球顶部才是朝向球心。## 限制diff --git a/docs/astro/src/data/components.generated.json b/docs/astro/src/data/components.generated.jsonindex 4882949da..f3548ad53 100644--- a/docs/astro/src/data/components.generated.json+++ b/docs/astro/src/data/components.generated.json@@ -3891,6 +3891,41 @@"default": "0.35","doc": "How strongly the ground's brightness wanders.","range": "0–1, step 0.01"+ },+ {+ "key": "collision",+ "type": "boolean",+ "default": "true",+ "doc": "Whether 3D bodies and characters collide with the ground: the finest tiles round each of them are built as collision geometry."+ },+ {+ "key": "collisionDistance",+ "type": "number",+ "default": "64",+ "doc": "How far round each moving body and character the ground is built for collision, in metres.",+ "range": "≥ 1"+ },+ {+ "key": "collisionLayer",+ "type": "number",+ "default": "0",+ "doc": "The collision layer the ground is in (0 to 15).",+ "range": "0–15, step 1",+ "advanced": true+ },+ {+ "key": "friction",+ "type": "number",+ "default": "0.6",+ "doc": "The ground's friction.",+ "range": "≥ 0",+ "advanced": true+ },+ {+ "key": "layers",+ "type": "array",+ "default": "empty",+ "doc": "The terrain layers (.esterrainlayer, up to four) the ground is drawn with, in the order the paint weighs them, each read on the planes of the world's axes. Empty draws the four layer colours."}],"animatable": [@@ -3916,7 +3951,10 @@"layerColor3.b","layerColor3.a","macroScale",- "macroVariation"+ "macroVariation",+ "collisionDistance",+ "collisionLayer",+ "friction"]},{diff --git a/sdk/etc/index.api.md b/sdk/etc/index.api.mdindex da4b7dfbb..53ac26c06 100644--- a/sdk/etc/index.api.md+++ b/sdk/etc/index.api.md@@ -6752,6 +6752,7 @@ layerColor0: ColorlayerColor1: ColorlayerColor2: ColorlayerColor3: Color+layers: string[]macroScale: numbermacroVariation: numberprovider: stringdiff --git a/sdk/etc/index.native.api.md b/sdk/etc/index.native.api.mdindex fa16304bf..7741b72ba 100644--- a/sdk/etc/index.native.api.md+++ b/sdk/etc/index.native.api.md@@ -6955,6 +6955,7 @@ layerColor0: ColorlayerColor1: ColorlayerColor2: ColorlayerColor3: Color+layers: string[]macroScale: numbermacroVariation: numberprovider: stringdiff --git a/sdk/etc/index.node.api.md b/sdk/etc/index.node.api.mdindex 6b12e0fd5..d0797729e 100644--- a/sdk/etc/index.node.api.md+++ b/sdk/etc/index.node.api.md@@ -6747,6 +6747,7 @@ layerColor0: ColorlayerColor1: ColorlayerColor2: ColorlayerColor3: Color+layers: string[]macroScale: numbermacroVariation: numberprovider: stringdiff --git a/sdk/etc/minigame.api.md b/sdk/etc/minigame.api.mdindex 329f64656..2eb142101 100644--- a/sdk/etc/minigame.api.md+++ b/sdk/etc/minigame.api.md@@ -7040,6 +7040,7 @@ layerColor0: ColorlayerColor1: ColorlayerColor2: ColorlayerColor3: Color+layers: string[]macroScale: numbermacroVariation: numberprovider: stringdiff --git a/sdk/etc/terrain.api.md b/sdk/etc/terrain.api.mdindex b7aaa8728..af1de18d1 100644--- a/sdk/etc/terrain.api.md+++ b/sdk/etc/terrain.api.md@@ -188,6 +188,7 @@ layerColor0: ColorlayerColor1: ColorlayerColor2: ColorlayerColor3: Color+layers: string[]macroScale: numbermacroVariation: numberprovider: stringdiff --git a/sdk/etc/wechat.api.md b/sdk/etc/wechat.api.mdindex 68d3211a9..666d98163 100644--- a/sdk/etc/wechat.api.md+++ b/sdk/etc/wechat.api.md@@ -6754,6 +6754,7 @@ layerColor0: ColorlayerColor1: ColorlayerColor2: ColorlayerColor3: Color+layers: string[]macroScale: numbermacroVariation: numberprovider: stringdiff --git a/sdk/src/terrain/layerArrays.ts b/sdk/src/terrain/layerArrays.tsnew file mode 100644index 000000000..12003ee2a--- /dev/null+++ b/sdk/src/terrain/layerArrays.ts@@ -0,0 +1,75 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file layerArrays.ts+ * @brief A ground's layer files (`.esterrainlayer`) read and packed into the texture arrays its shader samples.+ */+import type { App } from '../app/app';+import { Assets } from '../asset/AssetPlugin';+import { platformLoadImagePixels } from '../platform/base';+import { decodeImagePixels } from '../asset/imageDecode';+import { decodePngData } from '../asset/pngData';+import { isMiniGame } from '../platform';+import { createTextureArrayFromPixels } from '../runtime/runtimeAssets';+import { getResourceManager } from '../wasm/resourceManager';+import { TextureContent } from '../wasm';+import { log } from '../util/logger';+import { packLayers, type LayerImage, type LayerSource, type TerrainLayerDef } from './layers';++/** An image file's pixels exactly as stored (no premultiply, no colour conversion), by its project path or reference. */+export async function imagePixelsAt(app: App, path: string): Promise<{ width: number; height: number; pixels: Uint8Array; wide?: Uint16Array } | null> {+ if (!app.hasResource(Assets)) return null;+ const assets = app.getResource(Assets);+ try {+ // The bytes the asset layer would load, decoded unmodified (no premultiply, no colour conversion): a height is data.+ if (typeof createImageBitmap === 'function' && typeof Blob !== 'undefined') {+ const bytes = new Uint8Array(await assets.fetchBinary(path));+ return await decodePngData(bytes) ?? await decodeImagePixels(new Blob([bytes]));+ }+ const image = await platformLoadImagePixels(assets.resolveLoadPath(path));+ return { width: image.width, height: image.height, pixels: image.pixels };+ } catch (e) {+ log.warn('terrain', `reading ${path} failed`, e);+ return null;+ }+}++/** What a ground's layers came to: the albedo and normal arrays (engine texture handles) and how many world units a repeat of each layer covers. */+export interface LayerArrays {+ albedo: number;+ normal: number;+ tiles: number[];+}++/** Reads the layer files `refs` and packs them; null if the engine refuses the arrays. At most `most` layers are packed. */+export async function loadLayerArrays(app: App, refs: readonly string[], most: number): Promise<LayerArrays | null> {+ const assets = app.getResource(Assets);+ if (refs.length > most) log.warn('terrain', `a ground draws ${most} layers at most; it names ${refs.length}`);+ const sources: LayerSource[] = [];+ for (const ref of refs.slice(0, most)) {+ const def = await assets.load<TerrainLayerDef>('terrain-layer', ref);+ const image = async (path: string | undefined): Promise<LayerImage | null> => {+ if (!path) return null;+ const got = await imagePixelsAt(app, path);+ if (!got) log.warn('terrain', `the texture ${path} of terrain layer ${ref} could not be read`);+ return got;+ };+ sources.push({ def, albedo: await image(def.albedo), normal: await image(def.normal), mask: await image(def.mask) });+ }+ // A minigame's memory holds the layers at half the size.+ const packed = packLayers(sources, isMiniGame() ? 512 : 1024);+ const made = (layers: Uint8Array[], srgb: boolean): number => createTextureArrayFromPixels(app.wasmModule,+ { width: packed.size, height: packed.size, layers }, TextureContent.Retained, { filterMode: 'linear', wrapMode: 'repeat', mipmaps: true, srgb });+ const albedo = made(packed.albedo, true), normal = made(packed.normal, false);+ if (!albedo || !normal) {+ releaseLayerArrays([albedo, normal]);+ return null;+ }+ return { albedo, normal, tiles: packed.tiles };+}++/** Gives the engine back arrays made by {@link loadLayerArrays}. */+export function releaseLayerArrays(handles: readonly number[]): void {+ const rm = getResourceManager();+ for (const handle of handles) if (handle) rm?.releaseTexture(handle);+}diff --git a/sdk/src/terrain/planetPlugin.ts b/sdk/src/terrain/planetPlugin.tsindex bc290d372..af83ca0dc 100644--- a/sdk/src/terrain/planetPlugin.ts+++ b/sdk/src/terrain/planetPlugin.ts@@ -31,6 +31,7 @@ import { bakesOf } from '../runtime/bakes';import type { Color, Entity } from '../types';import { PageTable, PAGE_SIDE, PAGE_TEXELS, PATCH_CELLS, type PageImage } from './pages';import { buildPatchMesh } from './patch';+import { loadLayerArrays, releaseLayerArrays } from './layerArrays';import { removePlanetCollision, updatePlanetCollision } from './planetCollision';import { planetProvider, planetProvidersRevision, type PlanetProvider } from './planetProvider';import { makePlanetPage, type PlanetPageSource } from './planetPages';@@ -61,6 +62,8 @@ export interface PlanetData {collisionDistance: number;collisionLayer: number;friction: number;+ /** The terrain layers (`.esterrainlayer` files, up to four) the ground is drawn with, in the order the paint weighs them. Empty draws the four layer colours. */+ layers: string[];}const rgb = (r: number, g: number, b: number): Color => ({ r, g, b, a: 1 });@@ -73,7 +76,7 @@ const rgb = (r: number, g: number, b: number): Color => ({ r, g, b, a: 1 });export const Planet: ComponentDef<PlanetData> = defineComponent<PlanetData>('Planet', {radius: 4000, provider: '', world: '', generatorVersion: 1, seed: 1, cellSize: 1.5, detail: 1.5,layerColor0: rgb(0.28, 0.46, 0.2), layerColor1: rgb(0.45, 0.36, 0.24), layerColor2: rgb(0.93, 0.95, 0.98), layerColor3: rgb(0.4, 0.38, 0.36),- macroScale: 90, macroVariation: 0.35, collision: true, collisionDistance: 64, collisionLayer: 0, friction: 0.6,+ macroScale: 90, macroVariation: 0.35, collision: true, collisionDistance: 64, collisionLayer: 0, friction: 0.6, layers: [] as string[],}, {fields: {radius: { min: 1, category: 'Shape', tooltip: 'The planet\'s radius in metres. The planet stands at its entity, unrotated and unscaled.' },@@ -89,6 +92,7 @@ export const Planet: ComponentDef<PlanetData> = defineComponent<PlanetData>('PlalayerColor3: { label: 'Rock', category: 'Layers' },macroScale: { min: 1, category: 'Layers', tooltip: 'The size, in metres, of the ground\'s own wander in brightness.' },macroVariation: { min: 0, max: 1, step: 0.01, category: 'Layers', tooltip: 'How strongly the ground\'s brightness wanders.' },+ layers: { category: 'Layers', tooltip: 'The terrain layers (.esterrainlayer, up to four) the ground is drawn with, in the order the paint weighs them, each read on the planes of the world\'s axes. Empty draws the four layer colours.' },collision: { category: 'Collision', tooltip: 'Whether 3D bodies and characters collide with the ground: the finest tiles round each of them are built as collision geometry.' },collisionDistance: { min: 1, category: 'Collision', tooltip: 'How far round each moving body and character the ground is built for collision, in metres.' },collisionLayer: { min: 0, max: 15, step: 1, category: 'Collision', advanced: true, tooltip: 'The collision layer the ground is in (0 to 15).' },@@ -102,6 +106,8 @@ const ATLAS_SIZE = 2048;const MAX_LEVELS = 12;/** Pages asked at once of a provider that answers later. */const PAGES_IN_FLIGHT = 16;+/** The most layers a planet draws: one paint atlas of four weights. */+const MAX_LAYERS = 4;interface Built {signature: string;@@ -122,6 +128,10 @@ interface Built {asked: Set<string>;pending: boolean;failure: string | null;+ /** The layers' texture arrays, what they were packed from, and whether a packing is in hand. */+ arrays: number[];+ packed: string;+ packing: boolean;/** The registry's revision when the provider was last looked for, so a late registration is noticed. */providers: number;}@@ -192,7 +202,7 @@ export class PlanetPlugin implements Plugin {private make(signature: string, data: PlanetData, epoch: number): Built {const built: Built = {signature, data: { ...data }, provider: null, source: null, tree: null, epoch, table: new PageTable(ATLAS_SIZE),- heights: 0, paint: 0, mesh: 0, instance: 0, nodes: new Map(), spare: [], wanted: new Map(), asked: new Set(), pending: false, failure: null,+ heights: 0, paint: 0, mesh: 0, instance: 0, nodes: new Map(), spare: [], wanted: new Map(), asked: new Set(), pending: false, failure: null, arrays: [], packed: '', packing: false,providers: planetProvidersRevision(),};const provider = planetProvider(data.provider);@@ -320,6 +330,7 @@ export class PlanetPlugin implements Plugin {}}this.makePages(app, built, eye);+ this.pack(app, built);const set = (name: string, value: Parameters<typeof Material.setUniform>[2]): void => { Material.setUniform(built.instance, name, value); };set('u_planetCenter', { x: t.worldPosition.x, y: t.worldPosition.y, z: t.worldPosition.z, w: 0 });@@ -332,6 +343,44 @@ export class PlanetPlugin implements Plugin {this.place(app, entity, built, drawn);}+ /** Packs the layers into the arrays the material reads, when what they name changed: the ground keeps the arrays it has until the new ones are made. */+ private pack(app: App, built: Built): void {+ const refs = built.data.layers ?? [];+ if (refs.length === 0) {+ // Layers taken away: the colours draw the ground again.+ if (built.arrays.length > 0 && built.instance) Material.setUniform(built.instance, 'u_layerCount', 0);+ releaseLayerArrays(built.arrays);+ built.arrays = [];+ built.packed = '';+ return;+ }+ if (built.packing) return;+ const wanted = JSON.stringify(refs);+ if (wanted === built.packed) return;+ built.packing = true;+ const epoch = built.epoch;+ void (async () => {+ try {+ const got = await loadLayerArrays(app, refs, MAX_LAYERS);+ if (built.epoch !== epoch || !built.instance) { if (got) releaseLayerArrays([got.albedo, got.normal]); return; }+ if (!got) { log.warn('planet', 'the engine refused the planet layers\' texture arrays'); return; }+ releaseLayerArrays(built.arrays);+ built.arrays = [got.albedo, got.normal];+ const set = (name: string, value: Parameters<typeof Material.setUniform>[2]): void => { Material.setUniform(built.instance, name, value); };+ set('u_albedoLayers', Material.tex(got.albedo));+ set('u_normalLayers', Material.tex(got.normal));+ set('u_layerCount', got.tiles.length);+ const t = (i: number): number => got.tiles[i] ?? 4;+ set('u_tiles', { x: t(0), y: t(1), z: t(2), w: t(3) });+ } catch (e) {+ log.error('planet', 'packing the planet layers failed', e);+ } finally {+ built.packed = wanted;+ built.packing = false;+ }+ })();+ }+/** Makes the wanted pages, coarse and near first, for as long as the frame can spare. */private makePages(app: App, built: Built, eye: [number, number, number]): void {const bakes = bakesOf(app);@@ -442,6 +491,9 @@ export class PlanetPlugin implements Plugin {}if (built.instance) Material.release(built.instance);if (built.mesh && app.hasResource(Assets)) app.getResource(Assets).releaseBuiltMesh(built.mesh);+ releaseLayerArrays(built.arrays);+ built.arrays = [];+ built.packed = '';built.instance = built.mesh = built.heights = built.paint = 0;built.table.clear();}diff --git a/sdk/src/terrain/planetShader.ts b/sdk/src/terrain/planetShader.tsindex ebb390dca..95911969b 100644--- a/sdk/src/terrain/planetShader.ts+++ b/sdk/src/terrain/planetShader.ts@@ -23,6 +23,14 @@ const PLANET = `#pragma shader "Planet"#pragma param u_macroScale float default(90) range(1,100000) ui(slider)#pragma param u_macroVariation float default(0.35) range(0,1) ui(slider)#pragma param u_sharpness float default(1.6) range(1,8) ui(slider)+// The layers' textures, when the planet has any (the Planet component packs them: layerArrays.ts): albedo and normal, each layer read on the planes+// of the world's axes by how much the ground faces them, and how many world units a repeat of each covers. Without any, the layers are their colours.+#pragma param u_albedoLayers textureArray default(white)+#pragma param u_normalLayers textureArray default(white) texel(data)+#pragma param u_layerCount float default(0) range(0,4) ui(slider)+#pragma param u_tiles vec4 default(4,4,4,4)+// From the middle distance on, each layer is also read on a tile u_farScale times as wide and mixed in, so its repeat is lost far off.+#pragma param u_farScale float default(4.3) range(1,32) ui(slider)#pragma param u_roughness float default(0.92) range(0,1) ui(slider)// The ground in pages (pages.ts; the Planet component writes these): heights and normals, and the paint, in two atlases; the planet's radius, its centre// in the world, how many levels its tree has; level 0 drawn out to u_lodRange0, each level twice as far; u_terrainEye is the eye the nodes were chosen for,@@ -192,6 +200,7 @@ fn esMaterialVertex(local : ptr<function, vec3f>, localNormal : ptr<function, ve#pragma fragmentprecision highp float;+precision highp sampler2DArray;in vec4 v_color;in vec2 v_texCoord;@@ -226,6 +235,17 @@ vec3 pnB(int f) {if (f == 3) return vec3(0.0, 0.0, 1.0);return vec3(0.0, 1.0, 0.0);}+// A layer's albedo, with a wider read of it mixed in far off.+vec3 pnAlbedo(vec3 at, vec2 gx, vec2 gy, float far) {+ vec3 c = textureGrad(u_albedoLayers, at, gx, gy).rgb;+ if (far > 0.01) {+ float k = 1.0 / u_farScale;+ c = mix(c, textureGrad(u_albedoLayers, vec3(at.xy * k + 0.21, at.z), gx * k, gy * k).rgb, far);+ }+ return c;+}+// A texture's axis laid on the ground: the direction along the surface it points.+vec3 pnBend(vec3 axis, vec3 N) { return normalize(axis - N * dot(N, axis)); }// Value noise in three dimensions: a planet has no plane to lay a flat noise on.float pnHash(vec3 p) {p = fract(p * vec3(0.1031, 0.1030, 0.0973));@@ -260,7 +280,44 @@ void main() {w = pow(w, vec4(u_sharpness));w /= max(dot(w, vec4(1.0)), 1e-4);vec3 albedo = u_tint0.rgb * w.x + u_tint1.rgb * w.y + u_tint2.rgb * w.z + u_tint3.rgb * w.w;- vec3 q = (P - u_planetCenter.xyz) / u_macroScale;+ vec3 rel = P - u_planetCenter.xyz;+ if (u_layerCount > 0.5) {+ // Each layer on the three planes of the world's axes, those the ground faces by how much it does; the normal map's slope is laid back on the ground.+ vec3 dpx = dFdx(rel), dpy = dFdy(rel);+ vec3 axis = pow(abs(N), vec3(6.0));+ axis *= step(0.04 * dot(axis, vec3(1.0)), axis);+ axis /= max(dot(axis, vec3(1.0)), 1e-4);+ albedo = vec3(0.0);+ vec3 slope = vec3(0.0);+ float far = smoothstep(u_tiles.x * 6.0, u_tiles.x * 40.0, length(rel - u_terrainEye.xyz)) * 0.65;+ for (int i = 0; i < 4; i++) {+ if (w[i] <= 1e-3) continue;+ float tile = u_tiles[i];+ if (axis.y > 0.0) {+ vec3 at = vec3(rel.xz / tile, float(i));+ vec2 gx = dpx.xz / tile, gy = dpy.xz / tile;+ albedo += pnAlbedo(at, gx, gy, far) * (w[i] * axis.y);+ vec2 s = textureGrad(u_normalLayers, at, gx, gy).rg * 2.0 - 1.0;+ slope += (s.x * pnBend(vec3(1.0, 0.0, 0.0), N) + s.y * pnBend(vec3(0.0, 0.0, 1.0), N)) * (w[i] * axis.y);+ }+ if (axis.x > 0.0) {+ vec3 at = vec3(rel.zy / tile, float(i));+ vec2 gx = dpx.zy / tile, gy = dpy.zy / tile;+ albedo += pnAlbedo(at, gx, gy, far) * (w[i] * axis.x);+ vec2 s = textureGrad(u_normalLayers, at, gx, gy).rg * 2.0 - 1.0;+ slope += (s.x * pnBend(vec3(0.0, 0.0, 1.0), N) + s.y * pnBend(vec3(0.0, 1.0, 0.0), N)) * (w[i] * axis.x);+ }+ if (axis.z > 0.0) {+ vec3 at = vec3(rel.xy / tile, float(i));+ vec2 gx = dpx.xy / tile, gy = dpy.xy / tile;+ albedo += pnAlbedo(at, gx, gy, far) * (w[i] * axis.z);+ vec2 s = textureGrad(u_normalLayers, at, gx, gy).rg * 2.0 - 1.0;+ slope += (s.x * pnBend(vec3(1.0, 0.0, 0.0), N) + s.y * pnBend(vec3(0.0, 1.0, 0.0), N)) * (w[i] * axis.z);+ }+ }+ N = normalize(N + slope);+ }+ vec3 q = rel / u_macroScale;float broad = pnNoise(q) * 0.6 + pnNoise(q * 4.1 + 7.0) * 0.4;albedo *= mix(1.0, 0.7 + 0.6 * broad, u_macroVariation);@@ -287,6 +344,15 @@ fn pnB(f : i32) -> vec3f {if (f == 3) { return vec3f(0.0, 0.0, 1.0); }return vec3f(0.0, 1.0, 0.0);}+fn pnAlbedo(at : vec2f, layer : i32, gx : vec2f, gy : vec2f, far : f32) -> vec3f {+ var c = textureSampleGrad(u_albedoLayers, u_albedoLayers_s, at, layer, gx, gy).rgb;+ if (far > 0.01) {+ let k = 1.0 / mc.u_farScale;+ c = mix(c, textureSampleGrad(u_albedoLayers, u_albedoLayers_s, at * k + vec2f(0.21), layer, gx * k, gy * k).rgb, far);+ }+ return c;+}+fn pnBend(axis : vec3f, N : vec3f) -> vec3f { return normalize(axis - N * dot(N, axis)); }fn pnHash(p0 : vec3f) -> f32 {var p = fract(p0 * vec3f(0.1031, 0.1030, 0.0973));p = p + dot(p, p.yzx + 33.33);@@ -337,14 +403,55 @@ fn packNormal(n : vec3f) -> vec2f {let b = pnB(f);let eu = normalize(a - up * dot(a, up));let ev = normalize(b - up * dot(b, up));- let N = normalize(nl.x * eu + nl.y * up + nl.z * ev);+ let N0 = normalize(nl.x * eu + nl.y * up + nl.z * ev);var w = max(paint, vec4f(0.0));w = w / max(dot(w, vec4f(1.0)), 1e-4);w = pow(w, vec4f(mc.u_sharpness));w = w / max(dot(w, vec4f(1.0)), 1e-4);var albedo = mc.u_tint0.rgb * w.x + mc.u_tint1.rgb * w.y + mc.u_tint2.rgb * w.z + mc.u_tint3.rgb * w.w;- let q = (P - mc.u_planetCenter.xyz) / mc.u_macroScale;+ let rel = P - mc.u_planetCenter.xyz;+ var N = N0;+ let dpx = dpdx(rel);+ let dpy = dpdy(rel);+ if (mc.u_layerCount > 0.5) {+ var axis = pow(abs(N0), vec3f(6.0));+ axis = axis * step(vec3f(0.04 * dot(axis, vec3f(1.0))), axis);+ axis = axis / max(dot(axis, vec3f(1.0)), 1e-4);+ albedo = vec3f(0.0);+ var slope = vec3f(0.0);+ let far = smoothstep(mc.u_tiles.x * 6.0, mc.u_tiles.x * 40.0, length(rel - mc.u_terrainEye.xyz)) * 0.65;+ for (var i : i32 = 0; i < 4; i = i + 1) {+ if (w[i] <= 1e-3) { continue; }+ let tile = mc.u_tiles[i];+ if (axis.y > 0.0) {+ let at = rel.xz / tile;+ let gx = dpx.xz / tile;+ let gy = dpy.xz / tile;+ albedo = albedo + pnAlbedo(at, i, gx, gy, far) * (w[i] * axis.y);+ let s = textureSampleGrad(u_normalLayers, u_normalLayers_s, at, i, gx, gy).rg * 2.0 - vec2f(1.0);+ slope = slope + (s.x * pnBend(vec3f(1.0, 0.0, 0.0), N0) + s.y * pnBend(vec3f(0.0, 0.0, 1.0), N0)) * (w[i] * axis.y);+ }+ if (axis.x > 0.0) {+ let at = rel.zy / tile;+ let gx = dpx.zy / tile;+ let gy = dpy.zy / tile;+ albedo = albedo + pnAlbedo(at, i, gx, gy, far) * (w[i] * axis.x);+ let s = textureSampleGrad(u_normalLayers, u_normalLayers_s, at, i, gx, gy).rg * 2.0 - vec2f(1.0);+ slope = slope + (s.x * pnBend(vec3f(0.0, 0.0, 1.0), N0) + s.y * pnBend(vec3f(0.0, 1.0, 0.0), N0)) * (w[i] * axis.x);+ }+ if (axis.z > 0.0) {+ let at = rel.xy / tile;+ let gx = dpx.xy / tile;+ let gy = dpy.xy / tile;+ albedo = albedo + pnAlbedo(at, i, gx, gy, far) * (w[i] * axis.z);+ let s = textureSampleGrad(u_normalLayers, u_normalLayers_s, at, i, gx, gy).rg * 2.0 - vec2f(1.0);+ slope = slope + (s.x * pnBend(vec3f(1.0, 0.0, 0.0), N0) + s.y * pnBend(vec3f(0.0, 1.0, 0.0), N0)) * (w[i] * axis.z);+ }+ }+ N = normalize(N0 + slope);+ }+ let q = rel / mc.u_macroScale;let broad = pnNoise(q) * 0.6 + pnNoise(q * 4.1 + vec3f(7.0)) * 0.4;albedo = albedo * mix(1.0, 0.7 + 0.6 * broad, mc.u_macroVariation);diff --git a/sdk/src/terrain/terrainPlugin.ts b/sdk/src/terrain/terrainPlugin.tsindex 979eb0cfc..bbac93464 100644--- a/sdk/src/terrain/terrainPlugin.ts+++ b/sdk/src/terrain/terrainPlugin.ts@@ -52,6 +52,7 @@ import { TerrainSurface, TILE_CELLS, type SurfaceTile } from './surface';import { collisionGeometryOf } from '../runtime/collisionGeometry';import { chunksOf, ProceduralChunksRes } from '../residency/chunks';import { movers } from './movers';+import { imagePixelsAt } from './layerArrays';/** The engine's own provider of ground without end: seeded noise of the world's position. */export const NOISE_PROVIDER = 'estella:noise';@@ -666,21 +667,8 @@ export class TerrainPlugin implements Plugin {}/** An image file's pixels exactly as stored (no premultiply, no colour conversion), by its project path or reference. */- private async pixelsAt(app: App, path: string): Promise<{ width: number; height: number; pixels: Uint8Array; wide?: Uint16Array } | null> {- if (!app.hasResource(Assets)) return null;- const assets = app.getResource(Assets);- try {- // The bytes the asset layer would load, decoded unmodified (no premultiply, no colour conversion): a height is data.- if (typeof createImageBitmap === 'function' && typeof Blob !== 'undefined') {- const bytes = new Uint8Array(await assets.fetchBinary(path));- return await decodePngData(bytes) ?? await decodeImagePixels(new Blob([bytes]));- }- const image = await platformLoadImagePixels(assets.resolveLoadPath(path));- return { width: image.width, height: image.height, pixels: image.pixels };- } catch (e) {- log.warn('terrain', `reading ${path} failed`, e);- return null;- }+ private pixelsAt(app: App, path: string): ReturnType<typeof imagePixelsAt> {+ return imagePixelsAt(app, path);}/** The stock material: the Terrain shader, compiled once. */diff --git a/tools/releaseNotes.mjs b/tools/releaseNotes.mjsindex 1868e5184..aa4fc8e14 100644--- a/tools/releaseNotes.mjs+++ b/tools/releaseNotes.mjs@@ -2916,6 +2916,8 @@ export const NOTED = {{"note":"The editor's own eye shows the scene's post-processing."},"feat(terrain): the maths of ground on a cube sphere and the nodes drawn round an eye":{"internal":"The first layer of spherical terrain: pure maths and node selection, not yet drawn."},+ "feat(terrain): a planet's ground is drawn with the layers' textures":+ {"note":"A planet's ground has the layers' textures."},"feat(terrain): a planet's ground collides":{"note":"A planet's ground collides."},"fix(terrain): a planet's ground is one-sided and its fog is the ground's under it":