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 has a sea and a sky that follows the ground the camera stands on
yhh27aa83716daa
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex dd4886b00..9405749f0 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -16,6 +16,7 @@ published separately; it ships inside the editor.### Added+- **A planet's sea and sky.** `Planet.sea` draws a translucent, lit sphere at `seaLevel` in which the ground that dips below it stands, and `skyAtmosphere` takes the planet's radius and centre (`u_planetRadius`, `u_planetX/Y/Z`, as `heightFog` does) to work the sky out in the frame of the ground the camera stands on, so the horizon, the sun and the haze follow it round.- **A generated world on a planet.** A `WorldGen` with `surface` Planet, on a `Planet`'s entity, lays the world out over the cube's six faces, each as a plane of metres, by the same rules a flat world has: biomes over fields, recipes and layers. A direction is planned by the face it falls on; what is placed is taken to the planet and stands along its up. The fields are the planet's own (height, slope, noise in three dimensions with no seam between faces, `paint.<layer>`, and the fields a planet provider names with `fields`), the biomes paint the ground too, and `seaLevel` and `WorldZone`s work over a planet.- **A planet pulls and answers.** `Planet.gravity` pulls every dynamic 3D body toward the centre of the nearest planet that pulls (the world's gravity is taken off the body and the planet's put on, as a force each fixed step), and the `PlanetRegistryRes` resource answers `up`, `altitude`, `groundHeight`, `groundPoint` and `nearest` for what stands, aims or falls on a round world.- **A render origin for large worlds.** `setRenderOriginStep(step)` turns on drawing relative to a point near the camera: the origin is the camera's position rounded to `step` and moves only when the camera is further than `step` from it, the renderer takes every mesh, light, probe and shadow bound from it before the GPU sees them, and the camera's view-projection is built for the same origin, so a world tens of kilometres across stops jittering. It is off by default and changes nothing then. It covers meshes, lights, probes, occluders, planar reflections, sprites, text, particles (GPU too), trails, tilemaps, world-space UI, 2D shadows, and the terrain, planet, water, foliage, height fog and cloud shaders, which read the world's own position back from a new `u_renderOrigin` frame constant. Debug and custom draws stay in the world's coordinates, and the previous frame's view and meshes are taken to the new origin when it steps, so motion vectors and temporal effects carry on.diff --git a/docs/astro/src/content/docs/graphics/terrain.mdx b/docs/astro/src/content/docs/graphics/terrain.mdxindex db4974ed2..75e38c1cc 100644--- a/docs/astro/src/content/docs/graphics/terrain.mdx+++ b/docs/astro/src/content/docs/graphics/terrain.mdx@@ -286,7 +286,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. 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. 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.## Limitsdiff --git a/docs/astro/src/content/docs/zh-cn/graphics/terrain.mdx b/docs/astro/src/content/docs/zh-cn/graphics/terrain.mdxindex 65a4602d1..eda2ad9a3 100644--- a/docs/astro/src/content/docs/zh-cn/graphics/terrain.mdx+++ b/docs/astro/src/content/docs/zh-cn/graphics/terrain.mdx@@ -197,7 +197,7 @@ registerTerrainProvider(planet);生成的世界可以铺在星球上:在 `Planet` 所在的实体上放一个 `surface` 设为 Planet 的 `WorldGen`。立方体的六个面各按米制平面,用和平面世界一样的规则(字段之上的群落、配方、图层)铺设;一个方向由它落在的那个面来规划,放出来的东西被带到星球上,沿着当地的"上"站立。字段是星球自己的:地面高度、坡度、在三维里读的噪声(所以字段越过两个面之间的边没有接缝)、星球每个图层的 `paint.<层名>`,以及提供器用 `fields` 命名的字段(比如生态)。群落同时给地面上色(`paintGround`),画出来的和长出来的是同一张图。`seaLevel` 是海平面高度,比它低的地面在水下。区域(`WorldZone`)站在世界里的一个位置上,归它落在的那个面。-地面有碰撞:每个运动的 3D 刚体和角色在 `collisionDistance` 内的最细节点,会用画地面的同一批采样建成碰撞几何(`collision`、`collisionDistance`、`collisionLayer`、`friction`,和平面地形一样)。星球的变换只有位置:旋转或缩放过的星球,碰撞仍站在没旋转时的位置。`layers` 可以写最多四个 `.esterrainlayer` 文件,和平面地形一样;每层按地面朝向世界坐标轴的程度,在三个投影面上取样,远处混入更宽的一次取样,看不出重复。不写图层时地面就是四种颜色。海、跟着地平线转的天空和指向球心的重力还没有;物体沿世界唯一的重力下落,所以只有在星球顶部才是朝向球心。+地面有碰撞:每个运动的 3D 刚体和角色在 `collisionDistance` 内的最细节点,会用画地面的同一批采样建成碰撞几何(`collision`、`collisionDistance`、`collisionLayer`、`friction`,和平面地形一样)。星球的变换只有位置:旋转或缩放过的星球,碰撞仍站在没旋转时的位置。`layers` 可以写最多四个 `.esterrainlayer` 文件,和平面地形一样;每层按地面朝向世界坐标轴的程度,在三个投影面上取样,远处混入更宽的一次取样,看不出重复。不写图层时地面就是四种颜色。设置 `sea` 星球就有海:一个半透明、受光的球面,高出半径 `seaLevel`,低于它的地面站在水里(波浪和岸边泡沫是平面水体的,之后会来到球面)。天空跟着地平线转:给 `skyAtmosphere` 和 `heightFog` 填上星球的半径和中心,它们就按相机站着的那片地面算天空和雾,太阳是固定方向,所以一个地方的昼夜取决于它在星球上的位置。## 限制diff --git a/docs/astro/src/data/components.generated.json b/docs/astro/src/data/components.generated.jsonindex 3934ade23..48b477491 100644--- a/docs/astro/src/data/components.generated.json+++ b/docs/astro/src/data/components.generated.json@@ -3928,6 +3928,30 @@"doc": "How hard the planet pulls bodies toward its centre, in metres a second squared at the surface (9.81 is the Earth's). Needs 3D physics; the world's own gravity is taken off the bodies it pulls.","range": "≥ 0"},+ {+ "key": "sea",+ "type": "boolean",+ "default": "false",+ "doc": "Whether the planet has a sea: a sphere at the sea level, in which the ground that dips below it stands."+ },+ {+ "key": "seaLevel",+ "type": "number",+ "default": "0",+ "doc": "The height of the sea above the planet's radius, in metres."+ },+ {+ "key": "seaColor",+ "type": "Color",+ "default": "#0f476b"+ },+ {+ "key": "seaOpacity",+ "type": "number",+ "default": "0.82",+ "doc": "How much of the sea there is over what is under it.",+ "range": "0–1, step 0.01"+ },{"key": "layers","type": "array",@@ -3962,7 +3986,13 @@"collisionDistance","collisionLayer","friction",- "gravity"+ "gravity",+ "seaLevel",+ "seaColor.r",+ "seaColor.g",+ "seaColor.b",+ "seaColor.a",+ "seaOpacity"]},{diff --git a/sdk/etc/index.api.md b/sdk/etc/index.api.mdindex 6531a82c8..3fefb96b2 100644--- a/sdk/etc/index.api.md+++ b/sdk/etc/index.api.md@@ -6760,6 +6760,10 @@ macroScale: numbermacroVariation: numberprovider: stringradius: number+sea: boolean+seaColor: Color+seaLevel: number+seaOpacity: numberseed: numberworld: string```diff --git a/sdk/etc/index.native.api.md b/sdk/etc/index.native.api.mdindex 7463ec24a..f12c1c6f9 100644--- a/sdk/etc/index.native.api.md+++ b/sdk/etc/index.native.api.md@@ -6963,6 +6963,10 @@ macroScale: numbermacroVariation: numberprovider: stringradius: number+sea: boolean+seaColor: Color+seaLevel: number+seaOpacity: numberseed: numberworld: string```diff --git a/sdk/etc/index.node.api.md b/sdk/etc/index.node.api.mdindex d9046aba6..66c4dc6dc 100644--- a/sdk/etc/index.node.api.md+++ b/sdk/etc/index.node.api.md@@ -6755,6 +6755,10 @@ macroScale: numbermacroVariation: numberprovider: stringradius: number+sea: boolean+seaColor: Color+seaLevel: number+seaOpacity: numberseed: numberworld: string```diff --git a/sdk/etc/minigame.api.md b/sdk/etc/minigame.api.mdindex 2d44ee5b6..595f46a68 100644--- a/sdk/etc/minigame.api.md+++ b/sdk/etc/minigame.api.md@@ -7048,6 +7048,10 @@ macroScale: numbermacroVariation: numberprovider: stringradius: number+sea: boolean+seaColor: Color+seaLevel: number+seaOpacity: numberseed: numberworld: string```diff --git a/sdk/etc/terrain.api.md b/sdk/etc/terrain.api.mdindex 03ec79c9e..7b3cd2b55 100644--- a/sdk/etc/terrain.api.md+++ b/sdk/etc/terrain.api.md@@ -194,6 +194,10 @@ macroScale: numbermacroVariation: numberprovider: stringradius: number+sea: boolean+seaColor: Color+seaLevel: number+seaOpacity: numberseed: numberworld: string```@@ -208,6 +212,7 @@ height: ((dx: number, dy: number, dz: number) => number | null) | nulllayers: readonly string[]paint: ((dx: number, dy: number, dz: number) => readonly number[] | null) | nullradius: number+sampleMany: ((directions: Float32Array, count: number) => PlanetSamples | null) | null```## PlanetPageSource — interface @experimentaldiff --git a/sdk/etc/wechat.api.md b/sdk/etc/wechat.api.mdindex 0e0db55ae..7815c3a96 100644--- a/sdk/etc/wechat.api.md+++ b/sdk/etc/wechat.api.md@@ -6762,6 +6762,10 @@ macroScale: numbermacroVariation: numberprovider: stringradius: number+sea: boolean+seaColor: Color+seaLevel: number+seaOpacity: numberseed: numberworld: string```diff --git a/sdk/etc/worldgen.api.md b/sdk/etc/worldgen.api.mdindex a27722086..cc7584b20 100644--- a/sdk/etc/worldgen.api.md+++ b/sdk/etc/worldgen.api.md@@ -179,8 +179,10 @@ ev: [number, number, number]directionAt: (x: number, z: number) => [number, number, number]environment: () => Pick<EnvironmentInputs, "ground" | "space">face: number+fieldsAt: (x: number, z: number) => readonly number[] | nullframeAt: (x: number, z: number) => PlaneFrameground: (x: number, z: number) => { y: number; up: number; normal: [number, number, number]; } | null+paintAt: (x: number, z: number) => readonly number[] | nullplaneOf: (dx: number, dy: number, dz: number) => { x: number; z: number; } | nullplanet: () => PlanetFacts | nullsourcesOnFace: (sources: Iterable<{ x: number; y?: number; z: number; }>, reach: number) => { x: number; z: number; }[]diff --git a/sdk/src/postprocess/effects.ts b/sdk/src/postprocess/effects.tsindex 343625f71..c54b87bb5 100644--- a/sdk/src/postprocess/effects.ts+++ b/sdk/src/postprocess/effects.ts@@ -300,6 +300,11 @@ registerEffect({label: 'Sky Atmosphere',factory: () => postProcessEffects.createSkyAtmosphere(),uniforms: [+ // On a planet the sky is of the ground the camera stands on: the radius, above 0, turns that on, and the centre is where the planet stands.+ { name: 'u_planetRadius', label: 'Planet Radius', min: 0, max: 100000000, step: 100, defaultValue: 0, neutralValue: 0 },+ { name: 'u_planetX', label: 'Planet Centre X', min: -100000000, max: 100000000, step: 100, defaultValue: 0 },+ { name: 'u_planetY', label: 'Planet Centre Y', min: -100000000, max: 100000000, step: 100, defaultValue: 0 },+ { name: 'u_planetZ', label: 'Planet Centre Z', min: -100000000, max: 100000000, step: 100, defaultValue: 0 },// How bright the sky is.{ name: 'u_intensity', label: 'Brightness', min: 0, max: 8, step: 0.01, defaultValue: 1 },// How much of the sky behind the scene (a panorama, a clear colour) is kept: 0 replaces it, 1 leaves it.diff --git a/sdk/src/postprocess/sources/atmosphere.ts b/sdk/src/postprocess/sources/atmosphere.tsindex 7c6e7b94f..04649ead5 100644--- a/sdk/src/postprocess/sources/atmosphere.ts+++ b/sdk/src/postprocess/sources/atmosphere.ts@@ -37,6 +37,10 @@ export const atmosphereEffects = {#pragma param u_windSpeed float default(0.05) range(0,2)#pragma param u_windDirection float default(60) range(0,360)#pragma param u_followSun float default(1) range(0,1)+#pragma param u_planetRadius float default(0) range(0,100000000)+#pragma param u_planetX float default(0) range(-100000000,100000000)+#pragma param u_planetY float default(0) range(-100000000,100000000)+#pragma param u_planetZ float default(0) range(-100000000,100000000)#pragma param u_sunAzimuth float default(40) range(0,360)#pragma param u_sunElevation float default(35) range(-90,90)#pragma param u_cloudShadow float default(0) range(0,1)@@ -99,6 +103,14 @@ vec2 sphereHit(vec3 o, vec3 d, float r) {return vec2(-b - s, -b + s);}+/// The turn that takes up to +Y by the shortest way: the sky is worked out where up is +Y, so on a round world it is worked out in the frame of the ground the camera stands on.+mat3 upFrame(vec3 up) {+ vec3 v = vec3(-up.z, 0.0, up.x);+ float k = 1.0 / max(1.0 + up.y, 1e-4);+ mat3 cross = mat3(0.0, v.z, -v.y, -v.z, 0.0, v.x, v.y, -v.x, 0.0);+ return mat3(1.0) + cross + cross * cross * k;+}+/// The air between p and the top of the atmosphere along d, as (Rayleigh, Mie) optical depth; z is 0 where the planet is in the way.vec3 lightDepth(vec3 p, vec3 d) {vec2 ground = sphereHit(p, d, R_E);@@ -206,6 +218,12 @@ void main() {float az = radians(u_sunAzimuth);float el = radians(u_sunElevation);vec3 sun = follow ? lightDir.xyz : vec3(cos(el) * sin(az), sin(el), cos(el) * cos(az));+ if (u_planetRadius > 0.0) {+ // Up is away from the planet's centre where the camera is: the direction and the sun are turned into the frame where that is +Y.+ mat3 frame = upFrame(normalize(entry + u_renderOrigin.xyz - vec3(u_planetX, u_planetY, u_planetZ)));+ dir = frame * dir;+ sun = frame * sun;+ }float se = sun.y;float overcast = clamp(u_overcast, 0.0, 1.0);@@ -430,6 +448,16 @@ fn cloudDensity(p : vec3f, coverage : f32, base : f32, thick : f32, octaves : i3return smoothstep(1.0 - coverage, 1.0 - coverage + 0.22, n) * shape;}+fn frame_origin() -> vec3f { return frame.renderOrigin.xyz; }++/// The turn that takes up to +Y by the shortest way: the sky is worked out where up is +Y, so on a round world in the frame of the ground the camera stands on.+fn upFrame(up : vec3f) -> mat3x3f {+ let v = vec3f(-up.z, 0.0, up.x);+ let k = 1.0 / max(1.0 + up.y, 1e-4);+ let cross = mat3x3f(vec3f(0.0, v.z, -v.y), vec3f(-v.z, 0.0, v.x), vec3f(v.y, -v.x, 0.0));+ return mat3x3f(vec3f(1.0, 0.0, 0.0), vec3f(0.0, 1.0, 0.0), vec3f(0.0, 0.0, 1.0)) + cross + (cross * cross) * k;+}+fn cloudShadowAt(world : vec3f, cam : vec3f, sun : vec3f, coverage : f32, overcast : f32, drift : vec3f, px : vec2f) -> f32 {let strength = mc.u_cloudShadow * smoothstep(0.02, 0.14, sun.y);if (strength <= 0.001 || coverage <= 0.01) { return 1.0; }@@ -460,7 +488,7 @@ fn cloudShadowAt(world : vec3f, cam : vec3f, sun : vec3f, coverage : f32, overcaif (geometry && mc.u_cloudShadow <= 0.001) { return src; }let entry = worldFromDepth(v.v_texCoord, 0.0);- let dir = normalize(worldFromDepth(v.v_texCoord, 1.0) - entry);+ var dir = normalize(worldFromDepth(v.v_texCoord, 1.0) - entry);let found = findSun();let follow = mc.u_followSun > 0.5 && found.dir.w > 0.5;@@ -468,6 +496,11 @@ fn cloudShadowAt(world : vec3f, cam : vec3f, sun : vec3f, coverage : f32, overcalet el = radians(mc.u_sunElevation);var sun = vec3f(cos(el) * sin(az), sin(el), cos(el) * cos(az));if (follow) { sun = found.dir.xyz; }+ if (mc.u_planetRadius > 0.0) {+ let frame = upFrame(normalize(entry + frame_origin() - vec3f(mc.u_planetX, mc.u_planetY, mc.u_planetZ)));+ dir = frame * dir;+ sun = frame * sun;+ }let se = sun.y;let overcast = clamp(mc.u_overcast, 0.0, 1.0);diff --git a/sdk/src/terrain/planetPages.ts b/sdk/src/terrain/planetPages.tsindex 166c1818c..6e4408c75 100644--- a/sdk/src/terrain/planetPages.ts+++ b/sdk/src/terrain/planetPages.ts@@ -104,7 +104,7 @@ function encodePlanetPage(src: PlanetPageSource, node: SphereNode, dirs: Float32}/** How many samples apart a painter is asked: it paints as a biome does, over many metres, and is read at every few texels and filtered between. */-const PAINT_STRIDE = 4;+const PAINT_STRIDE = 8;/*** The page's paint from a painter asked every PAINT_STRIDE samples (from the first sample inside the page, so two pages that share an edge ask the samediff --git a/sdk/src/terrain/planetPlugin.ts b/sdk/src/terrain/planetPlugin.tsindex 20948c882..b2262880e 100644--- a/sdk/src/terrain/planetPlugin.ts+++ b/sdk/src/terrain/planetPlugin.ts@@ -15,7 +15,7 @@import type { App, Plugin } from '../app/app';import { defineSystem, Schedule } from '../ecs/system';import {- defineComponent, Camera, MeshRenderer, Transform,+ defineComponent, Camera, MeshRenderer, RuntimeOnly, Transform,type ComponentDef, type CameraData, type MeshRendererData, type TransformData,} from '../ecs/component';import { Assets } from '../asset/AssetPlugin';@@ -34,6 +34,7 @@ import { PageTable, PAGE_SIDE, PAGE_TEXELS, PATCH_CELLS, type PageImage } from 'import { buildPatchMesh } from './patch';import { loadLayerArrays, releaseLayerArrays } from './layerArrays';import { PlanetRegistry, PlanetRegistryRes } from './planetQuery';+import { buildSphereMesh } from './planetSea';import { removePlanetCollision, updatePlanetCollision } from './planetCollision';import { planetProvider, planetProvidersRevision, type PlanetProvider } from './planetProvider';import { makePlanetPage, type PlanetPageSource } from './planetPages';@@ -65,6 +66,12 @@ export interface PlanetData {collisionDistance: number;collisionLayer: number;friction: number;+ /** Whether the planet has a sea: a sphere at `seaLevel` above the radius, which the ground that dips below it stands in. */+ sea: boolean;+ seaLevel: number;+ /** The sea's colour and how much of it there is over what is under it (0 to 1). */+ seaColor: Color;+ seaOpacity: number;/** How hard the planet pulls what is on it, in metres a second squared at the surface; 0 pulls nothing. Bodies are pulled toward the centre of the nearest planet that pulls (physics3d/planetGravity.ts). */gravity: 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. */@@ -81,7 +88,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, gravity: 0, layers: [] as string[],+ macroScale: 90, macroVariation: 0.35, collision: true, collisionDistance: 64, collisionLayer: 0, friction: 0.6, gravity: 0, sea: false, seaLevel: 0, seaColor: rgb(0.06, 0.28, 0.42), seaOpacity: 0.82, 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.' },@@ -97,6 +104,10 @@ 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.' },+ sea: { category: 'Sea', tooltip: 'Whether the planet has a sea: a sphere at the sea level, in which the ground that dips below it stands.' },+ seaLevel: { category: 'Sea', tooltip: 'The height of the sea above the planet\'s radius, in metres.' },+ seaColor: { category: 'Sea' },+ seaOpacity: { min: 0, max: 1, step: 0.01, category: 'Sea', tooltip: 'How much of the sea there is over what is under it.' },gravity: { min: 0, category: 'Physics', tooltip: 'How hard the planet pulls bodies toward its centre, in metres a second squared at the surface (9.81 is the Earth\'s). Needs 3D physics; the world\'s own gravity is taken off the bodies it pulls.' },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.' },@@ -142,6 +153,8 @@ interface Built {providers: number;/** The painters' revision the pages were last painted at. */painted: number;+ /** The sea's entity, mesh and material instance, when the planet has one. */+ sea: { entity: Entity; mesh: number; material: number; base: number } | null;}/** Where a planet stands: still being made, ready, or failed (with why). */@@ -200,10 +213,15 @@ export class PlanetPlugin implements Plugin {centre: [at.x, at.y, at.z], radius: built.data.radius, gravity: built.data.gravity,height: (dx, dy, dz) => sampleAt(source, dx, dy, dz)?.heights[0] ?? null,paint: (dx, dy, dz) => { const got = sampleAt(source, dx, dy, dz); return got?.paint ? Array.from(got.paint.subarray(0, 4)) : null; },+ sampleMany: (directions, count) => {+ const got = source.provider.sample({ world: source.world, seed: source.seed, version: source.version, radius: source.radius, directions, count });+ return got instanceof Promise ? null : got;+ },fieldNames: source.provider.fields ?? [],fieldsAt: source.provider.fields ? (dx, dy, dz) => { const got = sampleAt(source, dx, dy, dz); return got?.fields ? Array.from(got.fields) : null; } : null,layers: built.data.layers.map((ref, i) => (ref.split('/').pop() ?? '').replace(/\.[^.]*$/, '') || `layer${i}`),});+ this.keepSea(app, entity, built);updatePlanetCollision(app, entity, built.source, built.epoch, built.data);if (!built.instance) {if (!built.pending) void this.prepare(app, built);@@ -227,7 +245,7 @@ export class PlanetPlugin implements Plugin {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, arrays: [], packed: '', packing: false,- providers: planetProvidersRevision(), painted: 0,+ providers: planetProvidersRevision(), painted: 0, sea: null,};const provider = planetProvider(data.provider);if (!provider) {@@ -369,6 +387,61 @@ export class PlanetPlugin implements Plugin {this.place(app, entity, built, drawn);}+ /** The sea: a sphere at the sea level standing at the planet, made when the planet has one and let go when it has not. */+ private keepSea(app: App, entity: Entity, built: Built): void {+ const d = built.data, world = app.world;+ if (!d.sea || !app.hasResource(Assets)) { this.dropSea(app, built); return; }+ if (!built.sea) {+ if (this.seaPending_) return;+ this.seaPending_ = true;+ void this.makeSea(app, entity, built).finally(() => { this.seaPending_ = false; });+ return;+ }+ const sea = built.sea;+ const r = d.radius + d.seaLevel;+ const t = world.get(sea.entity, Transform) as TransformData;+ if (t.scale.x !== r) world.insert(sea.entity, Transform, { ...t, scale: { x: r, y: r, z: r } });+ const c = d.seaColor;+ Material.setUniform(sea.material, 'u_seaColor', { x: c.r, y: c.g, z: c.b, w: 1 });+ Material.setUniform(sea.material, 'u_seaOpacity', d.seaOpacity);+ }++ private seaPending_ = false;++ /** Makes the sea: the sphere, a material on the Planet Sea shader that blends over what is under it and is hidden by what is nearer, and the entity. */+ private async makeSea(app: App, entity: Entity, built: Built): Promise<void> {+ const world = app.world, assets = app.getResource(Assets);+ const source = await assets.load<MaterialShaderSource>('material-shader', 'builtin:planet-sea');+ const shader = source.compile([]);+ const base = Material.createFromAsset({+ version: MATERIAL_FORMAT_VERSION, type: 'material', shader: 'builtin:planet-sea', blendMode: BlendMode.Normal,+ depthTest: true, depthWrite: false, cull: CullMode.Back, properties: {},+ }, shader);+ const material = Material.createInstance(base);+ const mesh = assets.createMesh(buildSphereMesh(96, 192));+ if (!material || !mesh || !world.valid(entity) || !built.data.sea || built.sea) {+ if (material) Material.release(material);+ Material.release(base);+ if (mesh) assets.releaseBuiltMesh(mesh);+ return;+ }+ const e = world.spawn('PlanetSea');+ world.insert(e, RuntimeOnly);+ world.insert(e, Transform, {});+ world.insert(e, MeshRenderer, { mesh, material, lit: true, opaque: false, cullBackfaces: true, castShadows: false, color: { r: 1, g: 1, b: 1, a: 1 } } as Partial<MeshRendererData>);+ world.setParent(e, entity);+ built.sea = { entity: e, mesh, material, base };+ }++ private dropSea(app: App, built: Built): void {+ if (!built.sea) return;+ if (app.world.valid(built.sea.entity)) app.world.despawn(built.sea.entity);+ if (app.hasResource(Assets)) app.getResource(Assets).releaseBuiltMesh(built.sea.mesh);+ Material.release(built.sea.material);+ Material.release(built.sea.base);+ built.sea = null;+ }+/** 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 ?? [];@@ -503,6 +576,7 @@ export class PlanetPlugin implements Plugin {private destroy(app: App, built: Built): void {built.epoch++;+ this.dropSea(app, built);bakesOf(app).clear(built);const world = app.world;for (const e of [...built.nodes.values(), ...built.spare]) if (world.valid(e)) world.despawn(e);diff --git a/sdk/src/terrain/planetQuery.ts b/sdk/src/terrain/planetQuery.tsindex 8d117506a..6f890e8c4 100644--- a/sdk/src/terrain/planetQuery.ts+++ b/sdk/src/terrain/planetQuery.ts@@ -12,6 +12,7 @@*/import { defineResource } from '../ecs/resource';import type { Entity } from '../types';+import type { PlanetSamples } from './planetProvider';/** What a planet says of itself, from its component and its provider. */export interface PlanetFacts {@@ -28,6 +29,8 @@ export interface PlanetFacts {/** The names of the provider's own fields, and their values in a direction (null where it cannot say yet). */fieldNames: readonly string[];fieldsAt: ((dx: number, dy: number, dz: number) => readonly number[] | null) | null;+ /** The provider's answer for many directions at once (heights, paint, fields), or null while it answers later: a world is laid out from tiles of it, not a call a point. */+ sampleMany: ((directions: Float32Array, count: number) => PlanetSamples | null) | null;}/**diff --git a/sdk/src/terrain/planetSea.ts b/sdk/src/terrain/planetSea.tsnew file mode 100644index 000000000..5a6107fe4--- /dev/null+++ b/sdk/src/terrain/planetSea.ts@@ -0,0 +1,132 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file planetSea.ts+ * @brief The sea of a planet: a sphere at the sea level, lit like any surface and seen through, in which the ground stands.+ *+ * @details The first slice of water on a round world. A flat world's water (water/) is a plane of waves lifted over a zone; a planet's sea is the sphere+ * at `radius + seaLevel`, so the ground that dips below it is under water and the horizon curves away over it. It has a colour and an opacity+ * and takes the sun and the sky as a smooth, shining surface does; waves, shore foam and depth colour are the flat water's, and come to the sphere later.+ */+import { MeshChannel, MeshChannelType, packChannels, type MeshData } from '../asset/meshFormat';++/** A unit sphere (radius 1, outward normals) of `rings` bands of `segments` quads, as a mesh. */+export function buildSphereMesh(rings: number, segments: number): MeshData {+ const r = Math.max(2, Math.floor(rings)), s = Math.max(3, Math.floor(segments));+ const { channels, vertexStride } = packChannels([+ { semantic: MeshChannel.Position, components: 3, type: MeshChannelType.Float32 },+ { semantic: MeshChannel.TexCoord0, components: 2, type: MeshChannelType.Float32 },+ { semantic: MeshChannel.Color, components: 4, type: MeshChannelType.UNorm8 },+ { semantic: MeshChannel.Normal, components: 3, type: MeshChannelType.Float32 },+ ]);+ const count = (r + 1) * (s + 1);+ const vertices = new Uint8Array(count * vertexStride);+ const view = new DataView(vertices.buffer);+ const [pos, uv, color, normal] = channels.map((c) => c.offset) as [number, number, number, number];+ for (let j = 0; j <= r; j++) {+ const theta = (j / r) * Math.PI, sin = Math.sin(theta), cos = Math.cos(theta);+ for (let i = 0; i <= s; i++) {+ const phi = (i / s) * Math.PI * 2;+ const x = sin * Math.cos(phi), y = cos, z = sin * Math.sin(phi);+ const base = (j * (s + 1) + i) * vertexStride;+ view.setFloat32(base + pos, x, true); view.setFloat32(base + pos + 4, y, true); view.setFloat32(base + pos + 8, z, true);+ view.setFloat32(base + uv, i / s, true); view.setFloat32(base + uv + 4, j / r, true);+ for (let k = 0; k < 4; k++) view.setUint8(base + color + k, 255);+ view.setFloat32(base + normal, x, true); view.setFloat32(base + normal + 4, y, true); view.setFloat32(base + normal + 8, z, true);+ }+ }+ const indices = new Uint32Array(r * s * 6);+ let at = 0;+ for (let j = 0; j < r; j++) for (let i = 0; i < s; i++) {+ const a = j * (s + 1) + i, b = a + 1, c = a + s + 1, d = c + 1;+ // Counter-clockwise from outside: down the band, then along it.+ indices.set([a, b, c, b, d, c], at);+ at += 6;+ }+ return { channels, vertexStride, vertexCount: count, vertices, indices, aabbMin: [-1, -1, -1], aabbMax: [1, 1, 1] };+}++import { makeBuiltinShaderTemplate } from '../render/builtinShaders';++const PLANET_SEA = `#pragma shader "Planet Sea"+#pragma version 300 es+#pragma domain Lit+// The sea's colour, and how much of it there is over what is under it.+#pragma param u_seaColor color default(0.05,0.3,0.45,1)+#pragma param u_seaOpacity float default(0.85) range(0,1) ui(slider)++#pragma fragment+precision highp float;++in vec4 v_color;+in vec2 v_texCoord;+in highp vec2 v_worldPos;+#ifdef MESH_NORMALS+in highp vec3 v_worldNormal;+in highp vec3 v_worldXYZ;+#endif++#ifdef ES_GBUFFER+layout(location = 0) out vec4 fragColor;+layout(location = 1) out vec4 fragSurface;+#else+out vec4 fragColor;+#endif++void main() {+#ifdef MESH_NORMALS+ highp vec3 P = v_worldXYZ;+ highp vec3 N = normalize(v_worldNormal);+#else+ highp vec3 P = vec3(v_worldPos.x, 0.0, v_worldPos.y);+ highp vec3 N = vec3(0.0, 1.0, 0.0);+#endif+ // A smooth, shining surface: the sun and the sky lie on it, and what is under it shows through by the opacity.+ float roughness = 0.08;+ SurfaceExt ext = surfaceExtNone(N);+ vec3 lit = applyLightingSurface(u_seaColor.rgb, N, P, viewDirection(P), 0.0, roughness, 0.5, 1.0, ext);+ fragColor = vec4(lit, u_seaOpacity);+#ifdef ES_GBUFFER+ fragSurface = vec4(0.5, 0.5, roughness, 0.0);+#endif+}+#pragma end++#pragma fragment wgsl+#ifdef ES_GBUFFER+struct FragOut {+ @location(0) color : vec4f,+ @location(1) surface : vec4f,+};+@fragment fn fs_main(v : VSOut) -> FragOut {+#else+@fragment fn fs_main(v : VSOut) -> @location(0) vec4f {+#endif+ g_probeSlot = v.v_probeSlot;+#ifdef MESH_LIGHTMAP+ g_lightmap = v.v_lightmap;+#endif+#ifdef MESH_NORMALS+ let P = v.v_worldXYZ;+ let N = normalize(v.v_worldNormal);+#else+ let P = vec3f(v.v_worldPos.x, 0.0, v.v_worldPos.y);+ let N = vec3f(0.0, 1.0, 0.0);+#endif+ let roughness = 0.08;+ let ext = surfaceExtNone(N);+ let lit = applyLightingSurface(mc.u_seaColor.rgb, N, P, viewDirection(P), 0.0, roughness, 0.5, 1.0, ext);+#ifdef ES_GBUFFER+ var frag : FragOut;+ frag.color = vec4f(lit, mc.u_seaOpacity);+ frag.surface = vec4f(0.5, 0.5, roughness, 0.0);+ return frag;+#else+ return vec4f(lit, mc.u_seaOpacity);+#endif+}+#pragma end+`;++export const PLANET_SEA_SHADER_TEMPLATE = makeBuiltinShaderTemplate('planet-sea', 'Planet Sea',+ 'The sea of a planet: a lit, translucent surface in a colour.', PLANET_SEA);diff --git a/sdk/src/terrain/terrainSupport.ts b/sdk/src/terrain/terrainSupport.tsindex 3ebc16e17..4f49ade8b 100644--- a/sdk/src/terrain/terrainSupport.ts+++ b/sdk/src/terrain/terrainSupport.ts@@ -12,12 +12,14 @@ import { TERRAIN_LAYERS_SHADER_TEMPLATE, TERRAIN_SHADER_TEMPLATE } from './terraimport { TerrainPlugin } from './terrainPlugin';import { PLANET_SHADER_TEMPLATE } from './planetShader';import { PlanetPlugin } from './planetPlugin';+import { PLANET_SEA_SHADER_TEMPLATE } from './planetSea';import { TerrainLayerAssetLoader } from './layers';export function registerTerrainSupport(): void {registerBuiltinShaderTemplate(TERRAIN_SHADER_TEMPLATE);registerBuiltinShaderTemplate(TERRAIN_LAYERS_SHADER_TEMPLATE);registerBuiltinShaderTemplate(PLANET_SHADER_TEMPLATE);+ registerBuiltinShaderTemplate(PLANET_SEA_SHADER_TEMPLATE);addEntryPlugin('terrain', () => new TerrainPlugin());addEntryPlugin('planet', () => new PlanetPlugin());addAssetLoader('terrain', () => new TerrainLayerAssetLoader());diff --git a/sdk/src/worldgen/planetSurface.ts b/sdk/src/worldgen/planetSurface.tsindex 870220950..2a3f3530b 100644--- a/sdk/src/worldgen/planetSurface.ts+++ b/sdk/src/worldgen/planetSurface.ts@@ -29,6 +29,23 @@ export interface PlaneFrame {ev: [number, number, number];}+/** Metres between the points of a tile, the cells along its side, and so its side; how many tiles a face keeps. */+const TILE_STEP = 1.5;+const TILE_CELLS = 32;+const TILE_SIDE = TILE_STEP * TILE_CELLS;+const TILES_KEPT = 6000;++/** A square of the planet's answer: its heights, its paint and its fields at a grid of points (one extra row and column each side). */+interface Tile {+ x0: number;+ z0: number;+ n: number;+ heights: Float32Array;+ paint: Float32Array | undefined;+ fields: Float32Array | undefined;+ fieldCount: number;+}+/** One face of a planet as a plane. */export class PlanetFace {constructor(readonly face: number, readonly planet: () => PlanetFacts | null) {}@@ -66,18 +83,76 @@ export class PlanetFace {return [f.centre[0] + d[0] * r, f.centre[1] + d[1] * r, f.centre[2] + d[2] * r];}+ /** The tiles of the planet's answer this face has read, newest last: a world is laid out from these, not from a call of the provider for each point it asks about. */+ private readonly tiles_ = new Map<string, Tile>();++ /** The tile of the plane that holds (x, z), read from the provider in one call for all its points; null while the provider answers later. */+ private tile(x: number, z: number): Tile | null {+ const tx = Math.floor(x / TILE_SIDE), tz = Math.floor(z / TILE_SIDE), key = `${tx},${tz}`;+ const had = this.tiles_.get(key);+ if (had) { this.tiles_.delete(key); this.tiles_.set(key, had); return had; }+ const f = this.facts();+ if (!f?.sampleMany) return null;+ // One more point than cells each way, and a point past each edge, so the neighbours' tiles agree at the join and a slope can be taken at the edge.+ const n = TILE_CELLS + 3;+ const dirs = new Float32Array(n * n * 3);+ for (let j = 0; j < n; j++) for (let i = 0; i < n; i++) {+ const d = this.directionAt(tx * TILE_SIDE + (i - 1) * TILE_STEP, tz * TILE_SIDE + (j - 1) * TILE_STEP);+ dirs[(j * n + i) * 3] = d[0]; dirs[(j * n + i) * 3 + 1] = d[1]; dirs[(j * n + i) * 3 + 2] = d[2];+ }+ const got = f.sampleMany(dirs, n * n);+ if (!got) return null;+ const tile: Tile = { x0: tx * TILE_SIDE - TILE_STEP, z0: tz * TILE_SIDE - TILE_STEP, n, heights: got.heights, paint: got.paint, fields: got.fields, fieldCount: f.fieldNames.length };+ this.tiles_.set(key, tile);+ if (this.tiles_.size > TILES_KEPT) this.tiles_.delete(this.tiles_.keys().next().value!);+ return tile;+ }++ /** The cell of a tile that holds (x, z), and where in it. */+ private cellOf(t: Tile, x: number, z: number): { i: number; j: number; fx: number; fz: number } {+ const u = (x - t.x0) / TILE_STEP, v = (z - t.z0) / TILE_STEP;+ const i = Math.min(Math.max(Math.floor(u), 0), t.n - 2), j = Math.min(Math.max(Math.floor(v), 0), t.n - 2);+ return { i, j, fx: Math.min(Math.max(u - i, 0), 1), fz: Math.min(Math.max(v - j, 0), 1) };+ }++ /** The ground's height above the radius at (x, z), filtered between the tile's points; null where it cannot be said yet. */+ private heightAt(x: number, z: number): number | null {+ const t = this.tile(x, z);+ if (!t) return null;+ const { i, j, fx, fz } = this.cellOf(t, x, z), n = t.n, h = t.heights;+ const a = h[j * n + i]!, b = h[j * n + i + 1]!, c = h[(j + 1) * n + i]!, d = h[(j + 1) * n + i + 1]!;+ return (a + (b - a) * fx) * (1 - fz) + (c + (d - c) * fx) * fz;+ }++ /** The planet's layers' paint at (x, z) from the provider (the nearest point of its tile), or null where it does not paint or cannot say yet. */+ paintAt(x: number, z: number): readonly number[] | null {+ const t = this.tile(x, z);+ if (!t?.paint) return null;+ const { i, j, fx, fz } = this.cellOf(t, x, z), k = (j + (fz > 0.5 ? 1 : 0)) * t.n + i + (fx > 0.5 ? 1 : 0);+ return [t.paint[k * 4]!, t.paint[k * 4 + 1]!, t.paint[k * 4 + 2]!, t.paint[k * 4 + 3]!];+ }++ /** The provider's own fields at (x, z), filtered between the tile's points; null where it has none or cannot say yet. */+ fieldsAt(x: number, z: number): readonly number[] | null {+ const t = this.tile(x, z);+ if (!t?.fields || t.fieldCount === 0) return null;+ const { i, j, fx, fz } = this.cellOf(t, x, z), m = t.fieldCount, n = t.n;+ const out: number[] = [];+ for (let c = 0; c < m; c++) {+ const a = t.fields[(j * n + i) * m + c]!, b = t.fields[(j * n + i + 1) * m + c]!, e = t.fields[((j + 1) * n + i) * m + c]!, d = t.fields[((j + 1) * n + i + 1) * m + c]!;+ out.push((a + (b - a) * fx) * (1 - fz) + (e + (d - e) * fx) * fz);+ }+ return out;+ }+/** The ground under a point of the plane: its height above the radius, how much it faces away from the centre, and its normal along the plane's x, up and z. */ground(x: number, z: number): { y: number; up: number; normal: [number, number, number] } | null {- const f = this.facts();- if (!f?.height) return null;- const at = (px: number, pz: number): number | null => { const d = this.directionAt(px, pz); return f.height!(d[0], d[1], d[2]); };- const h = at(x, z);+ const h = this.heightAt(x, z);if (h === null) return null;- // The normal from the ground a couple of metres either way along the plane, taken in the frame there.- const step = 2;- const hx0 = at(x - step, z), hx1 = at(x + step, z), hz0 = at(x, z - step), hz1 = at(x, z + step);+ // The normal from the ground a step either way along the plane: the rise over the run (the curve of the planet itself is not a slope).+ const step = TILE_STEP;+ const hx0 = this.heightAt(x - step, z), hx1 = this.heightAt(x + step, z), hz0 = this.heightAt(x, z - step), hz1 = this.heightAt(x, z + step);if (hx0 === null || hx1 === null || hz0 === null || hz1 === null) return { y: h, up: 1, normal: [0, 1, 0] };- // The ground's rise along each axis, over the run of the chord between the two points (the curve itself is not a slope).const run = 2 * step;const nx = -(hx1 - hx0) / run, nz = -(hz1 - hz0) / run;const len = Math.hypot(nx, 1, nz);diff --git a/sdk/src/worldgen/worldgenPlugin.ts b/sdk/src/worldgen/worldgenPlugin.tsindex be4c536fe..d94269247 100644--- a/sdk/src/worldgen/worldgenPlugin.ts+++ b/sdk/src/worldgen/worldgenPlugin.ts@@ -522,11 +522,11 @@ export class WorldGenPlugin implements Plugin {// The planet's layers, as the provider paints them, are fields (`paint.grass` for a layer file grass.esterrainlayer), as a terrain's are.const paintFields: Record<string, (x: number, z: number) => number> = {};(facts()?.layers ?? []).forEach((name, i) => {- paintFields[`paint.${name}`] = (x, z) => { const d = face.directionAt(x, z); return facts()?.paint?.(d[0], d[1], d[2])?.[i] ?? 0; };+ paintFields[`paint.${name}`] = (x, z) => face.paintAt(x, z)?.[i] ?? 0;});// And the provider's own fields (an ecology) by the names it gives them.(facts()?.fieldNames ?? []).forEach((name, i) => {- paintFields[name] = (x, z) => { const d = face.directionAt(x, z); return facts()?.fieldsAt?.(d[0], d[1], d[2])?.[i] ?? 0; };+ paintFields[name] = (x, z) => face.fieldsAt(x, z)?.[i] ?? 0;});const env = new Environment({seed: data.seed, noise: rules.noise, fields: { ...paintFields, ...rules.fields },diff --git a/sdk/tests/planet-gravity.test.ts b/sdk/tests/planet-gravity.test.tsindex f4712e1ee..2b8cf07aa 100644--- a/sdk/tests/planet-gravity.test.ts+++ b/sdk/tests/planet-gravity.test.ts@@ -9,8 +9,8 @@ const a = 1 as Entity, b = 2 as Entity;describe('the planets of a world', () => {const registry = new PlanetRegistry();- registry.planets.set(a, { centre: [0, -4000, 0], radius: 4000, gravity: 9.81, height: (dx, dy, dz) => 10 * dy + 0 * dx * dz, paint: null, layers: [], fieldNames: [], fieldsAt: null });- registry.planets.set(b, { centre: [50000, 0, 0], radius: 1000, gravity: 3, height: null, paint: null, layers: [], fieldNames: [], fieldsAt: null });+ registry.planets.set(a, { centre: [0, -4000, 0], radius: 4000, gravity: 9.81, height: (dx, dy, dz) => 10 * dy + 0 * dx * dz, paint: null, layers: [], fieldNames: [], fieldsAt: null, sampleMany: null });+ registry.planets.set(b, { centre: [50000, 0, 0], radius: 1000, gravity: 3, height: null, paint: null, layers: [], fieldNames: [], fieldsAt: null, sampleMany: null });it('name the planet whose surface is nearest, from anywhere', () => {expect(registry.nearest(0, 100, 0)).toBe(a);diff --git a/sdk/tests/worldgen-planet.test.ts b/sdk/tests/worldgen-planet.test.tsindex 9115160e1..a5d055d4b 100644--- a/sdk/tests/worldgen-planet.test.ts+++ b/sdk/tests/worldgen-planet.test.ts@@ -10,10 +10,16 @@ import { Zones } from '../src/worldgen/zones';const radius = 4000;/** A planet whose ground is a gentle function of the direction, with a hill, so slope and height both vary. */-const facts: PlanetFacts = {- centre: [0, -radius, 0], radius, gravity: 0, paint: null, layers: [], fieldNames: [], fieldsAt: null,- height: (dx, dy, dz) => 6 + 5 * Math.sin(dx * 40) * Math.cos(dz * 33) + 3 * dy,-};+/** A planet whose ground is `height` of the direction, answered for many directions at once as a provider does. */+const planetOf = (height: (dx: number, dy: number, dz: number) => number): PlanetFacts => ({+ centre: [0, -radius, 0], radius, gravity: 0, paint: null, layers: [], fieldNames: [], fieldsAt: null, height,+ sampleMany: (directions, count) => {+ const heights = new Float32Array(count);+ for (let i = 0; i < count; i++) heights[i] = height(directions[i * 3]!, directions[i * 3 + 1]!, directions[i * 3 + 2]!);+ return { heights };+ },+});+const facts = planetOf((dx, dy, dz) => 6 + 5 * Math.sin(dx * 40) * Math.cos(dz * 33) + 3 * dy);const planet = (): PlanetFacts => facts;const rules: WorldRules = {@@ -49,13 +55,13 @@ describe('a planet\'s face as a plane', () => {});it('reads the ground and its normal, level ground facing up', () => {- const flat: PlanetFacts = { ...facts, height: () => 4 };+ const flat = planetOf(() => 4);const f = new PlanetFace(2, () => flat);const g = f.ground(10, 20)!;expect(g.y).toBe(4);expect(g.up).toBeCloseTo(1, 9);expect(g.normal[1]).toBeCloseTo(1, 9);- const tilted: PlanetFacts = { ...facts, height: (dx) => dx * 4000 * 0.5 };+ const tilted = planetOf((dx) => dx * 4000 * 0.5);const t = new PlanetFace(2, () => tilted).ground(0, 0)!;expect(t.up).toBeLessThan(0.95);});diff --git a/tools/releaseNotes.mjs b/tools/releaseNotes.mjsindex d01f46852..932da4764 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 has a sea and a sky that follows the ground the camera stands on":+ {"note":"A planet's sea and sky."},"feat(worldgen): a generated world lays out over a planet's six faces":{"note":"A generated world on a planet."},"feat(terrain): a planet pulls bodies toward its centre and answers up, altitude and ground height":