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
perf(terrain): ground reads the four layers that weigh most at a pixel, and Planet draws its layers with the same code - the layer blend (weights, hex tiling, far tile, side planes, height blend) is one GLSL and one WGSL text in layerSurfaceShader.ts that Terrain Layers and Planet both call, and one loader binds the arrays for both; a pixel keeps the four heaviest layers (Unreal's landscape caps the layers a component blends) and a layer not painted there costs no noise: the terrain-water lakeside's ground 3.04 -> 2.58 ms, with the plants off 4.24 -> 3.62, the frame unchanged to 0.04% of pixels; a planet's layer masks now darken the sky's light as a flat terrain's do, and its height blend, blend noise and hex tiling default to 0, which draws it as before
yhh0f99abf46f99
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 72fa48c67..934caa25d 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -16,6 +16,7 @@ published separately; it ships inside the editor.### Added+- **Terrain layers cost less, and a Planet draws its layers as a Terrain does.** A point of ground is drawn from the four layers with the most weight there, and a layer not painted there costs nothing: on the Terrain & Water example's lakeside view the ground's shading went from 3.0 to 2.6 ms at 1080p with the picture unchanged. The Planet shader now uses the same layer code as Terrain Layers, so a layer's mask (and its `occlusion`) darkens the sky's light on a planet too, and the Planet material gains `u_heightBlend`, `u_blendNoise` and `u_antiTile`, 0 by default, which draws a planet as before.- **Components carry the tick of their last write.** Each component pool keeps, beside every component, the tick at which it was last written, added or replaced, and the latest such tick of the pool. `Registry::patch<T>()` is mutable access that stamps the write, `markChanged<T>()` stamps a write made through a reference held from before, and adding or replacing a component stamps it; `get<T>()` stamps nothing. A reader asks `beginChangeRead()` for the tick it looks at, and next time `changedSince<T>(entity, tick)` and `anyChangedSince<T>(tick)` say what was written after that look, including what was written later in the same frame. Stamps travel with their components through a removal and a re-sort, and are kept within half the counter's range so none reads as new after the tick wraps. `Registry::setChangeAudit` (`World.setChangeAudit` from script) keeps a copy of every component each frame and reports each type written without a stamp, which is what a consumer of changes would never see; `render-submit-cost.mjs --audit` runs it on an example. Nothing reads the stamps yet: this is the ground for a renderer that walks only what changed, and the audit lists what still writes without saying so (an animated rig's bones, the platformer's and the 3D physics example's moving bodies).- **A playable opens on a start screen.** A single-file playable showed an empty page until its first frame: the engine inflated and compiled, the scene loaded, and with `quality.prewarmShaders` its shaders warmed, twenty-five seconds for one lake scene in a headless browser. It now carries the web export's start screen (the game's title, a bar, what the boot is doing), in markup that is on screen before any script runs, and announces the same `esengine:bootprogress` and `esengine:firstframe` events. `initPlayableRuntime` takes `onBeforeRun`, called once everything is loaded and warmed, and `prewarmShaders.onProgress`. A stretch of a boot nothing measures (shaders compiling, then a ground or a field still being made) runs a light along the bar and says which it is, where the bar used to sit still on "Ready"; a web export's start screen does the same.- **A terrain layer and a field of plants each say how much of the sky reaches them.** A `.esterrainlayer`'s `occlusion` (0 to 1) scales the occlusion its mask holds, and the Foliage material's `u_rootOcclusion` is the sky's light at a plant's root, rising to all of it at the tip. Both dim only the environment's light, as a material's ambient occlusion does; the sun and other lights are as they were. Left out (1), nothing changes. The terrain layer editor has the field.diff --git a/docs/astro/src/content/docs/graphics/terrain.mdx b/docs/astro/src/content/docs/graphics/terrain.mdxindex 579a532b4..d135071cc 100644--- a/docs/astro/src/content/docs/graphics/terrain.mdx+++ b/docs/astro/src/content/docs/graphics/terrain.mdx@@ -94,6 +94,9 @@ A layer seen from the side is read by height, so a cliff texture's beds lie leve`u_strataWarp` is how far they wander up and down, by slow noise `u_strataSpan` wide (0, the default, leaves them straight).`u_antiTileTurn` is how far round a cell of the no-repeat reading may be turned: a layer with a grain (sand in ripples) turned cell bycell is lit cell by cell and shows the hexagons, and 0 shifts the cells without turning them.+A point of ground is drawn from the four layers with the most weight there, as Unreal's landscape caps the layers a component+blends: a fifth is a sliver of the blend once the weights are sharpened, and reading all eight cost every pixel of ground the+textures of all eight.What an artist delivers, per layer: the three textures, square, a power of two (1024 is plenty; they are packed at the largestlayer's size, at most 1024, 512 on a minigame), tiling seamlessly, the normal and mask saved as data (not colour-managed). A layer's@@ -311,7 +314,7 @@ A planet answers the questions a round world puts to everything standing on it,A generated world can be laid out over a planet: put a `WorldGen` with `surface` set to Planet on the `Planet`'s entity. Each of the cube's six faces is laid out as a plane of metres by the same rules a flat world has (biomes over fields, recipes, layers), a direction is planned by the face it falls on, and what is placed is taken to the planet and stands along its up. The fields are the planet's own: the ground's height, its slope, noise read in three dimensions (so a field wanders over an edge between two faces with no seam), `paint.<layer>` for each of the planet's layers, and the fields the provider names with `fields` (an ecology). The biomes also paint the ground (`paintGround`), so what is drawn and what grows are one map. `seaLevel` is the height of the sea: lower ground is under water. Zones (`WorldZone`) stand at a position in the world and are kept on the face they fall on.-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. A planet's provider can hand the engine its generator as a module a worker can load (`workerSource`: the text of a self-contained module of plain JavaScript whose default export answers `sample`, `fields`, `versions` and `id`). The world is then laid out and the ground painted on worker threads, and the main thread only puts each answer in the world as it arrives; without it everything is done on the main thread as before.+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. The layers are drawn by the same code as the Terrain Layers shader, so a layer's mask darkens the sky's light on a planet as it does on flat ground (its `occlusion` too), and the Planet material has the same `u_heightBlend`, `u_blendNoise` and `u_antiTile`; they are 0 by default, which draws a planet as it was before they were there. Without layers the ground is the four colours. A planet's provider can hand the engine its generator as a module a worker can load (`workerSource`: the text of a self-contained module of plain JavaScript whose default export answers `sample`, `fields`, `versions` and `id`). The world is then laid out and the ground painted on worker threads, and the main thread only puts each answer in the world as it arrives; without it everything is done on the main thread as before.Set `sea` and the planet has a sea: a translucent, lit sphere at `seaLevel` above the radius, in which the ground that dips below it stands (waves and shore foam are the flat water's and come to the sphere later). The sky follows the horizon round: give `skyAtmosphere` and `heightFog` the planet's radius and centre and they work out the sky and the haze for the ground the camera stands on, with the sun a fixed direction, so a place's day and night are where it is on the planet.diff --git a/docs/astro/src/content/docs/zh-cn/graphics/terrain.mdx b/docs/astro/src/content/docs/zh-cn/graphics/terrain.mdxindex 759335674..603f1c21d 100644--- a/docs/astro/src/content/docs/zh-cn/graphics/terrain.mdx+++ b/docs/astro/src/content/docs/zh-cn/graphics/terrain.mdx@@ -67,7 +67,7 @@ description: 一个 Terrain 组件,用高度图或噪声生成地面,可以是| `heightBlend` | 可选。这一层自己的高度在与别的层相交处起多大作用:0 只按涂色混合(草到沙),1 按各层高度混合(石头从草里露出)。多层相遇时,每层按它在此处所占的比例计入。缺省则用材质的 `u_heightBlend`。 || `occlusion` | 可选,0 到 1。这一层能接收多少天空光,再乘上遮罩里的遮蔽(红色):长着植物的地面被植物挡住天空,比旁边裸露的岩石接收得少,和材质的环境遮蔽一样。太阳和其他灯光不受影响。缺省为 1:只按遮罩。 |-地面由 **Terrain Layers** 着色器(`builtin:terrain-layers`)绘制。每一层按世界位置铺设,近处去除重复,远处混入更大的平铺;层与层交界处遮罩高度更高的一层显露(草间露出石头、石缝里填着沙);坡面上同时从侧面投影,悬崖不会被拉伸。法线贴图和遮罩的遮蔽、粗糙度参与光照。材质控制效果:`u_sharpness`、`u_heightBlend`、`u_blendNoise`、`u_antiTile`、`u_farScale`、`u_macroVariation`、`u_triplanarFrom`(多陡开始读侧面)和 `u_wetLevel`/`u_wetBand`,含义同下文 Terrain 着色器。从侧面读的层按高度取样,所以崖壁贴图的岩层是水平的,而且沿整面墙笔直:`u_strataWarp` 是岩层上下起伏的幅度,由宽度为 `u_strataSpan` 的缓慢噪声决定(默认 0,保持笔直)。`u_antiTileTurn` 是去重复采样时每个格子最多旋转多少:有方向的层(带沙纹的沙)逐格旋转后会逐格受光、露出六边形,设为 0 则只平移不旋转。+地面由 **Terrain Layers** 着色器(`builtin:terrain-layers`)绘制。每一层按世界位置铺设,近处去除重复,远处混入更大的平铺;层与层交界处遮罩高度更高的一层显露(草间露出石头、石缝里填着沙);坡面上同时从侧面投影,悬崖不会被拉伸。法线贴图和遮罩的遮蔽、粗糙度参与光照。材质控制效果:`u_sharpness`、`u_heightBlend`、`u_blendNoise`、`u_antiTile`、`u_farScale`、`u_macroVariation`、`u_triplanarFrom`(多陡开始读侧面)和 `u_wetLevel`/`u_wetBand`,含义同下文 Terrain 着色器。从侧面读的层按高度取样,所以崖壁贴图的岩层是水平的,而且沿整面墙笔直:`u_strataWarp` 是岩层上下起伏的幅度,由宽度为 `u_strataSpan` 的缓慢噪声决定(默认 0,保持笔直)。`u_antiTileTurn` 是去重复采样时每个格子最多旋转多少:有方向的层(带沙纹的沙)逐格旋转后会逐格受光、露出六边形,设为 0 则只平移不旋转。每个地面点只读取在那里权重最大的四层,和 Unreal 地形限制一个组件混合的层数一样:权重锐化之后第五层只占混合里很小的一部分,而读全部八层,每个地面像素都要付八层贴图的读取开销。美术每层交付:三张贴图,正方形,边长为 2 的幂(1024 足够;打包时取最大一层的尺寸,最大 1024,小游戏上 512),四方连续,法线和遮罩按数据保存(不做色彩管理)。地形构建时各层贴图会打包成纹理数组,地形层文件或其贴图保存后会重新打包。@@ -228,7 +228,7 @@ registerPlanetProvider({生成的世界可以铺在星球上:在 `Planet` 所在的实体上放一个 `surface` 设为 Planet 的 `WorldGen`。立方体的六个面各按米制平面,用和平面世界一样的规则(字段之上的群落、配方、图层)铺设;一个方向由它落在的那个面来规划,放出来的东西被带到星球上,沿着当地的"上"站立。字段是星球自己的:地面高度、坡度、在三维里读的噪声(所以字段越过两个面之间的边没有接缝)、星球每个图层的 `paint.<层名>`,以及提供器用 `fields` 命名的字段(比如生态)。群落同时给地面上色(`paintGround`),画出来的和长出来的是同一张图。`seaLevel` 是海平面高度,比它低的地面在水下。区域(`WorldZone`)站在世界里的一个位置上,归它落在的那个面。-地面有碰撞:每个运动的 3D 刚体和角色在 `collisionDistance` 内的最细节点,会用画地面的同一批采样建成碰撞几何(`collision`、`collisionDistance`、`collisionLayer`、`friction`,和平面地形一样)。星球的变换只有位置:旋转或缩放过的星球,碰撞仍站在没旋转时的位置。`layers` 可以写最多四个 `.esterrainlayer` 文件,和平面地形一样;每层按地面朝向世界坐标轴的程度,在三个投影面上取样,远处混入更宽的一次取样,看不出重复。不写图层时地面就是四种颜色。星球的提供器可以把自己的生成器交给引擎,作为 worker 能加载的模块(`workerSource`:一段自包含的纯 JavaScript 模块文本,默认导出实现 `sample`、`fields`、`versions` 和 `id`)。这样世界的铺设和地面上色都在 worker 线程里完成,主线程只负责在结果到达时把它放进世界;不提供时一切仍在主线程上做。+地面有碰撞:每个运动的 3D 刚体和角色在 `collisionDistance` 内的最细节点,会用画地面的同一批采样建成碰撞几何(`collision`、`collisionDistance`、`collisionLayer`、`friction`,和平面地形一样)。星球的变换只有位置:旋转或缩放过的星球,碰撞仍站在没旋转时的位置。`layers` 可以写最多四个 `.esterrainlayer` 文件,和平面地形一样;每层按地面朝向世界坐标轴的程度,在三个投影面上取样,远处混入更宽的一次取样,看不出重复。图层和 Terrain Layers 着色器用的是同一份代码,所以图层的遮罩(以及它的 `occlusion`)在星球上同样压暗天空光,Planet 材质也有同样的 `u_heightBlend`、`u_blendNoise` 和 `u_antiTile`;它们默认为 0,星球画出来和加入它们之前一样。不写图层时地面就是四种颜色。星球的提供器可以把自己的生成器交给引擎,作为 worker 能加载的模块(`workerSource`:一段自包含的纯 JavaScript 模块文本,默认导出实现 `sample`、`fields`、`versions` 和 `id`)。这样世界的铺设和地面上色都在 worker 线程里完成,主线程只负责在结果到达时把它放进世界;不提供时一切仍在主线程上做。设置 `sea` 星球就有海:一个半透明、受光的球面,高出半径 `seaLevel`,低于它的地面站在水里(波浪和岸边泡沫是平面水体的,之后会来到球面)。天空跟着地平线转:给 `skyAtmosphere` 和 `heightFog` 填上星球的半径和中心,它们就按相机站着的那片地面算天空和雾,太阳是固定方向,所以一个地方的昼夜取决于它在星球上的位置。diff --git a/fixtures/scenes/planet-layers.esscene b/fixtures/scenes/planet-layers.esscenenew file mode 100644index 000000000..9f754c958--- /dev/null+++ b/fixtures/scenes/planet-layers.esscene@@ -0,0 +1,151 @@+{+ "version": 4,+ "name": "planet-layers",+ "entities": [+ {+ "id": 0,+ "name": "Camera",+ "parent": null,+ "children": [],+ "visible": true,+ "components": [+ {+ "type": "Transform",+ "data": {+ "position": {+ "x": 0,+ "y": 40,+ "z": 0+ },+ "rotation": {+ "x": -0.7071068,+ "y": 0,+ "z": 0,+ "w": 0.7071068+ }+ }+ },+ {+ "type": "Camera",+ "data": {+ "projectionType": 1,+ "orthoSize": 12,+ "nearPlane": 0.1,+ "farPlane": 200,+ "isActive": true,+ "clearFlags": 3+ }+ }+ ]+ },+ {+ "id": 1,+ "name": "Sky",+ "parent": null,+ "children": [],+ "visible": true,+ "components": [+ {+ "type": "Transform",+ "data": {}+ },+ {+ "type": "Light",+ "data": {+ "type": 2,+ "color": {+ "r": 1,+ "g": 1,+ "b": 1,+ "a": 1+ },+ "intensity": 1,+ "enabled": true+ }+ }+ ]+ },+ {+ "id": 2,+ "name": "Colours",+ "parent": null,+ "children": [],+ "visible": true,+ "components": [+ {+ "type": "Transform",+ "data": {+ "position": {+ "x": -4.8,+ "y": 0,+ "z": 0+ },+ "scale": {+ "x": 0.08,+ "y": 0.01,+ "z": 0.08+ }+ }+ },+ {+ "type": "MeshRenderer",+ "data": {+ "mesh": "builtin:cube",+ "material": "/scenes/planet-layers/colours.esmaterial",+ "color": {+ "r": 1,+ "g": 1,+ "b": 1,+ "a": 1+ },+ "lit": true,+ "opaque": true,+ "cullBackfaces": true,+ "enabled": true+ }+ }+ ]+ },+ {+ "id": 3,+ "name": "Layers",+ "parent": null,+ "children": [],+ "visible": true,+ "components": [+ {+ "type": "Transform",+ "data": {+ "position": {+ "x": 4.8,+ "y": 0,+ "z": 0+ },+ "scale": {+ "x": 0.08,+ "y": 0.01,+ "z": 0.08+ }+ }+ },+ {+ "type": "MeshRenderer",+ "data": {+ "mesh": "builtin:cube",+ "material": "/scenes/planet-layers/layers.esmaterial",+ "color": {+ "r": 1,+ "g": 1,+ "b": 1,+ "a": 1+ },+ "lit": true,+ "opaque": true,+ "cullBackfaces": true,+ "enabled": true+ }+ }+ ]+ }+ ]+}\ No newline at end of filediff --git a/fixtures/scenes/planet-layers/colours.esmaterial b/fixtures/scenes/planet-layers/colours.esmaterialnew file mode 100644index 000000000..1f67a5bff--- /dev/null+++ b/fixtures/scenes/planet-layers/colours.esmaterial@@ -0,0 +1,42 @@+{+ "version": "1.0",+ "type": "material",+ "shader": "builtin:planet",+ "blendMode": 9,+ "depthTest": true,+ "depthWrite": true,+ "cull": 0,+ "properties": {+ "u_macroVariation": 0,+ "u_planetCenter": {+ "x": -1000,+ "y": 0,+ "z": 0,+ "w": 0+ },+ "u_tint0": {+ "r": 0.5,+ "g": 0.5,+ "b": 0.5,+ "a": 1+ },+ "u_tint1": {+ "r": 0.5,+ "g": 0.5,+ "b": 0.5,+ "a": 1+ },+ "u_tint2": {+ "r": 0.5,+ "g": 0.5,+ "b": 0.5,+ "a": 1+ },+ "u_tint3": {+ "r": 0.5,+ "g": 0.5,+ "b": 0.5,+ "a": 1+ }+ }+}\ No newline at end of filediff --git a/fixtures/scenes/planet-layers/layers.esmaterial b/fixtures/scenes/planet-layers/layers.esmaterialnew file mode 100644index 000000000..8586503b6--- /dev/null+++ b/fixtures/scenes/planet-layers/layers.esmaterial@@ -0,0 +1,43 @@+{+ "version": "1.0",+ "type": "material",+ "shader": "builtin:planet",+ "blendMode": 9,+ "depthTest": true,+ "depthWrite": true,+ "cull": 0,+ "properties": {+ "u_macroVariation": 0,+ "u_planetCenter": {+ "x": -1000,+ "y": 0,+ "z": 0,+ "w": 0+ },+ "u_tint0": {+ "r": 0.5,+ "g": 0.5,+ "b": 0.5,+ "a": 1+ },+ "u_tint1": {+ "r": 0.5,+ "g": 0.5,+ "b": 0.5,+ "a": 1+ },+ "u_tint2": {+ "r": 0.5,+ "g": 0.5,+ "b": 0.5,+ "a": 1+ },+ "u_tint3": {+ "r": 0.5,+ "g": 0.5,+ "b": 0.5,+ "a": 1+ },+ "u_layerCount": 1+ }+}\ No newline at end of filediff --git a/sdk/src/terrain/layerArrays.ts b/sdk/src/terrain/layerArrays.tsindex 71296fea3..4cda56871 100644--- a/sdk/src/terrain/layerArrays.ts+++ b/sdk/src/terrain/layerArrays.ts@@ -15,6 +15,7 @@ import { createTextureArrayFromPixels } from '../runtime/runtimeAssets';import { getResourceManager, provideTextureContent, withdrawTextureContent } from '../wasm/resourceManager';import { TextureContent } from '../wasm';import { log } from '../util/logger';+import { Material } from '../render/material';import { packLayers, type LayerImage, type LayerSource, type PackedLayers, type TerrainLayerDef } from './layers';/** An image file's pixels exactly as stored (no premultiply, no colour conversion), by its project path or reference. */@@ -37,13 +38,6 @@ export async function imagePixelsAt(app: App, path: string): Promise<{ width: nu}}-/** 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` (at most `most`) and packs them, at half the size on a minigame, whose memory is smaller. */export async function readAndPackLayers(app: App, refs: readonly string[], most: number): Promise<PackedLayers> {const assets = app.getResource(Assets);@@ -98,11 +92,29 @@ export function createLayerArrays(app: App, packed: PackedLayers, kinds: readonlreturn handles;}-/** 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> {+/**+ * Reads the layer files `refs` (at most `most`), packs them into the albedo, normal and mask arrays, and hands them to the material+ * `instance` with what the shared layer code reads of them (layerSurfaceShader.ts: the count, each layer's tile and height blend). The+ * arrays made, for {@link releaseLayerArrays}; null if the engine refused one. `still` is asked once the packing is done: false, and+ * nothing is kept (the ground was made again meanwhile).+ */+export async function loadLayersInto(app: App, instance: number, refs: readonly string[], most: number, still: () => boolean): Promise<number[] | null> {const packed = await readAndPackLayers(app, refs, most);- const made = createLayerArrays(app, packed, ['albedo', 'normal'], () => readAndPackLayers(app, refs, most));- return made ? { albedo: made[0]!, normal: made[1]!, tiles: packed.tiles } : null;+ if (!still()) return null;+ const arrays = createLayerArrays(app, packed, ['albedo', 'normal', 'mask'], () => readAndPackLayers(app, refs, most));+ if (!arrays) return null;+ const set = (name: string, value: Parameters<typeof Material.setUniform>[2]): void => { Material.setUniform(instance, name, value); };+ set('u_albedoLayers', Material.tex(arrays[0]!));+ set('u_normalLayers', Material.tex(arrays[1]!));+ set('u_maskLayers', Material.tex(arrays[2]!));+ set('u_layerCount', packed.tiles.length);+ 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) });+ return arrays;}/** Gives the engine back arrays made by {@link createLayerArrays}. */diff --git a/sdk/src/terrain/layerSurfaceShader.ts b/sdk/src/terrain/layerSurfaceShader.tsnew file mode 100644index 000000000..4d1c2b44e--- /dev/null+++ b/sdk/src/terrain/layerSurfaceShader.ts@@ -0,0 +1,372 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file layerSurfaceShader.ts+ * @brief The ground's layers as one piece of shader code, shared by every shader that draws ground from layer files (Terrain Layers, Planet).+ *+ * What a pixel of ground is made of, from its paint: each layer's weight (broken up by noise of its own and sharpened), the layers read+ * without repeat near the eye and on a wider tile far off, projected on the planes the ground faces, then blended by the layers' heights.+ * Only the four layers with the most weight at a pixel are read: past four the rest are a sliver of the blend, and reading all eight cost+ * every pixel of ground the textures of all eight, as Unreal's landscape caps the layers a component weighs.+ *+ * A shader that uses it declares the params `layerParams` writes (its own defaults keep its own look), puts `LAYER_SURFACE_GLSL` /+ * `LAYER_SURFACE_WGSL` in its fragment, and calls `tnLayers`. The vertex stage and the lighting stay the shader's own.+ */++/** The defaults a shader gives the shared params: how a ground drawn with it looks before a material says otherwise. */+export interface LayerParamDefaults {+ sharpness: number;+ heightBlend: number;+ blendNoise: number;+ antiTile: number;+}++/** The `#pragma param` lines of the layers, with this shader's defaults. */+export function layerParams(d: LayerParamDefaults): string {+ return `#pragma param u_albedoLayers textureArray default(white)+#pragma param u_normalLayers textureArray default(flatnormal) texel(data)+#pragma param u_maskLayers textureArray default(white) texel(data)+// How many layers there are, and how many world units one repeat of each covers (layers 1 to 4, then 5 to 8).+#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 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(${d.sharpness}) 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+// way, and sand fills the low places between stones. 0 is a plain blend of the weights.+#pragma param u_heightBlend float default(${d.heightBlend}) range(0,1) ui(slider)+// How much each layer's weight is broken up by slow noise of its own before the strongest wins.+#pragma param u_blendNoise float default(${d.blendNoise}) range(0,1) ui(slider)+// 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)+// How strongly each layer is read without repeat near the eye (hex tiling), so no tile is seen.+#pragma param u_antiTile float default(${d.antiTile}) range(0,1) ui(slider)+// How far round a cell may be turned (1 any way, 0 shifted only): a layer with a grain, sand in ripples or rock in beds, turned cell by+// cell is lit cell by cell, and shows the hexagons.+#pragma param u_antiTileTurn float default(1) range(0,1) ui(slider)+`;+}++/** The layers in GLSL: helpers, then `tnLayers`. Needs `precision highp sampler2DArray`. */+export const LAYER_SURFACE_GLSL = `float tnHash(vec2 p) {+ p = fract(p * vec2(0.1031, 0.1030));+ p += dot(p, p.yx + 33.33);+ return fract((p.x + p.y) * p.x);+}+float tnNoise(vec2 p) {+ vec2 i = floor(p), f = fract(p);+ f = f * f * (3.0 - 2.0 * f);+ return mix(mix(tnHash(i), tnHash(i + vec2(1.0, 0.0)), f.x), mix(tnHash(i + vec2(0.0, 1.0)), tnHash(i + vec2(1.0, 1.0)), f.x), f.y);+}+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; };+TnTap tnPlain(vec2 uv, float layer, vec2 gx, vec2 gy) {+ vec3 at = vec3(uv, layer);+ TnTap t;+ t.albedo = textureGrad(u_albedoLayers, at, gx, gy).rgb;+ t.slope = textureGrad(u_normalLayers, at, gx, gy).rg * 2.0 - 1.0;+ t.mask = textureGrad(u_maskLayers, at, gx, gy).rgb;+ return t;+}+// The same in one hex cell: shifted and turned by the cell's random numbers; the normal's slope turned back with it.+TnTap tnHexTap(vec2 uv, float layer, vec2 cell, vec2 gx, vec2 gy) {+ vec2 r = tnHash2(cell);+ float a = r.x * 6.2831853 * u_antiTileTurn;+ mat2 turn = mat2(cos(a), -sin(a), sin(a), cos(a));+ TnTap t = tnPlain(turn * uv + r, layer, turn * gx, turn * gy);+ t.slope = t.slope * turn;+ return t;+}+// A layer read without repeat (hex tiling, Mikkelsen 2022): three cells about a point blended by nearness, the higher reading winning.+TnTap tnHex(vec2 uv, float layer, vec2 gx, vec2 gy, float strength) {+ vec2 skewed = mat2(1.0, 0.0, -0.57735027, 1.15470054) * (uv * 3.4641016);+ vec2 base = floor(skewed);+ vec3 f = vec3(fract(skewed), 0.0);+ f.z = 1.0 - f.x - f.y;+ float s = step(0.0, -f.z), s2 = 2.0 * s - 1.0;+ vec3 w = vec3(-f.z * s2, s - f.y * s2, s - f.x * s2);+ TnTap c1 = tnHexTap(uv, layer, base + vec2(s, s), gx, gy);+ TnTap c2 = tnHexTap(uv, layer, base + vec2(s, 1.0 - s), gx, gy);+ TnTap c3 = tnHexTap(uv, layer, base + vec2(1.0 - s, s), gx, gy);+ vec3 h = vec3(c1.mask.b, c2.mask.b, c3.mask.b);+ w = pow(max(w * mix(vec3(1.0), 0.4 + h, strength), vec3(1e-4)), vec3(7.0));+ w /= dot(w, vec3(1.0));+ TnTap t;+ t.albedo = c1.albedo * w.x + c2.albedo * w.y + c3.albedo * w.z;+ t.slope = c1.slope * w.x + c2.slope * w.y + c3.slope * w.z;+ t.mask = c1.mask * w.x + c2.mask * w.y + c3.mask * w.z;+ return t;+}+// A tangent normal's slope laid on a plane whose texture runs along T and B, about the surface's normal N.+vec3 tnBend(vec2 slope, vec3 T, vec3 B, vec3 N) {+ T = normalize(T - N * dot(N, T));+ B = normalize(B - N * dot(N, B));+ return slope.x * T + slope.y * B;+}+// How strongly the layers are read without repeat (x) and how much of the wide tile is mixed in (y), at this distance from the eye.+vec2 tnNearFar(float eye) {+ float scale = tnTile(0);+ return vec2((1.0 - smoothstep(scale * 20.0, scale * 45.0, eye)) * u_antiTile, smoothstep(scale * 6.0, scale * 40.0, eye) * 0.65);+}++// What the layers make of a pixel: its colour, the slope its normal maps add, and its mask (occlusion, roughness, height).+struct TnSurface { vec3 albedo; vec3 slope; vec3 mask; };+// paintA / paintB: the weights of layers 1 to 4 and 5 to 8. at: where the ground is, as its layers are laid (the top plane reads at.xz,+// the sides (at.z, at.y) and (at.x, at.y)); dpx / dpy its gradients across the screen. N: the ground's normal. planes: how much of each+// plane is read (x, top, z). nearFar: tnNearFar.+TnSurface tnLayers(vec4 paintA, vec4 paintB, vec3 at, vec3 dpx, vec3 dpy, vec3 N, vec3 planes, vec2 nearFar) {+ int count = int(u_layerCount + 0.5);+ // Each painted layer's say, broken up 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. The four with+ // the most say are kept, heaviest first.+ vec4 wt = vec4(0.0);+ ivec4 id = ivec4(0);+ float sum = 0.0;+ for (int i = 0; i < 8; i++) {+ if (i >= count) break;+ float raw = i < 4 ? paintA[i] : paintB[i - 4];+ if (raw <= 0.0) continue;+ float tileSize = tnTile(i);+ float wander = tnNoise(at.xz / (tileSize * 2.3) + float(i) * 11.0 + 3.0) * 0.5+ + tnNoise(at.xz / (tileSize * 0.45) + float(i) * 7.0 + 17.0) * 0.3+ + tnNoise(at.xz / (tileSize * 0.11) + float(i) * 5.0 + 29.0) * 0.2;+ float v = raw * mix(1.0, 0.35 + 1.3 * wander, u_blendNoise);+ sum += v;+ if (v > wt.w) {+ if (v > wt.x) { wt = vec4(v, wt.xyz); id = ivec4(i, id.xyz); }+ else if (v > wt.y) { wt = vec4(wt.x, v, wt.yz); id = ivec4(id.x, i, id.yz); }+ else if (v > wt.z) { wt = vec4(wt.xy, v, wt.z); id = ivec4(id.xy, i, id.z); }+ else { wt.w = v; id.w = i; }+ }+ }+ wt = pow(wt / max(sum, 1e-4), vec4(u_sharpness));+ wt /= max(dot(wt, vec4(1.0)), 1e-4);++ vec3 albedo[4];+ vec3 bend[4];+ vec3 mask[4];+ for (int k = 0; k < 4; k++) {+ albedo[k] = vec3(0.0); bend[k] = vec3(0.0); mask[k] = vec3(1.0, 1.0, 0.0);+ if (wt[k] <= 1e-3) continue;+ int i = id[k];+ float layer = float(i), tile = tnTile(i);+ if (planes.y > 0.0) {+ // WebGL takes no ?: between structures.+ TnTap top;+ if (nearFar.x > 0.01) top = tnHex(at.xz / tile, layer, dpx.xz / tile, dpy.xz / tile, nearFar.x);+ else top = tnPlain(at.xz / tile, layer, dpx.xz / tile, dpy.xz / tile);+ if (nearFar.y > 0.01) {+ float big = tile * u_farScale;+ TnTap wide = tnPlain(at.xz / big + 0.21, layer, dpx.xz / big, dpy.xz / big);+ top.albedo = mix(top.albedo, wide.albedo, nearFar.y);+ top.mask = mix(top.mask, wide.mask, nearFar.y);+ }+ albedo[k] = top.albedo * planes.y;+ mask[k] = top.mask * planes.y;+ bend[k] = tnBend(top.slope, vec3(1.0, 0.0, 0.0), vec3(0.0, 0.0, 1.0), N) * planes.y;+ } else {+ mask[k] = vec3(0.0);+ }+ if (planes.x > 0.02) {+ TnTap x = tnPlain(at.zy / tile, layer, dpx.zy / tile, dpy.zy / tile);+ albedo[k] += x.albedo * planes.x; mask[k] += x.mask * planes.x;+ bend[k] += tnBend(x.slope, vec3(0.0, 0.0, 1.0), vec3(0.0, 1.0, 0.0), N) * planes.x;+ }+ if (planes.z > 0.02) {+ TnTap z = tnPlain(at.xy / tile, layer, dpx.xy / tile, dpy.xy / tile);+ albedo[k] += z.albedo * planes.z; mask[k] += z.mask * planes.z;+ bend[k] += tnBend(z.slope, vec3(1.0, 0.0, 0.0), vec3(0.0, 1.0, 0.0), N) * planes.z;+ }+ }+ // Then by height: each layer stands as high as its mask says, and where two meet the higher one shows. How much height decides is+ // 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 top = -1.0;+ for (int k = 0; k < 4; k++) if (wt[k] > 1e-3) top = max(top, mask[k].b + wt[k] * 1.5);+ float hsum = 0.0, byHeight = 0.0;+ vec4 hw = vec4(0.0);+ for (int k = 0; k < 4; k++) {+ if (wt[k] <= 1e-3) continue;+ hw[k] = max(mask[k].b + wt[k] * 1.5 - (top - 0.35), 0.0);+ hsum += hw[k];+ byHeight += wt[k] * tnHeightBlend(id[k]);+ }+ TnSurface s;+ s.albedo = vec3(0.0); s.slope = vec3(0.0); s.mask = vec3(0.0);+ for (int k = 0; k < 4; k++) {+ float f = mix(wt[k], hw[k] / max(hsum, 1e-4), byHeight);+ s.albedo += albedo[k] * f; s.slope += bend[k] * f; s.mask += mask[k] * f;+ }+ return s;+}+`;++/** The same in WGSL, under the engine's conventions (params as `mc.<name>`, textures with their `_s` samplers). */+export const LAYER_SURFACE_WGSL = `fn tnHash(p0 : vec2f) -> f32 {+ var p = fract(p0 * vec2f(0.1031, 0.1030));+ p = p + dot(p, p.yx + 33.33);+ return fract((p.x + p.y) * p.x);+}+fn tnNoise(p : vec2f) -> f32 {+ let i = floor(p);+ var f = fract(p);+ f = f * f * (3.0 - 2.0 * f);+ return mix(mix(tnHash(i), tnHash(i + vec2f(1.0, 0.0)), f.x), mix(tnHash(i + vec2f(0.0, 1.0)), tnHash(i + vec2f(1.0, 1.0)), f.x), f.y);+}+fn tnHash2(p : vec2f) -> vec2f {+ return fract(sin(vec2f(dot(p, vec2f(127.1, 311.7)), dot(p, vec2f(269.5, 183.3)))) * 43758.5453);+}+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;+ t.albedo = textureSampleGrad(u_albedoLayers, u_albedoLayers_s, uv, layer, gx, gy).rgb;+ t.slope = textureSampleGrad(u_normalLayers, u_normalLayers_s, uv, layer, gx, gy).rg * 2.0 - vec2f(1.0);+ t.mask = textureSampleGrad(u_maskLayers, u_maskLayers_s, uv, layer, gx, gy).rgb;+ return t;+}+fn tnHexTap(uv : vec2f, layer : i32, cell : vec2f, gx : vec2f, gy : vec2f) -> TnTap {+ let r = tnHash2(cell);+ let a = r.x * 6.2831853 * mc.u_antiTileTurn;+ let turn = mat2x2f(cos(a), -sin(a), sin(a), cos(a));+ var t = tnPlain(turn * uv + r, layer, turn * gx, turn * gy);+ t.slope = t.slope * turn;+ return t;+}+fn tnHex(uv : vec2f, layer : i32, gx : vec2f, gy : vec2f, strength : f32) -> TnTap {+ let skewed = mat2x2f(1.0, 0.0, -0.57735027, 1.15470054) * (uv * 3.4641016);+ let base = floor(skewed);+ let fr = fract(skewed);+ let fz = 1.0 - fr.x - fr.y;+ let s = step(0.0, -fz);+ let s2 = 2.0 * s - 1.0;+ var w = vec3f(-fz * s2, s - fr.y * s2, s - fr.x * s2);+ let c1 = tnHexTap(uv, layer, base + vec2f(s, s), gx, gy);+ let c2 = tnHexTap(uv, layer, base + vec2f(s, 1.0 - s), gx, gy);+ let c3 = tnHexTap(uv, layer, base + vec2f(1.0 - s, s), gx, gy);+ let h = vec3f(c1.mask.b, c2.mask.b, c3.mask.b);+ w = pow(max(w * mix(vec3f(1.0), vec3f(0.4) + h, vec3f(strength)), vec3f(1e-4)), vec3f(7.0));+ w = w / dot(w, vec3f(1.0));+ var t : TnTap;+ t.albedo = c1.albedo * w.x + c2.albedo * w.y + c3.albedo * w.z;+ t.slope = c1.slope * w.x + c2.slope * w.y + c3.slope * w.z;+ t.mask = c1.mask * w.x + c2.mask * w.y + c3.mask * w.z;+ return t;+}+fn tnBend(slope : vec2f, T0 : vec3f, B0 : vec3f, N : vec3f) -> vec3f {+ let T = normalize(T0 - N * dot(N, T0));+ let B = normalize(B0 - N * dot(N, B0));+ return slope.x * T + slope.y * B;+}+fn tnNearFar(eye : f32) -> vec2f {+ let scale = tnTile(0);+ return vec2f((1.0 - smoothstep(scale * 20.0, scale * 45.0, eye)) * mc.u_antiTile, smoothstep(scale * 6.0, scale * 40.0, eye) * 0.65);+}+struct TnSurface { albedo : vec3f, slope : vec3f, mask : vec3f };+fn tnLayers(paintA : vec4f, paintB : vec4f, at : vec3f, dpx : vec3f, dpy : vec3f, N : vec3f, planes : vec3f, nearFar : vec2f) -> TnSurface {+ let count = i32(mc.u_layerCount + 0.5);+ var wt = vec4f(0.0);+ var id = vec4i(0);+ var sum = 0.0;+ for (var i = 0; i < 8; i = i + 1) {+ if (i >= count) { break; }+ var raw = 0.0;+ if (i < 4) { raw = paintA[i]; } else { raw = paintB[i - 4]; }+ if (raw <= 0.0) { continue; }+ let tileSize = tnTile(i);+ let wander = tnNoise(at.xz / (tileSize * 2.3) + vec2f(f32(i) * 11.0 + 3.0)) * 0.5+ + tnNoise(at.xz / (tileSize * 0.45) + vec2f(f32(i) * 7.0 + 17.0)) * 0.3+ + tnNoise(at.xz / (tileSize * 0.11) + vec2f(f32(i) * 5.0 + 29.0)) * 0.2;+ let v = raw * mix(1.0, 0.35 + 1.3 * wander, mc.u_blendNoise);+ sum = sum + v;+ if (v > wt.w) {+ if (v > wt.x) { wt = vec4f(v, wt.xyz); id = vec4i(i, id.xyz); }+ else if (v > wt.y) { wt = vec4f(wt.x, v, wt.yz); id = vec4i(id.x, i, id.yz); }+ else if (v > wt.z) { wt = vec4f(wt.xy, v, wt.z); id = vec4i(id.xy, i, id.z); }+ else { wt.w = v; id.w = i; }+ }+ }+ wt = pow(wt / max(sum, 1e-4), vec4f(mc.u_sharpness));+ wt = wt / max(dot(wt, vec4f(1.0)), 1e-4);++ var albedo : array<vec3f, 4>;+ var bend : array<vec3f, 4>;+ var mask : array<vec3f, 4>;+ for (var k = 0; k < 4; k = k + 1) {+ albedo[k] = vec3f(0.0);+ bend[k] = vec3f(0.0);+ mask[k] = vec3f(1.0, 1.0, 0.0);+ if (wt[k] <= 1e-3) { continue; }+ let i = id[k];+ let tile = tnTile(i);+ if (planes.y > 0.0) {+ var top : TnTap;+ if (nearFar.x > 0.01) { top = tnHex(at.xz / tile, i, dpx.xz / tile, dpy.xz / tile, nearFar.x); }+ else { top = tnPlain(at.xz / tile, i, dpx.xz / tile, dpy.xz / tile); }+ if (nearFar.y > 0.01) {+ let big = tile * mc.u_farScale;+ let wide = tnPlain(at.xz / big + vec2f(0.21), i, dpx.xz / big, dpy.xz / big);+ top.albedo = mix(top.albedo, wide.albedo, vec3f(nearFar.y));+ top.mask = mix(top.mask, wide.mask, vec3f(nearFar.y));+ }+ albedo[k] = top.albedo * planes.y;+ mask[k] = top.mask * planes.y;+ bend[k] = tnBend(top.slope, vec3f(1.0, 0.0, 0.0), vec3f(0.0, 0.0, 1.0), N) * planes.y;+ } else {+ mask[k] = vec3f(0.0);+ }+ if (planes.x > 0.02) {+ let x = tnPlain(at.zy / tile, i, dpx.zy / tile, dpy.zy / tile);+ albedo[k] = albedo[k] + x.albedo * planes.x;+ mask[k] = mask[k] + x.mask * planes.x;+ bend[k] = bend[k] + tnBend(x.slope, vec3f(0.0, 0.0, 1.0), vec3f(0.0, 1.0, 0.0), N) * planes.x;+ }+ if (planes.z > 0.02) {+ let z = tnPlain(at.xy / tile, i, dpx.xy / tile, dpy.xy / tile);+ albedo[k] = albedo[k] + z.albedo * planes.z;+ mask[k] = mask[k] + z.mask * planes.z;+ bend[k] = bend[k] + tnBend(z.slope, vec3f(1.0, 0.0, 0.0), vec3f(0.0, 1.0, 0.0), N) * planes.z;+ }+ }+ var top = -1.0;+ for (var k = 0; k < 4; k = k + 1) { if (wt[k] > 1e-3) { top = max(top, mask[k].b + wt[k] * 1.5); } }+ var hsum = 0.0;+ var byHeight = 0.0;+ var hw = vec4f(0.0);+ for (var k = 0; k < 4; k = k + 1) {+ if (wt[k] <= 1e-3) { continue; }+ hw[k] = max(mask[k].b + wt[k] * 1.5 - (top - 0.35), 0.0);+ hsum = hsum + hw[k];+ byHeight = byHeight + wt[k] * tnHeightBlend(id[k]);+ }+ var s : TnSurface;+ s.albedo = vec3f(0.0);+ s.slope = vec3f(0.0);+ s.mask = vec3f(0.0);+ for (var k = 0; k < 4; k = k + 1) {+ let f = mix(wt[k], hw[k] / max(hsum, 1e-4), byHeight);+ s.albedo = s.albedo + albedo[k] * f;+ s.slope = s.slope + bend[k] * f;+ s.mask = s.mask + mask[k] * f;+ }+ return s;+}+`;diff --git a/sdk/src/terrain/planetPlugin.ts b/sdk/src/terrain/planetPlugin.tsindex d1739858f..b4c567bd8 100644--- a/sdk/src/terrain/planetPlugin.ts+++ b/sdk/src/terrain/planetPlugin.ts@@ -31,7 +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 { loadLayersInto, releaseLayerArrays } from './layerArrays';import { createPageAtlases } from './atlases';import { PlanetRegistry, PlanetRegistryRes } from './planetQuery';import { buildSphereMesh } from './planetSea';@@ -456,17 +456,12 @@ export class PlanetPlugin implements Plugin {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; }+ const still = (): boolean => built.epoch === epoch && !!built.instance;+ const got = await loadLayersInto(app, built.instance, refs, MAX_LAYERS, still);+ if (!still()) { if (got) releaseLayerArrays(got); 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) });+ built.arrays = got;} catch (e) {log.error('planet', 'packing the planet layers failed', e);} finally {diff --git a/sdk/src/terrain/planetShader.ts b/sdk/src/terrain/planetShader.tsindex 532aef555..21c6abe9e 100644--- a/sdk/src/terrain/planetShader.ts+++ b/sdk/src/terrain/planetShader.ts@@ -10,6 +10,7 @@* on the cube face, pushed out to the radius plus the page's height; it hands the fragment stage the page and the face to find its normal and paint by.*/import { makeBuiltinShaderTemplate } from '../render/builtinShaders';+import { layerParams, LAYER_SURFACE_GLSL, LAYER_SURFACE_WGSL } from './layerSurfaceShader';const PLANET = `#pragma shader "Planet"#pragma version 300 es@@ -22,16 +23,10 @@ const PLANET = `#pragma shader "Planet"// The ground's own wander in brightness, in metres a feature, and how strong it is.#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 layers' textures, when the planet has any (the Planet component packs them: layerArrays.ts), each read on the planes of the world's+// axes by how much the ground faces them: the same layer code as the Terrain Layers shader (layerSurfaceShader.ts). Without any, the+// layers are their colours.+${layerParams({ sharpness: 1.6, heightBlend: 0, blendNoise: 0, antiTile: 0 })}#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,// in the planet's space, so every pass (a shadow's too) slides the vertices by it and all draw one ground.@@ -237,17 +232,7 @@ 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)); }+${LAYER_SURFACE_GLSL}// 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));@@ -283,41 +268,16 @@ void main() {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 rel = P - u_planetCenter.xyz;+ float open = 1.0;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);+ // Each layer on the three planes of the world's axes, those the ground faces by how much it does.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);+ TnSurface layers = tnLayers(paint, vec4(0.0), rel, dFdx(rel), dFdy(rel), N, axis, tnNearFar(length(rel - u_terrainEye.xyz)));+ albedo = layers.albedo;+ N = normalize(N + layers.slope);+ open = layers.mask.r;}vec3 q = rel / u_macroScale;float broad = pnNoise(q) * 0.6 + pnNoise(q * 4.1 + 7.0) * 0.4;@@ -326,7 +286,7 @@ void main() {float roughness = u_roughness;SurfaceExt ext = surfaceExtNone(N);vec3 viewDir = viewDirection(P);- vec3 lit = applyLightingSurface(albedo, N, P, viewDir, 0.0, roughness, 0.5, 1.0, ext);+ vec3 lit = applyLightingSurface(albedo, N, P, viewDir, 0.0, roughness, 0.5, open, ext);fragColor = vec4(lit, 1.0);#ifdef ES_GBUFFERfragSurface = vec4(packNormal(N), roughness, 0.75);@@ -347,15 +307,7 @@ 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)); }+${LAYER_SURFACE_WGSL}fn pnHash(p0 : vec3f) -> f32 {var p = fract(p0 * vec3f(0.1031, 0.1030, 0.0973));p = p + dot(p, p.yzx + 33.33);@@ -416,44 +368,17 @@ fn packNormal(n : vec3f) -> vec2f {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 rel = P - mc.u_planetCenter.xyz;var N = N0;+ var open = 1.0;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 layers = tnLayers(paint, vec4f(0.0), rel, dpx, dpy, N0, axis, tnNearFar(length(rel - mc.u_terrainEye.xyz)));+ albedo = layers.albedo;+ N = normalize(N0 + layers.slope);+ open = layers.mask.r;}let q = rel / mc.u_macroScale;let broad = pnNoise(q) * 0.6 + pnNoise(q * 4.1 + vec3f(7.0)) * 0.4;@@ -462,7 +387,7 @@ fn packNormal(n : vec3f) -> vec2f {let roughness = mc.u_roughness;let ext = surfaceExtNone(N);let viewDir = viewDirection(P);- let lit = applyLightingSurface(albedo, N, P, viewDir, 0.0, roughness, 0.5, 1.0, ext);+ let lit = applyLightingSurface(albedo, N, P, viewDir, 0.0, roughness, 0.5, open, ext);#ifdef ES_GBUFFERvar frag : FragOut;frag.color = vec4f(lit, 1.0);diff --git a/sdk/src/terrain/terrainPlugin.ts b/sdk/src/terrain/terrainPlugin.tsindex 03a8c5fb9..6332e0424 100644--- a/sdk/src/terrain/terrainPlugin.ts+++ b/sdk/src/terrain/terrainPlugin.ts@@ -53,7 +53,7 @@ import { groundHeightAt, groundNormalAt, groundPaintAt, type GroundData } from 'import { collisionGeometryOf } from '../runtime/collisionGeometry';import { chunksOf, ProceduralChunksRes } from '../residency/chunks';import { movers } from './movers';-import { createLayerArrays, imagePixelsAt, readAndPackLayers, releaseLayerArrays } from './layerArrays';+import { imagePixelsAt, loadLayersInto, releaseLayerArrays } from './layerArrays';import { createPageAtlases } from './atlases';import { parseTerrainTiles, TiledSource } from './tiles';import { TiledGroundEdit } from './tiledGroundEdit';@@ -862,26 +862,15 @@ export class TerrainPlugin implements Plugin {}void (async () => {try {- const packed = await readAndPackLayers(app, refs, MAX_LAYERS);- if (built.epoch !== epoch || !built.instance) return;- const arrays = createLayerArrays(app, packed, ['albedo', 'normal', 'mask'], () => readAndPackLayers(app, refs, MAX_LAYERS));+ const still = (): boolean => built.epoch === epoch && !!built.instance;+ const arrays = await loadLayersInto(app, built.instance, refs, MAX_LAYERS, still);+ if (!still()) { if (arrays) releaseLayerArrays(arrays); return; }if (!arrays) {log.warn('terrain', 'the engine refused the terrain layers\' texture arrays');return;}releaseLayerArrays(built.arrays);built.arrays = arrays;- const set = (name: string, value: Parameters<typeof Material.setUniform>[2]): void => { Material.setUniform(built.instance, name, value); };- set('u_albedoLayers', Material.tex(arrays[0]!));- set('u_normalLayers', Material.tex(arrays[1]!));- set('u_maskLayers', Material.tex(arrays[2]!));- set('u_layerCount', packed.tiles.length);- 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.tsindex d25303dd0..e26a157ec 100644--- a/sdk/src/terrain/terrainShader.ts+++ b/sdk/src/terrain/terrainShader.ts@@ -7,6 +7,7 @@* The shader source lives with the module that installs it, not in the core's list of built-in shaders: a package that does not install the module carries none of it.*/import { makeBuiltinShaderTemplate } from '../render/builtinShaders';+import { layerParams, LAYER_SURFACE_GLSL, LAYER_SURFACE_WGSL } from './layerSurfaceShader';// The ground's vertices from its pages (pages.ts), shared by both terrain shaders: a node's patch placed and sized by its instance, its@@ -521,31 +522,7 @@ export const TERRAIN_SHADER_TEMPLATE = makeBuiltinShaderTemplate('terrain', 'Terconst TERRAIN_LAYERS = `#pragma shader "Terrain Layers"#pragma version 300 es#pragma domain Lit-#pragma param u_albedoLayers textureArray default(white)-#pragma param u_normalLayers textureArray default(white) texel(data)-#pragma param u_maskLayers textureArray default(white) texel(data)-// How many layers there are, and how many world units one repeat of each covers (layers 1 to 4, then 5 to 8).-#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-// way, and sand fills the low places between stones. 0 is a plain blend of the weights.-#pragma param u_heightBlend float default(0.8) range(0,1) ui(slider)-// How much each layer's weight is broken up by slow noise of its own before the strongest wins.-#pragma param u_blendNoise float default(0.5) range(0,1) ui(slider)-// 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)-// How strongly each layer is read without repeat near the eye (hex tiling), so no tile is seen.-#pragma param u_antiTile float default(0.6) range(0,1) ui(slider)-// How far round a cell may be turned (1 any way, 0 shifted only): a layer with a grain, sand in ripples or rock in beds, turned cell by-// cell is lit cell by cell, and shows the hexagons.-#pragma param u_antiTileTurn float default(1) range(0,1) ui(slider)-// The wide, slow variation in brightness laid over every layer so a big meadow is not one colour.+${layerParams({ sharpness: 1.6, heightBlend: 0.8, blendNoise: 0.5, antiTile: 0.6 })}// The wide, slow variation in brightness laid over every layer so a big meadow is not one colour.#pragma param u_macroVariation float default(0.25) range(0,1) ui(slider)// How steep the ground must be (1 minus its normal's up) before the layers are also projected from the sides.#pragma param u_triplanarFrom float default(0.15) range(0,1) ui(slider)@@ -608,68 +585,7 @@ vec2 packNormal(vec3 n) {out vec4 fragColor;#endif-float tnHash(vec2 p) {- p = fract(p * vec2(0.1031, 0.1030));- p += dot(p, p.yx + 33.33);- return fract((p.x + p.y) * p.x);-}-float tnNoise(vec2 p) {- vec2 i = floor(p), f = fract(p);- f = f * f * (3.0 - 2.0 * f);- return mix(mix(tnHash(i), tnHash(i + vec2(1.0, 0.0)), f.x), mix(tnHash(i + vec2(0.0, 1.0)), tnHash(i + vec2(1.0, 1.0)), f.x), f.y);-}-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; };-TnTap tnPlain(vec2 uv, float layer, vec2 gx, vec2 gy) {- vec3 at = vec3(uv, layer);- TnTap t;- t.albedo = textureGrad(u_albedoLayers, at, gx, gy).rgb;- t.slope = textureGrad(u_normalLayers, at, gx, gy).rg * 2.0 - 1.0;- t.mask = textureGrad(u_maskLayers, at, gx, gy).rgb;- return t;-}-// The same in one hex cell: shifted and turned by the cell's random numbers; the normal's slope turned back with it.-TnTap tnHexTap(vec2 uv, float layer, vec2 cell, vec2 gx, vec2 gy) {- vec2 r = tnHash2(cell);- float a = r.x * 6.2831853 * u_antiTileTurn;- mat2 turn = mat2(cos(a), -sin(a), sin(a), cos(a));- TnTap t = tnPlain(turn * uv + r, layer, turn * gx, turn * gy);- t.slope = t.slope * turn;- return t;-}-// A layer read without repeat (hex tiling, Mikkelsen 2022): three cells about a point blended by nearness, the higher reading winning.-TnTap tnHex(vec2 uv, float layer, vec2 gx, vec2 gy, float strength) {- vec2 skewed = mat2(1.0, 0.0, -0.57735027, 1.15470054) * (uv * 3.4641016);- vec2 base = floor(skewed);- vec3 f = vec3(fract(skewed), 0.0);- f.z = 1.0 - f.x - f.y;- float s = step(0.0, -f.z), s2 = 2.0 * s - 1.0;- vec3 w = vec3(-f.z * s2, s - f.y * s2, s - f.x * s2);- TnTap c1 = tnHexTap(uv, layer, base + vec2(s, s), gx, gy);- TnTap c2 = tnHexTap(uv, layer, base + vec2(s, 1.0 - s), gx, gy);- TnTap c3 = tnHexTap(uv, layer, base + vec2(1.0 - s, s), gx, gy);- vec3 h = vec3(c1.mask.b, c2.mask.b, c3.mask.b);- w = pow(max(w * mix(vec3(1.0), 0.4 + h, strength), vec3(1e-4)), vec3(7.0));- w /= dot(w, vec3(1.0));- TnTap t;- t.albedo = c1.albedo * w.x + c2.albedo * w.y + c3.albedo * w.z;- t.slope = c1.slope * w.x + c2.slope * w.y + c3.slope * w.z;- t.mask = c1.mask * w.x + c2.mask * w.y + c3.mask * w.z;- return t;-}-// A tangent normal's slope laid on a plane whose texture runs along T and B, about the surface's normal N.-vec3 tnBend(vec2 slope, vec3 T, vec3 B, vec3 N) {- T = normalize(T - N * dot(N, T));- B = normalize(B - N * dot(N, B));- return slope.x * T + slope.y * B;-}-+${LAYER_SURFACE_GLSL}void main() {#ifdef MESH_NORMALShighp vec3 P = v_worldXYZ;@@ -689,85 +605,20 @@ void main() {vec2 nxz = texture(u_heightPages, v_color.xy).ba * 2.0 - 1.0;N = normalize(vec3(nxz.x, sqrt(max(1.0 - dot(nxz, nxz), 0.0)), nxz.y));}- int count = int(u_layerCount + 0.5);- float w[8];- 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 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(Pw.xz / (tileSize * 2.3) + float(i) * 11.0 + 3.0) * 0.5- + tnNoise(Pw.xz / (tileSize * 0.45) + float(i) * 7.0 + 17.0) * 0.3- + tnNoise(Pw.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];- }- float sharp = 0.0;- for (int i = 0; i < 8; i++) { w[i] = pow(w[i] / max(sum, 1e-4), u_sharpness); sharp += w[i]; }- for (int i = 0; i < 8; i++) w[i] /= max(sharp, 1e-4);-// Gradients taken here, where every lane runs. Near the eye a layer is read without repeat, far off a wider tile is mixed in.vec3 dpx = dFdx(P), dpy = dFdy(P);float eye = u_camera.w > 0.5 ? length(P - u_camera.xyz) : 0.0;- float scale = tnTile(0);- float near = (1.0 - smoothstep(scale * 20.0, scale * 45.0, eye)) * u_antiTile;- float far = smoothstep(scale * 6.0, scale * 40.0, eye) * 0.65;// How much of each plane a slope is seen from: the top alone on gentle ground, the sides too from u_triplanarFrom.vec3 axis = pow(abs(N), vec3(4.0));axis /= dot(axis, vec3(1.0));float side = smoothstep(u_triplanarFrom, u_triplanarFrom + 0.15, 1.0 - abs(N.y));vec3 planes = mix(vec3(0.0, 1.0, 0.0), axis, side);+ // A layer seen from the side is read by height: its beds, wandering by u_strataWarp.float bedY = Pw.y;if (u_strataWarp > 0.0) bedY += (tnNoise(Pw.xz / u_strataSpan + 41.0) * 0.65 + tnNoise(Pw.xz / (u_strataSpan * 0.31) + 7.0) * 0.35 - 0.5) * 2.0 * u_strataWarp;-- vec3 albedo[8];- vec3 bend[8];- vec3 mask[8];- for (int i = 0; i < 8; i++) {- albedo[i] = vec3(0.0); bend[i] = vec3(0.0); mask[i] = vec3(1.0, 1.0, 0.0);- if (w[i] <= 1e-3) continue;- float layer = float(i), tile = tnTile(i);- // WebGL takes no ?: between structures.- TnTap top;- if (near > 0.01) top = tnHex(Pw.xz / tile, layer, dpx.xz / tile, dpy.xz / tile, near);- else top = tnPlain(Pw.xz / tile, layer, dpx.xz / tile, dpy.xz / tile);- if (far > 0.01) {- float big = tile * u_farScale;- TnTap wide = tnPlain(Pw.xz / big + 0.21, layer, dpx.xz / big, dpy.xz / big);- top.albedo = mix(top.albedo, wide.albedo, far);- top.mask = mix(top.mask, wide.mask, far);- }- albedo[i] = top.albedo * planes.y;- mask[i] = top.mask * planes.y;- bend[i] = tnBend(top.slope, vec3(1.0, 0.0, 0.0), vec3(0.0, 0.0, 1.0), N) * planes.y;- if (planes.x > 0.02) {- TnTap x = tnPlain(vec2(Pw.z, bedY) / tile, layer, dpx.zy / tile, dpy.zy / tile);- albedo[i] += x.albedo * planes.x; mask[i] += x.mask * planes.x;- bend[i] += tnBend(x.slope, vec3(0.0, 0.0, 1.0), vec3(0.0, 1.0, 0.0), N) * planes.x;- }- if (planes.z > 0.02) {- TnTap z = tnPlain(vec2(Pw.x, bedY) / tile, layer, dpx.xy / tile, dpy.xy / tile);- albedo[i] += z.albedo * planes.z; mask[i] += z.mask * planes.z;- bend[i] += tnBend(z.slope, vec3(1.0, 0.0, 0.0), vec3(0.0, 1.0, 0.0), N) * planes.z;- }- }- // Then by height: each layer stands as high as its mask says, and where two meet the higher one shows.- float top = -1.0;- for (int i = 0; i < 8; i++) if (w[i] > 1e-3) top = max(top, mask[i].b + w[i] * 1.5);- 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), byHeight);- colour += albedo[i] * k; slope += bend[i] * k; surface += mask[i] * k;- }+ TnSurface layers = tnLayers(paintA, paintB, vec3(Pw.x, bedY, Pw.z), dpx, dpy, N, planes, tnNearFar(eye));+ vec3 colour = layers.albedo, slope = layers.slope, surface = layers.mask;+ float scale = tnTile(0);float broad = tnNoise(Pw.xz / (scale * 7.3)) * 0.6 + tnNoise(Pw.xz / (scale * 29.0) + 5.0) * 0.4;colour *= mix(1.0, 0.7 + 0.6 * broad, u_macroVariation);N = normalize(N + slope);@@ -800,72 +651,7 @@ void main() {#pragma end#pragma fragment wgsl-fn tnHash(p0 : vec2f) -> f32 {- var p = fract(p0 * vec2f(0.1031, 0.1030));- p = p + dot(p, p.yx + 33.33);- return fract((p.x + p.y) * p.x);-}-fn tnNoise(p : vec2f) -> f32 {- let i = floor(p);- var f = fract(p);- f = f * f * (3.0 - 2.0 * f);- return mix(mix(tnHash(i), tnHash(i + vec2f(1.0, 0.0)), f.x), mix(tnHash(i + vec2f(0.0, 1.0)), tnHash(i + vec2f(1.0, 1.0)), f.x), f.y);-}-fn tnHash2(p : vec2f) -> vec2f {- return fract(sin(vec2f(dot(p, vec2f(127.1, 311.7)), dot(p, vec2f(269.5, 183.3)))) * 43758.5453);-}-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;- t.albedo = textureSampleGrad(u_albedoLayers, u_albedoLayers_s, uv, layer, gx, gy).rgb;- t.slope = textureSampleGrad(u_normalLayers, u_normalLayers_s, uv, layer, gx, gy).rg * 2.0 - vec2f(1.0);- t.mask = textureSampleGrad(u_maskLayers, u_maskLayers_s, uv, layer, gx, gy).rgb;- return t;-}-fn tnHexTap(uv : vec2f, layer : i32, cell : vec2f, gx : vec2f, gy : vec2f) -> TnTap {- let r = tnHash2(cell);- let a = r.x * 6.2831853 * mc.u_antiTileTurn;- let turn = mat2x2f(cos(a), -sin(a), sin(a), cos(a));- var t = tnPlain(turn * uv + r, layer, turn * gx, turn * gy);- t.slope = t.slope * turn;- return t;-}-fn tnHex(uv : vec2f, layer : i32, gx : vec2f, gy : vec2f, strength : f32) -> TnTap {- let skewed = mat2x2f(1.0, 0.0, -0.57735027, 1.15470054) * (uv * 3.4641016);- let base = floor(skewed);- let fr = fract(skewed);- let fz = 1.0 - fr.x - fr.y;- let s = step(0.0, -fz);- let s2 = 2.0 * s - 1.0;- var w = vec3f(-fz * s2, s - fr.y * s2, s - fr.x * s2);- let c1 = tnHexTap(uv, layer, base + vec2f(s, s), gx, gy);- let c2 = tnHexTap(uv, layer, base + vec2f(s, 1.0 - s), gx, gy);- let c3 = tnHexTap(uv, layer, base + vec2f(1.0 - s, s), gx, gy);- let h = vec3f(c1.mask.b, c2.mask.b, c3.mask.b);- w = pow(max(w * mix(vec3f(1.0), vec3f(0.4) + h, vec3f(strength)), vec3f(1e-4)), vec3f(7.0));- w = w / dot(w, vec3f(1.0));- var t : TnTap;- t.albedo = c1.albedo * w.x + c2.albedo * w.y + c3.albedo * w.z;- t.slope = c1.slope * w.x + c2.slope * w.y + c3.slope * w.z;- t.mask = c1.mask * w.x + c2.mask * w.y + c3.mask * w.z;- return t;-}-fn tnBend(slope : vec2f, T0 : vec3f, B0 : vec3f, N : vec3f) -> vec3f {- let T = normalize(T0 - N * dot(N, T0));- let B = normalize(B0 - N * dot(N, B0));- return slope.x * T + slope.y * B;-}-+${LAYER_SURFACE_WGSL}#ifdef ES_GBUFFERstruct FragOut {@location(0) color : vec4f,@@ -909,94 +695,21 @@ fn packNormal(n : vec3f) -> vec2f {paintB = pageB;N = normalize(vec3f(pageNormal.x, sqrt(max(1.0 - dot(pageNormal, pageNormal), 0.0)), pageNormal.y));}- let count = i32(mc.u_layerCount + 0.5);- var w : array<f32, 8>;- var sum = 0.0;- for (var i = 0; i < 8; i = i + 1) {- var raw = 0.0;- if (i < 4) { raw = paintA[i]; } else { raw = paintB[i - 4]; }- // 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(Pw.xz / (tileSize * 2.3) + vec2f(f32(i) * 11.0 + 3.0)) * 0.5- + tnNoise(Pw.xz / (tileSize * 0.45) + vec2f(f32(i) * 7.0 + 17.0)) * 0.3- + tnNoise(Pw.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];- }- var sharp = 0.0;- for (var i = 0; i < 8; i = i + 1) { w[i] = pow(w[i] / max(sum, 1e-4), mc.u_sharpness); sharp = sharp + w[i]; }- for (var i = 0; i < 8; i = i + 1) { w[i] = w[i] / max(sharp, 1e-4); }-let dpx = dpdx(P);let dpy = dpdy(P);var eye = 0.0;if (frame.camera.w > 0.5) { eye = length(P - frame.camera.xyz); }- let scale = tnTile(0);- let near = (1.0 - smoothstep(scale * 20.0, scale * 45.0, eye)) * mc.u_antiTile;- let far = smoothstep(scale * 6.0, scale * 40.0, eye) * 0.65;var axis = pow(abs(N), vec3f(4.0));axis = axis / dot(axis, vec3f(1.0));let side = smoothstep(mc.u_triplanarFrom, mc.u_triplanarFrom + 0.15, 1.0 - abs(N.y));let planes = mix(vec3f(0.0, 1.0, 0.0), axis, vec3f(side));var bedY = Pw.y;if (mc.u_strataWarp > 0.0) { bedY = bedY + (tnNoise(Pw.xz / mc.u_strataSpan + vec2f(41.0)) * 0.65 + tnNoise(Pw.xz / (mc.u_strataSpan * 0.31) + vec2f(7.0)) * 0.35 - 0.5) * 2.0 * mc.u_strataWarp; }-- var albedo : array<vec3f, 8>;- var bend : array<vec3f, 8>;- var mask : array<vec3f, 8>;- for (var i = 0; i < 8; i = i + 1) {- albedo[i] = vec3f(0.0);- bend[i] = vec3f(0.0);- mask[i] = vec3f(1.0, 1.0, 0.0);- if (w[i] <= 1e-3) { continue; }- let tile = tnTile(i);- var top : TnTap;- if (near > 0.01) { top = tnHex(Pw.xz / tile, i, dpx.xz / tile, dpy.xz / tile, near); }- else { top = tnPlain(Pw.xz / tile, i, dpx.xz / tile, dpy.xz / tile); }- if (far > 0.01) {- let big = tile * mc.u_farScale;- let wide = tnPlain(Pw.xz / big + vec2f(0.21), i, dpx.xz / big, dpy.xz / big);- top.albedo = mix(top.albedo, wide.albedo, vec3f(far));- top.mask = mix(top.mask, wide.mask, vec3f(far));- }- albedo[i] = top.albedo * planes.y;- mask[i] = top.mask * planes.y;- bend[i] = tnBend(top.slope, vec3f(1.0, 0.0, 0.0), vec3f(0.0, 0.0, 1.0), N) * planes.y;- if (planes.x > 0.02) {- let x = tnPlain(vec2f(Pw.z, bedY) / tile, i, dpx.zy / tile, dpy.zy / tile);- albedo[i] = albedo[i] + x.albedo * planes.x;- mask[i] = mask[i] + x.mask * planes.x;- bend[i] = bend[i] + tnBend(x.slope, vec3f(0.0, 0.0, 1.0), vec3f(0.0, 1.0, 0.0), N) * planes.x;- }- if (planes.z > 0.02) {- let z = tnPlain(vec2f(Pw.x, bedY) / tile, i, dpx.xy / tile, dpy.xy / tile);- albedo[i] = albedo[i] + z.albedo * planes.z;- mask[i] = mask[i] + z.mask * planes.z;- bend[i] = bend[i] + tnBend(z.slope, vec3f(1.0, 0.0, 0.0), vec3f(0.0, 1.0, 0.0), N) * planes.z;- }- }- var top = -1.0;- for (var i = 0; i < 8; i = i + 1) { if (w[i] > 1e-3) { top = max(top, mask[i].b + w[i] * 1.5); } }- var hsum = 0.0;- var hw : array<f32, 8>;- for (var i = 0; i < 8; i = i + 1) {- hw[i] = 0.0;- 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), byHeight);- colour = colour + albedo[i] * k;- slope = slope + bend[i] * k;- surface = surface + mask[i] * k;- }+ let layers = tnLayers(paintA, paintB, vec3f(Pw.x, bedY, Pw.z), dpx, dpy, N, planes, tnNearFar(eye));+ var colour = layers.albedo;+ let slope = layers.slope;+ let surface = layers.mask;+ let scale = tnTile(0);let broad = tnNoise(Pw.xz / (scale * 7.3)) * 0.6 + tnNoise(Pw.xz / (scale * 29.0) + vec2f(5.0)) * 0.4;colour = colour * mix(1.0, 0.7 + 0.6 * broad, mc.u_macroVariation);N = normalize(N + slope);diff --git a/sdk/tests/area-map-rows.test.ts b/sdk/tests/area-map-rows.test.tsindex d9142b3a6..cb395bdac 100644--- a/sdk/tests/area-map-rows.test.ts+++ b/sdk/tests/area-map-rows.test.ts@@ -31,7 +31,9 @@ describe('the rows of an image over an area', () => {it('a layer read from the side takes its height through the strata warp, in both languages, and the warp is off by default', () => {const source = TERRAIN_LAYERS_SHADER_TEMPLATE.source;expect(source).toContain('#pragma param u_strataWarp float default(0)');- for (const read of ['tnPlain(vec2(Pw.z, bedY) / tile', 'tnPlain(vec2(Pw.x, bedY) / tile', 'tnPlain(vec2f(Pw.z, bedY) / tile', 'tnPlain(vec2f(Pw.x, bedY) / tile']) {+ // The ground is handed to the shared layer code with the bed's height in place of its own, and the sides read (z, y) and (x, y) of it.+ for (const read of ['tnLayers(paintA, paintB, vec3(Pw.x, bedY, Pw.z)', 'tnLayers(paintA, paintB, vec3f(Pw.x, bedY, Pw.z)',+ 'tnPlain(at.zy / tile', 'tnPlain(at.xy / tile']) {expect(source).toContain(read);}expect(source).not.toContain('tnPlain(Pw.zy');diff --git a/sdk/tests/terrain-layer-surface.test.ts b/sdk/tests/terrain-layer-surface.test.tsnew file mode 100644index 000000000..9b4857b81--- /dev/null+++ b/sdk/tests/terrain-layer-surface.test.ts@@ -0,0 +1,41 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+import { describe, expect, it } from 'vitest';+import { TERRAIN_LAYERS_SHADER_TEMPLATE } from '../src/terrain/terrainShader';+import { PLANET_SHADER_TEMPLATE } from '../src/terrain/planetShader';+import { LAYER_SURFACE_GLSL, LAYER_SURFACE_WGSL } from '../src/terrain/layerSurfaceShader';++describe('the ground\'s layers are one piece of shader code', () => {+ it('Terrain Layers and Planet both draw their layers with it, in both languages', () => {+ for (const source of [TERRAIN_LAYERS_SHADER_TEMPLATE.source, PLANET_SHADER_TEMPLATE.source]) {+ expect(source).toContain(LAYER_SURFACE_GLSL);+ expect(source).toContain(LAYER_SURFACE_WGSL);+ expect(source).toContain('TnSurface layers = tnLayers(');+ expect(source).toContain('let layers = tnLayers(');+ // One copy of the code each: a layer read written a second time is a second place to change.+ expect(source.split('fn tnHex(').length).toBe(2);+ expect(source.split('TnTap tnHex(').length).toBe(2);+ }+ });++ it('reads the four layers with the most say at a pixel, not all eight', () => {+ for (const code of [LAYER_SURFACE_GLSL, LAYER_SURFACE_WGSL]) {+ expect(code).not.toMatch(/array<vec3f, 8>|vec3 albedo\[8\]/);+ expect(code).toMatch(/array<vec3f, 4>|vec3 albedo\[4\]/);+ // A layer not painted here costs no noise.+ expect(code).toMatch(/if \(raw <= 0\.0\) (\{ )?continue;/);+ }+ });++ it('the Planet keeps its own look by default: no height blend, blend noise or hex tiling', () => {+ const source = PLANET_SHADER_TEMPLATE.source;+ expect(source).toContain('#pragma param u_heightBlend float default(0)');+ expect(source).toContain('#pragma param u_blendNoise float default(0)');+ expect(source).toContain('#pragma param u_antiTile float default(0)');+ expect(source).not.toContain('u_tiles vec4');+ const layers = TERRAIN_LAYERS_SHADER_TEMPLATE.source;+ expect(layers).toContain('#pragma param u_heightBlend float default(0.8)');+ expect(layers).toContain('#pragma param u_blendNoise float default(0.5)');+ expect(layers).toContain('#pragma param u_antiTile float default(0.6)');+ });+});diff --git a/tools/releaseNotes.mjs b/tools/releaseNotes.mjsindex 503ea462a..34af735bc 100644--- a/tools/releaseNotes.mjs+++ b/tools/releaseNotes.mjs@@ -4822,4 +4822,6 @@ export const NOTED = {{"note": "Components carry the tick of their last write."},"fix(render): an unset texture array binds layers of its default - a textureArray param a material leaves unset was given the 2D white texture, which a sampler2DArray cannot read: on WebGL it read black, so a Planet with no layers packed yet, or any material whose array was not set, drew black where WebGPU drew white; the render context keeps white, black and flat-normal layers and MaterialStore::builtinDefault binds them for an array slot, in the scene and in post-processing alike":{"note": "An unset texture array reads its default on WebGL."},+ "perf(terrain): ground reads the four layers that weigh most at a pixel, and Planet draws its layers with the same code - the layer blend (weights, hex tiling, far tile, side planes, height blend) is one GLSL and one WGSL text in layerSurfaceShader.ts that Terrain Layers and Planet both call, and one loader binds the arrays for both; a pixel keeps the four heaviest layers (Unreal's landscape caps the layers a component blends) and a layer not painted there costs no noise: the terrain-water lakeside's ground 3.04 -> 2.58 ms, with the plants off 4.24 -> 3.62, the frame unchanged to 0.04% of pixels; a planet's layer masks now darken the sky's light as a flat terrain's do, and its height blend, blend noise and hex tiling default to 0, which draws it as before":+ {"note": "Terrain layers cost less, and a Planet draws its layers as a Terrain does."},};diff --git a/tools/renderScenes.mjs b/tools/renderScenes.mjsindex 286342f18..7b7c8e5ca 100644--- a/tools/renderScenes.mjs+++ b/tools/renderScenes.mjs@@ -107,6 +107,17 @@ export const SCENES = [ESTELLA_VERIFY_EXPECT: JSON.stringify(test.expect.map(([x, rgb]) => ({ x, y: 0.5, rgb, tol: 14 }))),},})),+ // The Planet shader draws its layers with the same code as Terrain Layers (layerSurfaceShader.ts). Two boxes under the sky's light+ // alone, white paint: on the left the layer colours (grey), on the right one layer of the stock arrays, nothing packed into them. An+ // unset texture array binds white layers (MaterialStore::builtinDefault): on WebGL it read black before, a black box here.+ {+ id: 'planet-layers', tier: 'pr', webgpu: true,+ env: {+ ESTELLA_VERIFY_SCENE: '/scenes/planet-layers.esscene',+ ESTELLA_VERIFY_W: '256', ESTELLA_VERIFY_H: '256', ESTELLA_VERIFY_STEPS: '3',+ ESTELLA_VERIFY_EXPECT: JSON.stringify([{ x: 0.3, y: 0.5, rgb: [129, 129, 129], tol: 10 }, { x: 0.7, y: 0.5, rgb: [242, 242, 242], tol: 10 }]),+ },+ },{id: 'shadow-vertex-displacement', tier: 'pr', webgpu: true,env: {