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(units): a shader param says it is a length with unit(length) and follows the project's units per metre, as components and effects do - the water's defaults were metres in an engine of centimetres

yhh5fdd64f41724
diff --git a/CHANGELOG.md b/CHANGELOG.md
index e1500aec1..0f0c9762a 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -14,9 +14,14 @@ published separately; it ships inside the editor.
## [Unreleased]
+### Added
+
+- **An ocean reaches the horizon.** The sea's surface is rings of mesh round the camera, and it ended where they did: from a hill, or with a small `cells` and `rings`, a straight edge with nothing past it. A flat apron now carries it on to 80 km, at the cost of one row of quads.
+- **One setting says what a unit is, for materials too.** A shader param declares `unit(length)` or `unit(perLength)` and its default and range follow the project's Units per Metre, as a component's lengths and a post-process effect's already did; the inspector shows the project's numbers. The water was the reason: its shader, `WaterBody`, `WaterZone` and the sky's World Units per km held their defaults in metres while the engine's reference is centimetres, so stock water in a default project was a hundredth of its size and a scene in metres copied from one in centimetres drew clear water. They are now written once, at the reference, and are the same water in either. **A scene that relied on the old defaults in a centimetre project** (a `WaterBody` or `WaterZone` field left unset, a Water material with unset lengths, clouds with World Units per km unset) draws them a hundred times larger than before, which is what they were meant to be; state the values, or set Units per Metre to 1 if the scene is in metres.
+
### Fixed
-- **A 16-bit heightmap keeps its depth and size in a build.** A texture is capped at its Max Size (2048 unless set) when a build cooks it, and the cap decodes a PNG to 8 bits a channel on the way. A `Terrain` heightmap of 4096 samples and 16 bits therefore shipped as 2048 samples of 256 steps: the exported ground was terraced and coarser than the same ground in the editor, which reads the file itself, and nothing said so. A PNG that holds 16 bits a channel now ships byte for byte.
+- **A 16-bit heightmap keeps its depth and size in a build.** A texture is capped at its Max Size (2048 unless set) when a build cooks it, and the cap decodes a PNG to 8 bits a channel on the way. A `Terrain` heightmap of 4096 samples and 16 bits therefore shipped as 2048 samples of 256 steps: the exported ground was terraced and coarser than the same ground in the editor, which reads the file itself, and nothing said so. A PNG that holds 16 bits a channel now ships byte for byte. A texture a `Terrain` names as its heightmap is never capped either, at any depth.
## [0.103.0] - 2026-11-12
diff --git a/desktop b/desktop
index dc7e68791..0fa4d369f 160000
--- a/desktop
+++ b/desktop
@@ -1 +1 @@
-Subproject commit dc7e68791ec7e0b78a2319763527ce77a116cb4c
+Subproject commit 0fa4d369f65ea31c0f1d8db8ab376cfcdfc7b99f
diff --git a/docs/astro/src/content/docs/graphics/materials.mdx b/docs/astro/src/content/docs/graphics/materials.mdx
index e0d89dca6..093f4a647 100644
--- a/docs/astro/src/content/docs/graphics/materials.mdx
+++ b/docs/astro/src/content/docs/graphics/materials.mdx
@@ -253,6 +253,17 @@ says which one found no unit.
Params live in an engine-generated std140 block, initialized from their `default(…)`
values — a material that never sets a param still draws correctly.
+A param that is a distance in the world says so with `unit(length)`, and one that is a rate per distance (a fog or water density) with
+`unit(perLength)`. Its default and range are then written at the engine's reference of 100 world units a metre, and follow the project's
+own **Units per Metre** (Project Settings → Physics → 3D): `default(250) unit(length)` is 2.5 m of whatever a unit is, 250 in a
+centimetre project and 2.5 in a metre one. The inspector shows the project's numbers, and a value a material states is never scaled.
+It is the same rule a component's lengths and a post-process effect's follow, so a project says what a unit is once.
+
+```glsl
+#pragma param u_foamWidth float default(120) range(0, 2000) ui(slider) unit(length)
+#pragma param u_density float default(0.0012) range(0, 0.04) unit(perLength)
+```
+
### Injected uniforms & helpers
The engine injects these into every compiled `.esshader` — never declare them yourself:
diff --git a/docs/astro/src/content/docs/graphics/post-processing.mdx b/docs/astro/src/content/docs/graphics/post-processing.mdx
index 84ba2d509..4ab4f93e0 100644
--- a/docs/astro/src/content/docs/graphics/post-processing.mdx
+++ b/docs/astro/src/content/docs/graphics/post-processing.mdx
@@ -115,7 +115,7 @@ Turn **Cloud Shadows** above 0 and the sun's ray from each surface is marched up
same density, so the ground is darker and patchier under a cloud and lit where the sky is open. The sun's own light is what is
kept off; ambient light is not shadowed. Casting shadows also pins the clouds to the world instead of carrying them along with the
camera, so walking under a cloud and out of it works. The sky is in kilometres and the scene in its own units: **World Units per km**
-says how many of the scene's units make one. At 0 (the default) the effect is exactly as it was. The shadow falls on surfaces only; the
+says how many of the scene's units make one, and left alone it follows the project's Units per Metre (100 000 in a centimetre project, 1000 in a metre one). At 0 (the default) the effect is exactly as it was. The shadow falls on surfaces only; the
clouds are still drawn where there is sky.
### Split toning and lifted blacks
diff --git a/sdk/etc/index.api.md b/sdk/etc/index.api.md
index f978c326e..bc44fb1af 100644
--- a/sdk/etc/index.api.md
+++ b/sdk/etc/index.api.md
@@ -9972,6 +9972,7 @@ range: { min: number; max: number; } | undefined
texel: "data" | undefined
type: ShaderParamType
ui: string | undefined
+worldUnits: 1 | -1 | undefined
```
## ShaderParamType — type @experimental
@@ -14783,7 +14784,7 @@ MotionDriver<AnimatorBlend2DMotion>
## buildOceanMesh — function @experimental
```
-(cells: number, rings: number, cellSize: number): MeshData
+(cells: number, rings: number, cellSize: number, skirt?: number): MeshData
```
## buildPatchMesh — function @experimental
diff --git a/sdk/etc/index.native.api.md b/sdk/etc/index.native.api.md
index 8a0425c1d..8cbe42675 100644
--- a/sdk/etc/index.native.api.md
+++ b/sdk/etc/index.native.api.md
@@ -10194,6 +10194,7 @@ range: { min: number; max: number; } | undefined
texel: "data" | undefined
type: ShaderParamType
ui: string | undefined
+worldUnits: 1 | -1 | undefined
```
## ShaderParamType — type @experimental
@@ -15020,7 +15021,7 @@ MotionDriver<AnimatorBlend2DMotion>
## buildOceanMesh — function @experimental
```
-(cells: number, rings: number, cellSize: number): MeshData
+(cells: number, rings: number, cellSize: number, skirt?: number): MeshData
```
## buildPatchMesh — function @experimental
diff --git a/sdk/etc/index.node.api.md b/sdk/etc/index.node.api.md
index 41ed613da..4bc6e389d 100644
--- a/sdk/etc/index.node.api.md
+++ b/sdk/etc/index.node.api.md
@@ -9967,6 +9967,7 @@ range: { min: number; max: number; } | undefined
texel: "data" | undefined
type: ShaderParamType
ui: string | undefined
+worldUnits: 1 | -1 | undefined
```
## ShaderParamType — type @experimental
@@ -14778,7 +14779,7 @@ MotionDriver<AnimatorBlend2DMotion>
## buildOceanMesh — function @experimental
```
-(cells: number, rings: number, cellSize: number): MeshData
+(cells: number, rings: number, cellSize: number, skirt?: number): MeshData
```
## buildPatchMesh — function @experimental
diff --git a/sdk/etc/minigame.api.md b/sdk/etc/minigame.api.md
index 9e3f280dc..00b7f1eba 100644
--- a/sdk/etc/minigame.api.md
+++ b/sdk/etc/minigame.api.md
@@ -10264,6 +10264,7 @@ range: { min: number; max: number; } | undefined
texel: "data" | undefined
type: ShaderParamType
ui: string | undefined
+worldUnits: 1 | -1 | undefined
```
## ShaderParamType — type @experimental
@@ -15081,7 +15082,7 @@ MotionDriver<AnimatorBlend2DMotion>
## buildOceanMesh — function @experimental
```
-(cells: number, rings: number, cellSize: number): MeshData
+(cells: number, rings: number, cellSize: number, skirt?: number): MeshData
```
## buildPatchMesh — function @experimental
diff --git a/sdk/etc/water.api.md b/sdk/etc/water.api.md
index 3e978796e..32f50962c 100644
--- a/sdk/etc/water.api.md
+++ b/sdk/etc/water.api.md
@@ -259,7 +259,7 @@ speed: number
## buildOceanMesh — function @experimental
```
-(cells: number, rings: number, cellSize: number): MeshData
+(cells: number, rings: number, cellSize: number, skirt?: number): MeshData
```
## currentShare — function @experimental
diff --git a/sdk/etc/wechat.api.md b/sdk/etc/wechat.api.md
index ff221bf8e..b8ac52129 100644
--- a/sdk/etc/wechat.api.md
+++ b/sdk/etc/wechat.api.md
@@ -9974,6 +9974,7 @@ range: { min: number; max: number; } | undefined
texel: "data" | undefined
type: ShaderParamType
ui: string | undefined
+worldUnits: 1 | -1 | undefined
```
## ShaderParamType — type @experimental
@@ -14812,7 +14813,7 @@ MotionDriver<AnimatorBlend2DMotion>
## buildOceanMesh — function @experimental
```
-(cells: number, rings: number, cellSize: number): MeshData
+(cells: number, rings: number, cellSize: number, skirt?: number): MeshData
```
## buildPatchMesh — function @experimental
diff --git a/sdk/src/postprocess/effects.ts b/sdk/src/postprocess/effects.ts
index 423fdbe94..b5c918703 100644
--- a/sdk/src/postprocess/effects.ts
+++ b/sdk/src/postprocess/effects.ts
@@ -490,7 +490,7 @@ registerEffect({
// How much of the sun the clouds keep off the scene's surfaces. Above 0 the clouds are fixed to the world, not carried along with the camera.
{ name: 'u_cloudShadow', label: 'Cloud Shadows', min: 0, max: 1, step: 0.01, defaultValue: 0, neutralValue: 0 },
// How many world units are a kilometre: the sky is in kilometres, the scene in its own units.
- { name: 'u_unitsPerKm', label: 'World Units per km', min: 1, max: 100000, step: 1, defaultValue: 1000 },
+ { name: 'u_unitsPerKm', label: 'World Units per km', min: 100, max: 10000000, step: 100, defaultValue: 100000, worldUnits: 1 },
// With a Cloud Mask, how many kilometres of the cloud layer one repeat of it covers (0 leaves the clouds to the noise): the mask gives the clouds
// their shape, the noise only erodes it. The second mask is a softer, higher layer folded in at a third.
{ name: 'u_cloudMaskTile', label: 'Cloud Mask Tile (km)', min: 0, max: 100, step: 0.1, defaultValue: 0 },
diff --git a/sdk/src/render/shaderReflect.ts b/sdk/src/render/shaderReflect.ts
index 660d94e76..b87dbb0b3 100644
--- a/sdk/src/render/shaderReflect.ts
+++ b/sdk/src/render/shaderReflect.ts
@@ -17,11 +17,13 @@
* otherwise drop without a word.
*
* Grammar (matches ShaderParser):
- * #pragma param <name> <type> [default(csv)] [range(min,max)] [ui(hint)] [texel(data)]
+ * #pragma param <name> <type> [default(csv)] [range(min,max)] [ui(hint)] [texel(data)] [unit(length|perLength)]
* (<type> `textureArray` reads as a `texture` param with `layered` set)
* #pragma domain <Unlit|Lit|PostProcess|UI>
*/
+import { worldUnitScale } from '../ecs/worldUnits';
+
export type ShaderParamType = 'float' | 'vec2' | 'vec3' | 'vec4' | 'color' | 'int' | 'texture';
export interface ShaderParam {
@@ -42,6 +44,12 @@ export interface ShaderParam {
* packed roughness), which sRGB decode would bend. Absent means colour.
*/
texel?: 'data';
+ /**
+ * `unit(length)` (1) or `unit(perLength)` (-1): the default and range are written at 100 world units a metre, the
+ * engine's reference, and follow the project's units per metre where a material leaves the param unset
+ * (ecs/worldUnits.ts; {@link shaderParamInUnits} is what an inspector shows). Absent is a plain number.
+ */
+ worldUnits?: 1 | -1;
/**
* Declared `textureArray`: a 2D texture array, sampled with a layer index
* (`texture(u_x, vec3(uv, layer))`). Set it with `Material.tex` on a handle from
@@ -50,6 +58,18 @@ export interface ShaderParam {
layered?: true;
}
+/**
+ * A param as it reads in this project: a world-unit one's default and range scaled to the project's units per metre (a length
+ * by the scale, a rate per length by its inverse), as the engine fills it; any other as declared.
+ */
+export function shaderParamInUnits(p: ShaderParam): ShaderParam {
+ const s = worldUnitScale();
+ if (!p.worldUnits || s === 1) return p;
+ const k = p.worldUnits === 1 ? s : 1 / s;
+ const range = p.range ? { min: p.range.min * k, max: p.range.max * k } : undefined;
+ return { ...p, default: p.default.map((v) => v * k), ...(range ? { range } : {}) };
+}
+
export interface ShaderReflection {
domain: string;
params: ShaderParam[];
@@ -113,6 +133,8 @@ function parseParam(arg: string): ShaderParam | null {
if (ui !== undefined) param.ui = ui;
if (type === 'texture' && clause(arg, 'texel') === 'data') param.texel = 'data';
+ const unit = clause(arg, 'unit');
+ if (type !== 'texture' && (unit === 'length' || unit === 'perLength')) param.worldUnits = unit === 'length' ? 1 : -1;
return param;
}
@@ -143,7 +165,7 @@ export function paramDefaultValue(param: ShaderParam): unknown {
*/
export const RENAMED_DOMAINS: Readonly<Record<string, string>> = { Lit2D: 'Lit', Unlit2D: 'Unlit' };
-/** Parse a `.esshader` source into its declared parameters and domain. */
+/** Parse a `.esshader` source into its declared parameters (world-unit ones in the project's units) and domain. */
export function reflectEsshader(source: string): ShaderReflection {
const params: ShaderParam[] = [];
let domain = 'Unlit';
@@ -158,7 +180,8 @@ export function reflectEsshader(source: string): ShaderReflection {
if (directive === 'param') {
const p = parseParam(arg);
- if (p) params.push(p);
+ // In the project's units, as the engine fills an unset param: an inspector, a template and a tool all read the same number.
+ if (p) params.push(shaderParamInUnits(p));
} else if (directive === 'domain' && arg) {
domain = RENAMED_DOMAINS[arg] ?? arg;
}
diff --git a/sdk/src/water/floating.ts b/sdk/src/water/floating.ts
index a45a820aa..e8ce0b4c2 100644
--- a/sdk/src/water/floating.ts
+++ b/sdk/src/water/floating.ts
@@ -50,6 +50,7 @@ export interface FloatingData {
export const Floating: ComponentDef<FloatingData> = defineComponent<FloatingData>('Floating', {
buoyancy: 2, drag: 1, radius: 50, points: [] as Vec3Like[], wake: 1,
}, {
+ worldUnitFields: ['radius'],
fields: {
buoyancy: { min: 0, max: 20, category: 'Water', tooltip: 'The water\'s density against the body\'s. 1 holds it up exactly when it is wholly under; 2 floats it half under.' },
drag: { min: 0, max: 20, category: 'Water', tooltip: 'How hard the water resists the body moving through it, per second.' },
diff --git a/sdk/src/water/waterPlugin.ts b/sdk/src/water/waterPlugin.ts
index 43b7ac978..71ce1ae0b 100644
--- a/sdk/src/water/waterPlugin.ts
+++ b/sdk/src/water/waterPlugin.ts
@@ -36,6 +36,7 @@ import { bakesOf } from '../runtime/bakes';
import type { Entity } from '../types';
import { surfHeight, waveHeight, waveSlope, type WaveParams } from './waves';
import { buildOceanMesh, oceanReach, oceanSnap } from './waterMesh';
+import { worldUnitsPerMeter } from '../ecs/worldUnits';
import { type Point2 } from './shore';
import { Spline, type SplineData } from '../spline/splinePlugin';
import { SplineCurve } from '../spline/curve';
@@ -79,8 +80,10 @@ export interface WaterBodyData {
* @experimental
*/
export const WaterBody: ComponentDef<WaterBodyData> = /* @__PURE__ */ defineComponent<WaterBodyData>('WaterBody', {
- form: WaterForm.Lake, bodyId: '', sizeX: 100, sizeZ: 100, boundary: [] as Point2[], shoreWidth: 3, flowSpeed: 2, waveHeight: 0.3, bedDepth: 0,
+ // Lengths at the engine's reference of 100 units a metre (ecs/worldUnits.ts): a 100 m lake with 30 cm waves in any project.
+ form: WaterForm.Lake, bodyId: '', sizeX: 10000, sizeZ: 10000, boundary: [] as Point2[], shoreWidth: 300, flowSpeed: 200, waveHeight: 30, bedDepth: 0,
}, {
+ worldUnitFields: ['sizeX', 'sizeZ', 'shoreWidth', 'flowSpeed', 'waveHeight', 'bedDepth'],
fields: {
form: { enum: [{ label: 'Ocean', value: WaterForm.Ocean }, { label: 'Lake', value: WaterForm.Lake }, { label: 'River', value: WaterForm.River }], category: 'Shape', tooltip: 'An ocean is without edge: everywhere at its height where the ground is lower; a lake is a rectangle or an outline of its own; a river follows the Spline on the same entity.' },
bodyId: { category: 'Shape', tooltip: 'What the game calls this body, the same in every session: what a query names the water by. Empty is named by its entity.' },
@@ -134,7 +137,8 @@ export function waterQualityOf(profile: Readonly<QualityProfile> | null, miniGam
}
/** The zone a scene without a `WaterZone` is given: the component's defaults, over every lake and river. */
-const ZONE_DEFAULTS: WaterZoneData = { ...WaterZone._default };
+/** The zone's defaults in the project's units: asked each time, since a project says what a unit is before its scene loads. */
+const zoneDefaults = (): WaterZoneData => ({ ...WaterZone._default });
/** Run-time access to the water: where its surface is at a point, for what floats on it or swims in it. */
export class Waters {
@@ -143,7 +147,7 @@ export class Waters {
quality: WaterQuality = FULL_WATER;
/** The baked water, and the zone it was baked by. @internal */
field_: WaterField | null = null;
- /** @internal */ zone_: WaterZoneData = ZONE_DEFAULTS;
+ /** @internal */ zone_: WaterZoneData = zoneDefaults();
/** The ripples the zone keeps, where it asks for them. @internal */
ripples_: RippleField | null = null;
/** The material instance the surface is drawn with, for what draws the same water (the underwater effect). @internal */
@@ -516,7 +520,7 @@ export class WaterPlugin implements Plugin {
keyParts.push([key, d.form, spline.points, spline.closed, d.flowSpeed, d.waveHeight, d.shoreWidth, t.worldPosition, t.worldRotation, scale]);
}
}
- let zone = ZONE_DEFAULTS;
+ let zone = zoneDefaults();
let grid: ZoneGrid | null = null;
for (const entity of app.world.getEntitiesWithComponents([WaterZone, Transform])) {
zone = app.world.get(entity, WaterZone) as WaterZoneData;
@@ -603,7 +607,9 @@ export class WaterPlugin implements Plugin {
const source = zone.material || await this.stock(app);
if (s.epoch !== epoch || this.surface_ !== s) return;
const assets = app.getResource(Assets);
- const mesh = assets.createMesh(buildOceanMesh(zone.cells, zone.rings, zone.cellSize));
+ // The rings are where the waves are; past them a flat apron carries the sea to the horizon (80 km, further than a camera a
+ // kilometre up can see), so an ocean does not end in a straight line where its mesh does.
+ const mesh = assets.createMesh(buildOceanMesh(zone.cells, zone.rings, zone.cellSize, 80000 * worldUnitsPerMeter()));
if (mesh === 0) { log.warn('water', 'the engine refused the water geometry'); return; }
const instance = Material.createInstance(source);
if (instance === 0) { assets.releaseBuiltMesh(mesh); log.warn('water', 'the water material could not be instanced'); return; }
diff --git a/sdk/src/water/waterShader.ts b/sdk/src/water/waterShader.ts
index c77a36305..5b8798c9b 100644
--- a/sdk/src/water/waterShader.ts
+++ b/sdk/src/water/waterShader.ts
@@ -23,30 +23,30 @@ const WATER = `#pragma shader "Water"
#pragma param u_deepColor color default(0.01,0.08,0.15,1)
// How fast each colour is absorbed along the way through the water (red goes first), and how thick the water is, per world unit.
#pragma param u_absorption color default(0.45,0.09,0.05,1)
-#pragma param u_density float default(0.12) range(0,4) ui(slider)
+#pragma param u_density float default(0.0012) range(0,0.04) ui(slider) unit(perLength)
// The waves: height, length of the longest, how sharp their crests are drawn, how fast they travel and which way (degrees).
-#pragma param u_waveHeight float default(0.3) range(0,8) ui(slider)
-#pragma param u_waveLength float default(14) range(0.5,300) ui(slider)
+#pragma param u_waveHeight float default(30) range(0,800) ui(slider) unit(length)
+#pragma param u_waveLength float default(1400) range(50,30000) ui(slider) unit(length)
#pragma param u_waveSpeed float default(1) range(0,4) ui(slider)
#pragma param u_waveDirection float default(30) range(0,360) ui(slider)
// The small ripples the long waves carry: how steep and how long each is.
#pragma param u_rippleStrength float default(0.3) range(0,1) ui(slider)
-#pragma param u_rippleLength float default(2.5) range(0.1,40) ui(slider)
+#pragma param u_rippleLength float default(250) range(10,4000) ui(slider) unit(length)
// How hard it rains on the water (the weather writes it): drops ring out on the surface, a few to every u_rippleLength.
#pragma param u_rain float default(0) range(0,4) ui(slider)
#pragma param u_roughness float default(0.04) range(0,1) ui(slider)
// How far what is seen through the water is shifted by its waves, and the depth of water at which that stops growing.
#pragma param u_refractionStrength float default(1) range(0,4) ui(slider)
-#pragma param u_distortionRange float default(12) range(0.1,200) ui(slider)
+#pragma param u_distortionRange float default(1200) range(10,20000) ui(slider) unit(length)
// Foam: its colour, how deep the water is where it begins at the shore (world units), and how much of the wave crests carry it.
#pragma param u_foamColor color default(0.95,0.97,1,1)
-#pragma param u_foamWidth float default(1.2) range(0,20) ui(slider)
+#pragma param u_foamWidth float default(120) range(0,2000) ui(slider) unit(length)
#pragma param u_foamCrest float default(0.5) range(0,1) ui(slider)
// How deep, in world units, the water is where it has thinned to nothing at its edge: over that last depth the ground behind shows through
// more and more, so the water meets it along a soft line. 0 keeps a hard edge.
-#pragma param u_edgeSoftness float default(0.3) range(0,1000) ui(slider)
+#pragma param u_edgeSoftness float default(30) range(0,100000) ui(slider) unit(length)
// The depth taken where the device could not measure one.
-#pragma param u_fallbackDepth float default(4) range(0,200) ui(slider)
+#pragma param u_fallbackDepth float default(400) range(0,20000) ui(slider) unit(length)
// Where the waves are measured. 0 is the world's xz plane, which is what a plain mesh of water wants. 1 is the surface a WaterZone draws: the mesh's uv
// is its x and z (plus u_origin, which the zone moves as the mesh follows the camera, so the waves stay put in the world), and the vertices are lifted
// to the zone's water and its waves.
@@ -73,7 +73,7 @@ const WATER = `#pragma shader "Water"
// The surf (the WaterZone writes these): how high a breaker stands against its body's waves (with the weather in), how long the surf's waves
// are, and a multiplier on their speed. 0 draws none.
#pragma param u_surfHeight float default(0) range(0,4) ui(slider)
-#pragma param u_surfLength float default(10) range(0.1,100000) ui(slider)
+#pragma param u_surfLength float default(1000) range(10,10000000) ui(slider) unit(length)
#pragma param u_surfSpeed float default(1) range(0,4) ui(slider)
// How long, in seconds, each of the two copies of the surface the shader carries down a current lives before the other takes over.
#pragma param u_flowCycle float default(2) range(0.2,20) ui(slider)
@@ -82,7 +82,7 @@ const WATER = `#pragma shader "Water"
// The net of light the waves throw on what is under the water: how strong it is, how large one cell of it is (world units), and how fast it swims. The Underwater
// effect draws the same one from below, with these numbers, so the two halves of the picture agree.
#pragma param u_causticStrength float default(0.6) range(0,3) ui(slider)
-#pragma param u_causticScale float default(2) range(0.05,2000) ui(slider)
+#pragma param u_causticScale float default(200) range(5,200000) ui(slider) unit(length)
#pragma param u_causticSpeed float default(0.35) range(0,4) ui(slider)
// What the quality level allows (the WaterZone writes these): how many of the four waves are summed, whether the surface seen from below mirrors the world under it,
// and whether the sun's web of light is drawn on what lies under the water.
diff --git a/sdk/src/water/zone.ts b/sdk/src/water/zone.ts
index 5035462fd..66d7d9678 100644
--- a/sdk/src/water/zone.ts
+++ b/sdk/src/water/zone.ts
@@ -59,11 +59,13 @@ export interface WaterZoneData {
* @experimental
*/
export const WaterZone: ComponentDef<WaterZoneData> = /* @__PURE__ */ defineComponent<WaterZoneData>('WaterZone', {
- sizeX: 200, sizeZ: 200, resolution: 256, material: 0,
- waveLength: 14, waveSpeed: 1, waveDirection: 30, surf: 0.6, surfLength: 8,
- cellSize: 1, cells: 64, rings: 5,
- ripples: 0, rippleSize: 64, rippleSpeed: 6, rippleDamping: 0.8, foamFade: 0.4,
+ // Lengths at the engine's reference of 100 units a metre (ecs/worldUnits.ts): 14 m waves on metre cells in any project.
+ sizeX: 20000, sizeZ: 20000, resolution: 256, material: 0,
+ waveLength: 1400, waveSpeed: 1, waveDirection: 30, surf: 0.6, surfLength: 800,
+ cellSize: 100, cells: 64, rings: 5,
+ ripples: 0, rippleSize: 6400, rippleSpeed: 600, rippleDamping: 0.8, foamFade: 0.4,
}, {
+ worldUnitFields: ['sizeX', 'sizeZ', 'waveLength', 'surfLength', 'cellSize', 'rippleSize', 'rippleSpeed'],
assetFields: [{ field: 'material', type: 'material' }],
fields: {
sizeX: { min: 1, category: 'Region', tooltip: 'The region baked along x, centred on the entity. Water outside it is not drawn; an ocean goes on past it.' },
diff --git a/sdk/tests/shader-param-units.test.ts b/sdk/tests/shader-param-units.test.ts
new file mode 100644
index 000000000..3fef84973
--- /dev/null
+++ b/sdk/tests/shader-param-units.test.ts
@@ -0,0 +1,44 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+import { afterEach, describe, expect, it } from 'vitest';
+import { reflectEsshader } from '../src/render/shaderReflect';
+import { setWorldUnitsPerMeter } from '../src/ecs/worldUnits';
+import { WATER_SHADER_TEMPLATE } from '../src/water/waterShader';
+import { WaterBody } from '../src/water/waterPlugin';
+import { WaterZone } from '../src/water/zone';
+
+const SOURCE = `#pragma shader "T"
+#pragma param u_reach float default(250) range(10,4000) unit(length)
+#pragma param u_density float default(0.0012) range(0,0.04) unit(perLength)
+#pragma param u_gain float default(2) range(0,4)
+`;
+const param = (source: string, name: string) => reflectEsshader(source).params.find((p) => p.name === name)!;
+
+describe('a shader param that is a world length', () => {
+ afterEach(() => setWorldUnitsPerMeter(100));
+
+ it('reads as declared at the reference of 100 units a metre', () => {
+ expect(param(SOURCE, 'u_reach').default).toEqual([250]);
+ expect(param(SOURCE, 'u_density').default).toEqual([0.0012]);
+ });
+
+ it('follows the project: a length by the scale, a rate per length by its inverse, a plain number not at all', () => {
+ setWorldUnitsPerMeter(1);
+ expect(param(SOURCE, 'u_reach').default[0]).toBeCloseTo(2.5, 9);
+ expect(param(SOURCE, 'u_reach').range).toEqual({ min: 0.1, max: 40 });
+ expect(param(SOURCE, 'u_density').default[0]).toBeCloseTo(0.12, 9);
+ expect(param(SOURCE, 'u_gain').default).toEqual([2]);
+ });
+
+ it('is how the water says its lengths: the same water in a centimetre project and a metre one', () => {
+ const lengths = ['u_waveLength', 'u_rippleLength', 'u_distortionRange', 'u_foamWidth', 'u_fallbackDepth', 'u_causticScale'];
+ const cm = lengths.map((n) => param(WATER_SHADER_TEMPLATE.source, n).default[0]!);
+ setWorldUnitsPerMeter(1);
+ lengths.forEach((n, i) => expect(param(WATER_SHADER_TEMPLATE.source, n).default[0]).toBeCloseTo(cm[i]! / 100, 9));
+ expect(param(WATER_SHADER_TEMPLATE.source, 'u_density').default[0]).toBeCloseTo(0.12, 9);
+ // And the components that place it: a 100 m lake with 30 cm waves, 14 m swell on 1 m cells.
+ const body = WaterBody._default, zone = WaterZone._default;
+ expect([body.sizeX, body.waveHeight, body.shoreWidth]).toEqual([100, 0.3, 3]);
+ expect([zone.waveLength, zone.cellSize, zone.surfLength]).toEqual([14, 1, 8]);
+ });
+});
diff --git a/src/esengine/renderer/frame/RenderFrame.hpp b/src/esengine/renderer/frame/RenderFrame.hpp
index a340cb8be..e71c34671 100644
--- a/src/esengine/renderer/frame/RenderFrame.hpp
+++ b/src/esengine/renderer/frame/RenderFrame.hpp
@@ -424,7 +424,11 @@ public:
}
/** @brief How many world units make a metre (the project's setting): what an inverse-square light measures in. */
- void setWorldUnitsPerMeter(f32 units) { world_units_per_meter_ = units > 0.0f ? units : 100.0f; }
+ void setWorldUnitsPerMeter(f32 units) {
+ world_units_per_meter_ = units > 0.0f ? units : 100.0f;
+ // The same answer for every default that is a length: a material's unset params follow it (MaterialParamSlot::worldUnits).
+ context_.materials().setWorldUnitsPerMeter(world_units_per_meter_);
+ }
/**
* @brief Colour @p entity in @p view by how much @p joint moves each of its vertices.
diff --git a/src/esengine/renderer/store/MaterialStore.cpp b/src/esengine/renderer/store/MaterialStore.cpp
index d40580ba8..08951a879 100644
--- a/src/esengine/renderer/store/MaterialStore.cpp
+++ b/src/esengine/renderer/store/MaterialStore.cpp
@@ -371,6 +371,7 @@ MaterialUniformLayout MaterialStore::layoutOf(const resource::ParsedShader& pars
}
} else if (p.std140Offset >= 0) {
MaterialParamSlot slot{ p.name, static_cast<u32>(p.std140Offset), paramArity(p.type) };
+ slot.worldUnits = p.worldUnits;
// default(a,b,c,d) csv -> the slot's initial block value.
// A trailing comma ends the list, as a stream's getline would: no empty last field.
usize at = 0;
@@ -406,6 +407,28 @@ void MaterialStore::seedSamplers(Shader& shader, const resource::ParsedShader& p
});
}
+void MaterialStore::setWorldUnitsPerMeter(f32 unitsPerMeter) {
+ const f32 scale = (unitsPerMeter > 0.0f ? unitsPerMeter : 100.0f) / 100.0f;
+ if (scale == world_unit_scale_) return;
+ const f32 was = world_unit_scale_;
+ world_unit_scale_ = scale;
+ // Blocks filled before the project said its unit hold the old defaults. No record says which params a material set, so one is
+ // taken to be unset where it still holds exactly what the default was.
+ for (auto& [id, rec] : materials_) {
+ auto lit = layouts_.find(rec.shaderRef.id());
+ if (lit == layouts_.end() || rec.uboBytes.size() < lit->second.blockSize) continue;
+ for (const auto& p : lit->second.params) {
+ if (p.worldUnits == 0) continue;
+ f32 before[4], now[4];
+ defaultInUnits(p, was, before);
+ if (std::memcmp(rec.uboBytes.data() + p.offset, before, p.arity * sizeof(f32)) != 0) continue;
+ defaultInUnits(p, scale, now);
+ std::memcpy(rec.uboBytes.data() + p.offset, now, p.arity * sizeof(f32));
+ rec.uboDirty = true;
+ }
+ }
+}
+
void MaterialStore::bindForDraw(u32 materialId) {
if (!device_) return;
auto it = materials_.find(materialId);
diff --git a/src/esengine/renderer/store/MaterialStore.hpp b/src/esengine/renderer/store/MaterialStore.hpp
index 6b7aa44ee..3efdbac2e 100644
--- a/src/esengine/renderer/store/MaterialStore.hpp
+++ b/src/esengine/renderer/store/MaterialStore.hpp
@@ -55,6 +55,7 @@ struct MaterialParamSlot {
u32 offset = 0; ///< std140 byte offset within the block.
u32 arity = 1; ///< Float component count (1..4); textures are not slots.
f32 defaults[4] = {0, 0, 0, 0}; ///< Shader-declared default(...); the block's initial value.
+ i8 worldUnits = 0; ///< 1 a length, -1 a rate per length: the default is at 100 units a metre (ShaderProperty::worldUnits).
};
/** @brief Which built-in texture a param falls back to when a material leaves it unset. */
@@ -445,6 +446,10 @@ public:
/// No-op for materials whose shader declares no params (uboBytes stays empty).
void bindForDraw(u32 materialId);
+ /// Says what a world unit is (the project's units per metre). A param a material left at its default follows the change;
+ /// one it set, to anything else, is the material's and stays.
+ void setWorldUnitsPerMeter(f32 unitsPerMeter);
+
/// Frees every per-material GPU UBO and clears all records/layouts. Call while the
/// device is still valid (RenderContext::shutdown).
void clear();
@@ -452,15 +457,26 @@ public:
private:
/// Fills an unpacked block with the shader's param defaults, so a material that never
/// sets a param still draws with the declared default(...) values (not zeros).
- static void ensureDefaults(MaterialRecord& rec, const MaterialUniformLayout& layout) {
+ void ensureDefaults(MaterialRecord& rec, const MaterialUniformLayout& layout) const {
if (layout.blockSize == 0 || rec.uboBytes.size() >= layout.blockSize) return;
rec.uboBytes.resize(layout.blockSize, 0);
for (const auto& p : layout.params) {
- std::memcpy(rec.uboBytes.data() + p.offset, p.defaults, p.arity * sizeof(f32));
+ f32 value[4];
+ defaultInUnits(p, world_unit_scale_, value);
+ std::memcpy(rec.uboBytes.data() + p.offset, value, p.arity * sizeof(f32));
}
rec.uboDirty = true;
}
+ /// A slot's default at @p scale units to the reference: a length times it, a rate per length over it, any other as declared.
+ static void defaultInUnits(const MaterialParamSlot& p, f32 scale, f32* out) {
+ const f32 k = p.worldUnits > 0 ? scale : p.worldUnits < 0 ? 1.0f / scale : 1.0f;
+ for (u32 i = 0; i < 4; ++i) out[i] = p.defaults[i] * k;
+ }
+
+ /// The project's units per metre over the reference 100: what a world-unit default is scaled by.
+ f32 world_unit_scale_ = 1.0f;
+
std::unordered_map<u32, MaterialRecord> materials_;
std::unordered_map<u32, MaterialUniformLayout> layouts_;
diff --git a/src/esengine/resource/ShaderParser.cpp b/src/esengine/resource/ShaderParser.cpp
index fd6d88afc..6f184a47f 100644
--- a/src/esengine/resource/ShaderParser.cpp
+++ b/src/esengine/resource/ShaderParser.cpp
@@ -4262,6 +4262,7 @@ ShaderProperty ShaderParser::parseParamDirective(const std::string& argument) {
if (auto d = clause("default")) prop.defaultValue = *d;
if (auto u = clause("ui")) prop.ui = *u;
+ if (auto u = clause("unit")) prop.worldUnits = *u == "length" ? 1 : *u == "perLength" ? -1 : 0;
if (auto r = clause("range")) {
usize comma = r->find(',');
if (comma != std::string::npos) {
diff --git a/src/esengine/resource/ShaderParser.hpp b/src/esengine/resource/ShaderParser.hpp
index ed136eba9..9979e0d43 100644
--- a/src/esengine/resource/ShaderParser.hpp
+++ b/src/esengine/resource/ShaderParser.hpp
@@ -119,6 +119,9 @@ struct ShaderProperty {
f32 rangeMin = 0.0f;
f32 rangeMax = 1.0f;
std::string ui; ///< UI hint, e.g. "slider", "color" (free-form).
+ /// `unit(length)` (1) or `unit(perLength)` (-1): the default and range are written at 100 world units a metre and
+ /// follow the project's units per metre where a material leaves the param unset. 0 is a plain number.
+ i8 worldUnits = 0;
};
/**
diff --git a/tools/releaseNotes.mjs b/tools/releaseNotes.mjs
index a755eada8..4d3ae486c 100644
--- a/tools/releaseNotes.mjs
+++ b/tools/releaseNotes.mjs
@@ -4510,4 +4510,10 @@ export const NOTED = {
{"note": "A quality level decides what the dynamic GI spends."},
"fix(export): a 16-bit PNG ships as the file it is - a build shrank a 4096 heightmap to 2048 and decoded it to 8 bits, so exported ground stood in 256 steps where the editor drew 65536":
{"note": "A 16-bit heightmap keeps its depth and size in a build."},
+ "fix(export): a texture a Terrain reads as its heightmap ships as the file it is, whatever its size cap - an 8-bit heightmap over Max Size was still shrunk":
+ {"note": "A 16-bit heightmap keeps its depth and size in a build."},
+ "feat(water): an ocean reaches the horizon - a flat apron carries the surface on from its rings, so the sea no longer ends in a line where its mesh does":
+ {"note": "An ocean reaches the horizon."},
+ "feat(units): a shader param says it is a length with unit(length) and follows the project's units per metre, as components and effects do - the water's defaults were metres in an engine of centimetres":
+ {"note": "One setting says what a unit is, for materials too."},
};