Skip to content

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

feat(terrain): a planet pulls bodies toward its centre and answers up, altitude and ground height

yhh4aa60f46194f
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 9a3c63a8b..b08b9f7eb 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -16,6 +16,7 @@ published separately; it ships inside the editor.
### Added
+- **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.
- **A planet's ground has the layers' textures.** `Planet.layers` names up to four `.esterrainlayer` files, as on a flat terrain: each layer's albedo and normal map are read on the planes of the world's axes by how much the ground faces them, with a wider read mixed in far off so the repeat is lost. Without layers the ground is still the four colours.
- **A planet's ground collides.** `Planet` takes `collision`, `collisionDistance`, `collisionLayer` and `friction` as flat terrain does: the finest nodes round every moving 3D body and character are built as collision geometry from the same samples the ground is drawn from, one chunk layer to each face of the cube.
diff --git a/docs/astro/src/content/docs/graphics/terrain.mdx b/docs/astro/src/content/docs/graphics/terrain.mdx
index 5d583d5ef..68538f069 100644
--- a/docs/astro/src/content/docs/graphics/terrain.mdx
+++ b/docs/astro/src/content/docs/graphics/terrain.mdx
@@ -282,6 +282,8 @@ registerPlanetProvider({
});
```
+A planet answers the questions a round world puts to everything standing on it, through the `PlanetRegistryRes` resource: `up(planet, x, y, z)` is the unit direction away from its centre, `altitude` the height above the radius, `groundHeight` the generator's own height under a position (null while a provider answers later) and `groundPoint` the point on the ground under it. `nearest(x, y, z)` names the planet whose surface is nearest. Set `gravity` (metres a second squared at the surface) and 3D physics pulls every dynamic body toward the centre of the nearest planet that pulls: the world's one gravity is taken off the body and the planet's put on, as a force each fixed step, so with the world's gravity at zero a body simply falls toward the planet.
+
The ground collides: the finest nodes within `collisionDistance` of every moving 3D body and character are built as collision geometry from the same samples the ground is drawn from (`collision`, `collisionDistance`, `collisionLayer`, `friction`, as on a flat terrain). A planet's transform is a position only: a turned or scaled planet's collision stands where it would be unturned. `layers` names up to four `.esterrainlayer` files, as on a flat terrain; each is read on the planes of the world's axes by how much the ground faces them, with a wider read mixed in far off so the repeat is lost. Without layers the ground is the four colours. The sea, a sky that follows the horizon round and gravity toward the centre are not in it yet; a body falls along the world's one gravity, so toward the centre only at the top of the planet.
## Limits
diff --git a/docs/astro/src/content/docs/zh-cn/graphics/terrain.mdx b/docs/astro/src/content/docs/zh-cn/graphics/terrain.mdx
index b2e61d6dc..b86bbe015 100644
--- a/docs/astro/src/content/docs/zh-cn/graphics/terrain.mdx
+++ b/docs/astro/src/content/docs/zh-cn/graphics/terrain.mdx
@@ -193,6 +193,8 @@ registerTerrainProvider(planet);
星球的提供器回答的是**方向**,不是位置:它拿到从星球中心出发的单位方向和它们所在的半径,给出每个方向上高出半径的高度,如果上色,再给出四个图层权重。球面没有 x 和 z,所以生成器读三维噪声,没有接缝也没有极点。
+星球回答圆形世界向站在上面的一切提出的问题,通过 `PlanetRegistryRes` 资源:`up(planet, x, y, z)` 是背离球心的单位方向,`altitude` 是高出半径的高度,`groundHeight` 是生成器自己在某位置下的地面高度(提供器稍后才回答时为 null),`groundPoint` 是它下面地面上的那个点。`nearest(x, y, z)` 给出表面最近的星球。设置 `gravity`(表面处的米每二次方秒),3D 物理就把每个动态刚体拉向最近的、有引力的星球中心:世界唯一的重力从刚体上拿掉,换上星球的,每个固定步长作为一个力施加;世界重力设为 0 时,刚体就是朝星球落下。
+
地面有碰撞:每个运动的 3D 刚体和角色在 `collisionDistance` 内的最细节点,会用画地面的同一批采样建成碰撞几何(`collision`、`collisionDistance`、`collisionLayer`、`friction`,和平面地形一样)。星球的变换只有位置:旋转或缩放过的星球,碰撞仍站在没旋转时的位置。`layers` 可以写最多四个 `.esterrainlayer` 文件,和平面地形一样;每层按地面朝向世界坐标轴的程度,在三个投影面上取样,远处混入更宽的一次取样,看不出重复。不写图层时地面就是四种颜色。海、跟着地平线转的天空和指向球心的重力还没有;物体沿世界唯一的重力下落,所以只有在星球顶部才是朝向球心。
## 限制
diff --git a/docs/astro/src/data/apiStability.generated.json b/docs/astro/src/data/apiStability.generated.json
index c32f3472a..c772e8387 100644
--- a/docs/astro/src/data/apiStability.generated.json
+++ b/docs/astro/src/data/apiStability.generated.json
@@ -3,10 +3,10 @@
"counts": {
"public": 115,
"beta": 171,
- "experimental": 2548,
+ "experimental": 2551,
"deprecated": 3
},
- "total": 2834,
+ "total": 2837,
"subsystems": [
{
"id": "mobile-controls",
diff --git a/sdk/etc/index.api.md b/sdk/etc/index.api.md
index 2b2e76d72..439f873a7 100644
--- a/sdk/etc/index.api.md
+++ b/sdk/etc/index.api.md
@@ -6749,6 +6749,7 @@ collisionLayer: number
detail: number
friction: number
generatorVersion: number
+gravity: number
layerColor0: Color
layerColor1: Color
layerColor2: Color
diff --git a/sdk/etc/index.native.api.md b/sdk/etc/index.native.api.md
index b03abfc6b..0b9152b90 100644
--- a/sdk/etc/index.native.api.md
+++ b/sdk/etc/index.native.api.md
@@ -6952,6 +6952,7 @@ collisionLayer: number
detail: number
friction: number
generatorVersion: number
+gravity: number
layerColor0: Color
layerColor1: Color
layerColor2: Color
diff --git a/sdk/etc/index.node.api.md b/sdk/etc/index.node.api.md
index 78391bccb..43dbf3133 100644
--- a/sdk/etc/index.node.api.md
+++ b/sdk/etc/index.node.api.md
@@ -6744,6 +6744,7 @@ collisionLayer: number
detail: number
friction: number
generatorVersion: number
+gravity: number
layerColor0: Color
layerColor1: Color
layerColor2: Color
diff --git a/sdk/etc/minigame.api.md b/sdk/etc/minigame.api.md
index b3d353c97..ad9ac0625 100644
--- a/sdk/etc/minigame.api.md
+++ b/sdk/etc/minigame.api.md
@@ -7037,6 +7037,7 @@ collisionLayer: number
detail: number
friction: number
generatorVersion: number
+gravity: number
layerColor0: Color
layerColor1: Color
layerColor2: Color
diff --git a/sdk/etc/terrain.api.md b/sdk/etc/terrain.api.md
index af1de18d1..738e79c78 100644
--- a/sdk/etc/terrain.api.md
+++ b/sdk/etc/terrain.api.md
@@ -1,7 +1,7 @@
# API surface — esengine/terrain
<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->
-Symbols: 0 public · 0 beta · 94 experimental · 0 deprecated
+Symbols: 0 public · 0 beta · 97 experimental · 0 deprecated
## Eroded — interface @experimental
```
@@ -184,6 +184,7 @@ collisionLayer: number
detail: number
friction: number
generatorVersion: number
+gravity: number
layerColor0: Color
layerColor1: Color
layerColor2: Color
@@ -197,6 +198,14 @@ seed: number
world: string
```
+## PlanetFacts — interface @experimental
+```
+centre: [number, number, number]
+gravity: number
+height: ((dx: number, dy: number, dz: number) => number | null) | null
+radius: number
+```
+
## PlanetPageSource — interface @experimental
```
levels: number
@@ -236,6 +245,23 @@ version: number
world: string
```
+## PlanetRegistry — class @experimental
+```
+altitude: (entity: Entity, x: number, y: number, z: number) => number | null
+groundHeight: (entity: Entity, x: number, y: number, z: number) => number | null
+groundPoint: (entity: Entity, x: number, y: number, z: number) => [number, number, number] | null
+nearest: (x: number, y: number, z: number) => Entity | null
+planets: Map<number, PlanetFacts>
+up: (entity: Entity, x: number, y: number, z: number) => [number, number, number] | null
+static new (): PlanetRegistry
+static prototype: PlanetRegistry
+```
+
+## PlanetRegistryRes — const @experimental
+```
+ResourceDef<PlanetRegistry>
+```
+
## PlanetStatus — interface @experimental
```
reason: string | undefined
diff --git a/sdk/etc/wechat.api.md b/sdk/etc/wechat.api.md
index 83b45aa17..78cff04f2 100644
--- a/sdk/etc/wechat.api.md
+++ b/sdk/etc/wechat.api.md
@@ -6751,6 +6751,7 @@ collisionLayer: number
detail: number
friction: number
generatorVersion: number
+gravity: number
layerColor0: Color
layerColor1: Color
layerColor2: Color
diff --git a/sdk/src/physics3d/Physics3DPlugin.ts b/sdk/src/physics3d/Physics3DPlugin.ts
index 0ca54f882..86136fa97 100644
--- a/sdk/src/physics3d/Physics3DPlugin.ts
+++ b/sdk/src/physics3d/Physics3DPlugin.ts
@@ -4,6 +4,7 @@
* @file Physics3DPlugin.ts
* @brief Loads the 3D physics module and drives one world from the ECS.
*/
+import { installPlanetGravity } from './planetGravity';
import type { App, Plugin } from '../app/app';
import { Schedule, defineSystem } from '../ecs/system';
import { defineResource } from '../ecs/resource';
@@ -69,6 +70,8 @@ export class Physics3DPlugin implements Plugin {
};
app.insertResource(Physics3DEvents, events);
app.insertResource(Physics3DRuntime, runtime);
+ // A planet in the world pulls bodies toward its centre; with none, this does nothing.
+ installPlanetGravity(app);
app.subsystems?.transition?.('physics3d', 'initializing');
const initPromise = loadPhysics3DModule(this.wasmUrl_, this.factory_).then((module) => {
diff --git a/sdk/src/physics3d/planetGravity.ts b/sdk/src/physics3d/planetGravity.ts
new file mode 100644
index 000000000..2de5cfe88
--- /dev/null
+++ b/sdk/src/physics3d/planetGravity.ts
@@ -0,0 +1,62 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file planetGravity.ts
+ * @brief A planet pulls bodies toward its centre: the world's one gravity is taken off each body it pulls and the planet's put on, as a force.
+ *
+ * @details The physics world has one gravity vector, which on a round world is down only at one place. A body (a `RigidBody3D` that moves) is pulled
+ * by the nearest planet whose `gravity` is above 0: each fixed step, before the world steps, it gets the force that turns what the world
+ * would give it (`gravity * gravityScale`) into `gravity` toward the planet's centre, `mass * (g * down - world gravity * gravityScale)`.
+ * A world gravity of zero (the usual choice on a planet) makes that just the planet's pull. A planet that pulls nothing, and a world
+ * with no planet, leave every body as it was.
+ */
+import type { App } from '../app/app';
+import { defineSystem, Schedule } from '../ecs/system';
+import { Transform } from '../ecs/component';
+import type { Entity } from '../types';
+import { PlanetRegistryRes } from '../terrain/planetQuery';
+import { Physics3DRuntime } from './Physics3DPlugin';
+import { RigidBody3D, type RigidBody3DData } from './Physics3DComponents';
+
+/** The force on a body of `mass` that the planet's pull is, over the world's gravity: all in metres, kilograms and seconds. */
+export function planetPullForce(
+ mass: number, gravityScale: number, down: readonly [number, number, number], pull: number, world: readonly [number, number, number],
+): [number, number, number] {
+ return [
+ mass * (down[0] * pull - world[0] * gravityScale),
+ mass * (down[1] * pull - world[1] * gravityScale),
+ mass * (down[2] * pull - world[2] * gravityScale),
+ ];
+}
+
+/** Installs the system that pulls bodies toward the planets: every fixed step, before the world steps. */
+export function installPlanetGravity(app: App): void {
+ app.addSystemToSchedule(Schedule.FixedUpdate, defineSystem([], () => {
+ if (!app.hasResource(PlanetRegistryRes) || !app.hasResource(Physics3DRuntime)) return;
+ const registry = app.getResource(PlanetRegistryRes);
+ if (registry.planets.size === 0) return;
+ const runtime = app.getResource(Physics3DRuntime);
+ const module = runtime.module, config = runtime.config;
+ if (!module?._physics3d_addForce || !module._physics3d_getBodyDynamics || !config) return;
+ const ppu = config.pixelsPerUnit;
+ const world: [number, number, number] = [config.gravity.x, config.gravity.y, config.gravity.z];
+ for (const entity of app.world.getEntitiesWithComponents([RigidBody3D, Transform])) {
+ const body = app.world.get(entity, RigidBody3D) as RigidBody3DData;
+ if (!body.enabled || body.bodyType !== 2) continue;
+ const id = runtime.bodies.get(entity as Entity);
+ if (!id || !module._physics3d_getBodyState(id)) continue;
+ const f = module.HEAPF32;
+ const state = module._physics3d_queryResult() >> 2;
+ const x = f[state]! * ppu, y = f[state + 1]! * ppu, z = f[state + 2]! * ppu;
+ const planet = registry.nearest(x, y, z);
+ if (planet === null) continue;
+ const facts = registry.planets.get(planet)!;
+ const up = registry.up(planet, x, y, z);
+ if (facts.gravity <= 0 || !up) continue;
+ if (!module._physics3d_getBodyDynamics(id)) continue;
+ const mass = module.HEAPF32[module._physics3d_queryResult() >> 2]!;
+ const force = planetPullForce(mass, body.gravityScale, [-up[0], -up[1], -up[2]], facts.gravity, world);
+ module._physics3d_addForce(id, force[0], force[1], force[2], f[state]!, f[state + 1]!, f[state + 2]!);
+ }
+ }, { name: 'PlanetGravitySystem' }));
+}
diff --git a/sdk/src/terrain/index.ts b/sdk/src/terrain/index.ts
index 5db782810..daa671d50 100644
--- a/sdk/src/terrain/index.ts
+++ b/sdk/src/terrain/index.ts
@@ -23,6 +23,7 @@ import { registerTerrainSupport } from './terrainSupport';
registerTerrainSupport();
export { paintWeights } from './paint';
+export { PlanetRegistry, PlanetRegistryRes, type PlanetFacts } from './planetQuery';
export { Planet, Planets, PlanetPlugin, planetPlugin, type PlanetData, type PlanetStatus } from './planetPlugin';
export { registerPlanetProvider, planetProvider, type PlanetProvider, type PlanetRegion } from './planetProvider';
export { makePlanetPage, tangentFrame, type PlanetPageSource } from './planetPages';
diff --git a/sdk/src/terrain/planetPlugin.ts b/sdk/src/terrain/planetPlugin.ts
index b574e3d8b..2e40194d7 100644
--- a/sdk/src/terrain/planetPlugin.ts
+++ b/sdk/src/terrain/planetPlugin.ts
@@ -33,6 +33,7 @@ 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 { PlanetRegistry, PlanetRegistryRes } from './planetQuery';
import { removePlanetCollision, updatePlanetCollision } from './planetCollision';
import { planetProvider, planetProvidersRevision, type PlanetProvider } from './planetProvider';
import { makePlanetPage, type PlanetPageSource } from './planetPages';
@@ -63,6 +64,8 @@ export interface PlanetData {
collisionDistance: number;
collisionLayer: number;
friction: 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. */
layers: string[];
}
@@ -77,7 +80,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, layers: [] as string[],
+ macroScale: 90, macroVariation: 0.35, collision: true, collisionDistance: 64, collisionLayer: 0, friction: 0.6, gravity: 0, 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.' },
@@ -93,6 +96,7 @@ export const Planet: ComponentDef<PlanetData> = defineComponent<PlanetData>('Pla
layerColor3: { 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.' },
+ 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.' },
collisionDistance: { min: 1, category: 'Collision', tooltip: 'How far round each moving body and character the ground is built for collision, in metres.' },
@@ -161,6 +165,8 @@ export class PlanetPlugin implements Plugin {
build(app: App): void {
const planets = new Planets();
this.planets_ = planets;
+ const registry = new PlanetRegistry();
+ app.insertResource(PlanetRegistryRes, registry);
app.addSystemToSchedule(Schedule.Update, defineSystem([], () => {
if (!app.hasResource(Assets)) return;
// A planet whose entity has gone is let go.
@@ -169,6 +175,7 @@ export class PlanetPlugin implements Plugin {
this.destroy(app, built);
removePlanetCollision(app, entity);
planets.built_.delete(entity);
+ registry.planets.delete(entity);
}
for (const entity of app.world.getEntitiesWithComponents([Planet, Transform])) {
const data = app.world.get(entity, Planet) as PlanetData;
@@ -181,6 +188,15 @@ export class PlanetPlugin implements Plugin {
}
built.data = { ...data };
if (built.failure || !built.source || !built.tree) continue;
+ const at = (app.world.get(entity, Transform) as TransformData).worldPosition;
+ const source = built.source;
+ registry.planets.set(entity, {
+ centre: [at.x, at.y, at.z], radius: built.data.radius, gravity: built.data.gravity,
+ height: (dx, dy, dz) => {
+ const got = source.provider.sample({ world: source.world, seed: source.seed, version: source.version, radius: source.radius, directions: Float32Array.of(dx, dy, dz), count: 1 });
+ return got instanceof Promise ? null : (got.heights[0] ?? null);
+ },
+ });
updatePlanetCollision(app, entity, built.source, built.epoch, built.data);
if (!built.instance) {
if (!built.pending) void this.prepare(app, built);
diff --git a/sdk/src/terrain/planetQuery.ts b/sdk/src/terrain/planetQuery.ts
new file mode 100644
index 000000000..7d18d3a91
--- /dev/null
+++ b/sdk/src/terrain/planetQuery.ts
@@ -0,0 +1,77 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file planetQuery.ts
+ * @brief What the world asks of a planet: which way is up where something stands, how high the ground is under it, and what pulls it.
+ *
+ * @details A round world has no one up. Everything that stands, falls or aims on a planet asks it here: `up` is away from the centre of the planet
+ * the position is over, `altitude` the height above the radius, `groundHeight` the generator's own height at the direction (the ground
+ * itself, before any tile is built), and `gravity` how hard the nearest planet pulls. The planets themselves are kept by the Planet
+ * plugin; this file holds only the registry they are written into, so a system that needs to ask (physics, a character, a camera) does
+ * not carry the renderer.
+ */
+import { defineResource } from '../ecs/resource';
+import type { Entity } from '../types';
+
+/** What a planet says of itself, from its component and its provider. */
+export interface PlanetFacts {
+ /** The centre, in world units. */
+ centre: [number, number, number];
+ radius: number;
+ /** How hard it pulls, in metres a second squared at the surface (0: it pulls nothing). */
+ gravity: number;
+ /** The ground's height above the radius in a direction from the centre, or null while the provider answers later or the planet is not made. */
+ height: ((dx: number, dy: number, dz: number) => number | null) | null;
+}
+
+/** The planets of the app. @experimental */
+export class PlanetRegistry {
+ readonly planets = new Map<Entity, PlanetFacts>();
+
+ /** The planet whose surface is nearest the position (a planet pulls from any distance), or null with none. */
+ nearest(x: number, y: number, z: number): Entity | null {
+ let best: Entity | null = null;
+ let bestGap = Infinity;
+ for (const [entity, p] of this.planets) {
+ const gap = Math.abs(Math.hypot(x - p.centre[0], y - p.centre[1], z - p.centre[2]) - p.radius);
+ if (gap < bestGap) { bestGap = gap; best = entity; }
+ }
+ return best;
+ }
+
+ /** The unit direction away from the centre of the planet `entity`, at a position; null for no such planet, or at its very centre. */
+ up(entity: Entity, x: number, y: number, z: number): [number, number, number] | null {
+ const p = this.planets.get(entity);
+ if (!p) return null;
+ const dx = x - p.centre[0], dy = y - p.centre[1], dz = z - p.centre[2];
+ const len = Math.hypot(dx, dy, dz);
+ return len > 1e-9 ? [dx / len, dy / len, dz / len] : null;
+ }
+
+ /** How far the position is above the planet's radius (negative inside), or null for no such planet. */
+ altitude(entity: Entity, x: number, y: number, z: number): number | null {
+ const p = this.planets.get(entity);
+ return p ? Math.hypot(x - p.centre[0], y - p.centre[1], z - p.centre[2]) - p.radius : null;
+ }
+
+ /** The ground's height above the radius under the position, from the generator; null where it cannot say yet. */
+ groundHeight(entity: Entity, x: number, y: number, z: number): number | null {
+ const p = this.planets.get(entity);
+ if (!p?.height) return null;
+ const dx = x - p.centre[0], dy = y - p.centre[1], dz = z - p.centre[2];
+ const len = Math.hypot(dx, dy, dz);
+ return len > 1e-9 ? p.height(dx / len, dy / len, dz / len) : null;
+ }
+
+ /** The point on the ground under the position, in world units, or null where the ground cannot be said yet. */
+ groundPoint(entity: Entity, x: number, y: number, z: number): [number, number, number] | null {
+ const p = this.planets.get(entity);
+ const h = this.groundHeight(entity, x, y, z);
+ const up = this.up(entity, x, y, z);
+ if (!p || h === null || !up) return null;
+ const r = p.radius + h;
+ return [p.centre[0] + up[0] * r, p.centre[1] + up[1] * r, p.centre[2] + up[2] * r];
+ }
+}
+
+export const PlanetRegistryRes = defineResource<PlanetRegistry>(new PlanetRegistry(), 'PlanetRegistry');
diff --git a/sdk/tests/planet-gravity.test.ts b/sdk/tests/planet-gravity.test.ts
new file mode 100644
index 000000000..5b266adde
--- /dev/null
+++ b/sdk/tests/planet-gravity.test.ts
@@ -0,0 +1,51 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+import { describe, expect, it } from 'vitest';
+import type { Entity } from '../src/types';
+import { PlanetRegistry } from '../src/terrain/planetQuery';
+import { planetPullForce } from '../src/physics3d/planetGravity';
+
+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 });
+ registry.planets.set(b, { centre: [50000, 0, 0], radius: 1000, gravity: 3, height: null });
+
+ it('name the planet whose surface is nearest, from anywhere', () => {
+ expect(registry.nearest(0, 100, 0)).toBe(a);
+ expect(registry.nearest(49000, 0, 0)).toBe(b);
+ expect(registry.nearest(25000, 0, 0)).toBe(a);
+ });
+
+ it('say which way is up and how high', () => {
+ expect(registry.up(a, 0, 100, 0)).toEqual([0, 1, 0]);
+ const side = registry.up(a, 4000, -4000, 0)!;
+ expect(side[0]).toBeCloseTo(1, 12);
+ expect(registry.altitude(a, 0, 120, 0)).toBeCloseTo(120, 9);
+ expect(registry.altitude(a, 0, -100, 0)).toBeCloseTo(-100, 9);
+ expect(registry.up(a, 0, -4000, 0)).toBeNull();
+ });
+
+ it('give the ground under a position from the generator, and the point on it', () => {
+ expect(registry.groundHeight(a, 0, 100, 0)).toBeCloseTo(10, 6);
+ const p = registry.groundPoint(a, 0, 100, 0)!;
+ expect(p[1]).toBeCloseTo(10, 6);
+ expect(registry.groundHeight(b, 50000, 2000, 0)).toBeNull();
+ });
+});
+
+describe('the pull of a planet on a body', () => {
+ it('is the planet\'s gravity down, in place of the world\'s', () => {
+ // The world's gravity is zero: the force is the planet's pull alone.
+ expect(planetPullForce(10, 1, [0, -1, 0], 9.81, [0, 0, 0])[1]).toBeCloseTo(-98.1, 9);
+ // The world pulls along -Y at 9.81: standing on the top of the planet needs nothing more.
+ expect(planetPullForce(10, 1, [0, -1, 0], 9.81, [0, -9.81, 0])[1]).toBeCloseTo(0, 9);
+ // Round the side it takes the world's pull off and puts the planet's on.
+ const f = planetPullForce(2, 1, [-1, 0, 0], 9.81, [0, -9.81, 0]);
+ expect(f[0]).toBeCloseTo(-19.62, 9);
+ expect(f[1]).toBeCloseTo(19.62, 9);
+ // A body the world does not pull (gravity scale 0) is pulled by the planet alone.
+ expect(planetPullForce(2, 0, [0, -1, 0], 9.81, [0, -9.81, 0])[1]).toBeCloseTo(-19.62, 9);
+ });
+});
diff --git a/tools/check-gizmo-coverage.mjs b/tools/check-gizmo-coverage.mjs
index 09790f967..f40edeae1 100644
--- a/tools/check-gizmo-coverage.mjs
+++ b/tools/check-gizmo-coverage.mjs
@@ -115,6 +115,7 @@ const DISPOSITION = {
'MeshInstances.drawDistance': ['no-place', 'a distance from the eye, not a region of the entity'],
'MeshInstances.shadowDistance': ['no-place', 'a distance from the eye, not a region of the entity'],
'Planet.radius': ['renders', 'the sphere drawn at the entity is the outline'],
+ 'Planet.collisionDistance': ['no-place', 'how far round each moving body the ground is built for collision, not a region of the entity'],
'Planet.cellSize': ['no-place', 'the finest cell of the ground\'s mesh near the eye, not a region of the entity'],
'PlacedFoliage.sizeX': ['renders', 'the area the plants are placed over is the outline'],
'PlacedFoliage.sizeZ': ['renders', 'the area the plants are placed over is the outline'],
diff --git a/tools/releaseNotes.mjs b/tools/releaseNotes.mjs
index aabfedacf..b7ee3175b 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 pulls bodies toward its centre and answers up, altitude and ground height":
+ {"note":"A planet pulls and answers."},
"feat(render): temporal history follows the render origin when it steps":
{"internal":"The render origin of this release, extended."},
"feat(render): the render origin covers every renderer and the terrain, water and sky shaders":