A fast 2D and 3D game engine — TypeScript SDK, C++/WebAssembly core, visual editor. Ship one project to web, desktop, WeChat MiniGames, playable ads, and native Android / iOS.
TypeScript 2d-game-engine3d3d-game-engineandroidcppecsgame-editorgame-enginegamedeviostypescriptwebassemblywebglwebgpuwechat-minigame
feat(terrain): a planet's ground collides
yhhd3ad33ba1e35
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 66282f5dc..a99b871e0 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -16,6 +16,7 @@ published separately; it ships inside the editor.### Added+- **A planet's ground collides.** `Planet` takes `collision`, `collisionDistance`, `collisionLayer` and `friction` as flat terrain does: the finest nodes round every moving 3D body and character are built as collision geometry from the same samples the ground is drawn from, one chunk layer to each face of the cube.- **Height Fog by height above a planet.** `heightFog` takes `u_planetRadius` and the planet's centre (`u_planetX/Y/Z`): with a radius above 0 the fog thins with the height above the ground's sphere and not with world Y, so a round world is hazy at its horizon and clear from orbit.## [0.95.0] - 2026-10-25diff --git a/docs/astro/src/content/docs/graphics/terrain.mdx b/docs/astro/src/content/docs/graphics/terrain.mdxindex 02b7a7921..3bcf6b331 100644--- a/docs/astro/src/content/docs/graphics/terrain.mdx+++ b/docs/astro/src/content/docs/graphics/terrain.mdx@@ -282,7 +282,7 @@ registerPlanetProvider({});```-This is the first slice of round worlds: it draws the ground. Collision, the layers' textures, the sea, a sky that follows the horizon round and gravity toward the centre are not in it yet.+The ground collides: the finest nodes within `collisionDistance` of every moving 3D body and character are built as collision geometry from the same samples the ground is drawn from (`collision`, `collisionDistance`, `collisionLayer`, `friction`, as on a flat terrain). A planet's transform is a position only: a turned or scaled planet's collision stands where it would be unturned. The layers' textures, the sea, a sky that follows the horizon round and gravity toward the centre are not in it yet; a body falls along the world's one gravity, so toward the centre only at the top of the planet.## Limitsdiff --git a/docs/astro/src/content/docs/zh-cn/graphics/terrain.mdx b/docs/astro/src/content/docs/zh-cn/graphics/terrain.mdxindex a2b9a31e0..935ad4094 100644--- a/docs/astro/src/content/docs/zh-cn/graphics/terrain.mdx+++ b/docs/astro/src/content/docs/zh-cn/graphics/terrain.mdx@@ -193,7 +193,7 @@ registerTerrainProvider(planet);星球的提供器回答的是**方向**,不是位置:它拿到从星球中心出发的单位方向和它们所在的半径,给出每个方向上高出半径的高度,如果上色,再给出四个图层权重。球面没有 x 和 z,所以生成器读三维噪声,没有接缝也没有极点。-这是圆形世界的第一片:它画出地面。碰撞、图层贴图、海、跟着地平线转的天空和指向球心的重力还没有。+地面有碰撞:每个运动的 3D 刚体和角色在 `collisionDistance` 内的最细节点,会用画地面的同一批采样建成碰撞几何(`collision`、`collisionDistance`、`collisionLayer`、`friction`,和平面地形一样)。星球的变换只有位置:旋转或缩放过的星球,碰撞仍站在没旋转时的位置。图层贴图、海、跟着地平线转的天空和指向球心的重力还没有;物体沿世界唯一的重力下落,所以只有在星球顶部才是朝向球心。## 限制diff --git a/sdk/etc/index.api.md b/sdk/etc/index.api.mdindex 20c08feef..da4b7dfbb 100644--- a/sdk/etc/index.api.md+++ b/sdk/etc/index.api.md@@ -2485,6 +2485,7 @@ stale: number## ChunkSource — interface @experimental```x: number+y: number | undefinedz: number```@@ -6741,7 +6742,11 @@ ComponentDef<PlanetData>## PlanetData — interface @experimental```cellSize: number+collision: boolean+collisionDistance: number+collisionLayer: numberdetail: number+friction: numbergeneratorVersion: numberlayerColor0: ColorlayerColor1: Colordiff --git a/sdk/etc/index.native.api.md b/sdk/etc/index.native.api.mdindex 61f621329..fa16304bf 100644--- a/sdk/etc/index.native.api.md+++ b/sdk/etc/index.native.api.md@@ -2485,6 +2485,7 @@ stale: number## ChunkSource — interface @experimental```x: number+y: number | undefinedz: number```@@ -6944,7 +6945,11 @@ ComponentDef<PlanetData>## PlanetData — interface @experimental```cellSize: number+collision: boolean+collisionDistance: number+collisionLayer: numberdetail: number+friction: numbergeneratorVersion: numberlayerColor0: ColorlayerColor1: Colordiff --git a/sdk/etc/index.node.api.md b/sdk/etc/index.node.api.mdindex 79084028c..6b12e0fd5 100644--- a/sdk/etc/index.node.api.md+++ b/sdk/etc/index.node.api.md@@ -2480,6 +2480,7 @@ stale: number## ChunkSource — interface @experimental```x: number+y: number | undefinedz: number```@@ -6736,7 +6737,11 @@ ComponentDef<PlanetData>## PlanetData — interface @experimental```cellSize: number+collision: boolean+collisionDistance: number+collisionLayer: numberdetail: number+friction: numbergeneratorVersion: numberlayerColor0: ColorlayerColor1: Colordiff --git a/sdk/etc/minigame.api.md b/sdk/etc/minigame.api.mdindex d24018f70..329f64656 100644--- a/sdk/etc/minigame.api.md+++ b/sdk/etc/minigame.api.md@@ -2480,6 +2480,7 @@ stale: number## ChunkSource — interface @experimental```x: number+y: number | undefinedz: number```@@ -7029,7 +7030,11 @@ ComponentDef<PlanetData>## PlanetData — interface @experimental```cellSize: number+collision: boolean+collisionDistance: number+collisionLayer: numberdetail: number+friction: numbergeneratorVersion: numberlayerColor0: ColorlayerColor1: Colordiff --git a/sdk/etc/terrain.api.md b/sdk/etc/terrain.api.mdindex 13e0c8a1a..b7aaa8728 100644--- a/sdk/etc/terrain.api.md+++ b/sdk/etc/terrain.api.md@@ -178,7 +178,11 @@ ComponentDef<PlanetData>## PlanetData — interface @experimental```cellSize: number+collision: boolean+collisionDistance: number+collisionLayer: numberdetail: number+friction: numbergeneratorVersion: numberlayerColor0: ColorlayerColor1: Colordiff --git a/sdk/etc/wechat.api.md b/sdk/etc/wechat.api.mdindex 25caa13fe..68d3211a9 100644--- a/sdk/etc/wechat.api.md+++ b/sdk/etc/wechat.api.md@@ -2480,6 +2480,7 @@ stale: number## ChunkSource — interface @experimental```x: number+y: number | undefinedz: number```@@ -6743,7 +6744,11 @@ ComponentDef<PlanetData>## PlanetData — interface @experimental```cellSize: number+collision: boolean+collisionDistance: number+collisionLayer: numberdetail: number+friction: numbergeneratorVersion: numberlayerColor0: ColorlayerColor1: Colordiff --git a/sdk/src/residency/chunks.ts b/sdk/src/residency/chunks.tsindex b239da2ad..1691b43f1 100644--- a/sdk/src/residency/chunks.ts+++ b/sdk/src/residency/chunks.ts@@ -29,7 +29,7 @@ import { bakesOf } from '../runtime/bakes';import { log } from '../util/logger';/** A place a layer is wanted round, on the ground plane, in world units. */-export interface ChunkSource { x: number; z: number }+export interface ChunkSource { x: number; z: number; /** Its height, where a layer is not on a plane (a planet's collision reads the whole position). */ y?: number }/** One kind of chunk: how it is cut, where it is wanted and how it is made. */export interface ChunkLayer<T> {diff --git a/sdk/src/terrain/movers.ts b/sdk/src/terrain/movers.tsnew file mode 100644index 000000000..aefe9cdae--- /dev/null+++ b/sdk/src/terrain/movers.ts@@ -0,0 +1,33 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file movers.ts+ * @brief What the ground is made for: every moving 3D body and every character, where they stand in the world.+ */+import type { App } from '../app/app';+import { getComponent, Transform, type TransformData } from '../ecs/component';+import type { ChunkSource } from '../residency/chunks';++/** Where what collides with the ground is: every moving 3D body and every character. */+export function movers(app: App): ChunkSource[] {+ const world = app.world;+ world.ensureTransformsComposed();+ const out: ChunkSource[] = [];+ // By name: a project without 3D physics has neither component, and the terrain must not carry the solver to look for them.+ const rigid = getComponent('RigidBody3D'), character = getComponent('CharacterController3D');+ if (rigid) {+ for (const e of world.getEntitiesWithComponents([rigid, Transform])) {+ const body = world.get(e, rigid) as { enabled: boolean; bodyType: number };+ if (!body.enabled || body.bodyType === 0) continue;+ const p = (world.get(e, Transform) as TransformData).worldPosition;+ out.push({ x: p.x, y: p.y, z: p.z });+ }+ }+ if (character) {+ for (const e of world.getEntitiesWithComponents([character, Transform])) {+ const p = (world.get(e, Transform) as TransformData).worldPosition;+ out.push({ x: p.x, y: p.y, z: p.z });+ }+ }+ return out;+}diff --git a/sdk/src/terrain/planetCollision.ts b/sdk/src/terrain/planetCollision.tsnew file mode 100644index 000000000..df4f134cc--- /dev/null+++ b/sdk/src/terrain/planetCollision.ts@@ -0,0 +1,120 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file planetCollision.ts+ * @brief The planet's ground as collision geometry: the finest nodes round everything that moves, each cut into a grid of triangles.+ *+ * @details Each of the cube's six faces is a layer of procedural chunks (residency/chunks.ts) whose chunks are the finest nodes: a chunk is one node's+ * square of the face, its place the node's ix and iz, so a layer's "world" is the face in node units and every mover is put there by+ * where its direction from the centre falls on the face. A mover near an edge falls on both faces and is wanted by both. Every tile samples+ * the same provider at the same directions the drawn ground does, so the ground stood on is the ground seen; two tiles that share an edge+ * share its samples. A planet's transform carries a position only: a turned or scaled planet's collision stands where it would be unturned.+ */+import type { App } from '../app/app';+import { Transform, type TransformData } from '../ecs/component';+import type { Entity } from '../types';+import { chunksOf } from '../residency/chunks';+import { collisionGeometryOf } from '../runtime/collisionGeometry';+import { movers } from './movers';+import { direction, facePlace, nodeRect, type SphereNode } from './sphere';+import type { PlanetPageSource } from './planetPages';++/** How a planet's ground collides: whether it does, how far round a mover its tiles are built, its layer and friction, and its cells. */+export interface PlanetCollisionOptions {+ collision: boolean;+ collisionDistance: number;+ collisionLayer: number;+ friction: number;+}++/** Cells along a tile's side. */+const TILE_CELLS = 32;+const layerOf = (entity: Entity, face: number): string => `planet-collision:${entity}:${face}`;+const keyOf = (entity: Entity, n: SphereNode): string => `planet:${entity}:${n.face}:${n.ix}:${n.iz}`;++interface Tile { key: string; origin: [number, number, number]; positions: Float32Array; indices: Uint32Array }++/** One node's ground as triangles: positions measured from the node's middle (in the planet's space), wound to face out. @internal */+export function tileOf(src: PlanetPageSource, node: SphereNode, key: string): Tile | Promise<Tile> {+ const n = TILE_CELLS + 1;+ const { u0, v0, span } = nodeRect(src.levels, node);+ const dirs = new Float32Array(n * n * 3);+ const d: [number, number, number] = [0, 0, 0];+ for (let j = 0; j < n; j++) for (let i = 0; i < n; i++) {+ direction(node.face, u0 + (i / TILE_CELLS) * span, v0 + (j / TILE_CELLS) * span, d);+ const k = (j * n + i) * 3;+ dirs[k] = d[0]; dirs[k + 1] = d[1]; dirs[k + 2] = d[2];+ }+ const build = (h: Float32Array): Tile => {+ const mid = direction(node.face, u0 + span / 2, v0 + span / 2);+ const origin: [number, number, number] = [mid[0] * src.radius, mid[1] * src.radius, mid[2] * src.radius];+ const positions = new Float32Array(n * n * 3);+ for (let q = 0; q < n * n; q++) {+ const r = src.radius + h[q]!;+ for (let c = 0; c < 3; c++) positions[q * 3 + c] = dirs[q * 3 + c]! * r - origin[c]!;+ }+ // Which way a cell's first triangle faces depends on the face's handedness: measured once, then every triangle is wound the same way.+ const p = (q: number, c: number): number => positions[q * 3 + c]!;+ const ex = [p(1, 0) - p(0, 0), p(1, 1) - p(0, 1), p(1, 2) - p(0, 2)], ez = [p(n, 0) - p(0, 0), p(n, 1) - p(0, 1), p(n, 2) - p(0, 2)];+ const cross = [ex[1]! * ez[2]! - ex[2]! * ez[1]!, ex[2]! * ez[0]! - ex[0]! * ez[2]!, ex[0]! * ez[1]! - ex[1]! * ez[0]!];+ const outward = cross[0]! * mid[0] + cross[1]! * mid[1] + cross[2]! * mid[2] > 0;+ const indices = new Uint32Array(TILE_CELLS * TILE_CELLS * 6);+ let w = 0;+ for (let j = 0; j < TILE_CELLS; j++) for (let i = 0; i < TILE_CELLS; i++) {+ const a = j * n + i, b = a + 1, c = a + n, e = c + 1;+ const tris = outward ? [a, b, c, b, e, c] : [a, c, b, b, c, e];+ for (const t of tris) indices[w++] = t;+ }+ return { key, origin, positions, indices };+ };+ const got = src.provider.sample({ world: src.world, seed: src.seed, version: src.version, radius: src.radius, directions: dirs, count: n * n });+ return got instanceof Promise ? got.then((r) => build(r.heights)) : build(got.heights);+}++/**+ * Keeps the planet's collision layers: set every frame for the faces a mover is over, taken away when collision is off. Returns nothing; the geometry+ * is the physics world's to read (runtime/collisionGeometry.ts).+ */+export function updatePlanetCollision(app: App, entity: Entity, src: PlanetPageSource, epoch: number, options: PlanetCollisionOptions): void {+ const chunks = chunksOf(app);+ if (!options.collision) { removePlanetCollision(app, entity); return; }+ const centre = (app.world.get(entity, Transform) as TransformData).worldPosition;+ const geometry = collisionGeometryOf(app);+ const nodes = 2 ** (src.levels - 1);+ const leaf = (src.radius * Math.PI / 2) / nodes;+ const load = Math.max(options.collisionDistance, 0) / leaf;+ for (let face = 0; face < 6; face++) {+ chunks.set<Tile>(layerOf(entity, face), {+ label: 'Building the planet\'s collision',+ originX: 0, originZ: 0, sizeX: 1, sizeZ: 1,+ extent: [0, 0, nodes, nodes],+ loadRadius: load,+ unloadRadius: load + 1,+ generation: `${epoch}:${centre.x}:${centre.y}:${centre.z}:${options.collisionLayer}:${options.friction}`,+ sources: () => {+ const out: { x: number; z: number }[] = [];+ for (const m of movers(app)) {+ const dx = m.x - centre.x, dy = (m.y ?? 0) - centre.y, dz = m.z - centre.z;+ const len = Math.hypot(dx, dy, dz) || 1;+ const at = facePlace(face, dx / len, dy / len, dz / len);+ if (at) out.push({ x: (at.u + 1) / 2 * nodes, z: (at.v + 1) / 2 * nodes });+ }+ return out;+ },+ make: (ix, iz) => tileOf(src, { face, level: 0, ix, iz }, keyOf(entity, { face, level: 0, ix, iz })),+ publish: (_ix, _iz, tile) => {+ geometry.set(tile.key, {+ owner: entity, origin: [centre.x + tile.origin[0], centre.y + tile.origin[1], centre.z + tile.origin[2]],+ positions: tile.positions, indices: tile.indices, friction: options.friction, restitution: 0, layer: options.collisionLayer,+ });+ },+ release: (_ix, _iz, tile) => geometry.delete(tile.key),+ });+ }+}++/** Takes the planet's collision away. */+export function removePlanetCollision(app: App, entity: Entity): void {+ const chunks = chunksOf(app);+ for (let face = 0; face < 6; face++) chunks.remove(layerOf(entity, face));+}diff --git a/sdk/src/terrain/planetPlugin.ts b/sdk/src/terrain/planetPlugin.tsindex b9ef04ebf..bc290d372 100644--- a/sdk/src/terrain/planetPlugin.ts+++ b/sdk/src/terrain/planetPlugin.ts@@ -31,6 +31,7 @@ import { bakesOf } from '../runtime/bakes';import type { Color, Entity } from '../types';import { PageTable, PAGE_SIDE, PAGE_TEXELS, PATCH_CELLS, type PageImage } from './pages';import { buildPatchMesh } from './patch';+import { removePlanetCollision, updatePlanetCollision } from './planetCollision';import { planetProvider, planetProvidersRevision, type PlanetProvider } from './planetProvider';import { makePlanetPage, type PlanetPageSource } from './planetPages';import { levelsFor, nodePoint, selectSphereNodes, sphereNodeKey, type SphereNode, type SphereTreeParams } from './sphere';@@ -55,6 +56,11 @@ export interface PlanetData {/** The size, in metres, of the ground's own wander in brightness, and how strong it is (0 to 1). */macroScale: number;macroVariation: number;+ /** Whether bodies and characters collide with the ground; how far round each thing that moves it is built for collision; its layer and friction. */+ collision: boolean;+ collisionDistance: number;+ collisionLayer: number;+ friction: number;}const rgb = (r: number, g: number, b: number): Color => ({ r, g, b, a: 1 });@@ -67,7 +73,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,+ macroScale: 90, macroVariation: 0.35, collision: true, collisionDistance: 64, collisionLayer: 0, friction: 0.6,}, {fields: {radius: { min: 1, category: 'Shape', tooltip: 'The planet\'s radius in metres. The planet stands at its entity, unrotated and unscaled.' },@@ -83,6 +89,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.' },+ collision: { category: 'Collision', tooltip: 'Whether 3D bodies and characters collide with the ground: the finest tiles round each of them are built as collision geometry.' },+ collisionDistance: { min: 1, category: 'Collision', tooltip: 'How far round each moving body and character the ground is built for collision, in metres.' },+ collisionLayer: { min: 0, max: 15, step: 1, category: 'Collision', advanced: true, tooltip: 'The collision layer the ground is in (0 to 15).' },+ friction: { min: 0, category: 'Collision', advanced: true, tooltip: 'The ground\'s friction.' },},});@@ -146,6 +156,7 @@ export class PlanetPlugin implements Plugin {for (const [entity, built] of planets.built_) {if (app.world.valid(entity) && app.world.has(entity, Planet)) continue;this.destroy(app, built);+ removePlanetCollision(app, entity);planets.built_.delete(entity);}for (const entity of app.world.getEntitiesWithComponents([Planet, Transform])) {@@ -153,12 +164,13 @@ export class PlanetPlugin implements Plugin {const signature = signatureOf(data);let built = planets.built_.get(entity);if (!built || built.signature !== signature || (built.failure && built.providers !== planetProvidersRevision())) {- if (built) this.destroy(app, built);+ if (built) { this.destroy(app, built); removePlanetCollision(app, entity); }built = this.make(signature, data, (built?.epoch ?? 0) + 1);planets.built_.set(entity, built);}built.data = { ...data };if (built.failure || !built.source || !built.tree) continue;+ updatePlanetCollision(app, entity, built.source, built.epoch, built.data);if (!built.instance) {if (!built.pending) void this.prepare(app, built);continue;@@ -170,7 +182,7 @@ export class PlanetPlugin implements Plugin {cleanup(app?: App): void {const planets = this.planets_;- if (app && planets) for (const built of planets.built_.values()) this.destroy(app, built);+ if (app && planets) for (const [entity, built] of planets.built_) { this.destroy(app, built); removePlanetCollision(app, entity); }planets?.built_.clear();if (this.stock_) Material.release(this.stock_);this.stock_ = 0;diff --git a/sdk/src/terrain/sphere.ts b/sdk/src/terrain/sphere.tsindex 696c55655..bd3c28f59 100644--- a/sdk/src/terrain/sphere.ts+++ b/sdk/src/terrain/sphere.ts@@ -74,6 +74,16 @@ export function faceOf(dx: number, dy: number, dz: number): { face: number; u: nreturn { face, u: Math.atan(a / n) / QUARTER_PI, v: Math.atan(b / n) / QUARTER_PI };}+/** Where a direction falls on a given face's plane, in the face's units (beyond -1 to 1 past its edge); null for a direction that does not face it. */+export function facePlace(face: number, dx: number, dy: number, dz: number): { u: number; v: number } | null {+ const f = FACES[face]!;+ const n = dx * f.normal[0] + dy * f.normal[1] + dz * f.normal[2];+ if (n <= 1e-6) return null;+ const a = dx * f.a[0] + dy * f.a[1] + dz * f.a[2];+ const b = dx * f.b[0] + dy * f.b[1] + dz * f.b[2];+ return { u: Math.atan(a / n) / QUARTER_PI, v: Math.atan(b / n) / QUARTER_PI };+}+/** The side of a node of `level` on its face, in the face's -1 to 1 units. */export const nodeSpan = (levels: number, level: number): number => 2 / 2 ** (levels - 1 - level);diff --git a/sdk/src/terrain/terrainPlugin.ts b/sdk/src/terrain/terrainPlugin.tsindex e66b5d44b..979eb0cfc 100644--- a/sdk/src/terrain/terrainPlugin.ts+++ b/sdk/src/terrain/terrainPlugin.ts@@ -50,7 +50,8 @@ import { isMiniGame } from '../platform';import { packLayers, type LayerImage, type LayerSource, type TerrainLayerDef } from './layers';import { TerrainSurface, TILE_CELLS, type SurfaceTile } from './surface';import { collisionGeometryOf } from '../runtime/collisionGeometry';-import { chunksOf, ProceduralChunksRes, type ChunkSource } from '../residency/chunks';+import { chunksOf, ProceduralChunksRes } from '../residency/chunks';+import { movers } from './movers';/** The engine's own provider of ground without end: seeded noise of the world's position. */export const NOISE_PROVIDER = 'estella:noise';@@ -528,30 +529,6 @@ async function windowOf(provider: TerrainProvider, data: TerrainData, cx: numberreturn { width: nx, height: nz, data: out };}-/** Where what collides with the ground is: every moving 3D body and every character. */-function movers(app: App): ChunkSource[] {- const world = app.world;- world.ensureTransformsComposed();- const out: ChunkSource[] = [];- // By name: a project without 3D physics has neither component, and the terrain must not carry the solver to look for them.- const rigid = getComponent('RigidBody3D'), character = getComponent('CharacterController3D');- if (rigid) {- for (const e of world.getEntitiesWithComponents([rigid, Transform])) {- const body = world.get(e, rigid) as { enabled: boolean; bodyType: number };- if (!body.enabled || body.bodyType === 0) continue;- const p = (world.get(e, Transform) as TransformData).worldPosition;- out.push({ x: p.x, z: p.z });- }- }- if (character) {- for (const e of world.getEntitiesWithComponents([character, Transform])) {- const p = (world.get(e, Transform) as TransformData).worldPosition;- out.push({ x: p.x, z: p.z });- }- }- return out;-}-export class TerrainPlugin implements Plugin {name = 'terrain';diff --git a/sdk/tests/terrain-planet-collision.test.ts b/sdk/tests/terrain-planet-collision.test.tsnew file mode 100644index 000000000..341ce0d1b--- /dev/null+++ b/sdk/tests/terrain-planet-collision.test.ts@@ -0,0 +1,70 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+import { describe, expect, it } from 'vitest';+import { FACES, direction, facePlace, faceOf } from '../src/terrain/sphere';+import { tileOf } from '../src/terrain/planetCollision';+import type { PlanetPageSource } from '../src/terrain/planetPages';++const radius = 4000;+/** Ground that is a function of the direction alone: a gentle swell, so a shared edge can only agree if it samples the same directions. */+const src = {+ provider: {+ id: 't', versions: [1], range: () => [-10, 10],+ sample: (r: { directions: Float32Array; count: number }) => {+ const heights = new Float32Array(r.count);+ for (let i = 0; i < r.count; i++) heights[i] = 8 * Math.sin(r.directions[i * 3]! * 9) * Math.cos(r.directions[i * 3 + 1]! * 7 + r.directions[i * 3 + 2]! * 5);+ return { heights };+ },+ },+ world: 'w', seed: 1, version: 1, radius, levels: 8, minHeight: -10, maxHeight: 10,+} as unknown as PlanetPageSource;++describe('a planet\'s collision tiles', () => {+ it('are wound to face out on every face', () => {+ for (let face = 0; face < 6; face++) {+ const tile = tileOf(src, { face, level: 0, ix: 3, iz: 5 }, 'k') as Awaited<ReturnType<typeof tileOf>>;+ const p = tile.positions, i = tile.indices;+ let facing = 0;+ for (let t = 0; t < i.length; t += 3) {+ const a = i[t]! * 3, b = i[t + 1]! * 3, c = i[t + 2]! * 3;+ const e1 = [p[b]! - p[a]!, p[b + 1]! - p[a + 1]!, p[b + 2]! - p[a + 2]!], e2 = [p[c]! - p[a]!, p[c + 1]! - p[a + 1]!, p[c + 2]! - p[a + 2]!];+ const n = [e1[1]! * e2[2]! - e1[2]! * e2[1]!, e1[2]! * e2[0]! - e1[0]! * e2[2]!, e1[0]! * e2[1]! - e1[1]! * e2[0]!];+ const out = [tile.origin[0] + p[a]!, tile.origin[1] + p[a + 1]!, tile.origin[2] + p[a + 2]!];+ if (n[0]! * out[0]! + n[1]! * out[1]! + n[2]! * out[2]! > 0) facing++;+ }+ expect(facing).toBe(i.length / 3);+ }+ });++ it('put every point at the radius plus the ground\'s height', () => {+ const tile = tileOf(src, { face: 2, level: 0, ix: 10, iz: 20 }, 'k') as Awaited<ReturnType<typeof tileOf>>;+ for (let q = 0; q < tile.positions.length / 3; q++) {+ const r = Math.hypot(tile.origin[0] + tile.positions[q * 3]!, tile.origin[1] + tile.positions[q * 3 + 1]!, tile.origin[2] + tile.positions[q * 3 + 2]!);+ expect(Math.abs(r - radius)).toBeLessThanOrEqual(10.01);+ }+ });++ it('share the edge two neighbours meet at', () => {+ const a = tileOf(src, { face: 4, level: 0, ix: 3, iz: 5 }, 'a') as Awaited<ReturnType<typeof tileOf>>;+ const b = tileOf(src, { face: 4, level: 0, ix: 4, iz: 5 }, 'b') as Awaited<ReturnType<typeof tileOf>>;+ const n = 33;+ for (let j = 0; j < n; j++) {+ for (let c = 0; c < 3; c++) {+ const left = a.origin[c]! + a.positions[(j * n + n - 1) * 3 + c]!, right = b.origin[c]! + b.positions[(j * n) * 3 + c]!;+ expect(Math.abs(left - right)).toBeLessThan(2e-3);+ }+ }+ });+});++describe('where a direction falls on a face', () => {+ it('is faceOf for the face it is on, and nothing for a face turned away', () => {+ const d = direction(3, 0.3, -0.4);+ const on = faceOf(d[0], d[1], d[2]);+ const place = facePlace(on.face, d[0], d[1], d[2])!;+ expect(place.u).toBeCloseTo(on.u, 9);+ expect(place.v).toBeCloseTo(on.v, 9);+ const back = FACES[on.face]!.normal;+ expect(facePlace(on.face, -back[0], -back[1], -back[2])).toBeNull();+ });+});diff --git a/tools/releaseNotes.mjs b/tools/releaseNotes.mjsindex 18e51e41f..1868e5184 100644--- a/tools/releaseNotes.mjs+++ b/tools/releaseNotes.mjs@@ -2916,6 +2916,8 @@ export const NOTED = {{"note":"The editor's own eye shows the scene's post-processing."},"feat(terrain): the maths of ground on a cube sphere and the nodes drawn round an eye":{"internal":"The first layer of spherical terrain: pure maths and node selection, not yet drawn."},+ "feat(terrain): a planet's ground collides":+ {"note":"A planet's ground collides."},"fix(terrain): a planet's ground is one-sided and its fog is the ground's under it":{"internal":"A fix to the Planet and height fog of this release."},"feat(postprocess): height fog by height above a planet's sphere":