Skip to content

armgit / raea

Public Imported from GitHub
0

Render Anything Engine: tell your AI what to make. Videos, motion graphics, 3D and games as React and TypeScript, rendered on your own GPU. Rust + Bevy, macOS, Linux and Windows.

SG6: Line3d and Tube, a line through points as one part drawn on solid at every frame

shinyobjectz34bf8eb02109
diff --git a/docs/manual/reference/sdk/index.md b/docs/manual/reference/sdk/index.md
index e307d87a..af4aadbf 100644
--- a/docs/manual/reference/sdk/index.md
+++ b/docs/manual/reference/sdk/index.md
@@ -73,7 +73,7 @@ Bevy's 3D: cameras, lights, materials, meshes and the frame after it's drawn.
| [`raea/camera`](camera.md) | Cameras and the views they make: Camera3d, the Canvas3D a 2D scene draws in, HDR and matchmoved cameras. | 5 components, 1 hook, 4 functions, 13 types |
| [`raea/light`](light.md) | Bevy's lights in Bevy's units, environments, skies and daylight. | 15 components, 9 functions, 2 values, 15 types |
| [`raea/pbr`](pbr.md) | Materials and volumes: StandardMaterial, extended and toon materials, custom shaders, decals, fog and fire. | 22 components, 1 function, 1 value, 35 types |
-| [`raea/mesh`](mesh.md) | Shapes and solids: Mesh3d and Mesh2d, Bevy's primitives, buffer meshes, instancing and exact solids. | 14 components, 1 function, 2 classes, 10 values, 24 types |
+| [`raea/mesh`](mesh.md) | Shapes and solids: Mesh3d and Mesh2d, Bevy's primitives, buffer meshes, instancing and exact solids. | 16 components, 1 function, 2 classes, 10 values, 26 types |
| [`raea/transform`](transform.md) | Where things are: Bevy's Transform and Quat, and nesting. | 2 functions, 2 values, 4 types |
| [`raea/post_process`](post_process.md) | What's done to the frame after it's drawn: tone mapping, bloom, depth of field, motion blur, grading and outlines. | 12 components, 14 types |
| [`raea/picking`](picking.md) | What the pointer is over: the nearest part under it, and the ray it casts. | 2 functions, 3 types |
diff --git a/docs/manual/reference/sdk/mesh.md b/docs/manual/reference/sdk/mesh.md
index 1de792a3..f338cad5 100644
--- a/docs/manual/reference/sdk/mesh.md
+++ b/docs/manual/reference/sdk/mesh.md
@@ -29,7 +29,7 @@ const Box = () => (
import { ATTRIBUTE_COLOR, ATTRIBUTE_NORMAL, ATTRIBUTE_POSITION, ATTRIBUTE_TANGENT } from "raea/mesh"
```
-`raea/mesh` exports 14 components, 1 function, 2 classes, 10 values, 24 types. Bevy's counterpart: `bevy_mesh, bevy_shape`. Source: [sdk/raea/src/mesh.ts](https://github.com/shinyobjectz/raea/blob/main/sdk/raea/src/mesh.ts).
+`raea/mesh` exports 16 components, 1 function, 2 classes, 10 values, 26 types. Bevy's counterpart: `bevy_mesh, bevy_shape`. Source: [sdk/raea/src/mesh.ts](https://github.com/shinyobjectz/raea/blob/main/sdk/raea/src/mesh.ts).
## Components
@@ -100,6 +100,22 @@ Bevy: `bevy_pbr::render::mesh::MeshPipeline (automatic batching of entities shar
Takes [`InstancesProps`](3d.md#instancesprops)'s props.
+### `Line3d`
+
+A line through points in 3D: one flat mesh of a width, round at its ends and joins, drawn up to `p` of its length.
+One part, so a curve that grows is solid at every frame (never a chain of parts: SG6). Its material is its child.
+`<Line3d points={pts} width={0.04} p={t}><StandardMaterial base_color="#e5484d" unlit /></Line3d>`
+
+| Prop | Type | What it does |
+| --- | --- | --- |
+| `points` (required) | `readonly Vec3[]` | the points it passes through, in order (two or more); give enough for a curve to read smooth |
+| `p` | `number` | how much of it is drawn, 0 to 1 of its length from the first point (1): animate it to draw the line on |
+| `width` | `number` | its width in metres (0.05) |
+| `normal` | `Vec3` | the way its face looks: the normal of the plane it lies in (left out: the plane of its points, else +z) |
+| `children` | `ReactNode` | its material (a white StandardMaterial when left out) |
+
+Also takes the props of `MeshProps` (`animate`, `name`, `pass`, `quaternion`, `allowOverlap`, `posed`, `shape`, `driven`, `shadow`, `material`, `castShadow`, `surface`, `receiveShadow`, `attributes`, `compressed`, `layers`); `PointerHandlers3d` (`onClick`, `onDrag`, `onDragEnd`, `onDragEnter`, `onDragLeave`, `onDragOver`, `onDragStart`, `onDrop`, `onPointerDown`, `onPointerMove`, `onPointerUp`, `onPointerEnter`, `onPointerLeave`, `onPointerOver`, `onPointerOut`, `onWheel`); [`Mesh3dProps`](#mesh3dprops) (`visibility`, `transform`, `detail`).
+
### `Mesh2d`
Bevy's Mesh2d with its Transform, a primitive and a ColorMaterial: <Shape2D> in Bevy's 2D world.
@@ -153,6 +169,20 @@ Used in: [3d/fog](https://github.com/shinyobjectz/raea/blob/main/sdk/raea/bench/
Also takes the props of [`TorusProps`](3d.md#torusprops) (`args`, `major_radius`, `minor_radius`).
+### `Tube`
+
+A line through points in 3D with a round section (a pipe, a wire): one mesh, drawn up to `p` of its length.
+
+| Prop | Type | What it does |
+| --- | --- | --- |
+| `points` (required) | `readonly Vec3[]` | the points it passes through, in order (two or more); give enough for a curve to read smooth |
+| `p` | `number` | how much of it is drawn, 0 to 1 of its length from the first point (1): animate it to draw the line on |
+| `children` | `ReactNode` | its material (a white StandardMaterial when left out) |
+| `radius` | `number` | its radius in metres (0.025) |
+| `sides` | `number` | sides around its section (12) |
+
+Also takes the props of `MeshProps` (`animate`, `name`, `pass`, `quaternion`, `allowOverlap`, `posed`, `shape`, `driven`, `shadow`, `material`, `castShadow`, `surface`, `receiveShadow`, `attributes`, `compressed`, `layers`); `PointerHandlers3d` (`onClick`, `onDrag`, `onDragEnd`, `onDragEnter`, `onDragLeave`, `onDragOver`, `onDragStart`, `onDrop`, `onPointerDown`, `onPointerMove`, `onPointerUp`, `onPointerEnter`, `onPointerLeave`, `onPointerOver`, `onPointerOut`, `onWheel`); [`Mesh3dProps`](#mesh3dprops) (`visibility`, `transform`, `detail`).
+
## Functions
### `scatter`
@@ -402,6 +432,12 @@ copy together). Rotation in radians, XYZ order, as everywhere.
| `pass` | `string` | the composition pass it draws in ("scene" by default) |
| `children` | `ReactNode` | the mesh form: a geometry and a material (MeshStandardMaterial, MeshPhysicalMaterial or MeshBasicMaterial). The glTF form: MeshStandardMaterial children re-covering its materials, as on a Model |
+### `Line3dProps`
+
+Line3d's props: a flat line of a width, its ends and joins round.
+
+The props of [`Line3d`](#line3d), tabled there.
+
### `Mesh2dProps`
| Field | Type | What it is |
@@ -544,6 +580,12 @@ subdivisions, or `ico` of them (Bevy's `.ico(n)`, 0 to 80), or a UV sphere of `u
| `major_radius` | `number` | from the centre to the middle of the tube, metres (0.75) |
| `minor_radius` | `number` | the tube's radius, metres (0.25) |
+### `TubeProps`
+
+Tube's props: a line with a round section.
+
+The props of [`Tube`](#tube), tabled there.
+
### `Vec3`
```ts
diff --git a/docs/stage-guards.feature b/docs/stage-guards.feature
index 6ae0e854..cd3c3cc7 100644
--- a/docs/stage-guards.feature
+++ b/docs/stage-guards.feature
@@ -169,9 +169,15 @@ Feature: Stage guards: a 3D render an agent can't break
Scenario: SG6. Lines are lines
Given the plan
| crate | file | lines | job |
- | @raea/render | sdk/render/src/3d/line.tsx | 140 | Line3d: points, width, drawn up to p, round joins, one mesh (a swept outline); Tube for a round section |
+ | @raea/render | sdk/render/src/3d/line.tsx | 160 | Line3d: points, width, drawn up to p, round joins, one mesh (a swept outline); Tube for a round section |
+ | raea | sdk/raea/src/mesh.ts | +2 | raea/mesh exports them |
+ | raea (test) | sdk/raea/conformance/line3d.test.tsx | 80 | one part at every share drawn, the cut at p, the width and plane, the tube's radius and untwisted rings, caps, refusals |
+ | (guide) | sdk/guides/craft/bevy/meshes.md | +22 | the curve recipe, and a chain of parts as a common mistake |
Then a curve is one part, solid at every frame, and the 3D guide's curve recipe uses it
And SG12 flags a chain of more than 8 parts named `NAME-i` whose ends touch as "a line made of parts: Line3d"
+ # Status 11-21 (branch stage-guards-5): Line3d and Tube are built, one BufferMesh each, cut at p; renders of a
+ # 120-point Tube and an 80-point Line3d growing over 40 frames read smooth with round ends at every frame. The
+ # meshes guide's recipe uses them. The SG12 flag is SG12's.
@done
Scenario: SG7. A camera path that can't lurch
diff --git a/sdk/guides/craft/bevy.md b/sdk/guides/craft/bevy.md
index 5e4d4703..6f147fb4 100644
--- a/sdk/guides/craft/bevy.md
+++ b/sdk/guides/craft/bevy.md
@@ -24,7 +24,7 @@ pieces; then write the file. Each file's example is a complete composition you c
| a whole scene to build and make believable: the brief, which tool makes which object, build order, review sheets, the judge, when to stop | `bevy/scenes` |
| the words to paste for a whole scene: the brief template, the builder prompt, the judge prompt | `bevy/prompts` |
| a Godot project: its scenes and resources scripted from TypeScript, run headless, recorded as frames to use as footage | `bevy/godot` |
-| shapes: boxes to modelled solids, blended organic bodies (`sdf`), trees, terrain, rocks and plants (`grow`), 3D letters | `bevy/meshes` |
+| shapes: boxes to modelled solids, blended organic bodies (`sdf`), trees, terrain, rocks and plants (`grow`), 3D letters, lines and curves drawn on (`Line3d`, `Tube`) | `bevy/meshes` |
| moving things: spins, springs, reveals, things arriving later, model clips | `bevy/animation` |
| a 3D game: state, input, many entities, collisions, state machines | `bevy/games` |
| glTF models, pictures in space, where files go | `bevy/assets` |
diff --git a/sdk/guides/craft/bevy/meshes.md b/sdk/guides/craft/bevy/meshes.md
index b06992fd..b1b26f5f 100644
--- a/sdk/guides/craft/bevy/meshes.md
+++ b/sdk/guides/craft/bevy/meshes.md
@@ -64,6 +64,26 @@
- `grow.rosette({ leaves, length, tilt, rise })` is a succulent, an agave, a lettuce or a flower's petals, set at
the golden angle and blended from one heart.
+## Lines and curves: `Line3d` and `Tube` (`raea/mesh`)
+
+A line through points, such as a graph's curve, a route on a map, a drawn stroke or a wire, is one part: `<Line3d>`
+(flat, a `width`, round at its joins and ends) or `<Tube>` (round, a `radius`). Give it the points in order and its
+material as its child. `p` is how much of it is drawn, 0 to 1 of its length, so animating `p` draws the line on, and it
+stays one part, solid at every frame.
+
+```tsx
+const pts = Array.from({ length: 64 }, (_, i) => [i / 16 - 2, Math.sin(i / 6) * 0.5, 0] as [number, number, number]);
+const p = interpolate(frame, [0, 40], [0, 1], { extrapolateLeft: "clamp", extrapolateRight: "clamp" });
+<Line3d name="trend" points={pts} width={0.04} p={p}><StandardMaterial base_color="#e5484d" unlit /></Line3d>
+```
+
+- Give enough points for the curve to read smooth (a point every few degrees of turn); the line is straight between
+ them.
+- A Line3d lies in its points' plane and faces along that plane's normal; for a line seen edge-on, give `normal`, or use
+ a Tube.
+- Never build a curve from a chain of boxes, one a segment (`NAME-0`, `NAME-1`, ...). A part mounts on the frame it
+ first appears, so a growing chain comes in a chunk at a time and its joins show.
+
## Text in the 3D world, animated glyph by glyph (`RichText`)
`<RichText>` is flat lettering standing in the scene: every glyph its own lit, shaded entity (it takes the lights,
@@ -141,6 +161,8 @@ cached, then drawn by Bevy. A modelled solid and a primitive travel the same way
- Text3D with quotes or backslashes in it: they throw.
- A 2D outline revolved with points at negative x: revolve takes x >= 0 (the axis is x = 0).
- Building solids inside the component body: every frame rebuilds them. Build once (module level, `??=`).
+- A curve drawn as a chain of parts (a box a segment): it grows in chunks with its joins showing. Use one `Line3d` or
+ `Tube` and animate its `p`.
## Example: a sign with the word cut through it, and solid letters in front
diff --git a/sdk/raea/conformance/line3d.test.tsx b/sdk/raea/conformance/line3d.test.tsx
new file mode 100644
index 00000000..3b94e976
--- /dev/null
+++ b/sdk/raea/conformance/line3d.test.tsx
@@ -0,0 +1,79 @@
+// Lines are lines (docs/stage-guards.feature SG6): a curve is one part at every frame of its growth, never a chain of
+// parts mounted one a frame. Line3d is a flat line of a width with round joins and ends, Tube a round one.
+import { describe, expect, test } from "bun:test";
+import { Line3d, Tube } from "../src/mesh";
+import { drawn, planeNormal, ribbon, tube } from "@raea/render/3d/line";
+import { renderFrame } from "../src/test";
+
+type V = [number, number, number];
+const html = (el: React.ReactElement) => renderFrame(el, { frame: 0, width: 320, height: 240, fps: 30, durationInFrames: 30 });
+const L: V[] = [[0, 0, 0], [1, 0, 0], [1, 1, 0]];
+const arc: V[] = Array.from({ length: 33 }, (_, i) => [Math.cos((Math.PI * i) / 32), Math.sin((Math.PI * i) / 32), 0]);
+const near = (a: number[], b: number[], e = 1e-9) => a.every((x, i) => Math.abs(x - b[i]) <= e);
+const verts = (ps: number[]) => Array.from({ length: ps.length / 3 }, (_, i) => ps.slice(3 * i, 3 * i + 3) as V);
+
+/** A point's distance from the polyline through pts. */
+function fromLine(q: V, pts: V[]): number {
+ let best = Infinity;
+ for (let i = 0; i + 1 < pts.length; i++) {
+ const a = pts[i], b = pts[i + 1], ab = b.map((x, k) => x - a[k]), aq = q.map((x, k) => x - a[k]);
+ const t = Math.max(0, Math.min(1, aq.reduce((s, x, k) => s + x * ab[k], 0) / ab.reduce((s, x) => s + x * x, 0)));
+ best = Math.min(best, Math.hypot(...q.map((x, k) => x - (a[k] + t * ab[k]))));
+ }
+ return best;
+}
+
+describe("SG6: lines are lines", () => {
+ test("a growing curve is one part, by its own name, at every share drawn", () => {
+ for (const p of [0.02, 0.25, 0.5, 0.75, 1]) {
+ const out = html(<Line3d name="curve" points={arc} p={p} />);
+ expect(out.match(/data-3d="Mesh"/g)?.length).toBe(1);
+ expect(out.match(/data-shape="buffer:/g)?.length).toBe(1);
+ expect(out).toContain("&quot;name&quot;:&quot;curve&quot;");
+ const tubeOut = html(<Tube name="wire" points={arc} p={p} />);
+ expect(tubeOut.match(/data-3d="Mesh"/g)?.length).toBe(1);
+ }
+ expect(html(<Line3d points={arc} p={0} />)).not.toContain('data-3d="Mesh"');
+ });
+
+ test("drawn up to p of its length, ending between two points", () => {
+ expect(drawn("Line3d", L, 0.75)).toEqual([[0, 0, 0], [1, 0, 0], [1, 0.5, 0]]);
+ expect(drawn("Line3d", L, 0.5)).toEqual([[0, 0, 0], [1, 0, 0]]);
+ expect(drawn("Line3d", L, 1)).toEqual(L);
+ expect(drawn("Line3d", [[0, 0, 0], [0, 0, 0], [2, 0, 0]], 0.25)).toEqual([[0, 0, 0], [0.5, 0, 0]]);
+ expect(drawn("Line3d", L, 0)).toEqual([]);
+ });
+
+ test("a flat line keeps its width everywhere, faces its plane on both sides, and is round at its joins", () => {
+ const m = ribbon(L, 0.05, [0, 0, 1]);
+ const vs = verts(m.positions);
+ expect(Math.max(...vs.map((q) => fromLine(q, L)))).toBeLessThanOrEqual(0.05 + 1e-9);
+ // every vertex lies in the line's plane, and the corner's outside is covered by its round join
+ expect(vs.every((q) => q[2] === 0)).toBe(true);
+ expect(vs.some((q) => near(q, [1 + 0.05 * Math.cos(-Math.PI / 4), 0.05 * Math.sin(-Math.PI / 4), 0], 1e-9))).toBe(true);
+ expect(new Set(verts(m.normals).map((n) => n.join())).size).toBe(2);
+ expect(m.indices.length % 3).toBe(0);
+ expect(planeNormal(arc.map(([x, y]) => [x, 0, y] as V)).map(Math.abs)).toEqual([0, 1, 0]);
+ expect(planeNormal([[0, 0, 0], [1, 1, 1], [2, 2, 2]])).toEqual([0, 0, 1]);
+ });
+
+ test("a tube is round at its radius along the whole line, its rings never twist, and its ends are capped", () => {
+ const sides = 12, m = tube(arc, 0.02, sides);
+ const ring = verts(m.positions).slice(0, arc.length * sides);
+ expect(Math.max(...ring.map((q) => Math.abs(fromLine(q, arc) - 0.02)))).toBeLessThan(2e-3);
+ // vertex j of one ring and of the next point nearly the same way (a twist would turn them apart)
+ const dir = (i: number, j: number) => ring[i * sides + j].map((x, k) => (x - arc[i][k]) / 0.02);
+ for (let i = 0; i + 1 < arc.length; i++) expect(dir(i, 0).reduce((s, x, k) => s + x * dir(i + 1, 0)[k], 0)).toBeGreaterThan(0.9);
+ // two caps of a centre and a ring each
+ expect(m.positions.length / 3).toBe(arc.length * sides + 2 * (1 + sides));
+ expect(m.indices.length / 3).toBe((arc.length - 1) * sides * 2 + 2 * sides);
+ });
+
+ test("refusals name the prop", () => {
+ expect(() => html(<Line3d points={[[0, 0, 0]]} />)).toThrow("Line3d: points is two or more [x, y, z]");
+ expect(() => html(<Line3d points={L} p={1.5} />)).toThrow("Line3d: p is how much of it is drawn, 0 to 1, got 1.5");
+ expect(() => html(<Line3d points={L} width={0} />)).toThrow("Line3d: width is in metres, more than 0, got 0");
+ expect(() => html(<Tube points={L} sides={2} />)).toThrow("Tube: sides is a whole number, 3 or more, got 2");
+ expect(() => html(<Tube points={L} radius={-1} />)).toThrow("Tube: radius is in metres, more than 0, got -1");
+ });
+});
diff --git a/sdk/raea/src/mesh.ts b/sdk/raea/src/mesh.ts
index d744c942..e11ceb9e 100644
--- a/sdk/raea/src/mesh.ts
+++ b/sdk/raea/src/mesh.ts
@@ -5,6 +5,8 @@ export { Sphere, Cylinder, Torus, Cone, Capsule, BufferMesh, type SphereProps, t
export * from "@raea/render/solid";
export { Mesh3d, ConicalFrustum, type Mesh3dProps, type ConicalFrustumProps } from "@raea/render/bevy3d";
export { Cuboid, Capsule3d, Plane3d, type CuboidProps, type Capsule3dProps, type Plane3dProps } from "./3d";
+// a line through points as one part, drawn on solid at every frame (docs/stage-guards.feature SG6)
+export { Line3d, Tube, type Line3dProps, type TubeProps } from "@raea/render/3d/line";
// a mesh's own vertex attributes (Mesh3d attributes) and the ones a Material's vertex buffer reads (vertex_attributes)
export { MeshVertexAttribute, ATTRIBUTE_POSITION, ATTRIBUTE_NORMAL, ATTRIBUTE_UV_0, ATTRIBUTE_UV_1, ATTRIBUTE_TANGENT, ATTRIBUTE_COLOR, type VertexFormat, type MeshAttribute } from "./3d";
export { MeshSequence, type MeshSequenceProps } from "@raea/physics/physics";
diff --git a/sdk/render/package.json b/sdk/render/package.json
index 5baa853b..921a7f6b 100644
--- a/sdk/render/package.json
+++ b/sdk/render/package.json
@@ -23,7 +23,8 @@
"./bevy-own": "./src/bevy-own.gen.tsx",
"./feathers": "./src/feathers.ts",
"./camera/path": "./src/camera/path.ts",
- "./3d/clock": "./src/3d/clock.ts"
+ "./3d/clock": "./src/3d/clock.ts",
+ "./3d/line": "./src/3d/line.tsx"
},
"raea": {
"plugins": {
diff --git a/sdk/render/src/3d/line.tsx b/sdk/render/src/3d/line.tsx
new file mode 100644
index 00000000..38e04ae5
--- /dev/null
+++ b/sdk/render/src/3d/line.tsx
@@ -0,0 +1,162 @@
+// Lines are lines (docs/stage-guards.feature SG6). A curve drawn as a chain of parts (a box a segment, named NAME-i)
+// mounts a part a frame as it grows, and each new part came in a frame late or at another's place: the stage film's
+// curves were drawn in chunks. Line3d and Tube are one part each, one mesh through every point, drawn up to `p` of the
+// way along, solid at every frame.
+import type { ReactNode } from "react";
+import { Mesh3d, type Mesh3dProps } from "../bevy3d/core";
+import { StandardMaterial } from "../bevy3d/materials";
+import { BufferMesh, type BufferMeshProps } from "./shapes";
+import type { Vec3 } from "./core";
+
+type V = Vec3;
+
+/** Line3d's props: a flat line of a width, its ends and joins round. */
+export interface Line3dProps extends Omit<Mesh3dProps, "children"> {
+ /** the points it passes through, in order (two or more); give enough for a curve to read smooth */
+ points: readonly Vec3[];
+ /** how much of it is drawn, 0 to 1 of its length from the first point (1): animate it to draw the line on */
+ p?: number;
+ /** its width in metres (0.05) */
+ width?: number;
+ /** the way its face looks: the normal of the plane it lies in (left out: the plane of its points, else +z) */
+ normal?: Vec3;
+ /** its material (a white StandardMaterial when left out) */
+ children?: ReactNode;
+}
+
+/** Tube's props: a line with a round section. */
+export interface TubeProps extends Omit<Mesh3dProps, "children"> {
+ /** the points it passes through, in order (two or more); give enough for a curve to read smooth */
+ points: readonly Vec3[];
+ /** how much of it is drawn, 0 to 1 of its length from the first point (1): animate it to draw the line on */
+ p?: number;
+ /** its material (a white StandardMaterial when left out) */
+ children?: ReactNode;
+ /** its radius in metres (0.025) */
+ radius?: number;
+ /** sides around its section (12) */
+ sides?: number;
+}
+
+/** A line through points in 3D: one flat mesh of a width, round at its ends and joins, drawn up to `p` of its length.
+ * One part, so a curve that grows is solid at every frame (never a chain of parts: SG6). Its material is its child.
+ * `<Line3d points={pts} width={0.04} p={t}><StandardMaterial base_color="#e5484d" unlit /></Line3d>` */
+export function Line3d({ points, width = 0.05, normal, p = 1, children, ...mesh }: Line3dProps) {
+ const pts = drawn("Line3d", points, p);
+ if (!(width > 0) || !Number.isFinite(width)) throw new RangeError(`Line3d: width is in metres, more than 0, got ${width}`);
+ if (pts.length < 2) return null;
+ return <Mesh3d {...mesh}><BufferMesh {...ribbon(pts, width / 2, unit(normal ?? planeNormal(points)))} />{children ?? <StandardMaterial />}</Mesh3d>;
+}
+
+/** A line through points in 3D with a round section (a pipe, a wire): one mesh, drawn up to `p` of its length. */
+export function Tube({ points, radius = 0.025, sides = 12, p = 1, children, ...mesh }: TubeProps) {
+ const pts = drawn("Tube", points, p);
+ if (!(radius > 0) || !Number.isFinite(radius)) throw new RangeError(`Tube: radius is in metres, more than 0, got ${radius}`);
+ if (!(Number.isInteger(sides) && sides >= 3)) throw new RangeError(`Tube: sides is a whole number, 3 or more, got ${sides}`);
+ if (pts.length < 2) return null;
+ return <Mesh3d {...mesh}><BufferMesh {...tube(pts, radius, sides)} />{children ?? <StandardMaterial />}</Mesh3d>;
+}
+
+const sub = (a: V, b: V): V => [a[0] - b[0], a[1] - b[1], a[2] - b[2]];
+const add = (a: V, b: V, s = 1): V => [a[0] + b[0] * s, a[1] + b[1] * s, a[2] + b[2] * s];
+const cross = (a: V, b: V): V => [a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0]];
+const dot = (a: V, b: V) => a[0] * b[0] + a[1] * b[1] + a[2] * b[2];
+const len = (a: V) => Math.hypot(a[0], a[1], a[2]);
+const unit = (a: V): V => { const l = len(a); return l > 1e-12 ? [a[0] / l, a[1] / l, a[2] / l] : [0, 0, 1]; };
+// a unit vector square to n
+const across = (n: V): V => unit(cross(n, Math.abs(n[0]) < 0.9 ? [1, 0, 0] : [0, 1, 0]));
+
+/** The points drawn: the line cut at `p` of its length (a point between two where it ends), repeats dropped. */
+export function drawn(owner: string, points: readonly V[], p: number): V[] {
+ if (!Array.isArray(points) || points.length < 2 || !points.every((q) => Array.isArray(q) && q.length === 3 && q.every(Number.isFinite)))
+ throw new TypeError(`${owner}: points is two or more [x, y, z], got ${JSON.stringify(points)?.slice(0, 80)}`);
+ if (!(p >= 0 && p <= 1)) throw new RangeError(`${owner}: p is how much of it is drawn, 0 to 1, got ${p}`);
+ const pts: V[] = [points[0]];
+ for (const q of points.slice(1)) if (len(sub(q, pts[pts.length - 1])) > 1e-9) pts.push(q);
+ const segs = pts.slice(1).map((q, i) => len(sub(q, pts[i])));
+ let left = p * segs.reduce((a, b) => a + b, 0);
+ if (left <= 0) return [];
+ const out: V[] = [pts[0]];
+ for (let i = 0; i < segs.length; i++) {
+ if (left >= segs[i]) { out.push(pts[i + 1]); left -= segs[i]; continue; }
+ if (left > 1e-9) out.push(add(pts[i], sub(pts[i + 1], pts[i]), left / segs[i]));
+ break;
+ }
+ return out;
+}
+
+/** The normal of the plane the points lie in (Newell's), +z when they lie on a line. */
+export function planeNormal(points: readonly V[]): V {
+ const n: V = [0, 0, 0];
+ for (let i = 0; i < points.length; i++) {
+ const a = points[i], b = points[(i + 1) % points.length];
+ n[0] += (a[1] - b[1]) * (a[2] + b[2]);
+ n[1] += (a[2] - b[2]) * (a[0] + b[0]);
+ n[2] += (a[0] - b[0]) * (a[1] + b[1]);
+ }
+ return len(n) > 1e-9 * Math.max(1, ...points.map(len)) ** 2 ? unit(n) : [0, 0, 1];
+}
+
+const ROUND = 16;
+
+/** A flat line half `h` wide facing n: a quad a segment and a disc at each point (its round joins and ends), drawn on
+ * both faces. The pieces overlap where they meet, which an opaque material draws as one. */
+export function ribbon(pts: V[], h: number, n: V): Required<Pick<BufferMeshProps, "positions" | "normals" | "indices">> {
+ const positions: number[] = [], normals: number[] = [], indices: number[] = [];
+ const back: V = [-n[0], -n[1], -n[2]];
+ const tri = (a: V, b: V, c: V) => {
+ for (const [face, w] of [[n, [a, b, c]], [back, [a, c, b]]] as [V, V[]][]) {
+ const k = positions.length / 3;
+ for (const q of w) positions.push(...q), normals.push(...face);
+ indices.push(k, k + 1, k + 2);
+ }
+ };
+ for (let i = 0; i + 1 < pts.length; i++) {
+ const a = pts[i], b = pts[i + 1], s = unit(cross(n, sub(b, a)));
+ const al = add(a, s, h), ar = add(a, s, -h), br = add(b, s, -h), bl = add(b, s, h);
+ tri(al, ar, br);
+ tri(al, br, bl);
+ }
+ const u = across(n), v = cross(n, u);
+ for (const c of pts) {
+ for (let j = 0; j < ROUND; j++) {
+ const t0 = (2 * Math.PI * j) / ROUND, t1 = (2 * Math.PI * (j + 1)) / ROUND;
+ tri(c, add(add(c, u, h * Math.cos(t0)), v, h * Math.sin(t0)), add(add(c, u, h * Math.cos(t1)), v, h * Math.sin(t1)));
+ }
+ }
+ return { positions, normals, indices };
+}
+
+/** A round line: a ring of `sides` at each point, square to the line there (frames carried along it, so the rings
+ * never twist), joined into one surface, with a flat cap at each end. */
+export function tube(pts: V[], r: number, sides: number): Required<Pick<BufferMeshProps, "positions" | "normals" | "indices">> {
+ const positions: number[] = [], normals: number[] = [], indices: number[] = [];
+ const dirs = pts.slice(1).map((q, i) => unit(sub(q, pts[i])));
+ const tangent = (i: number) => unit(add(dirs[Math.max(0, i - 1)], dirs[Math.min(dirs.length - 1, i)]));
+ let side = across(tangent(0));
+ pts.forEach((c, i) => {
+ const t = tangent(i);
+ side = unit(sub(side, t.map((x) => x * dot(side, t)) as V));
+ const up = cross(t, side);
+ for (let j = 0; j < sides; j++) {
+ const a = (2 * Math.PI * j) / sides, d = add(side.map((x) => x * Math.cos(a)) as V, up, Math.sin(a));
+ positions.push(...add(c, d, r)); normals.push(...d);
+ }
+ });
+ for (let i = 0; i + 1 < pts.length; i++)
+ for (let j = 0; j < sides; j++) {
+ const a = i * sides + j, b = i * sides + ((j + 1) % sides), c = a + sides, d = b + sides;
+ indices.push(a, b, d, a, d, c);
+ }
+ // the caps: a centre and its own ring (so their normals are the line's), wound to face out
+ for (const [at, out] of [[0, -1], [pts.length - 1, 1]] as const) {
+ const t = tangent(at).map((x) => x * out) as V, base = positions.length / 3;
+ positions.push(...pts[at]); normals.push(...t);
+ for (let j = 0; j < sides; j++) { positions.push(...positions.slice((at * sides + j) * 3, (at * sides + j) * 3 + 3)); normals.push(...t); }
+ for (let j = 0; j < sides; j++) {
+ const a = base + 1 + j, b = base + 1 + ((j + 1) % sides);
+ out > 0 ? indices.push(base, a, b) : indices.push(base, b, a);
+ }
+ }
+ return { positions, normals, indices };
+}
diff --git a/tools/taxonomy.list b/tools/taxonomy.list
index a579540f..08ac52e3 100644
--- a/tools/taxonomy.list
+++ b/tools/taxonomy.list
@@ -71,6 +71,7 @@ raea RichText 3D text in runs (raea-render's text3d), as HTML's rich text
raea Span a run of a RichText (HTML's <span>, inside RichText only)
raea Text3D solid 3D letters as a mesh's geometry (Manifold's text3d)
raea BufferMesh a mesh from its own vertex buffers (Bevy's Mesh built from attributes, as JSX)
+raea Tube a line through points with a round section, one mesh drawn on to a share of its length (SG6; Bevy has no swept shape)
raea Instances one mesh or glTF drawn at many placements (Bevy batches the copies; it has no component of its own)
raea Grass a field of grass the engine makes in tiles by distance from a few grids of the ground (no Bevy component)
raea MeshSequence a baked simulation, one mesh a frame