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(water): a Floating component holds a rigid body up in water and carries it with the current

yhhe94c93a7f4f6
diff --git a/CHANGELOG.md b/CHANGELOG.md
index cfcec33cb..a79017dc7 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -35,6 +35,7 @@ published separately; it ships inside the editor.
- **Contact shadows and screen-space bounce light.** Contact Shadows and Screen Space GI effects add small sharp shadows at contacts and one bounce of colour between surfaces, and the weather softens the sun's shadows. `contactShadows` marches a short ray toward the scene's sun in the depth buffer; `ssgi` gathers eight rays a pixel over the G-buffer's normals at half size into a float target and averages the neighbours on the same surface before laying the light, times the receiver's colour, over the picture. The Weather component raises the sun's `sourceAngle` and lowers its `shadowStrength` as the sky clouds over.
- **Terrain and Foliage.** A Terrain component makes ground from a heightmap or noise, paints it with grass, dirt, snow and rock layers and draws it in chunks that coarsen with distance; a Foliage component scatters grass or a mesh over it, swaying in the wind and thinning out with distance.
- **Separate material maps packed on import.** Importing an FBX with separate metalness, roughness and occlusion images now packs them into the one map the Model shader samples, instead of dropping them. Occlusion goes in red, roughness in green and metal in blue, each from its image's red channel (a glossiness map is inverted); a channel with no image stays at full so the material's own value speaks. Only PNG and DDS can be read.
+- **Floating bodies.** Water holds things up. A Floating component on an entity with a RigidBody3D floats it: a buoyant force against gravity (`buoyancy` is the water's density against the body's, so 2 floats it half under) and a drag against its velocity relative to the water, which brings it to rest in a lake and carries it with a river's current, applied at a few points of the body so waves tip it. It works from the CPU's own water surface, so it needs no renderer, and it needs the 3D physics module, which gains force and mass queries.
- **Rivers and splines.** A WaterBody can be a river: put a Spline on its entity and it lays a ribbon along the curve, as wide as the curve says at each point and at its height, with a current (`flowSpeed`, faster where it narrows) that the shader carries the waves and ripples along and that `Waters.sample` reports as `flow`. Splines are a new optional module (`esengine/spline`): a curve through points with a width each, measured by the distance along it.
- **Lake outlines and shores.** A lake can have an outline of its own and knows its shore. `boundary` cuts it to a polygon on its plane (crisp at the pixel, not at the grid's cells), `shoreWidth` calms its waves toward the edge and where it is shallow over a Terrain, and the shore foams along the outline. `Waters.sample` answers with the same calmed waves and says a point in the notch of a concave lake is not inside.
- **Water bodies.** Water gets a component and a chapter of its own. A WaterBody builds an ocean (without an edge, following the camera, in rings that coarsen with distance) or a rectangular lake, lifts its geometry with the waves, follows its own up when it is tilted, and answers for its surface from code (`Waters.sample`) with the same formula the shader draws. Water is an optional module (`esengine/water`): a 2D game carries none of it.
diff --git a/desktop b/desktop
index f1447f30b..eb78c6afc 160000
--- a/desktop
+++ b/desktop
@@ -1 +1 @@
-Subproject commit f1447f30bd1debe8d4d077d6e7d87350140180a8
+Subproject commit eb78c6afcfc0d54fe86c59b845d22ca6413e1c0f
diff --git a/docs/astro/src/content/docs/graphics/water.mdx b/docs/astro/src/content/docs/graphics/water.mdx
index 410d1b46f..64ebda9e7 100644
--- a/docs/astro/src/content/docs/graphics/water.mdx
+++ b/docs/astro/src/content/docs/graphics/water.mdx
@@ -74,6 +74,27 @@ entity and the river is built when the scene runs.
back: `Waters.sample` gives its curve's height, a normal of up, and the current in `flow` (world units a second, along the river; zero elsewhere).
- **Banks.** The edge is the ribbon's own, so it is as crisp as the geometry. Foam where it meets the ground comes from the depth of the scene, as at any shore.
+## Floating
+
+Put a `Floating` component on an entity with a `RigidBody3D` and a collider and the water holds it up and carries it along. It works through forces on the
+rigid body, from asking the water's surface ([Asking the surface](#asking-the-surface)) where it is under a few points of the body, so it needs no renderer:
+a server, a test or a build that draws nothing floats things the same.
+
+| Field | What it does |
+|---|---|
+| `buoyancy` | The water's density against the body's. 1 holds it up exactly when it is wholly under; 2 floats it half under. |
+| `drag` | How hard the water resists the body moving through it, per second. It brings a body to rest in still water and carries it with a river's current. |
+| `radius` | How deep, in world units, a point of the body has to be under the surface to be wholly wet. |
+| `points` | Points of the body, in its own space and world units, the water is asked about. Spread them (the corners of a hull) and the waves tip it. Empty is the one at its origin. |
+
+At each point the share of it under water (0 at the surface, 1 from `radius` down) gives a buoyant force against gravity of `mass * g * buoyancy * share / points`,
+applied at the point, and a drag against the point's velocity relative to the water (the body's own and what its turning adds there, less the current). The forces are
+applied every fixed step before the world steps. A body with `buoyancy` 2 and one point settles with its centre `radius / 2` under the surface.
+
+It needs the 3D physics module, and a build of it with the force functions (`_physics3d_addForce`, `_physics3d_getBodyDynamics`); one without them warns once and
+floats nothing. Floating is one rigid body in one fluid: there is no added mass, no lift from the shape of a hull, and a body that is wholly under is not pushed
+toward anything but by the current.
+
## Splines
`Spline` is data and nothing draws it: `points` (each an `x`, `y`, `z` in the entity's own space and a `width`) and `closed`. A river reads the one on its
@@ -134,7 +155,7 @@ What is not there yet, so nobody is surprised:
- Like glass, it refracts the opaque scene only: a boat's hull seen through it is, but another transparent surface is not.
- A river does not carve the ground, rapids and falls are not foamed by how fast or steep the water runs, and two bodies do not blend where they meet.
A lake's outline is a polygon on a plane: it does not follow a curved shore, and the waves die toward the shore without breaking on it.
-- Nothing floats on it or swims in it yet: `Waters.sample` gives what a buoyancy force needs, but there is no force.
+- Things float (see [Floating](#floating)); nothing swims yet, and a body in the water makes no ripple or wake.
- A camera under the surface sees the water turned over, and nothing else changes: no underwater fog or tint.
- It does not react to what moves through it: no ripples, no wake.
- The waves are the four peaked sines, not a spectrum, and they lift the surface without pushing it sideways.
diff --git a/docs/astro/src/content/docs/zh-cn/graphics/water.mdx b/docs/astro/src/content/docs/zh-cn/graphics/water.mdx
index e0042ac5e..c1d83d5bd 100644
--- a/docs/astro/src/content/docs/zh-cn/graphics/water.mdx
+++ b/docs/astro/src/content/docs/zh-cn/graphics/water.mdx
@@ -51,6 +51,21 @@ description: 一个 WaterBody 组件,构建海洋或湖泊,用 CPU 能读回的
- **几何体是平的。** 河流的几何体不被波浪抬起(表面画成平的,只在着色里流动),所以河流没有可读回的波浪:`Waters.sample` 给出它的曲线高度、向上的法线,以及 `flow` 里的水流(世界单位每秒,沿河道方向;别处为零)。
- **河岸。** 边缘就是这条带子自己的边,和几何体一样清晰。它和地面相接处的泡沫来自场景深度,和任何岸边一样。
+## 漂浮
+
+给一个有 `RigidBody3D` 和碰撞体的实体加上 `Floating` 组件,水就会托住它并带着它走。它通过作用在刚体上的力来工作,力来自询问水面([查询表面](#查询表面))在身体的几个点之下在哪里,所以不需要渲染器:不画任何东西的服务器、测试或构建,漂浮的结果也一样。
+
+| 字段 | 作用 |
+|---|---|
+| `buoyancy` | 水的密度与物体密度之比。1 表示完全没入时刚好托住;2 表示漂在一半没入的位置。 |
+| `drag` | 水对物体穿行的阻力,每秒。它让物体在静水里停下来,在河里随水流前进。 |
+| `radius` | 物体上的一个点要在水面以下多深(世界单位)才算完全湿透。 |
+| `points` | 物体自身空间里、世界单位的点,水会针对它们作答。把它们散开(比如船体的四个角),波浪就会让它倾斜。留空就是原点那一个。 |
+
+在每个点上,没入水里的份额(水面处为 0,从 `radius` 往下为 1)给出一个逆着重力的浮力 `mass * g * buoyancy * 份额 / 点数`,作用在这个点上,还有一个对抗这个点相对水的速度的阻力(物体自己的速度加上转动在那里带来的,再减去水流)。这些力在每个固定步长、世界步进之前施加。`buoyancy` 为 2 且只有一个点的物体,中心会停在水面以下 `radius / 2` 处。
+
+它需要 3D 物理模块,并且是带有施力函数(`_physics3d_addForce`、`_physics3d_getBodyDynamics`)的那一版;没有这些函数的构建会警告一次,什么也不会漂。漂浮是一个刚体在一种流体里:没有附加质量,没有船体形状带来的升力,完全没入的物体除了水流外不会被推向任何方向。
+
## 样条
`Spline` 是数据,什么也不画:`points`(每个点是实体自身空间里的 `x`、`y`、`z` 和一个 `width`)和 `closed`。河流读取它实体上的那一个;任何沿路径走的东西都可以用 `SplineCurve` 读它:
@@ -95,7 +110,7 @@ curve.nearest(x, z); // 在 xz 平面上离它最近的地方:s、距离、在
- 它需要与玻璃相同的、由引擎拷贝的场景(有后处理链在运行),以及渲染目标能存浮点数的设备来存深度。没有链时,水作为半透明表面画在场景上;没有浮点目标时,深度处处是 `u_fallbackDepth`,所以没有岸边泡沫,颜色也不随水深变化。
- 与玻璃一样,它只折射不透明场景:透过它能看到船体,但看不到另一个透明表面。
- 河流不会切削地面,急流和瀑布不会按水流的快慢或陡度起泡沫,两个水体相接处也不会融合。湖泊的轮廓是平面上的多边形:它不跟随弯曲的岸线,波浪向岸边消失而不是在岸上破碎。
-- 还没有东西能漂在上面或在里面游:`Waters.sample` 给出了浮力需要的量,但还没有这个力。
+- 东西可以漂浮(见[漂浮](#漂浮));还没有东西能游泳,水里的物体也不会激起涟漪或尾迹。
- 相机在水面以下时,看到的是翻过来的水,别的没有变化:没有水下的雾和染色。
- 它不会对穿过它的东西作出反应:没有涟漪,没有尾迹。
- 波浪是这四道波峰尖的正弦,不是波谱,并且只把表面抬起,不会把它推向一侧。
diff --git a/docs/astro/src/data/apiStability.generated.json b/docs/astro/src/data/apiStability.generated.json
index e149f879b..002ddf0e6 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": 2368,
+ "experimental": 2374,
"deprecated": 3
},
- "total": 2654,
+ "total": 2660,
"subsystems": [
{
"id": "mobile-controls",
diff --git a/docs/astro/src/data/componentDocs.ts b/docs/astro/src/data/componentDocs.ts
index 91c562743..1b13b54b6 100644
--- a/docs/astro/src/data/componentDocs.ts
+++ b/docs/astro/src/data/componentDocs.ts
@@ -89,6 +89,7 @@ export const COMPONENT_DOCS: Record<string, ComponentDoc> = {
StaticBatch: { category: 'graphics', summary: 'Marks a mesh that will not move, so the meshes sharing its material are merged into one draw while the game runs; it also records what became of this one.', doc: 'performance/static-batching', anchor: 'what-happens', anchorZh: '会发生什么' },
Terrain: { category: 'graphics', summary: 'Ground made from a heightmap or noise, painted by height and slope, and drawn in chunks that coarsen with distance.', doc: 'graphics/terrain', anchor: 'the-component', anchorZh: '组件' },
Foliage: { category: 'graphics', summary: 'Scatters grass or a mesh across an area and over a terrain, drawn a cell at a time, swaying in the wind and thinning out with distance.', doc: 'graphics/foliage', anchor: 'the-component', anchorZh: '组件' },
+ Floating: { category: 'graphics', summary: 'Holds a RigidBody3D up in water and carries it with the current, by forces at a few points of the body.', doc: 'graphics/water', anchor: 'floating', anchorZh: '漂浮' },
Spline: { category: 'graphics', summary: 'A curve through points, each with a width, read by what follows it (a river\'s WaterBody on the same entity); measured by the distance along it.', doc: 'graphics/water', anchor: 'splines', anchorZh: '样条' },
WaterBody: { category: 'graphics', summary: 'An ocean or a lake: geometry lifted by waves the code can read back, tilting with the entity, drawn by the Water shader.', doc: 'graphics/water', anchor: 'the-component', anchorZh: '组件' },
LODGroup: { category: 'graphics', summary: 'Cheaper stand-in meshes for a MeshRenderer, chosen by how much of the screen the object covers.', doc: 'performance/level-of-detail', anchor: 'the-lodgroup-component', anchorZh: 'lodgroup-组件' },
diff --git a/docs/astro/src/data/components.generated.json b/docs/astro/src/data/components.generated.json
index edde48c74..a0dd65360 100644
--- a/docs/astro/src/data/components.generated.json
+++ b/docs/astro/src/data/components.generated.json
@@ -1587,6 +1587,44 @@
}
]
},
+ {
+ "name": "Floating",
+ "source": "ts",
+ "fields": [
+ {
+ "key": "buoyancy",
+ "type": "number",
+ "default": "2",
+ "doc": "The water's density against the body's. 1 holds it up exactly when it is wholly under; 2 floats it half under.",
+ "range": "0–20"
+ },
+ {
+ "key": "drag",
+ "type": "number",
+ "default": "1",
+ "doc": "How hard the water resists the body moving through it, per second.",
+ "range": "0–20"
+ },
+ {
+ "key": "radius",
+ "type": "number",
+ "default": "50",
+ "doc": "How deep under the surface, in world units, a point of the body is wholly wet.",
+ "range": "≥ 0.01"
+ },
+ {
+ "key": "points",
+ "type": "array",
+ "default": "empty",
+ "doc": "Points of the body, in its own space, the water is asked about: spread them (the corners of a hull) and waves tip it. Empty is the one at its origin."
+ }
+ ],
+ "animatable": [
+ "buoyancy",
+ "drag",
+ "radius"
+ ]
+ },
{
"name": "Focusable",
"source": "ts",
diff --git a/pipeline/src/project/targetSupport.ts b/pipeline/src/project/targetSupport.ts
index 6eea2529c..81b87e993 100644
--- a/pipeline/src/project/targetSupport.ts
+++ b/pipeline/src/project/targetSupport.ts
@@ -46,7 +46,7 @@ export const SUBSYSTEM_COMPONENTS: Readonly<Record<Subsystem, readonly string[]>
fxAtmosphere: ['Weather', 'TimeOfDay'],
fxLighting: [],
foliage: ['Foliage'],
- water: ['WaterBody'],
+ water: ['WaterBody', 'Floating'],
spline: ['Spline'],
particles: ['ParticleEmitter', 'ParticleForceField'],
postprocess: ['PostProcessVolume'],
diff --git a/sdk/etc/physics3d.api.md b/sdk/etc/physics3d.api.md
index 943574bd5..c3eaff903 100644
--- a/sdk/etc/physics3d.api.md
+++ b/sdk/etc/physics3d.api.md
@@ -286,6 +286,7 @@ static prototype: Physics3DQueries
```
bodies: Map<number, number>
characters: Map<number, number>
+config: Physics3DConfig | null
initPromise: Promise<unknown> | null
joints: Joint3DMap
module: Physics3DWasmModule | null
@@ -303,6 +304,7 @@ _physics3d_addCharacter: (entity: number, radius: number, halfHeight: number, px
_physics3d_addConvexBody: (entity: number, vertexPtr: number, vertexCount: number, px: number, py: number, pz: number, qx: number, qy: number, qz: number, qw: number, motion: number, gravityScale: number, linearDamping: number, angularDamping: number, fixedRotation: number, layer: number, continuous: number, friction: number, restitution: number, isSensor: number) => number
_physics3d_addDistanceJoint: (entity: number, bodyA: number, bodyB: number, ax: number, ay: number, az: number, bx: number, by: number, bz: number, minLength: number, maxLength: number, frequency: number, damping: number, collideConnected: number) => number
_physics3d_addFixedJoint: (entity: number, bodyA: number, bodyB: number, collideConnected: number) => number
+_physics3d_addForce: ((bodyId: number, fx: number, fy: number, fz: number, px: number, py: number, pz: number) => void) | undefined
_physics3d_addHingeJoint: (entity: number, bodyA: number, bodyB: number, px: number, py: number, pz: number, ax: number, ay: number, az: number, enableLimit: number, lower: number, upper: number, enableMotor: number, motorSpeed: number, maxTorque: number, collideConnected: number) => number
_physics3d_addMeshBody: (entity: number, vertexPtr: number, vertexCount: number, indexPtr: number, indexCount: number, px: number, py: number, pz: number, qx: number, qy: number, qz: number, qw: number, layer: number, friction: number, restitution: number) => number
_physics3d_addPointJoint: (entity: number, bodyA: number, bodyB: number, px: number, py: number, pz: number, collideConnected: number) => number
@@ -310,10 +312,12 @@ _physics3d_addSixDOFJoint: (entity: number, bodyA: number, bodyB: number, px: nu
_physics3d_addSliderJoint: (entity: number, bodyA: number, bodyB: number, px: number, py: number, pz: number, ax: number, ay: number, az: number, enableLimit: number, lower: number, upper: number, enableMotor: number, motorSpeed: number, maxForce: number, collideConnected: number) => number
_physics3d_addSphere: (entity: number, radius: number, px: number, py: number, pz: number, qx: number, qy: number, qz: number, qw: number, motion: number, gravityScale: number, linearDamping: number, angularDamping: number, fixedRotation: number, layer: number, continuous: number, friction: number, restitution: number, isSensor: number) => number
_physics3d_addSwingTwistJoint: (entity: number, bodyA: number, bodyB: number, px: number, py: number, pz: number, ax: number, ay: number, az: number, nx: number, ny: number, nz: number, normalHalf: number, planeHalf: number, twistMin: number, twistMax: number, collideConnected: number) => number
+_physics3d_addTorque: ((bodyId: number, tx: number, ty: number, tz: number) => void) | undefined
_physics3d_contactEnters: () => number
_physics3d_contactEntersBytes: () => number
_physics3d_contactExits: () => number
_physics3d_contactExitsBytes: () => number
+_physics3d_getBodyDynamics: ((bodyId: number) => number) | undefined
_physics3d_getBodyState: (bodyId: number) => number
_physics3d_init: (gx: number, gy: number, gz: number, maxBodies: number) => void
_physics3d_isReady: () => number
diff --git a/sdk/etc/water.api.md b/sdk/etc/water.api.md
index 8ebd9c51f..3c7e794bc 100644
--- a/sdk/etc/water.api.md
+++ b/sdk/etc/water.api.md
@@ -1,7 +1,42 @@
# API surface — esengine/water
<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->
-Symbols: 0 public · 0 beta · 27 experimental · 0 deprecated
+Symbols: 0 public · 0 beta · 33 experimental · 0 deprecated
+
+## Floating — const @experimental
+```
+ComponentDef<FloatingData>
+```
+
+## FloatingBody — interface @experimental
+```
+angularVelocity: [number, number, number]
+mass: number
+position: [number, number, number]
+velocity: [number, number, number]
+```
+
+## FloatingData — interface @experimental
+```
+buoyancy: number
+drag: number
+points: Vec3Like[]
+radius: number
+```
+
+## FloatingForce — interface @experimental
+```
+force: [number, number, number]
+point: [number, number, number]
+```
+
+## FloatingPlugin — class @experimental
+```
+build: (app: App) => void
+name: string
+static new (): FloatingPlugin
+static prototype: FloatingPlugin
+```
## GroundDepth — type @experimental
```
@@ -144,6 +179,11 @@ speed: number
(width: number, widest: number): number
```
+## floatingForce — function @experimental
+```
+(body: FloatingBody, point: [number, number, number], sample: WaterSample | null, floating: FloatingData, gravity: [number, number, number], ppu: number, dt: number, points: number): FloatingForce | null
+```
+
## oceanReach — function @experimental
```
(cells: number, rings: number, cellSize: number): number
diff --git a/sdk/src/app/pluginSets.ts b/sdk/src/app/pluginSets.ts
index 5eb834963..013cd15f6 100644
--- a/sdk/src/app/pluginSets.ts
+++ b/sdk/src/app/pluginSets.ts
@@ -67,7 +67,7 @@ export const presentationBasePlugins = (): Plugin[] => [
*/
export const PLUGIN_BUILD_ORDER: readonly string[] = [
'Diagnostics', 'timer', 'velocity', 'lifecycle', 'animation', 'audio', 'video',
- 'particle', 'trail', 'meshRenderer', 'staticBatch', 'terrain', 'foliage', 'spline', 'water', 'tilemap', 'postProcess', 'timeline',
+ 'particle', 'trail', 'meshRenderer', 'staticBatch', 'terrain', 'foliage', 'spline', 'water', 'floating', 'tilemap', 'postProcess', 'timeline',
'gameplay',
'perception', 'fsm', 'bt', 'scriptGraph', 'nav', 'eventBinding', 'replication',
'services',
diff --git a/sdk/src/physics3d/Physics3DModule.ts b/sdk/src/physics3d/Physics3DModule.ts
index f6d234ea5..5ed193423 100644
--- a/sdk/src/physics3d/Physics3DModule.ts
+++ b/sdk/src/physics3d/Physics3DModule.ts
@@ -61,6 +61,12 @@ export interface Physics3DWasmModule {
qx: number, qy: number, qz: number, qw: number): void;
_physics3d_setLinearVelocity(bodyId: number, vx: number, vy: number, vz: number): void;
_physics3d_getBodyState(bodyId: number): number;
+ /** Writes (mass, wx, wy, wz) to the query buffer; 0 when the body is gone or does not move. */
+ _physics3d_getBodyDynamics?(bodyId: number): number;
+ /** A force in newtons at a world point, over the next step. */
+ _physics3d_addForce?(bodyId: number, fx: number, fy: number, fz: number, px: number, py: number, pz: number): void;
+ /** A torque in newton metres, over the next step. */
+ _physics3d_addTorque?(bodyId: number, tx: number, ty: number, tz: number): void;
_physics3d_addCharacter(entity: number, radius: number, halfHeight: number,
px: number, py: number, pz: number,
diff --git a/sdk/src/physics3d/Physics3DPlugin.ts b/sdk/src/physics3d/Physics3DPlugin.ts
index e606c311b..bf2393fc9 100644
--- a/sdk/src/physics3d/Physics3DPlugin.ts
+++ b/sdk/src/physics3d/Physics3DPlugin.ts
@@ -32,11 +32,13 @@ export interface Physics3DRuntime {
characters: Map<Entity, number>;
/** Entity -> the joint it declared, with the bodies it was built between. */
joints: Joint3DMap;
+ /** The world's configuration (gravity, the scale of a world unit), for what applies forces to it. Null until the plugin is built. */
+ config: Physics3DConfig | null;
}
export const Physics3DRuntime = defineResource<Physics3DRuntime>(
{ module: null, initPromise: null, bodies: new Map(), characters: new Map(),
- joints: new Map() },
+ joints: new Map(), config: null },
'Physics3DRuntime',
);
@@ -57,7 +59,7 @@ export class Physics3DPlugin implements Plugin {
build(app: App): void {
const runtime: Physics3DRuntime = {
module: null, initPromise: null, bodies: new Map(), characters: new Map(),
- joints: new Map(),
+ joints: new Map(), config: this.config_,
};
const events: Physics3DEventsData = {
contactEnters: [], contactExits: [], sensorEnters: [], sensorExits: [],
diff --git a/sdk/src/water/floating.ts b/sdk/src/water/floating.ts
new file mode 100644
index 000000000..d638e6ce4
--- /dev/null
+++ b/sdk/src/water/floating.ts
@@ -0,0 +1,170 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file floating.ts
+ * @brief A body that floats: the water holds it up and carries it along, through forces on its rigid body.
+ *
+ * @details `Floating` goes on an entity that has a `RigidBody3D` (and a collider), and the forces come from asking the water's surface
+ * ({@link Waters.sample}) where it is under a few points of the body. It touches nothing a renderer owns: the surface is the
+ * CPU's own, so a server, a test or a build that draws nothing floats things the same.
+ *
+ * At each sample point the share of it under water (`wet`: 0 at the surface, 1 from `radius` down) gives
+ * - a buoyant force against gravity of `mass * g * buoyancy * wet / points` (so `buoyancy` is the ratio of the water's density
+ * to the body's, and a body of 2 floats half under), applied AT the point so waves tip it and a body weighted to one side
+ * leans; and
+ * - a drag of `mass * drag * wet / points` against the point's velocity relative to the water, which is what brings it to
+ * rest in still water and carries it along with a river's current.
+ * The forces are applied each fixed step, before the world is stepped, and Jolt keeps them for that step only.
+ */
+import type { App, Plugin } from '../app/app';
+import { defineSystem, Schedule } from '../ecs/system';
+import { defineComponent, Transform, type ComponentDef } from '../ecs/component';
+import { Physics3DRuntime } from '../physics3d/Physics3DPlugin';
+import { RigidBody3D } from '../physics3d/Physics3DComponents';
+import { log } from '../util/logger';
+import type { Entity } from '../types';
+import { WatersRes, type WaterSample } from './waterPlugin';
+
+/** A point in space. */
+export interface Vec3Like { x: number; y: number; z: number }
+
+/** The fields of the `Floating` component. @experimental */
+export interface FloatingData {
+ /** The water's density against the body's: 1 holds it up exactly when it is wholly under, 2 floats it half under. */
+ buoyancy: number;
+ /** How hard the water resists the body moving through it (a rate, per second). */
+ drag: number;
+ /** How deep, in world units, a sample point has to be under the surface to be wholly wet. */
+ radius: number;
+ /** The points of the body, in its own space and world units, the water is asked about. Empty is the one at its origin. */
+ points: Vec3Like[];
+}
+
+/**
+ * A body the water holds up. It needs a `RigidBody3D`; presence is the opt-in.
+ *
+ * @experimental
+ */
+export const Floating: ComponentDef<FloatingData> = defineComponent<FloatingData>('Floating', {
+ buoyancy: 2, drag: 1, radius: 50, points: [] as Vec3Like[],
+}, {
+ 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.' },
+ radius: { min: 0.01, category: 'Water', tooltip: 'How deep under the surface, in world units, a point of the body is wholly wet.' },
+ points: { category: 'Water', tooltip: 'Points of the body, in its own space, the water is asked about: spread them (the corners of a hull) and waves tip it. Empty is the one at its origin.' },
+ },
+});
+
+/** What the water does to one point of a body. */
+export interface FloatingForce {
+ /** The force in newtons, world space. */
+ force: [number, number, number];
+ /** Where it acts, in physics units (metres). */
+ point: [number, number, number];
+}
+
+/** The state a force is worked out from, in physics units (metres, kilograms, seconds), world space. */
+export interface FloatingBody {
+ position: [number, number, number];
+ velocity: [number, number, number];
+ angularVelocity: [number, number, number];
+ mass: number;
+}
+
+/** The longest a step's drag may be a share of the relative velocity: past 1 it would reverse it, and the step would blow up. */
+const MAX_DRAG_PER_STEP = 0.9;
+
+/**
+ * The force on one point of a floating body, or null where it is dry. `gravity` is the world's, in metres a second squared; `ppu` is how many world
+ * units a metre is; `dt` the fixed step. `sample` is what the water says at the point (world units).
+ */
+export function floatingForce(
+ body: FloatingBody, point: [number, number, number], sample: WaterSample | null, floating: FloatingData,
+ gravity: [number, number, number], ppu: number, dt: number, points: number,
+): FloatingForce | null {
+ if (!sample) return null;
+ const wet = Math.min(Math.max(-sample.depth / Math.max(floating.radius, 1e-6), 0), 1);
+ if (wet <= 0) return null;
+ const g = Math.hypot(gravity[0], gravity[1], gravity[2]);
+ if (g <= 0) return null;
+ const share = body.mass * wet / points;
+ // Against gravity, by as much as the body would weigh at this point's share, times how much denser the water is.
+ const lift = share * g * floating.buoyancy;
+ const up: [number, number, number] = [-gravity[0] / g, -gravity[1] / g, -gravity[2] / g];
+ // The velocity of the point itself: the body's, and what its turning adds at that distance from it.
+ const r: [number, number, number] = [point[0] - body.position[0], point[1] - body.position[1], point[2] - body.position[2]];
+ const w = body.angularVelocity;
+ const atPoint: [number, number, number] = [
+ body.velocity[0] + (w[1] * r[2] - w[2] * r[1]),
+ body.velocity[1] + (w[2] * r[0] - w[0] * r[2]),
+ body.velocity[2] + (w[0] * r[1] - w[1] * r[0]),
+ ];
+ const relative: [number, number, number] = [
+ atPoint[0] - sample.flow[0] / ppu, atPoint[1] - sample.flow[1] / ppu, atPoint[2] - sample.flow[2] / ppu,
+ ];
+ const rate = Math.min(floating.drag, MAX_DRAG_PER_STEP / Math.max(dt, 1e-6));
+ return {
+ force: [up[0] * lift - share * rate * relative[0], up[1] * lift - share * rate * relative[1], up[2] * lift - share * rate * relative[2]],
+ point,
+ };
+}
+
+/** Rotates `v` by the unit quaternion `q`. */
+function rotate(q: { x: number; y: number; z: number; w: number }, v: Vec3Like): [number, number, number] {
+ const tx = 2 * (q.y * v.z - q.z * v.y), ty = 2 * (q.z * v.x - q.x * v.z), tz = 2 * (q.x * v.y - q.y * v.x);
+ return [v.x + q.w * tx + (q.y * tz - q.z * ty), v.y + q.w * ty + (q.z * tx - q.x * tz), v.z + q.w * tz + (q.x * ty - q.y * tx)];
+}
+
+let warned = false;
+
+/** Installs the system that floats bodies: every fixed step, before the world steps, one force at each sample point of each `Floating` body. */
+export function installFloating(app: App): void {
+ app.addSystemToSchedule(Schedule.FixedUpdate, defineSystem([], () => {
+ if (!app.hasResource(Physics3DRuntime) || !app.hasResource(WatersRes)) return;
+ const runtime = app.getResource(Physics3DRuntime);
+ const module = runtime.module, config = runtime.config;
+ if (!module || !config) return;
+ if (!module._physics3d_addForce || !module._physics3d_getBodyDynamics) {
+ if (!warned) { warned = true; log.warn('water', 'this 3D physics build has no force API: nothing will float'); }
+ return;
+ }
+ const waters = app.getResource(WatersRes);
+ const ppu = config.pixelsPerUnit;
+ const gravity: [number, number, number] = [config.gravity.x, config.gravity.y, config.gravity.z];
+ for (const entity of app.world.getEntitiesWithComponents([Floating, RigidBody3D, Transform])) {
+ const id = runtime.bodies.get(entity as Entity);
+ if (!id) continue;
+ const floating = app.world.get(entity, Floating) as FloatingData;
+ if (!module._physics3d_getBodyState(id)) continue;
+ const base = module._physics3d_queryResult() >> 2;
+ const f = module.HEAPF32;
+ const state = {
+ position: [f[base]!, f[base + 1]!, f[base + 2]!] as [number, number, number],
+ rotation: { x: f[base + 3]!, y: f[base + 4]!, z: f[base + 5]!, w: f[base + 6]! },
+ velocity: [f[base + 7]!, f[base + 8]!, f[base + 9]!] as [number, number, number],
+ };
+ if (!module._physics3d_getBodyDynamics(id)) continue;
+ const dynamics = module._physics3d_queryResult() >> 2;
+ const body: FloatingBody = {
+ position: state.position, velocity: state.velocity, mass: f[dynamics]!,
+ angularVelocity: [f[dynamics + 1]!, f[dynamics + 2]!, f[dynamics + 3]!],
+ };
+ const offsets = floating.points.length > 0 ? floating.points : [{ x: 0, y: 0, z: 0 }];
+ for (const offset of offsets) {
+ // The point in the world (world units), then the water's answer for it, then the force in metres and newtons.
+ const turned = rotate(state.rotation, offset);
+ const world: [number, number, number] = [state.position[0] * ppu + turned[0], state.position[1] * ppu + turned[1], state.position[2] * ppu + turned[2]];
+ const sample = waters.sample(world[0], world[1], world[2]);
+ const result = floatingForce(body, [world[0] / ppu, world[1] / ppu, world[2] / ppu], sample, floating, gravity, ppu, config.fixedTimestep, offsets.length);
+ if (result) module._physics3d_addForce(id, result.force[0], result.force[1], result.force[2], result.point[0], result.point[1], result.point[2]);
+ }
+ }
+ }, { name: 'FloatingSystem' }));
+}
+
+/** The plugin that floats bodies, for a build that has water. */
+export class FloatingPlugin implements Plugin {
+ name = 'floating';
+ build(app: App): void { installFloating(app); }
+}
diff --git a/sdk/src/water/index.ts b/sdk/src/water/index.ts
index 2ed20db70..ad44fb528 100644
--- a/sdk/src/water/index.ts
+++ b/sdk/src/water/index.ts
@@ -4,6 +4,7 @@ export {
WaterBody, WaterForm, Waters, WatersRes, WaterPlugin, waterPlugin, type WaterBodyData, type WaterSample,
} from './waterPlugin';
export { WAVE_SET, waveFade, waveHeight, waveSlope, type WaveParams } from './waves';
+export { Floating, FloatingPlugin, floatingForce, type FloatingBody, type FloatingData, type FloatingForce } from './floating';
export { buildRiverMesh, currentShare } from './riverMesh';
export { buildBoxMesh, buildOceanMesh, buildRectMesh, oceanReach, oceanSnap, type RectOptions } from './waterMesh';
export { ShoreField, UNKNOWN_DEPTH, polygonSdf, shoreDamp, type GroundDepth, type Point2 } from './shore';
diff --git a/sdk/src/water/waterPlugin.ts b/sdk/src/water/waterPlugin.ts
index 945dc5d08..6fdd6a40b 100644
--- a/sdk/src/water/waterPlugin.ts
+++ b/sdk/src/water/waterPlugin.ts
@@ -245,10 +245,12 @@ export class WaterPlugin implements Plugin {
app.insertResource(WatersRes, waters);
app.addSystemToSchedule(Schedule.Update, defineSystem([], () => {
- if (!app.hasResource(Assets)) return;
this.sweep(app, waters);
+ // What a body IS (its outline and shore, its curve) needs no renderer: it is built here whether or not anything is drawn, so a
+ // server or a test that never draws can still ask the surface where it is. What is DRAWN waits for the asset layer.
+ const rendering = app.hasResource(Assets);
const time = app.getResource(Time).elapsed;
- const eye = this.eye(app);
+ const eye = rendering ? this.eye(app) : null;
for (const entity of app.world.getEntitiesWithComponents([WaterBody, Transform])) {
const data = app.world.get(entity, WaterBody) as WaterBodyData;
const spline = data.form === WaterForm.River ? app.world.tryGet(entity, Spline) as SplineData | null : null;
@@ -258,8 +260,10 @@ export class WaterPlugin implements Plugin {
if (built) this.destroy(app, built);
built = { signature, data: { ...data }, mesh: 0, field: null, curve: null, widest: 0, shoreTexture: 0, child: 0 as Entity, instance: 0, epoch: (built?.epoch ?? 0) + 1, pending: false };
waters.built_.set(entity, built);
+ this.surface(app, entity, built);
}
built.data = { ...data };
+ if (!rendering) continue;
if (!built.child && !built.pending) void this.build_(app, entity, built);
if (built.child && built.instance) this.update(app, entity, built, eye, time);
}
@@ -312,20 +316,14 @@ export class WaterPlugin implements Plugin {
if (d.form === WaterForm.Ocean) {
mesh = assets.createMesh(buildOceanMesh(d.cells, d.rings, d.cellSize));
} else if (d.form === WaterForm.River) {
- // A river: the Spline on its entity, laid as a ribbon.
- const spline = app.world.tryGet(entity, Spline) as SplineData | null;
- if (!spline || spline.points.length < 2) { log.warn('water', 'a river needs a Spline of two points or more on its entity'); return; }
- built.curve = new SplineCurve(spline.points, spline.closed);
- for (let i = 0; i <= 64; i++) built.widest = Math.max(built.widest, built.curve.width((i / 64) * built.curve.length));
+ // A river: the curve of the Spline on its entity, laid as a ribbon.
+ if (!built.curve) return;
const across = Math.min(64, Math.max(2, Math.ceil(built.widest / Math.max(d.cellSize, 0.05))));
mesh = assets.createMesh(buildRiverMesh(built.curve, d.cellSize, across));
} else {
- // A lake: its outline (or its rectangle), the ground under it, and what the two say about the waves and the shore.
- const poly = outlineOf(d);
- const reach = Math.max(...poly.map((p) => Math.abs(p.x)), ...poly.map((p) => Math.abs(p.y)));
- const res = Math.min(256, Math.max(32, Math.ceil((reach * 2) / Math.max(d.cellSize * 0.5, 0.05))));
- built.field = new ShoreField(poly, res, d.shoreWidth, this.groundUnder(app, entity));
+ // A lake: cut to its outline, calmer toward its shore.
const field = built.field;
+ if (!field) return;
mesh = assets.createMesh(buildBoxMesh(field.minX, field.minZ, field.minX + field.sizeX, field.minZ + field.sizeZ, d.cellSize, {
damp: (x, z) => field.damp(x, z),
keep: (x, z, cell) => field.distance(x, z) > -cell,
@@ -351,6 +349,25 @@ export class WaterPlugin implements Plugin {
}
}
+ /** What a body is, apart from how it is drawn: a lake's outline with its shore and depth, a river's curve with its widest reach. */
+ private surface(app: App, entity: Entity, built: Built): void {
+ const d = built.data;
+ built.field = null;
+ built.curve = null;
+ built.widest = 0;
+ if (d.form === WaterForm.River) {
+ const spline = app.world.tryGet(entity, Spline) as SplineData | null;
+ if (!spline || spline.points.length < 2) { log.warn('water', 'a river needs a Spline of two points or more on its entity'); return; }
+ built.curve = new SplineCurve(spline.points, spline.closed);
+ for (let i = 0; i <= 64; i++) built.widest = Math.max(built.widest, built.curve.width((i / 64) * built.curve.length));
+ } else if (d.form === WaterForm.Lake) {
+ const poly = outlineOf(d);
+ const reach = Math.max(...poly.map((p) => Math.abs(p.x)), ...poly.map((p) => Math.abs(p.y)));
+ const res = Math.min(256, Math.max(32, Math.ceil((reach * 2) / Math.max(d.cellSize * 0.5, 0.05))));
+ built.field = new ShoreField(poly, res, d.shoreWidth, this.groundUnder(app, entity));
+ }
+ }
+
/** Gives the shader a lake's shore: the baked field as a texture, and where over the lake it lies. */
private uploadShore(app: App, built: Built): void {
const field = built.field!;
@@ -425,9 +442,6 @@ export class WaterPlugin implements Plugin {
if (built.instance) Material.release(built.instance);
if (built.shoreTexture) getResourceManager()?.releaseTexture(built.shoreTexture);
built.shoreTexture = 0;
- built.field = null;
- built.curve = null;
- built.widest = 0;
if (built.mesh && app.hasResource(Assets)) app.getResource(Assets).releaseBuiltMesh(built.mesh);
built.child = 0 as Entity;
built.instance = 0;
diff --git a/sdk/src/water/waterSupport.ts b/sdk/src/water/waterSupport.ts
index feb566623..6b3de0dfc 100644
--- a/sdk/src/water/waterSupport.ts
+++ b/sdk/src/water/waterSupport.ts
@@ -7,7 +7,9 @@
*/
import { addEntryPlugin } from '../runtime/entryPlugins';
import { WaterPlugin } from './waterPlugin';
+import { FloatingPlugin } from './floating';
export function registerWaterSupport(): void {
addEntryPlugin('water', () => new WaterPlugin());
+ addEntryPlugin('floating', () => new FloatingPlugin());
}
diff --git a/sdk/tests/physics3d-smoke.mjs b/sdk/tests/physics3d-smoke.mjs
index 698b28475..ba7884882 100644
--- a/sdk/tests/physics3d-smoke.mjs
+++ b/sdk/tests/physics3d-smoke.mjs
@@ -700,6 +700,44 @@ check('parallel reference axes are rejected', m._physics3d_addSwingTwistJoint(15
const invalidSix = [...sixArgs]; invalidSix[0] = 157; invalidSix[14] = 2;
check('reversed limited bounds are rejected', m._physics3d_addSixDOFJoint(...invalidSix) === 0);
+// Forces: a floating body is held up by a force the SDK applies each step, so the force has to do what its units say.
+// A dynamic sphere of known size and density has a mass the solver reports; with gravity off, a force of F newtons over t seconds
+// makes a speed of F * t / mass, and a force off the centre makes it spin.
+const FORCE = 6100;
+const pushed = m._physics3d_addSphere(FORCE, 0.5, 5000, 50, 0, ...IDENTITY, ...FREE(DYNAMIC), 0.5, 0, 0);
+const dynamics = () => {
+ if (!m._physics3d_getBodyDynamics(pushed)) return null;
+ const base = m._physics3d_queryResult() >> 2;
+ return { mass: m.HEAPF32[base], wx: m.HEAPF32[base + 1], wy: m.HEAPF32[base + 2], wz: m.HEAPF32[base + 3] };
+};
+const before = dynamics();
+// A sphere of radius 0.5 at the default density of 1000 kg a cubic metre.
+check('a dynamic body reports its mass', !!before && near(before.mass, (4 / 3) * Math.PI * 0.125 * 1000, 1), JSON.stringify(before));
+check('a body that is not dynamic has none to report', m._physics3d_getBodyDynamics(pushed + 99999) === 0);
+if (before) {
+ // Gravity is on in this world, so cancel it with a force of the body's weight and add a push along +x: it should speed up along +x and not fall.
+ const weight = before.mass * 9.81;
+ const v0 = bodyState(pushed);
+ for (let i = 0; i < 60; i++) {
+ const at = bodyState(pushed);
+ m._physics3d_addForce(pushed, 2000, weight, 0, at.x, at.y, at.z);
+ m._physics3d_step(1 / 60, 1);
+ }
+ const v1 = bodyState(pushed);
+ check('a force at the centre of mass pushes by F / mass', near(v1.vx, 2000 / before.mass, 0.1), `vx ${v1.vx.toFixed(3)}, expected ${(2000 / before.mass).toFixed(3)}`);
+ check('a force that is the body\'s weight holds it up', Math.abs(v1.vy - v0.vy) < 0.1, `vy ${v1.vy.toFixed(3)}`);
+ const spin0 = dynamics();
+ for (let i = 0; i < 30; i++) {
+ const at = bodyState(pushed);
+ m._physics3d_addForce(pushed, 0, weight + 20, 0, at.x + 0.4, at.y, at.z);
+ m._physics3d_step(1 / 60, 1);
+ }
+ const spin1 = dynamics();
+ check('a force off the centre turns the body', Math.abs(spin1.wz) > Math.abs(spin0.wz) + 0.05, `wz ${spin1.wz.toFixed(3)}`);
+ for (let i = 0; i < 30; i++) { m._physics3d_addTorque(pushed, 0, 0, 5); m._physics3d_step(1 / 60, 1); }
+ check('a torque turns it too', dynamics().wz !== spin1.wz, `wz ${dynamics().wz.toFixed(3)}`);
+}
+
m._physics3d_shutdown();
check('the world reports itself gone', m._physics3d_isReady() === 0);
diff --git a/sdk/tests/water-floating.test.ts b/sdk/tests/water-floating.test.ts
new file mode 100644
index 000000000..b865d0822
--- /dev/null
+++ b/sdk/tests/water-floating.test.ts
@@ -0,0 +1,76 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+import { describe, expect, it } from 'vitest';
+import { floatingForce, type FloatingBody, type FloatingData } from '../src/water/floating';
+import type { WaterSample } from '../src/water/waterPlugin';
+
+const gravity: [number, number, number] = [0, -9.81, 0];
+const floating = (extra: Partial<FloatingData> = {}): FloatingData => ({ buoyancy: 1, drag: 0, radius: 50, points: [], ...extra });
+const body = (extra: Partial<FloatingBody> = {}): FloatingBody => ({ position: [0, 0, 0], velocity: [0, 0, 0], angularVelocity: [0, 0, 0], mass: 100, ...extra });
+const water = (depth: number, flow: [number, number, number] = [0, 0, 0]): WaterSample => ({
+ entity: 1 as never, depth, normal: [0, 1, 0], flow, surface: [0, 0, 0], inside: true,
+});
+const at: [number, number, number] = [0, 0, 0];
+
+describe('floatingForce', () => {
+ it('holds a body up by exactly its weight when it is wholly under water of its own density', () => {
+ const f = floatingForce(body(), at, water(-50), floating(), gravity, 100, 1 / 60, 1)!;
+ expect(f.force[0]).toBeCloseTo(0, 9);
+ expect(f.force[1]).toBeCloseTo(100 * 9.81, 6);
+ expect(f.force[2]).toBeCloseTo(0, 9);
+ });
+
+ it('gives half the force half under, and more for denser water', () => {
+ const half = floatingForce(body(), at, water(-25), floating(), gravity, 100, 1 / 60, 1)!;
+ expect(half.force[1]).toBeCloseTo(0.5 * 100 * 9.81, 6);
+ const dense = floatingForce(body(), at, water(-50), floating({ buoyancy: 2 }), gravity, 100, 1 / 60, 1)!;
+ expect(dense.force[1]).toBeCloseTo(2 * 100 * 9.81, 6);
+ // Deeper than the radius is no more wet than at it.
+ const deep = floatingForce(body(), at, water(-5000), floating(), gravity, 100, 1 / 60, 1)!;
+ expect(deep.force[1]).toBeCloseTo(100 * 9.81, 6);
+ });
+
+ it('does nothing in the air, or where there is no water', () => {
+ expect(floatingForce(body(), at, water(0), floating(), gravity, 100, 1 / 60, 1)).toBeNull();
+ expect(floatingForce(body(), at, water(30), floating(), gravity, 100, 1 / 60, 1)).toBeNull();
+ expect(floatingForce(body(), at, null, floating(), gravity, 100, 1 / 60, 1)).toBeNull();
+ expect(floatingForce(body(), at, water(-50), floating(), [0, 0, 0], 100, 1 / 60, 1)).toBeNull();
+ });
+
+ it('shares a body\'s weight among its points', () => {
+ const f = floatingForce(body(), at, water(-50), floating(), gravity, 100, 1 / 60, 4)!;
+ expect(f.force[1]).toBeCloseTo(100 * 9.81 / 4, 6);
+ });
+
+ it('lifts against whatever gravity there is', () => {
+ const f = floatingForce(body(), at, water(-50), floating(), [9.81, 0, 0], 100, 1 / 60, 1)!;
+ expect(f.force[0]).toBeCloseTo(-100 * 9.81, 6);
+ expect(f.force[1]).toBeCloseTo(0, 9);
+ });
+
+ it('resists moving through still water, by the drag times the body\'s share', () => {
+ const f = floatingForce(body({ velocity: [3, 0, 0] }), at, water(-50), floating({ drag: 2 }), gravity, 100, 1 / 60, 1)!;
+ expect(f.force[0]).toBeCloseTo(-100 * 2 * 3, 6);
+ });
+
+ it('does not resist moving with the current, and pushes a body that is still along it', () => {
+ // The water runs 200 world units a second along +x: two metres a second at 100 units to a metre.
+ const along = floatingForce(body({ velocity: [2, 0, 0] }), at, water(-50, [200, 0, 0]), floating({ drag: 2 }), gravity, 100, 1 / 60, 1)!;
+ expect(along.force[0]).toBeCloseTo(0, 6);
+ const still = floatingForce(body(), at, water(-50, [200, 0, 0]), floating({ drag: 2 }), gravity, 100, 1 / 60, 1)!;
+ expect(still.force[0]).toBeCloseTo(100 * 2 * 2, 6);
+ });
+
+ it('feels a turning body\'s own speed at the point, as well as its middle\'s', () => {
+ // Spinning about +y at 1 rad/s, a point 2 m out along +x is moving at 2 m/s along -z.
+ const f = floatingForce(body({ angularVelocity: [0, 1, 0] }), [2, 0, 0], water(-50), floating({ drag: 1 }), gravity, 100, 1 / 60, 1)!;
+ expect(f.force[2]).toBeCloseTo(100 * 1 * 2, 6);
+ expect(f.force[0]).toBeCloseTo(0, 6);
+ });
+
+ it('caps a drag that would reverse the velocity in one step', () => {
+ const f = floatingForce(body({ velocity: [1, 0, 0] }), at, water(-50), floating({ drag: 1000 }), gravity, 100, 1 / 60, 1)!;
+ // The most the step may take is nine tenths of the velocity, as a force: mass * (0.9 / dt) * v.
+ expect(f.force[0]).toBeCloseTo(-100 * (0.9 * 60) * 1, 6);
+ });
+});
diff --git a/src/esengine/bindings/modules/physics3d/Physics3DBindings.hpp b/src/esengine/bindings/modules/physics3d/Physics3DBindings.hpp
index bcbd4ee80..19f6e9562 100644
--- a/src/esengine/bindings/modules/physics3d/Physics3DBindings.hpp
+++ b/src/esengine/bindings/modules/physics3d/Physics3DBindings.hpp
@@ -72,6 +72,11 @@ void physics3d_setTransform(uint32_t bodyId, float px, float py, float pz,
float qx, float qy, float qz, float qw);
void physics3d_setLinearVelocity(uint32_t bodyId, float vx, float vy, float vz);
int physics3d_getBodyState(uint32_t bodyId);
+// What a force needs to know of a body: its mass and how it is turning.
+int physics3d_getBodyDynamics(uint32_t bodyId);
+// Forces, held until the next step and applied over it: at a world point (so it turns the body as well as pushing it), and as a torque.
+void physics3d_addForce(uint32_t bodyId, float fx, float fy, float fz, float px, float py, float pz);
+void physics3d_addTorque(uint32_t bodyId, float tx, float ty, float tz);
// Characters — swept rather than solved, and not bodies.
uint32_t physics3d_addCharacter(uint32_t entity, float radius, float halfHeight,
diff --git a/src/esengine/bindings/modules/physics3d/Physics3DModuleEntry.cpp b/src/esengine/bindings/modules/physics3d/Physics3DModuleEntry.cpp
index d019b41d9..4a4dc6f16 100644
--- a/src/esengine/bindings/modules/physics3d/Physics3DModuleEntry.cpp
+++ b/src/esengine/bindings/modules/physics3d/Physics3DModuleEntry.cpp
@@ -462,6 +462,36 @@ int physics3d_getBodyState(uint32_t bodyId) {
return 1;
}
+/// Writes (mass, wx,wy,wz) into the query buffer: the body's mass in kilograms and its angular velocity in radians a
+/// second, world space. 0 when the body is gone or does not move (a static or kinematic body has no mass to push).
+EMSCRIPTEN_KEEPALIVE
+int physics3d_getBodyDynamics(uint32_t bodyId) {
+ if (!g().isValid() || bodyId == 0) return 0;
+ const BodyLockRead lock(g().system->GetBodyLockInterface(), BodyID(bodyId));
+ if (!lock.Succeeded() || !lock.GetBody().IsDynamic()) return 0;
+ const Body& body = lock.GetBody();
+ const float inverseMass = body.GetMotionProperties()->GetInverseMass();
+ if (!(inverseMass > 0.0f)) return 0;
+ const Vec3 spin = body.GetAngularVelocity();
+ g().queryBuffer = { 1.0f / inverseMass, spin.GetX(), spin.GetY(), spin.GetZ() };
+ return 1;
+}
+
+/// A force of (fx, fy, fz) newtons at the world point (px, py, pz), over the next step. It turns the body as well as pushing it,
+/// by as much as the point is off the centre of mass; and it wakes a body that has gone to sleep.
+EMSCRIPTEN_KEEPALIVE
+void physics3d_addForce(uint32_t bodyId, float fx, float fy, float fz, float px, float py, float pz) {
+ if (!g().isValid() || bodyId == 0) return;
+ g().system->GetBodyInterface().AddForce(BodyID(bodyId), Vec3(fx, fy, fz), RVec3(px, py, pz));
+}
+
+/// A torque of (tx, ty, tz) newton metres, over the next step.
+EMSCRIPTEN_KEEPALIVE
+void physics3d_addTorque(uint32_t bodyId, float tx, float ty, float tz) {
+ if (!g().isValid() || bodyId == 0) return;
+ g().system->GetBodyInterface().AddTorque(BodyID(bodyId), Vec3(tx, ty, tz));
+}
+
// Characters
/**
diff --git a/tools/check-corpus-authoring.mjs b/tools/check-corpus-authoring.mjs
index 4b298761d..32be9d15e 100644
--- a/tools/check-corpus-authoring.mjs
+++ b/tools/check-corpus-authoring.mjs
@@ -123,6 +123,7 @@ const DISPOSITION = {
SceneOwner: ['derived', 'scene loading records which scene an entity came from; authoring it would claim an ownership the loader never granted'],
// — code-only: an example demonstrates it from TypeScript, honestly —
+ Floating: ['owed', 'no example floats anything yet; the first boat or buoy goes into one'],
Spline: ['owed', 'no example carries a spline yet; the first river, with a spline tool in the editor, goes into one'],
WaterBody: ['owed', 'no example carries a body of water yet; the first of the water work that is shown off (rivers, with the spline) goes into one'],
Replicated: ['code-only', 'multiplayer-arena declares its replicated set beside the server systems that own it; the wire table is a contract both ends compile against, not scene content'],
diff --git a/tools/check-gizmo-coverage.mjs b/tools/check-gizmo-coverage.mjs
index 8a06a8e08..928a71ba2 100644
--- a/tools/check-gizmo-coverage.mjs
+++ b/tools/check-gizmo-coverage.mjs
@@ -123,6 +123,7 @@ const DISPOSITION = {
'WaterBody.sizeX': ['owed', 'the lake extent is not outlined in the viewport yet; the lake tools will draw its boundary'],
'WaterBody.sizeZ': ['owed', 'the lake extent is not outlined in the viewport yet; the lake tools will draw its boundary'],
'WaterBody.shoreWidth': ['no-place', 'a distance in from a lake edge over which the waves come to full height, not a region of the entity'],
+ 'Floating.radius': ['no-place', 'how deep under the surface a point of the body is wholly wet, not a region of the entity'],
'WaterBody.cellSize': ['no-place', 'the cell size of the finest ring of geometry, not a region of the entity'],
'WaterBody.waveHeight': ['no-place', 'the height of the tallest wave, not a region of the entity'],
'Sprite.size': ['renders', 'the sprite drawn at it is the outline'],
diff --git a/tools/releaseNotes.mjs b/tools/releaseNotes.mjs
index 765e333b7..ba48a3e8e 100644
--- a/tools/releaseNotes.mjs
+++ b/tools/releaseNotes.mjs
@@ -2563,6 +2563,8 @@ export const NOTED = {
{"note":"A lake can have an outline of its own and knows its shore. `boundary` cuts it to a polygon on its plane (crisp at the pixel, not at the grid's cells), `shoreWidth` calms its waves toward the edge and where it is shallow over a Terrain, and the shore foams along the outline. `Waters.sample` answers with the same calmed waves and says a point in the notch of a concave lake is not inside."},
"feat(water): a river follows a Spline and runs with a current the surface and the code can both read":
{"note":"A WaterBody can be a river: put a Spline on its entity and it lays a ribbon along the curve, as wide as the curve says at each point and at its height, with a current (`flowSpeed`, faster where it narrows) that the shader carries the waves and ripples along and that `Waters.sample` reports as `flow`. Splines are a new optional module (`esengine/spline`): a curve through points with a width each, measured by the distance along it."},
+ "feat(water): a Floating component holds a rigid body up in water and carries it with the current":
+ {"note":"Water holds things up. A Floating component on an entity with a RigidBody3D floats it: a buoyant force against gravity (`buoyancy` is the water's density against the body's, so 2 floats it half under) and a drag against its velocity relative to the water, which brings it to rest in a lake and carries it with a river's current, applied at a few points of the body so waves tip it. It works from the CPU's own water surface, so it needs no renderer, and it needs the 3D physics module, which gains force and mass queries."},
"chore(tools): the gates run in parallel with --jobs, and the reds a full run gathered are cleared":
{"internal":"tooling for the static gates, and fixes to checks that had drifted from the code they guard"},
"fix(render): a wire narrower than a pixel is no longer painted over by the sky in dashes":