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(worldgen): a part's soft turns the normals of a card that stands for a crown toward up

yhhc9d52f402fb8
diff --git a/CHANGELOG.md b/CHANGELOG.md
index bca3b5454..18db94728 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -19,7 +19,7 @@ published separately; it ships inside the editor.
- **A Display LUT.** The `displayLut` effect reads a look off a 1024x32 lookup table by the picture as the display will show it, in the last pass, after the output transform and the transfer function: the place a look authored against the finished image belongs, and one no effect in the chain can be, since they run on scene values before the curve. It is a variant of the pass that was running, one texture read and no pass of its own, and `PostProcessStack.setDisplayLut(texture, amount)` is the same thing in code. The last pass now reads its parameters off the reflected layout as a material does, and the copies it makes share them.
- **Light beams that follow the clouds.** `heightFog` has a `cloudShade`: its volumetric light marches the sun's ray up through the cloud layer of a `skyAtmosphere` whose clouds cast shadows (the same density the sky draws, fixed to the world and drifting with its wind), so a gap in the clouds is a beam in the air and what they cover is dark, whichever way the camera looks. `volumeRange` may now be as long as a million units, for beams through clouds kilometres up. The sky's clouds are copied onto the fog each frame, and an effect's uniform may be `internal`, which an inspector does not list.
- **Sparkle on the water.** The Water shader reads two tiled normal maps that scroll over the surface (`u_detailMap`, `u_detailTile0/1`, `u_detailStrength0/1`, `u_detailFlow0/1`), packed into the one texture a material has room for, so the sun's glints on small slopes come from lit specular response and not a white texture; a material that sets no strength is unchanged.
-- **A generated world's plants.** A recipe's members can name a **plant** in the rules' `plants` (a `.esworld` file holds them): several parts (a trunk and its crown), a cheaper mesh and a far version, the colourings the art gives it, how far it is sunk and its `unit` (100 for metres in a world of centimetres). The world is laid out from the rules as the eye moves, the plants grown a cell at a time by the machinery a `PlacedFoliage` uses: a chunk stands at once and fills in over the frames after it inside the frame's budget, a cheaper mesh stands in at the middle distance, and a tree's crossed cards, laid out as a layer of their own, stand for it far off. A plant with no cards of its own may use its cheaper mesh as its far version and set `farKeep`, the share of its plants that version draws, so ground cover far off costs a share of what it does near; a member with `attach: 'align'` leans a plant with the ground, so a stone on a slope sits as the slope lies; the far versions are laid out in cells as wide as the shortest distance they are shown over allows, which took the Terrain & Water example's draws from about 1,800 to about 1,100. The terrain's paint is a field each of its layers (`paint.grass`), a rules file names noise fields of its own, and fields are worked out only where a condition reads them. The Terrain & Water example's woods, shrubs, stones, grass, flowers and reeds are laid out this way from `assets/worlds/plants.esworld`.
+- **A generated world's plants.** A recipe's members can name a **plant** in the rules' `plants` (a `.esworld` file holds them): several parts (a trunk and its crown), a cheaper mesh and a far version, the colourings the art gives it, how far it is sunk and its `unit` (100 for metres in a world of centimetres). The world is laid out from the rules as the eye moves, the plants grown a cell at a time by the machinery a `PlacedFoliage` uses: a chunk stands at once and fills in over the frames after it inside the frame's budget, a cheaper mesh stands in at the middle distance, and a tree's crossed cards, laid out as a layer of their own, stand for it far off (a part's `soft` turns the normals of such a card toward up, so a crown's card is lit as a rounded crown and not a dark slab on the side away from the sun). A plant with no cards of its own may use its cheaper mesh as its far version and set `farKeep`, the share of its plants that version draws, so ground cover far off costs a share of what it does near; a member with `attach: 'align'` leans a plant with the ground, so a stone on a slope sits as the slope lies; the far versions are laid out in cells as wide as the shortest distance they are shown over allows, which took the Terrain & Water example's draws from about 1,800 to about 1,100. The terrain's paint is a field each of its layers (`paint.grass`), a rules file names noise fields of its own, and fields are worked out only where a condition reads them. The Terrain & Water example's woods, shrubs, stones, grass, flowers and reeds are laid out this way from `assets/worlds/plants.esworld`.
- **Each terrain layer says how it meets the others.** A `.esterrainlayer` may name a `heightBlend`: 0 blends by the paint alone (grass into sand), 1 by the layers' heights (stones standing through grass), weighted by how much of each layer is there; absent, it is the material's `u_heightBlend`. The editor's layer panel sets it.
- **Placed plants.** `PlacedFoliage` keeps every plant an artist placed by hand as data in one entity, a table of kinds and six numbers a plant, instead of an entity, a renderer and a draw each. The engine cuts the area into cells and grows only those round the eye, each as one mesh for every part of every kind in it, a few milliseconds a piece of the frame's budget so a cell fills in over the frames after it appears, and lets them go past their distance. A kind keeps the mesh as made (normal map, second uv, vertex colour), has a cheaper mesh for the middle distance and a far version, a tree's crossed cards, drawn out to a far distance: a hierarchical level of detail that makes the whole area stand at once. The Terrain & Water example now grows its woods, shrubs, stones, grass, flowers and reeds this way from the lakewood plant set, and its grass and sand are that set's terrain layers.
- **Water zones.** Oceans, lakes and rivers are now drawn as one surface. A `WaterBody` says what water is where (its form, outline or Spline, shore width, current and how high its waves stand), and a new `WaterZone` bakes every body over its region into one field: the surface's height, the distance to the shore, the waves' height, the current and the depth over the terrain. One mesh of rings that follows the camera reads it, so a river runs into a lake or the sea at one height with its banks running on into the shore, its current fades into the still water, and no shore foams across its mouth; a lake or a river over the sea is the lake's, not the sea's, and the sea's waves calm and foam where it shallows over the terrain. The zone holds what the bodies share: the material, the waves' length, speed and heading, the mesh's detail and the ripples. A scene without one gets a zone over its lakes and rivers, and the ocean goes on past it. `Waters.sample` reads the same field, so what floats or looks out from under the water meets the surface that is drawn. In the editor the zone's region is outlined in the viewport.
diff --git a/docs/astro/src/content/docs/world/generation.mdx b/docs/astro/src/content/docs/world/generation.mdx
index 601cb7c6e..945616653 100644
--- a/docs/astro/src/content/docs/world/generation.mdx
+++ b/docs/astro/src/content/docs/world/generation.mdx
@@ -94,7 +94,7 @@ group stands.
### Plants
-A member names a mesh and a material, or a **plant**: an entry in the rules' `plants`, for what a mesh and a material cannot say. A plant is its `parts` (a trunk and a crown are two, each with its `mesh`, a cheaper `lod1Mesh`, `material`, `texture`, `tint` and whether it is `opaque`), the `lodDistance` past which the cheaper meshes stand in and the `drawDistance` past which it is not drawn, a `far` version (a tree's crossed cards, baked to an atlas of their own) drawn from `drawDistance` out to `farDistance`, and optionally:
+A member names a mesh and a material, or a **plant**: an entry in the rules' `plants`, for what a mesh and a material cannot say. A plant is its `parts` (a trunk and a crown are two, each with its `mesh`, a cheaper `lod1Mesh`, `material`, `texture`, `tint`, whether it is `opaque` and, for a card that stands for a crown, how `soft` its normals are: turned toward up by that share, so it is lit as a rounded crown and not as the flat board it is), the `lodDistance` past which the cheaper meshes stand in and the `drawDistance` past which it is not drawn, a `far` version (a tree's crossed cards, baked to an atlas of their own) drawn from `drawDistance` out to `farDistance`, and optionally:
| Field | What it is |
|---|---|
diff --git a/docs/astro/src/content/docs/zh-cn/world/generation.mdx b/docs/astro/src/content/docs/zh-cn/world/generation.mdx
index 93b2b06ad..0f995cb68 100644
--- a/docs/astro/src/content/docs/zh-cn/world/generation.mdx
+++ b/docs/astro/src/content/docs/zh-cn/world/generation.mdx
@@ -71,7 +71,7 @@ registerWorldRules({
### 植物
-成员可以是网格加材质,也可以是**植物**:规则 `plants` 里的一项,用来表达网格和材质表达不了的东西。植物由 `parts` 部件组成(树干和树冠是两个部件,各有 `mesh`、更省的 `lod1Mesh`、`material`、`texture`、`tint` 以及是否 `opaque`),超过 `lodDistance` 换成更省的网格,超过 `drawDistance` 不再绘制,`far` 远景版本(树的交叉卡片,烘到自己的图集上)从 `drawDistance` 一直画到 `farDistance`,另外可选:
+成员可以是网格加材质,也可以是**植物**:规则 `plants` 里的一项,用来表达网格和材质表达不了的东西。植物由 `parts` 部件组成(树干和树冠是两个部件,各有 `mesh`、更省的 `lod1Mesh`、`material`、`texture`、`tint`、是否 `opaque`,以及对代表树冠的卡片用 `soft` 说明它的法线朝上偏转多少:按这个比例转向上方,让它像圆润的树冠那样受光,而不是像一块平板),超过 `lodDistance` 换成更省的网格,超过 `drawDistance` 不再绘制,`far` 远景版本(树的交叉卡片,烘到自己的图集上)从 `drawDistance` 一直画到 `farDistance`,另外可选:
| 字段 | 含义 |
|---|---|
diff --git a/sdk/etc/foliage.api.md b/sdk/etc/foliage.api.md
index d777fa0ee..813e18ad8 100644
--- a/sdk/etc/foliage.api.md
+++ b/sdk/etc/foliage.api.md
@@ -1,7 +1,7 @@
# API surface — esengine/foliage
<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->
-Symbols: 0 public · 0 beta · 31 experimental · 0 deprecated
+Symbols: 0 public · 0 beta · 32 experimental · 0 deprecated
## BladeParams — interface @experimental
```
@@ -140,6 +140,7 @@ lod1Mesh: string
material: string
mesh: string
opaque: boolean
+soft: number | undefined
texture: string
tint: [number, number, number, number]
```
@@ -250,6 +251,11 @@ Plugin
(p: ScatterParams, ground: Ground): Plant[]
```
+## softenNormals — function @experimental
+```
+(source: MeshData, amount: number): MeshData
+```
+
## thinPlants — function @experimental
```
(plants: readonly Plant[], keep: number): readonly Plant[]
diff --git a/sdk/src/foliage/builder.ts b/sdk/src/foliage/builder.ts
index 96f9dc42f..4ea1a6930 100644
--- a/sdk/src/foliage/builder.ts
+++ b/sdk/src/foliage/builder.ts
@@ -299,6 +299,25 @@ export function buildPlacedMesh(source: MeshData, plants: readonly Plant[]): Mes
return { channels: source.channels, vertexStride: stride, vertexCount: count * plants.length, vertices, indices, aabbMin: min, aabbMax: max };
}
+/**
+ * The mesh with its normals turned toward up by `amount` (0 leaves them, 1 makes them all up): a card that stands for a crown lit as a rounded thing
+ * rather than as the flat it is. A copy; the source is shared by every plant of the kind.
+ */
+export function softenNormals(source: MeshData, amount: number): MeshData {
+ const normal = source.channels.find((c) => c.semantic === MeshChannel.Normal && c.type === MeshChannelType.Float32 && c.components >= 3);
+ const a = Math.min(Math.max(amount, 0), 1);
+ if (!normal || a <= 0) return source;
+ const vertices = new Uint8Array(source.vertices.subarray(0, source.vertexCount * source.vertexStride));
+ const f32 = new Float32Array(vertices.buffer), words = source.vertexStride >> 2, at = normal.offset >> 2;
+ for (let v = 0; v < source.vertexCount; v++) {
+ const o = v * words + at;
+ const x = f32[o]! * (1 - a), y = f32[o + 1]! * (1 - a) + a, z = f32[o + 2]! * (1 - a);
+ const len = Math.hypot(x, y, z) || 1;
+ f32[o] = x / len; f32[o + 1] = y / len; f32[o + 2] = z / len;
+ }
+ return { ...source, vertices };
+}
+
/**
* The plants a far version draws, when it draws a share `keep` of them (above 0 to 1): every n-th, n the nearest whole number to 1 / keep, each grown by the
* square root of n (to a most of twice) so the ground they cover is what it was. The same plants every time: what is kept is a matter of order.
diff --git a/sdk/src/foliage/index.ts b/sdk/src/foliage/index.ts
index 107abfb7b..481314c3c 100644
--- a/sdk/src/foliage/index.ts
+++ b/sdk/src/foliage/index.ts
@@ -10,7 +10,7 @@ export {
export { PlantGrowth, PlantGrowthRes, plantGrowthOf } from './plantGrowth';
export { PLACED_STRIDE, type PlacedKind, type PlacedPart, type PlantKind } from './plantKind';
export {
- scatterCell, buildGrassMesh, buildInstancedMesh, buildPlacedMesh, thinPlants, buildBillboardMesh, rng,
+ scatterCell, buildGrassMesh, buildInstancedMesh, buildPlacedMesh, thinPlants, softenNormals, buildBillboardMesh, rng,
type Plant, type Ground, type ScatterParams, type BladeParams, type CardRect,
} from './builder';
diff --git a/sdk/src/foliage/plantGrowth.ts b/sdk/src/foliage/plantGrowth.ts
index ea8e99155..3d43d1a3e 100644
--- a/sdk/src/foliage/plantGrowth.ts
+++ b/sdk/src/foliage/plantGrowth.ts
@@ -26,7 +26,7 @@ import type { MeshData } from '../asset/meshFormat';
import { log } from '../util/logger';
import { bakesOf } from '../runtime/bakes';
import type { Entity } from '../types';
-import { buildPlacedMesh, thinPlants, type Plant } from './builder';
+import { buildPlacedMesh, softenNormals, thinPlants, type Plant } from './builder';
import type { PlacedKind, PlacedPart } from './plantKind';
/** A part with what it needs in hand: its geometry read, its handles made. */
@@ -60,7 +60,7 @@ export async function prepareKinds(assets: AssetsApi, kinds: readonly PlacedKind
let lod1: MeshData | null = null;
if (withLod && part.lod1Mesh) lod1 = await assets.readMeshData((await assets.load<{ handle: number }>('mesh', part.lod1Mesh)).handle);
return {
- part, source, lod1,
+ part, source: part.soft ? softenNormals(source, part.soft) : source, lod1,
material: part.material ? (await assets.loadMaterial(part.material)).handle : 0,
texture: part.texture ? (await assets.loadTexture(part.texture)).handle : 0,
};
diff --git a/sdk/src/foliage/plantKind.ts b/sdk/src/foliage/plantKind.ts
index 2a7849f04..cbbc519de 100644
--- a/sdk/src/foliage/plantKind.ts
+++ b/sdk/src/foliage/plantKind.ts
@@ -17,6 +17,11 @@ export interface PlacedPart {
tint: [number, number, number, number];
/** False for a part that is blended (glass, a decal): it is drawn after what is solid. */
opaque: boolean;
+ /**
+ * How far its normals are turned to face up, 0 to 1 (default 0): for a flat card that stands for a crown, which lit by its own normal is bright
+ * on the side the sun is on and a dark slab on the other. A crown is lit as a rounded thing, and facing up is how a card is.
+ */
+ soft?: number;
}
/** A kind of plant: its parts, and how far it is drawn. */
diff --git a/sdk/src/worldgen/rulesAsset.ts b/sdk/src/worldgen/rulesAsset.ts
index aad979839..d540372a1 100644
--- a/sdk/src/worldgen/rulesAsset.ts
+++ b/sdk/src/worldgen/rulesAsset.ts
@@ -66,6 +66,7 @@ function part(v: unknown, where: string): PlantKind['parts'][number] {
mesh: str(p.mesh, `${where}.mesh`), lod1Mesh: typeof p.lod1Mesh === 'string' ? p.lod1Mesh : '', material: typeof p.material === 'string' ? p.material : '',
texture: typeof p.texture === 'string' ? p.texture : '', tint: (tint as unknown[]).map((c, i) => num(c, `${where}.tint[${i}]`)) as [number, number, number, number],
opaque: p.opaque !== false,
+ ...(p.soft === undefined ? {} : { soft: Math.min(Math.max(num(p.soft, `${where}.soft`), 0), 1) }),
};
}
diff --git a/sdk/tests/foliage-builder.test.ts b/sdk/tests/foliage-builder.test.ts
index b304ec73b..cb6c2a755 100644
--- a/sdk/tests/foliage-builder.test.ts
+++ b/sdk/tests/foliage-builder.test.ts
@@ -2,7 +2,7 @@
// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
import { describe, it, expect } from 'vitest';
import { MeshChannel, MeshChannelType, packChannels, type MeshData } from '../src/asset/meshFormat';
-import { buildBillboardMesh, buildGrassMesh, buildInstancedMesh, buildPlacedMesh, thinPlants, rng, scatterCell, type Ground, type Plant } from '../src/foliage/builder';
+import { buildBillboardMesh, buildGrassMesh, buildInstancedMesh, buildPlacedMesh, softenNormals, thinPlants, rng, scatterCell, type Ground, type Plant } from '../src/foliage/builder';
const flat: Ground = () => ({ y: 2, up: 1 });
const params = {
@@ -206,6 +206,37 @@ describe('placed meshes', () => {
});
});
+describe('softening a card\'s normals', () => {
+ const channels = packChannels([
+ { semantic: MeshChannel.Position, type: MeshChannelType.Float32, components: 3 },
+ { semantic: MeshChannel.Normal, type: MeshChannelType.Float32, components: 3 },
+ ]).channels;
+ const stride = 24;
+ const make = (normal: number[]): MeshData => {
+ const vertices = new Uint8Array(stride);
+ new Float32Array(vertices.buffer).set([0, 0, 0, ...normal]);
+ return { channels, vertexStride: stride, vertexCount: 1, vertices, indices: new Uint32Array([0, 0, 0]), aabbMin: [0, 0, 0], aabbMax: [0, 0, 0] };
+ };
+ const normalOf = (m: MeshData) => [...new Float32Array(m.vertices.buffer, 12, 3)];
+
+ it('turns a normal toward up by the amount, to a unit vector, and copies rather than changes the source', () => {
+ const source = make([1, 0, 0]);
+ const half = normalOf(softenNormals(source, 0.5));
+ expect(Math.hypot(...half)).toBeCloseTo(1, 5);
+ expect(half[1]).toBeGreaterThan(0.6);
+ expect(half[0]).toBeGreaterThan(0.6);
+ expect(normalOf(softenNormals(source, 1))).toEqual([0, 1, 0]);
+ expect(normalOf(source)).toEqual([1, 0, 0]);
+ });
+
+ it('leaves a mesh as it is for none, or for a mesh with no normals', () => {
+ const source = make([1, 0, 0]);
+ expect(softenNormals(source, 0)).toBe(source);
+ const flat: MeshData = { ...source, channels: channels.slice(0, 1) };
+ expect(softenNormals(flat, 1)).toBe(flat);
+ });
+});
+
describe('thinning plants for a far version', () => {
const plants: Plant[] = Array.from({ length: 12 }, (_, i) => ({ x: i, y: 0, z: 0, yaw: 0, scale: 1, phase: 0, shade: 1 }));
diff --git a/sdk/tests/worldgen-rules-asset.test.ts b/sdk/tests/worldgen-rules-asset.test.ts
index ccad2c1ad..1778857c7 100644
--- a/sdk/tests/worldgen-rules-asset.test.ts
+++ b/sdk/tests/worldgen-rules-asset.test.ts
@@ -44,7 +44,7 @@ describe('plants in a world rules file', () => {
const r = JSON.parse(JSON.stringify(good));
r.plants = {
oak: { parts: [{ mesh: 'assets/oak_trunk.esmesh', material: 'assets/bark.esmaterial' }, { mesh: 'assets/oak_crown.esmesh', lod1Mesh: 'assets/oak_crown1.esmesh', opaque: true }],
- lodDistance: 6000, drawDistance: 16000, far: [{ mesh: 'assets/oak_cards.esmesh' }], farDistance: 200000, farKeep: 0.25, tints: [[0.9, 1, 0.9], [1, 1, 1]], sink: 8 },
+ lodDistance: 6000, drawDistance: 16000, far: [{ mesh: 'assets/oak_cards.esmesh', soft: 0.85 }], farDistance: 200000, farKeep: 0.25, tints: [[0.9, 1, 0.9], [1, 1, 1]], sink: 8 },
};
r.recipes[0].anchor = { id: 'oak', plant: 'oak', footprint: 8 };
delete r.recipes[0].anchor.mesh;
@@ -59,6 +59,8 @@ describe('plants in a world rules file', () => {
expect(oak.parts).toHaveLength(2);
expect(oak.parts[1]!.lod1Mesh).toBe('assets/oak_crown1.esmesh');
expect(oak.far[0]!.mesh).toBe('assets/oak_cards.esmesh');
+ expect(oak.far[0]!.soft).toBe(0.85);
+ expect(oak.parts[0]!.soft).toBeUndefined();
expect(oak.tints).toHaveLength(2);
expect(oak.sink).toBe(8);
expect(oak.farKeep).toBe(0.25);
diff --git a/tools/releaseNotes.mjs b/tools/releaseNotes.mjs
index 58ce0d984..901ae0753 100644
--- a/tools/releaseNotes.mjs
+++ b/tools/releaseNotes.mjs
@@ -2848,6 +2848,10 @@ export const NOTED = {
{"note":"A Display LUT."},
"feat(examples): Terrain & Water is graded warm by a display LUT":
{"note":"A Display LUT."},
+ "feat(worldgen): a part's soft turns the normals of a card that stands for a crown toward up":
+ {"note":"A generated world's plants."},
+ "feat(examples): Terrain & Water draws its trees as models out to 380 metres, and their cards are lit as crowns":
+ {"note":"A generated world's plants."},
"feat(water): two tiled, scrolling detail normal maps give the surface its sparkle":
{"note":"Sparkle on the water."},
"fix(lod): a LODGroup with only a cull size is no longer ignored":