Code-first video & image, rendered natively on WebGPU.
feat(3d): expand Layer3D shape library with torus, capsule, ring, solid prism/pyramid, extrude, lathe, tube, line/points, and polyhedra
okanaslaa58813618ca
diff --git a/packages/framefields/src/builder-schema-conformance.test.ts b/packages/framefields/src/builder-schema-conformance.test.tsindex 4b8c5901..6ccb2011 100644--- a/packages/framefields/src/builder-schema-conformance.test.ts+++ b/packages/framefields/src/builder-schema-conformance.test.ts@@ -68,6 +68,66 @@ const builders = {sphere: () => Layer3D.sphere({ radius: 40, color: "#f00" }),cylinder: () =>Layer3D.cylinder({ radiusTop: 10, radiusBottom: 20, height: 40 }),+ capsule: () => Layer3D.capsule({ radius: 20, height: 50, color: "#22c55e" }),+ torus: () => Layer3D.torus({ radius: 45, tubeRadius: 12, color: "#ec4899" }),+ ring: () =>+ Layer3D.ring({ innerRadius: 20, outerRadius: 45, color: "#eab308" }),+ pyramid: () => Layer3D.pyramid({ sides: 4, radius: 40, height: 70 }),+ polyhedron: () =>+ Layer3D.polyhedron({ type: "dodecahedron", radius: 35, color: "#06b6d4" }),+ icosahedron: () => Layer3D.icosahedron({ radius: 35 }),+ icosphere: () =>+ Layer3D.icosphere({ radius: 40, detail: 2, flatShaded: false }),+ extrude: () =>+ Layer3D.extrude({+ d: "M -30 -30 L 30 -30 L 30 30 L -30 30 Z",+ depth: 16,+ bevelThickness: 3,+ bevelSize: 2,+ }),+ lathe: () =>+ Layer3D.lathe({+ points: [+ [0, -40],+ [25, 0],+ [0, 40],+ ],+ segments: 24,+ }),+ tube: () =>+ Layer3D.tube({+ points: [+ [-40, 0, 0],+ [0, -30, 0],+ [40, 0, 0],+ ],+ radius: 10,+ innerRadius: 6,+ }),+ line3d: () =>+ Layer3D.line({+ points: [+ [0, 0, 0],+ [50, 20, -10],+ ],+ dashSize: 6,+ gapSize: 4,+ }),+ points3d: () =>+ Layer3D.points({+ points: [+ [0, 0, 0],+ [20, -10, 5],+ ],+ pointSize: 8,+ }),+ prismWithSideConfigs: () =>+ Layer3D.prism({+ sides: 5,+ radius: 40,+ height: 80,+ sideConfigs: ["#ff0000", { background: "#00ff00" }],+ }),barChart: () =>Layer.chart({type: "bar",diff --git a/packages/framefields/src/index.ts b/packages/framefields/src/index.tsindex dcdabc63..19d456d6 100644--- a/packages/framefields/src/index.ts+++ b/packages/framefields/src/index.ts@@ -299,6 +299,7 @@ import {Layer3D,type Plane3DOptions,type Prism3DOptions,+ type SolidShape3DNode,} from "./shapes3d.js";import {type SceneSequenceOptions,@@ -923,24 +924,37 @@ export {type World3DOptions,} from "./physics/index.js";export {+ type Capsule3DOptions,type Carousel3DOptions,type Cube3DOptions,type CubeFaceConfig,type CubeFaceInput,type Cylinder3DOptions,type ExtrudedText3DOptions,+ type ExtrudeShape3DOptions,type Grid3DOptions,+ type Icosphere3DOptions,type Instances3DOptions,type InstanceTransform3D,+ type Lathe3DOptions,Layer3D,+ type Line3DOptions,type Plane3DOptions,+ type Points3DOptions,+ type Polyhedron3DOptions,type Primitive3DNodeOptions,type Prism3DOptions,+ type Pyramid3DOptions,+ type Ring3DOptions,type RoundedBox3DOptions,type Shape3DContainer,+ type Shard3DOptions,+ type SolidShape3DNode,type Sphere3DOptions,type Surface3DOptions,type Text3DOptions,+ type Torus3DOptions,+ type Tube3DOptions,} from "./shapes3d.js";export { type StyleName, Styles } from "./styles.js";export type { Swarm3DOptions } from "./swarm3d.js";@@ -3252,7 +3266,7 @@ export const Layer = {Layer3D.carousel(options),plane3d: (options: Plane3DOptions): AnimatableNode<BoxNode> =>Layer3D.plane(options),- prism3d: (options: Prism3DOptions): AnimatableNode<BoxNode> =>+ prism3d: (options: Prism3DOptions = {}): SolidShape3DNode =>Layer3D.prism(options),model: (options: Partial<Model3DNode> = {}): AnimatableNode<Model3DNode> =>withAnimation({diff --git a/packages/framefields/src/physics/world3d.ts b/packages/framefields/src/physics/world3d.tsindex 39a1c289..9b0c7f10 100644--- a/packages/framefields/src/physics/world3d.ts+++ b/packages/framefields/src/physics/world3d.ts@@ -703,10 +703,14 @@ function num(v: unknown, fallback: number): number {interface PrimitiveSpec {type?: string;+ shape?: string;width?: number;height?: number;depth?: number;+ length?: number;radius?: number;+ tube?: number;+ outerRadius?: number;radiusTop?: number;radiusBottom?: number;taper?: number;@@ -750,7 +754,10 @@ function colliderShape3D(t: LayerLike, options: Body3DOptions): Shape3D {if (h) return h;}const sphere =- mode === "sphere" || (mode === "auto" && prim.type === "sphere");+ mode === "sphere" ||+ (mode === "auto" &&+ (prim.type === "sphere" ||+ (prim.type === "polyhedron" && prim.shape === "icosphere")));if (sphere && (uniform || mode === "sphere")) {const r = num(prim.radius, 0) || Math.max(...(boxSize(t, prim) ?? [0])) / 2;if (r > 0) return { kind: "ball", radius: r * Math.max(...scale) };@@ -803,10 +810,25 @@ function colliderShape3D(t: LayerLike, options: Body3DOptions): Shape3D {function boxSize(t: LayerLike, prim: PrimitiveSpec): Vec3 | undefined {if (prim.type === "roundedBox")return [num(prim.width, 0), num(prim.height, 0), num(prim.depth, 0)];- if (prim.type === "sphere") {- const d = num(prim.radius, 0) * 2;+ if (prim.type === "sphere" || prim.type === "polyhedron") {+ const d = num(prim.radius, 50) * 2;return [d, d, d];}+ if (prim.type === "capsule") {+ const r = num(prim.radius, 30);+ const len = num(prim.length, 60);+ return [r * 2, len + r * 2, r * 2];+ }+ if (prim.type === "torus") {+ const R = num(prim.radius, 60);+ const r = num(prim.tube, 20);+ return [(R + r) * 2, (R + r) * 2, r * 2];+ }+ if (prim.type === "ring") {+ const rOut = num(prim.outerRadius, 60);+ const depth = Math.max(2, num(prim.depth, 0));+ return [rOut * 2, rOut * 2, depth];+ }if (prim.type === "cylinder") {const d =Math.max(diff --git a/packages/framefields/src/primitives-3d-render.test.ts b/packages/framefields/src/primitives-3d-render.test.tsindex 33e08d09..d91f8756 100644--- a/packages/framefields/src/primitives-3d-render.test.ts+++ b/packages/framefields/src/primitives-3d-render.test.ts@@ -1,6 +1,12 @@import { Canvas, loadImage } from "skia-canvas";import { describe, expect, it } from "vitest";-import { Composition, Layer, Layer3D, LayerAnimation } from "./index.js";+import {+ Composition,+ Layer,+ Layer3D,+ LayerAnimation,+ Path3D,+} from "./index.js";async function decode(png: Buffer) {const img = await loadImage(png);@@ -222,6 +228,136 @@ describe("Layer3D mesh primitives", () => {expect(pixel.r).toBeGreaterThan(100);expect(pixel.b).toBeGreaterThan(30);});++ it("renders torus, capsule, ring, solid prism, pyramid, and icosphere with materials", async () => {+ const comp = stage();+ comp.add(+ Layer.directionalLight({+ color: "#ffffff",+ intensity: 1.4,+ x: 200,+ y: -400,+ z: -500,+ targetX: 400,+ targetY: 300,+ targetZ: 0,+ }),+ );+ comp.add([+ Layer3D.torus({+ radius: 70,+ tube: 24,+ x: 220,+ y: 300,+ rotateX: 55,+ color: "#ef4444",+ roughness: 0.3,+ metallic: 0.2,+ }),+ Layer3D.capsule({+ radius: 35,+ length: 70,+ x: 400,+ y: 300,+ color: "#22c55e",+ }),+ Layer3D.prism({+ sides: 6,+ radius: 55,+ height: 80,+ x: 580,+ y: 300,+ color: "#3b82f6",+ emissive: "#1d4ed8",+ emissiveIntensity: 0.25,+ }),+ Layer3D.pyramid({+ sides: 4,+ radius: 50,+ height: 80,+ x: 300,+ y: 300,+ z: 140,+ color: "#eab308",+ }),+ Layer3D.icosphere({+ radius: 45,+ detail: 2,+ x: 500,+ y: 300,+ z: 140,+ color: "#a855f7",+ }),+ ]);+ const decoded = await decode(await comp.renderFrame({ frame: 0 }));+ // Capsule at center (400, 300) is green+ const center = decoded.at(400, 300);+ expect(center.g).toBeGreaterThan(120);+ expect(center.g).toBeGreaterThan(center.r);+ // Prism at right is blue+ const right = decoded.at(555, 300);+ expect(right.b).toBeGreaterThan(100);+ });++ it("renders extruded 2D shapes, lathe profiles, hollow tubes, and 3D diagram lines/points", async () => {+ const comp = stage();+ comp.add([+ Layer3D.extrude({+ shape: "M -40 -40 L 40 -40 L 40 40 L -40 40 Z",+ depth: 30,+ bevelThickness: 4,+ bevelSize: 4,+ x: 240,+ y: 300,+ rotateX: 40,+ color: "#f97316",+ }),+ Layer3D.lathe({+ points: [+ [15, -40],+ [45, 0],+ [25, 40],+ ],+ capped: true,+ x: 400,+ y: 300,+ color: "#06b6d4",+ }),+ Layer3D.tube({+ path: Path3D.catmullRom([+ [-60, -40, -40],+ [0, 0, 0],+ [60, 40, 40],+ ]),+ x: 560,+ y: 300,+ radius: 18,+ innerRadius: 10,+ color: "#ec4899",+ }),+ Layer3D.line({+ points: [+ [-220, -100, 0],+ [220, -100, 0],+ ],+ x: 400,+ y: 300,+ color: "#ffffff",+ }),+ Layer3D.points({+ points: [[-180, -100, -100]],+ x: 400,+ y: 300,+ pointSize: 16,+ color: "#facc15",+ }),+ ]);+ const decoded = await decode(await comp.renderFrame({ frame: 0 }));+ // Lathe at center (400, 300) is cyan+ const center = decoded.at(400, 300);+ expect(center.b).toBeGreaterThan(100);+ expect(center.g).toBeGreaterThan(80);+ });});describe("text reveal by count", () => {diff --git a/packages/framefields/src/shapes3d.ts b/packages/framefields/src/shapes3d.tsindex d13d542d..f4823e05 100644--- a/packages/framefields/src/shapes3d.ts+++ b/packages/framefields/src/shapes3d.ts@@ -5,15 +5,26 @@ import type {Model3DNode,} from "@framefields/compositions/program";import {+ type CapsuleGeometryOptions,type CylinderGeometryOptions,+ type ExtrudeShapeGeometryOptions,generateExtrudedTextGeometry,getPrimitiveGeometry,+ type LatheGeometryOptions,+ type Line3DGeometryOptions,type Model3DData,+ Path3D,+ type Points3DGeometryOptions,+ type PolyhedronGeometryOptions,type PrimitiveGeometryOptions,+ type RingGeometryOptions,type RoundedBoxGeometryOptions,type ShardGeometryOptions,SlugFontCache,type SphereGeometryOptions,+ type TorusGeometryOptions,+ type TubeGeometryOptions,+ type TubePathSpec,} from "@framefields/webgpu-renderers";import { autoId } from "./ids.js";import { type AnimatableNode, Layer } from "./index.js";@@ -128,17 +139,39 @@ export interface Carousel3DOptions {opacity?: number;}-export interface Prism3DOptions {+export interface Prism3DOptions extends Surface3DOptions {id?: string;- sides: number;- radius: number;- height: number;+ /** Number of polygon sides (default 6). */+ sides?: number;+ /** Circumradius of the polygon (default 60). */+ radius?: number;+ /** Optional top (-y) radius; defaults to `radius`. */+ radiusTop?: number;+ /** Optional bottom (+y) radius; defaults to `radius`. */+ radiusBottom?: number;+ /** Height along Y (default 100). */+ height?: number;x?: number;y?: number;z?: number;rotateX?: number;rotateY?: number;rotateZ?: number;+ scale?: number;+ scaleX?: number;+ scaleY?: number;+ scaleZ?: number;+ /** Leave the top and bottom polygon caps off (default false = solid capped prism). */+ openEnded?: boolean;+ /** Flat-shade each polygonal side facet (default true for crisp prism edges). */+ flatShaded?: boolean;+ /** Draw triangle edges instead of filled surfaces. */+ wireframe?: boolean;+ /** Surface color baked into the mesh (default `#3b82f6`). */+ color?: string;+ /** Animated color multiplier (`node.color`). */+ tint?: string;+ /** Optional per-side panel configs; when provided, builds a multi-panel preserve-3d container. */sideConfigs?: Array<CubeFaceInput>;twoSided?: boolean;material?: MaterialType;@@ -153,6 +186,52 @@ export interface Prism3DOptions {fresnelPower?: number;envIntensity?: number;opacity?: number;+ startFrame?: number;+ durationFrames?: number;+}++export interface Pyramid3DOptions extends Surface3DOptions {+ id?: string;+ /** Number of base polygon sides (default 4 = square pyramid; 3 = triangular pyramid). */+ sides?: number;+ /** Circumradius of the base polygon (default 60). */+ radius?: number;+ /** Optional top (-y) truncation radius for a frustum pyramid (default 0 = sharp apex). */+ radiusTop?: number;+ /** Height from base (+y) to apex (-y) (default 100). */+ height?: number;+ /** Leave the base cap off (default false = solid capped pyramid). */+ openEnded?: boolean;+ /** Flat-shade each triangular side face (default true). */+ flatShaded?: boolean;+ x?: number;+ y?: number;+ z?: number;+ rotateX?: number;+ rotateY?: number;+ rotateZ?: number;+ scale?: number;+ scaleX?: number;+ scaleY?: number;+ scaleZ?: number;+ wireframe?: boolean;+ color?: string;+ tint?: string;+ twoSided?: boolean;+ material?: MaterialType;+ shininess?: number;+ roughness?: number;+ specularIntensity?: number;+ metallic?: number;+ ambientIntensity?: number;+ ior?: number;+ transmission?: number;+ dispersion?: number;+ fresnelPower?: number;+ envIntensity?: number;+ opacity?: number;+ startFrame?: number;+ durationFrames?: number;}export interface Plane3DOptions extends Surface3DOptions {@@ -267,7 +346,7 @@ export interface ExtrudedText3DOptions extends Text3DOptions {curveTolerance?: number;}-/** Node props shared by the mesh primitives (roundedBox, sphere, cylinder). */+/** Node props shared by the mesh primitives (roundedBox, sphere, cylinder, torus, capsule, …). */export interface Primitive3DNodeOptions extends Surface3DOptions {id?: string;x?: number;@@ -280,6 +359,8 @@ export interface Primitive3DNodeOptions extends Surface3DOptions {scaleX?: number;scaleY?: number;scaleZ?: number;+ /** Render both front and back faces (default false for closed solids). */+ twoSided?: boolean;/** Draw triangle edges instead of filled surfaces. */wireframe?: boolean;/** Surface color baked into the mesh (default white). */@@ -295,6 +376,11 @@ export interface Primitive3DNodeOptions extends Surface3DOptions {specularIntensity?: number;ambientIntensity?: number;metallic?: number;+ ior?: number;+ transmission?: number;+ dispersion?: number;+ fresnelPower?: number;+ envIntensity?: number;opacity?: number;startFrame?: number;durationFrames?: number;@@ -306,6 +392,38 @@ export type Sphere3DOptions = Primitive3DNodeOptions &Omit<SphereGeometryOptions, "type" | "color" | "material">;export type Cylinder3DOptions = Primitive3DNodeOptions &Omit<CylinderGeometryOptions, "type" | "color" | "material">;+export type Torus3DOptions = Primitive3DNodeOptions &+ Omit<TorusGeometryOptions, "type" | "color" | "material">;+export type Capsule3DOptions = Primitive3DNodeOptions &+ Omit<CapsuleGeometryOptions, "type" | "color" | "material">;+export type Ring3DOptions = Primitive3DNodeOptions &+ Omit<RingGeometryOptions, "type" | "color" | "material">;+export type Polyhedron3DOptions = Primitive3DNodeOptions &+ Omit<PolyhedronGeometryOptions, "type" | "color" | "material">;+export type Icosphere3DOptions = Omit<Polyhedron3DOptions, "shape">;+export type ExtrudeShape3DOptions = Primitive3DNodeOptions &+ Omit<ExtrudeShapeGeometryOptions, "type" | "color" | "material">;+export type Lathe3DOptions = Primitive3DNodeOptions &+ Omit<LatheGeometryOptions, "type" | "color" | "material">;+export type Tube3DOptions = Primitive3DNodeOptions &+ Omit<TubeGeometryOptions, "type" | "color" | "material" | "path"> & {+ /** A `Path3D` instance, `TubePathSpec`, or array of 3D waypoints `[x, y, z]`. */+ path?: Path3D | TubePathSpec;+ /** Alias for `path` when passing an array of 3D waypoints `[x, y, z]` or a `Path3D`. */+ points?: Path3D | TubePathSpec;+ };+export type Line3DOptions = Primitive3DNodeOptions &+ Omit<Line3DGeometryOptions, "type" | "color" | "material" | "points"> & {+ /** A `Path3D` instance, `TubePathSpec`, or array of 3D points `[x, y, z]`. */+ points?: Path3D | TubePathSpec;+ /** Alias for `points` when passing a `Path3D` or `TubePathSpec`. */+ path?: Path3D | TubePathSpec;+ };+export type Points3DOptions = Primitive3DNodeOptions &+ Omit<Points3DGeometryOptions, "type" | "color" | "material" | "points"> & {+ /** A `Path3D` instance, `TubePathSpec`, or array of 3D points `[x, y, z]`. */+ points: Path3D | TubePathSpec;+ };export type Shard3DOptions = Primitive3DNodeOptions &Omit<ShardGeometryOptions, "type" | "color" | "material">;@@ -374,6 +492,13 @@ function meshShading(: undefined;}+function normalizePathSpec(input: Path3D | TubePathSpec): TubePathSpec {+ if (input instanceof Path3D) {+ return input.getPoints(96);+ }+ return input;+}+function primitiveNode(prefix: string,geometry: PrimitiveGeometryOptions,@@ -415,12 +540,8 @@ function primitiveNode(specularIntensity: o.specularIntensity ?? 0.5,ambientIntensity: o.ambientIntensity ?? 1.0,metallic: o.metallic,- ...materialProps({- emissive: o.emissive,- emissiveIntensity: o.emissiveIntensity,- castShadow: o.castShadow,- }),- twoSided: false,+ ...materialProps(o),+ twoSided: o.twoSided ?? false,wireframe: o.wireframe,startFrame: o.startFrame,durationFrames: o.durationFrames,@@ -433,6 +554,12 @@ export type Shape3DContainer = AnimatableNode<BoxNode> & {[Symbol.iterator](): Iterator<LayoutNode>;};+export type SolidShape3DNode = AnimatableNode<Model3DNode> & {+ faces?: LayoutNode[];+ items?: LayoutNode[];+ [Symbol.iterator](): Iterator<LayoutNode>;+};+/*** Attaches the faces/items handles as non-enumerable properties, like* `animate`, so they stay out of `toSpec()` and schema validation.@@ -540,9 +667,8 @@ export const Layer3D = {ambientIntensity:cfg.ambientIntensity ?? options.ambientIntensity ?? 1.0,...materialProps({- emissive: cfg.emissive ?? options.emissive,- emissiveIntensity: cfg.emissiveIntensity ?? options.emissiveIntensity,- castShadow: cfg.castShadow ?? options.castShadow,+ ...options,+ ...cfg,}),background: cfg.background ?? defaultColor,borderRadius: cfg.borderRadius ?? 0,@@ -666,8 +792,8 @@ export const Layer3D = {x: options.x ?? 0,y: options.y ?? 0,z: options.z ?? 0,- width: (options.itemWidth ?? 200) as any,- height: (options.itemHeight ?? 200) as any,+ width: options.itemWidth ?? 200,+ height: options.itemHeight ?? 200,is3D: true,transformStyle: "preserve-3d",rotateX: options.rotateX ?? 0,@@ -682,63 +808,144 @@ export const Layer3D = {},/**- * Creates an N-sided regular polygonal 3D prism.+ * Creates an N-sided regular polygonal 3D prism with top and bottom caps,+ * outward flat-shaded facet normals, and full material options.+ * If `sideConfigs` are provided, builds a multi-panel preserve-3d container with all material props applied.*/prism(options: Prism3DOptions): Shape3DContainer {- const { sides, radius, height, twoSided = true } = options;- const n = Math.max(3, sides);- const sideWidth = 2 * radius * Math.tan(Math.PI / n);- const angleStep = 360 / n;- const panels: AnimatableNode<BoxNode>[] = [];-- for (let i = 0; i < n; i++) {- const angleDeg = i * angleStep;- const rad = (angleDeg * Math.PI) / 180;- const x = radius * Math.sin(rad);- const z = radius * Math.cos(rad);- const cfg = options.sideConfigs?.[i];- const color =- typeof cfg === "string"- ? cfg- : ((cfg as { background?: string } | undefined)?.background ??- `hsl(${(i * 360) / n}, 70%, 50%)`);-- panels.push(- Layer.box({- id: `${options.id ?? "prism"}-panel-${i}`,- position: "absolute",- width: sideWidth,- height,- is3D: true,- twoSided,- x,- y: 0,- z,- rotateY: angleDeg,- background: color,- }),- );+ const n = Math.max(3, Math.round(options.sides));+ if (options.sideConfigs && options.sideConfigs.length > 0) {+ const { radius, height, twoSided = true } = options;+ const sideWidth = 2 * radius * Math.tan(Math.PI / n);+ const angleStep = 360 / n;+ const panels: AnimatableNode<BoxNode>[] = [];++ for (let i = 0; i < n; i++) {+ const angleDeg = i * angleStep;+ const rad = (angleDeg * Math.PI) / 180;+ const x = radius * Math.sin(rad);+ const z = -radius * Math.cos(rad);+ const input = options.sideConfigs[i];+ const defaultColor = options.color ?? `hsl(${(i * 360) / n}, 70%, 50%)`;++ if (input && typeof input === "object" && "kind" in input) {+ const node = input as AnimatableNode<BoxNode>;+ node.position = "absolute";+ node.is3D = true;+ node.twoSided = twoSided;+ node.x = x;+ node.y = 0;+ node.z = z;+ node.rotateY = -angleDeg;+ Object.assign(node, materialProps(options));+ panels.push(node);+ continue;+ }++ const cfg: CubeFaceConfig =+ typeof input === "string"+ ? { background: input }+ : (input ?? { background: defaultColor });++ panels.push(+ Layer.box({+ id: `${options.id ?? "prism"}-panel-${i}`,+ position: "absolute",+ width: sideWidth,+ height,+ is3D: true,+ twoSided,+ x,+ y: 0,+ z,+ rotateY: -angleDeg,+ background: cfg.background ?? defaultColor,+ borderRadius: cfg.borderRadius ?? 0,+ borderWidth: cfg.borderWidth,+ borderColor: cfg.borderColor,+ opacity: cfg.opacity ?? options.opacity ?? 1,+ material: cfg.material ?? options.material ?? "lit",+ shininess: cfg.shininess ?? options.shininess ?? 32,+ specularIntensity:+ cfg.specularIntensity ?? options.specularIntensity ?? 0.5,+ ambientIntensity:+ cfg.ambientIntensity ?? options.ambientIntensity ?? 1.0,+ ...materialProps({ ...options, ...cfg }),+ children: cfg.children ?? [],+ }),+ );+ }++ const container = Layer.box({+ id: options.id ?? autoId("prism"),+ position: "absolute",+ x: options.x ?? 0,+ y: options.y ?? 0,+ z: options.z ?? 0,+ width: sideWidth,+ height,+ is3D: true,+ transformStyle: "preserve-3d",+ rotateX: options.rotateX ?? 0,+ rotateY: options.rotateY ?? 0,+ rotateZ: options.rotateZ ?? 0,+ opacity: options.opacity ?? 1,+ background: "transparent",+ children: panels,+ });++ return withParts(container, { faces: panels });}- const container = Layer.box({- id: options.id ?? autoId("prism"),- position: "absolute",- x: options.x ?? 0,- y: options.y ?? 0,- z: options.z ?? 0,- width: sideWidth,- height,- is3D: true,- transformStyle: "preserve-3d",- rotateX: options.rotateX ?? 0,- rotateY: options.rotateY ?? 0,- rotateZ: options.rotateZ ?? 0,- opacity: options.opacity ?? 1,- background: "transparent",- children: panels,- });+ const modelNode = primitiveNode(+ "prism",+ {+ type: "cylinder",+ radius: options.radius,+ radiusTop: options.radiusTop ?? options.radius,+ radiusBottom: options.radiusBottom ?? options.radius,+ height: options.height,+ segments: n,+ openEnded: options.openEnded ?? false,+ flatShaded: options.flatShaded ?? true,+ },+ {+ ...options,+ color: options.color ?? "#3b82f6",+ twoSided: options.twoSided ?? Boolean(options.openEnded),+ },+ );- return withParts(container, { faces: panels });+ return withParts(modelNode, {+ faces: [modelNode],+ items: [modelNode],+ }) as unknown as Shape3DContainer;+ },++ /**+ * Creates a solid N-sided regular polygonal pyramid (or truncated pyramid when `radiusTop > 0`)+ * with a bottom cap and crisp flat-shaded side facets.+ */+ pyramid(options: Pyramid3DOptions): AnimatableNode<Model3DNode> {+ const n = Math.max(3, Math.round(options.sides ?? 4));+ return primitiveNode(+ "pyramid",+ {+ type: "cylinder",+ radius: options.radius ?? 60,+ radiusTop: options.radiusTop ?? 0,+ radiusBottom: options.radius ?? 60,+ height: options.height,+ segments: n,+ openEnded: options.openEnded ?? false,+ flatShaded: options.flatShaded ?? true,+ },+ {+ ...options,+ color: options.color ?? "#f59e0b",+ twoSided: options.twoSided ?? Boolean(options.openEnded),+ },+ );},/**@@ -861,7 +1068,12 @@ export const Layer3D = {fontWeight: options.fontWeight ?? "bold",fontStyle: options.fontStyle,fill: options.fill ?? "#ffffff",- align: (options.align as any) ?? "center",+ align: (options.align ?? "center") as+ | "left"+ | "center"+ | "right"+ | "start"+ | "end",direction: options.direction,verticalAlign: options.verticalAlign ?? "middle",letterSpacing: options.letterSpacing,@@ -1009,11 +1221,238 @@ export const Layer3D = {height: options.height,segments: options.segments,openEnded: options.openEnded,+ flatShaded: options.flatShaded,+ },+ {+ ...options,+ twoSided: options.twoSided ?? Boolean(options.openEnded),+ },+ );+ },++ /**+ * A 3D torus (donut / ring) mesh with major `radius`, tube radius `tube`,+ * and optional partial `arc` sweep in degrees.+ */+ torus(options: Torus3DOptions = {}): AnimatableNode<Model3DNode> {+ return primitiveNode(+ "torus",+ {+ type: "torus",+ radius: options.radius,+ tube: options.tube,+ radialSegments: options.radialSegments,+ tubularSegments: options.tubularSegments,+ arc: options.arc,+ },+ options,+ );+ },++ /**+ * A smooth 3D capsule (pill) mesh aligned along the Y axis: a cylinder of+ * length `length` and radius `radius` capped by two hemispheres.+ */+ capsule(options: Capsule3DOptions = {}): AnimatableNode<Model3DNode> {+ return primitiveNode(+ "capsule",+ {+ type: "capsule",+ radius: options.radius,+ length: options.length,+ capSegments: options.capSegments,+ radialSegments: options.radialSegments,+ },+ options,+ );+ },++ /**+ * A 3D ring / annulus with `innerRadius`, `outerRadius`, and optional `depth`+ * for a thick-walled washer/annular solid.+ */+ ring(options: Ring3DOptions = {}): AnimatableNode<Model3DNode> {+ return primitiveNode(+ "ring",+ {+ type: "ring",+ innerRadius: options.innerRadius,+ outerRadius: options.outerRadius,+ depth: options.depth,+ thetaSegments: options.thetaSegments,+ phiSegments: options.phiSegments,+ thetaStart: options.thetaStart,+ thetaLength: options.thetaLength,+ },+ options,+ );+ },++ /**+ * A Platonic polyhedron (`tetrahedron`, `octahedron`, `dodecahedron`, `icosahedron`)+ * or geodesic `icosphere` with configurable subdivision `detail` and `flatShaded` facets.+ */+ polyhedron(options: Polyhedron3DOptions = {}): AnimatableNode<Model3DNode> {+ return primitiveNode(+ options.shape ?? "icosahedron",+ {+ type: "polyhedron",+ shape: options.shape,+ radius: options.radius,+ detail: options.detail,+ flatShaded: options.flatShaded,},options,);},+ /**+ * An icosahedron (20-sided regular polyhedron), optionally subdivided with `detail`.+ */+ icosahedron(options: Icosphere3DOptions = {}): AnimatableNode<Model3DNode> {+ return Layer3D.polyhedron({ ...options, shape: "icosahedron" });+ },++ /**+ * An evenly distributed geodesic icosphere mesh (`detail` defaults to 2, smooth-shaded by default).+ */+ icosphere(options: Icosphere3DOptions = {}): AnimatableNode<Model3DNode> {+ return Layer3D.polyhedron({+ ...options,+ shape: "icosphere",+ detail: options.detail ?? 2,+ flatShaded: options.flatShaded ?? false,+ });+ },++ /**+ * Extrudes a 2D outline (an SVG path string with curves/holes or a 2D point contour array)+ * into a 3D solid mesh with optional front/back bevels (`bevelThickness`, `bevelSize`, `bevelSegments`)+ * and separate side wall color (`bevelColor`).+ */+ extrude(options: ExtrudeShape3DOptions): AnimatableNode<Model3DNode> {+ return primitiveNode(+ "extrude",+ {+ type: "extrude",+ shape: options.shape,+ depth: options.depth,+ bevelThickness: options.bevelThickness,+ bevelSize: options.bevelSize,+ bevelSegments: options.bevelSegments,+ bevelColor: options.bevelColor,+ curveSegments: options.curveSegments,+ curveTolerance: options.curveTolerance,+ center: options.center,+ },+ options,+ );+ },++ /**+ * Revolves a 2D profile (`[[r, y], ...]` or an SVG path string) around the Y axis+ * to create bowls, bottles, goblets, vases, and turned solids.+ */+ lathe(options: Lathe3DOptions): AnimatableNode<Model3DNode> {+ return primitiveNode(+ "lathe",+ {+ type: "lathe",+ points: options.points,+ segments: options.segments,+ phiStart: options.phiStart,+ phiLength: options.phiLength,+ capped: options.capped,+ flatShaded: options.flatShaded,+ },+ {+ ...options,+ twoSided: options.twoSided ?? !(options.capped ?? false),+ },+ );+ },++ /**+ * Sweeps a circular or thick-walled hollow pipe cross-section (`innerRadius > 0`)+ * along a 3D curve (`Path3D`, `TubePathSpec`, or 3D waypoints `[x, y, z]`) using+ * Rotation-Minimizing Frames.+ */+ tube(options: Tube3DOptions): AnimatableNode<Model3DNode> {+ const pathInput = options.path ?? options.points;+ if (!pathInput) {+ throw new Error("Layer3D.tube requires `path` or `points`");+ }+ return primitiveNode(+ "tube",+ {+ type: "tube",+ path: normalizePathSpec(pathInput),+ radius: options.radius,+ innerRadius: options.innerRadius,+ radiusTaper: options.radiusTaper,+ tubularSegments: options.tubularSegments,+ radialSegments: options.radialSegments,+ closed: options.closed,+ capped: options.capped,+ },+ {+ ...options,+ twoSided: options.twoSided ?? options.capped === false,+ },+ );+ },++ /**+ * 3D line / curve geometry (`line-list` topology) along 3D points or a `Path3D` curve,+ * supporting dashed segments (`dashSize`, `gapSize`) and per-vertex colors for 3D diagrams.+ */+ line(options: Line3DOptions): AnimatableNode<Model3DNode> {+ const pointsInput = options.points ?? options.path;+ if (!pointsInput) {+ throw new Error("Layer3D.line requires `points` or `path`");+ }+ return primitiveNode(+ "line3d",+ {+ type: "line3d",+ points: normalizePathSpec(pointsInput),+ colors: options.colors,+ mode: options.mode,+ closed: options.closed,+ dashSize: options.dashSize,+ gapSize: options.gapSize,+ },+ {+ ...options,+ material: options.material ?? "unlit",+ castShadow: options.castShadow ?? false,+ },+ );+ },++ /**+ * 3D point cloud / diagram vertex geometry along 3D points or a `Path3D` curve.+ * Pass `pointSize > 0` for 3D spherical diagram dots that scale in perspective,+ * or omit `pointSize` for native GPU `point-list` pixels.+ */+ points(options: Points3DOptions): AnimatableNode<Model3DNode> {+ const isPixelPoints = (options.pointSize ?? 0) <= 0;+ return primitiveNode(+ "points3d",+ {+ type: "points3d",+ points: normalizePathSpec(options.points),+ colors: options.colors,+ pointSize: options.pointSize,+ },+ {+ ...options,+ material: options.material ?? (isPixelPoints ? "unlit" : "lit"),+ castShadow: options.castShadow ?? !isPixelPoints,+ },+ );+ },+/*** A procedural faceted convex polyhedron / rock shard: carved from half-space planes.* Convex hull collider in Physics.world3d is derived automatically.diff --git a/packages/webgpu-renderers/src/math3d/path3d.ts b/packages/webgpu-renderers/src/math3d/path3d.tsindex c4e60707..9653eabb 100644--- a/packages/webgpu-renderers/src/math3d/path3d.ts+++ b/packages/webgpu-renderers/src/math3d/path3d.ts@@ -91,12 +91,15 @@ export class Path3D {upRef = [0, 0, 1];}let n0 = Vector3Math.normalize(- Vector3Math.subtract(upRef, Vector3Math.multiplyScalar(t0, Vector3Math.dot(upRef, t0))),+ Vector3Math.subtract(+ upRef,+ Vector3Math.multiplyScalar(t0, Vector3Math.dot(upRef, t0)),+ ),);if (Vector3Math.lengthSq(n0) < 1e-4) {n0 = [1, 0, 0];}- let b0 = Vector3Math.normalize(Vector3Math.cross(t0, n0));+ const b0 = Vector3Math.normalize(Vector3Math.cross(t0, n0));this.frames[0] = {normal: n0,binormal: b0,@@ -132,7 +135,10 @@ export class Path3D {if (c2 > 1e-8) {n_next = Vector3Math.subtract(n_i_L,- Vector3Math.multiplyScalar(v2, (2 * Vector3Math.dot(v2, n_i_L)) / c2),+ Vector3Math.multiplyScalar(+ v2,+ (2 * Vector3Math.dot(v2, n_i_L)) / c2,+ ),);} else {n_next = n_i_L;@@ -162,12 +168,32 @@ export class Path3D {*/private eulerFromFrame(tangent: Vec3, normal: Vec3, _binormal: Vec3): Vec3 {// Tangent is the forward viewing axis Z_fwd or X_fwd- const pitch = Math.asin(Math.max(-1, Math.min(1, -tangent[1]))) * (180 / Math.PI);+ const pitch =+ Math.asin(Math.max(-1, Math.min(1, -tangent[1]))) * (180 / Math.PI);const yaw = Math.atan2(tangent[0], tangent[2]) * (180 / Math.PI);const roll = Math.atan2(normal[0], normal[1]) * (180 / Math.PI);return [pitch, yaw, roll];}+ /**+ * Returns a copy of the discrete samples `[position, tangent, distance]` along this path.+ */+ public getSamples(): ReadonlyArray<Path3DSample> {+ return this.samples;+ }++ /**+ * Evaluates `count` evenly arc-length-spaced 3D positions along the path.+ */+ public getPoints(count = 64): Vec3[] {+ const n = Math.max(2, Math.round(count));+ const pts: Vec3[] = [];+ for (let i = 0; i < n; i++) {+ pts.push(this.getPointAt(i / (n - 1)).position);+ }+ return pts;+ }+/*** Evaluates point, tangent, normal, binormal, and rotation at normalized progress u in [0, 1].* Progression moves with constant velocity along the arc length of the path.@@ -205,11 +231,15 @@ export class Path3D {const alpha = segLen > 1e-6 ? (d - s0.distance) / segLen : 0;const position = Vector3Math.lerp(s0.position, s1.position, alpha);- const tangent = Vector3Math.normalize(Vector3Math.lerp(s0.tangent, s1.tangent, alpha));+ const tangent = Vector3Math.normalize(+ Vector3Math.lerp(s0.tangent, s1.tangent, alpha),+ );const f0 = this.frames[idx0];const f1 = this.frames[idx1];- const normal = Vector3Math.normalize(Vector3Math.lerp(f0.normal, f1.normal, alpha));+ const normal = Vector3Math.normalize(+ Vector3Math.lerp(f0.normal, f1.normal, alpha),+ );const binormal = Vector3Math.normalize(Vector3Math.cross(tangent, normal));const rotation: Vec3 = [f0.rotation[0] + (f1.rotation[0] - f0.rotation[0]) * alpha,@@ -258,7 +288,9 @@ export class Path3D {const pSecond = waypoints[1];const pLast = waypoints[waypoints.length - 1];const pPrevLast = waypoints[waypoints.length - 2];- pts.push(Vector3Math.subtract(pFirst, Vector3Math.subtract(pSecond, pFirst)));+ pts.push(+ Vector3Math.subtract(pFirst, Vector3Math.subtract(pSecond, pFirst)),+ );pts.push(...waypoints);pts.push(Vector3Math.add(pLast, Vector3Math.subtract(pLast, pPrevLast)));}@@ -272,7 +304,8 @@ export class Path3D {const p2 = pts[s + 2];const p3 = pts[s + 3];- const steps = s === numSegments - 1 ? samplesPerSegment : samplesPerSegment - 1;+ const steps =+ s === numSegments - 1 ? samplesPerSegment : samplesPerSegment - 1;for (let step = 0; step <= steps; step++) {const t = step / samplesPerSegment;const t2 = t * t;@@ -346,7 +379,8 @@ export class Path3D {for (let s = 0; s < segments.length; s++) {const seg = segments[s];- const steps = s === segments.length - 1 ? samplesPerSegment : samplesPerSegment - 1;+ const steps =+ s === segments.length - 1 ? samplesPerSegment : samplesPerSegment - 1;for (let step = 0; step <= steps; step++) {const t = step / samplesPerSegment;@@ -357,15 +391,30 @@ export class Path3D {const ttt = tt * t;const pos: Vec3 = [- uuu * seg.p0[0] + 3 * uu * t * seg.p1[0] + 3 * u * tt * seg.p2[0] + ttt * seg.p3[0],- uuu * seg.p0[1] + 3 * uu * t * seg.p1[1] + 3 * u * tt * seg.p2[1] + ttt * seg.p3[1],- uuu * seg.p0[2] + 3 * uu * t * seg.p1[2] + 3 * u * tt * seg.p2[2] + ttt * seg.p3[2],+ uuu * seg.p0[0] ++ 3 * uu * t * seg.p1[0] ++ 3 * u * tt * seg.p2[0] ++ ttt * seg.p3[0],+ uuu * seg.p0[1] ++ 3 * uu * t * seg.p1[1] ++ 3 * u * tt * seg.p2[1] ++ ttt * seg.p3[1],+ uuu * seg.p0[2] ++ 3 * uu * t * seg.p1[2] ++ 3 * u * tt * seg.p2[2] ++ ttt * seg.p3[2],];const tanVel: Vec3 = [- 3 * uu * (seg.p1[0] - seg.p0[0]) + 6 * u * t * (seg.p2[0] - seg.p1[0]) + 3 * tt * (seg.p3[0] - seg.p2[0]),- 3 * uu * (seg.p1[1] - seg.p0[1]) + 6 * u * t * (seg.p2[1] - seg.p1[1]) + 3 * tt * (seg.p3[1] - seg.p2[1]),- 3 * uu * (seg.p1[2] - seg.p0[2]) + 6 * u * t * (seg.p2[2] - seg.p1[2]) + 3 * tt * (seg.p3[2] - seg.p2[2]),+ 3 * uu * (seg.p1[0] - seg.p0[0]) ++ 6 * u * t * (seg.p2[0] - seg.p1[0]) ++ 3 * tt * (seg.p3[0] - seg.p2[0]),+ 3 * uu * (seg.p1[1] - seg.p0[1]) ++ 6 * u * t * (seg.p2[1] - seg.p1[1]) ++ 3 * tt * (seg.p3[1] - seg.p2[1]),+ 3 * uu * (seg.p1[2] - seg.p0[2]) ++ 6 * u * t * (seg.p2[2] - seg.p1[2]) ++ 3 * tt * (seg.p3[2] - seg.p2[2]),];const tangent = Vector3Math.normalize(tanVel);rawSamples.push({ position: pos, tangent });@@ -379,7 +428,14 @@ export class Path3D {* Creates a 3D volumetric helix / spiral path.*/public static helix(options: HelixOptions): Path3D {- const { center, radius, pitch, turns, axis = "z", samplesPerTurn = 60 } = options;+ const {+ center,+ radius,+ pitch,+ turns,+ axis = "z",+ samplesPerTurn = 60,+ } = options;const totalSamples = Math.max(10, Math.round(turns * samplesPerTurn));const rawSamples: Array<{ position: Vec3; tangent: Vec3 }> = [];@@ -395,17 +451,44 @@ export class Path3D {let tanVel: Vec3;if (axis === "z") {- pos = [center[0] + radius * c, center[1] + radius * s, center[2] + axial];- tanVel = [-radius * s, radius * c, (pitch * turns) / (turns * Math.PI * 2)];+ pos = [+ center[0] + radius * c,+ center[1] + radius * s,+ center[2] + axial,+ ];+ tanVel = [+ -radius * s,+ radius * c,+ (pitch * turns) / (turns * Math.PI * 2),+ ];} else if (axis === "y") {- pos = [center[0] + radius * c, center[1] + axial, center[2] + radius * s];- tanVel = [-radius * s, (pitch * turns) / (turns * Math.PI * 2), radius * c];+ pos = [+ center[0] + radius * c,+ center[1] + axial,+ center[2] + radius * s,+ ];+ tanVel = [+ -radius * s,+ (pitch * turns) / (turns * Math.PI * 2),+ radius * c,+ ];} else {- pos = [center[0] + axial, center[1] + radius * c, center[2] + radius * s];- tanVel = [(pitch * turns) / (turns * Math.PI * 2), -radius * s, radius * c];+ pos = [+ center[0] + axial,+ center[1] + radius * c,+ center[2] + radius * s,+ ];+ tanVel = [+ (pitch * turns) / (turns * Math.PI * 2),+ -radius * s,+ radius * c,+ ];}- rawSamples.push({ position: pos, tangent: Vector3Math.normalize(tanVel) });+ rawSamples.push({+ position: pos,+ tangent: Vector3Math.normalize(tanVel),+ });}return Path3D.fromRawSamples(rawSamples);@@ -415,7 +498,13 @@ export class Path3D {* Creates a 3D circular or arc orbit path.*/public static circle(options: CirclePathOptions): Path3D {- const { center, radius, startAngleDeg = 0, endAngleDeg = 360, samples = 128 } = options;+ const {+ center,+ radius,+ startAngleDeg = 0,+ endAngleDeg = 360,+ samples = 128,+ } = options;const startRad = (startAngleDeg * Math.PI) / 180;const endRad = (endAngleDeg * Math.PI) / 180;const rawSamples: Array<{ position: Vec3; tangent: Vec3 }> = [];@@ -424,9 +513,16 @@ export class Path3D {const theta = startRad + (endRad - startRad) * (i / samples);const c = Math.cos(theta);const s = Math.sin(theta);- const pos: Vec3 = [center[0] + radius * c, center[1], center[2] + radius * s];+ const pos: Vec3 = [+ center[0] + radius * c,+ center[1],+ center[2] + radius * s,+ ];const tanVel: Vec3 = [-radius * s, 0, radius * c];- rawSamples.push({ position: pos, tangent: Vector3Math.normalize(tanVel) });+ rawSamples.push({+ position: pos,+ tangent: Vector3Math.normalize(tanVel),+ });}return Path3D.fromRawSamples(rawSamples);diff --git a/packages/webgpu-renderers/src/renderer3d/primitive-geometry.test.ts b/packages/webgpu-renderers/src/renderer3d/primitive-geometry.test.tsindex f0408ca0..739bd91e 100644--- a/packages/webgpu-renderers/src/renderer3d/primitive-geometry.test.ts+++ b/packages/webgpu-renderers/src/renderer3d/primitive-geometry.test.ts@@ -179,4 +179,310 @@ describe("3D primitive geometry", () => {}),).toBe(cached);});++ it("builds torus and partial-arc torus wound outward", () => {+ const full = generatePrimitiveGeometry({+ type: "torus",+ radius: 80,+ tube: 20,+ radialSegments: 16,+ tubularSegments: 32,+ });+ expect(full.bounds.size[0]).toBeCloseTo(200, 1);+ expect(full.bounds.size[1]).toBeCloseTo(200, 1);+ expect(full.bounds.size[2]).toBeCloseTo(40, 1);+ // Verify every triangle face normal agrees with its vertex normal+ const mesh = full.meshes[0]!;+ const p = mesh.positions;+ const n = mesh.normals;+ const at = (i: number): V => [p[i * 3]!, p[i * 3 + 1]!, p[i * 3 + 2]!];+ const normalAt = (i: number): V => [+ n[i * 3]!,+ n[i * 3 + 1]!,+ n[i * 3 + 2]!,+ ];+ for (let t = 0; t < mesh.indices.length; t += 3) {+ const [i0, i1, i2] = [+ mesh.indices[t]!,+ mesh.indices[t + 1]!,+ mesh.indices[t + 2]!,+ ];+ const a = at(i0);+ const face = cross(sub(at(i1), a), sub(at(i2), a));+ if (Math.hypot(...face) < 1e-6) continue;+ expect(dot(face, normalAt(i0))).toBeGreaterThan(0);+ }++ const partial = generatePrimitiveGeometry({+ type: "torus",+ radius: 80,+ tube: 20,+ arc: 180,+ });+ expect(partial.meshes[0]!.indices.length).toBeGreaterThan(0);+ });++ it("builds a capsule wound outward with total height length + 2 * radius", () => {+ const cap = generatePrimitiveGeometry({+ type: "capsule",+ radius: 25,+ length: 70,+ capSegments: 8,+ radialSegments: 24,+ });+ expect(cap.bounds.size[0]).toBeCloseTo(50, 1);+ expect(cap.bounds.size[1]).toBeCloseTo(120, 1);+ expect(cap.bounds.size[2]).toBeCloseTo(50, 1);+ expectOutwardSolid(cap);+ });++ it("builds flat and thick-walled rings with outward normals", () => {+ const flatRing = generatePrimitiveGeometry({+ type: "ring",+ innerRadius: 30,+ outerRadius: 60,+ });+ expect(flatRing.bounds.size[0]).toBeCloseTo(120, 1);+ expect(flatRing.bounds.size[1]).toBeCloseTo(120, 1);+ expect(flatRing.bounds.size[2]).toBeCloseTo(0, 4);++ const solidRing = generatePrimitiveGeometry({+ type: "ring",+ innerRadius: 30,+ outerRadius: 60,+ depth: 16,+ });+ expect(solidRing.bounds.size[2]).toBeCloseTo(16, 4);+ const mesh = solidRing.meshes[0]!;+ const p = mesh.positions;+ const n = mesh.normals;+ const at = (i: number): V => [p[i * 3]!, p[i * 3 + 1]!, p[i * 3 + 2]!];+ const normalAt = (i: number): V => [+ n[i * 3]!,+ n[i * 3 + 1]!,+ n[i * 3 + 2]!,+ ];+ for (let t = 0; t < mesh.indices.length; t += 3) {+ const [i0, i1, i2] = [+ mesh.indices[t]!,+ mesh.indices[t + 1]!,+ mesh.indices[t + 2]!,+ ];+ const a = at(i0);+ const face = cross(sub(at(i1), a), sub(at(i2), a));+ if (Math.hypot(...face) < 1e-6) continue;+ expect(dot(face, normalAt(i0))).toBeGreaterThan(0);+ }+ });++ it("builds flat-shaded prisms and pyramids with caps and outward normals", () => {+ const hexPrism = generatePrimitiveGeometry({+ type: "cylinder",+ radiusTop: 40,+ radiusBottom: 40,+ height: 80,+ segments: 6,+ flatShaded: true,+ });+ expectOutwardSolid(hexPrism);++ const pyramid = generatePrimitiveGeometry({+ type: "cylinder",+ radiusTop: 0,+ radiusBottom: 50,+ height: 90,+ segments: 4,+ flatShaded: true,+ });+ expectOutwardSolid(pyramid);+ });++ it("builds all Platonic polyhedra and subdivided icospheres wound outward", () => {+ for (const shape of [+ "tetrahedron",+ "octahedron",+ "dodecahedron",+ "icosahedron",+ "icosphere",+ ] as const) {+ const model = generatePrimitiveGeometry({+ type: "polyhedron",+ shape,+ radius: 50,+ });+ expectOutwardSolid(model);+ }+ const subdivided = generatePrimitiveGeometry({+ type: "polyhedron",+ shape: "icosahedron",+ radius: 50,+ detail: 2,+ flatShaded: true,+ });+ expectOutwardSolid(subdivided);+ // 20 * 4^2 = 320 triangles -> 960 indices+ expect(subdivided.meshes[0]!.indices.length).toBe(20 * 16 * 3);+ });++ it("extrudes 2D SVG paths (with holes and bevels) and polygon contours", () => {+ const svgWithHole =+ "M 0 0 L 100 0 L 100 100 L 0 100 Z M 25 25 L 25 75 L 75 75 L 75 25 Z";+ const extruded = generatePrimitiveGeometry({+ type: "extrude",+ shape: svgWithHole,+ depth: 24,+ bevelThickness: 3,+ bevelSize: 2,+ bevelSegments: 2,+ color: "#38bdf8",+ bevelColor: "#0284c7",+ });+ expect(extruded.meshes.length).toBe(2);+ expect(extruded.bounds.size[0]).toBeCloseTo(100, 1);+ expect(extruded.bounds.size[1]).toBeCloseTo(100, 1);+ expect(extruded.bounds.size[2]).toBeCloseTo(24, 1);++ for (const mesh of extruded.meshes) {+ const p = mesh.positions;+ const n = mesh.normals;+ const at = (i: number): V => [p[i * 3]!, p[i * 3 + 1]!, p[i * 3 + 2]!];+ const normalAt = (i: number): V => [+ n[i * 3]!,+ n[i * 3 + 1]!,+ n[i * 3 + 2]!,+ ];+ for (let t = 0; t < mesh.indices.length; t += 3) {+ const [i0, i1, i2] = [+ mesh.indices[t]!,+ mesh.indices[t + 1]!,+ mesh.indices[t + 2]!,+ ];+ const a = at(i0);+ const face = cross(sub(at(i1), a), sub(at(i2), a));+ if (Math.hypot(...face) < 1e-6) continue;+ expect(dot(face, normalAt(i0))).toBeGreaterThan(0);+ }+ }+ });++ it("revolves a 2D profile with lathe and caps the ends", () => {+ const goblet = generatePrimitiveGeometry({+ type: "lathe",+ points: [+ [25, -50],+ [35, -10],+ [10, 20],+ [30, 50],+ ],+ segments: 24,+ capped: true,+ });+ expect(goblet.bounds.size[0]).toBeCloseTo(70, 1);+ expect(goblet.bounds.size[1]).toBeCloseTo(100, 1);+ const mesh = goblet.meshes[0]!;+ const p = mesh.positions;+ const n = mesh.normals;+ const at = (i: number): V => [p[i * 3]!, p[i * 3 + 1]!, p[i * 3 + 2]!];+ const normalAt = (i: number): V => [+ n[i * 3]!,+ n[i * 3 + 1]!,+ n[i * 3 + 2]!,+ ];+ for (let t = 0; t < mesh.indices.length; t += 3) {+ const [i0, i1, i2] = [+ mesh.indices[t]!,+ mesh.indices[t + 1]!,+ mesh.indices[t + 2]!,+ ];+ const a = at(i0);+ const face = cross(sub(at(i1), a), sub(at(i2), a));+ if (Math.hypot(...face) < 1e-6) continue;+ expect(dot(face, normalAt(i0))).toBeGreaterThan(0);+ }+ });++ it("sweeps solid and hollow thick-walled tubes along 3D paths", () => {+ const solidTube = generatePrimitiveGeometry({+ type: "tube",+ path: [+ [-100, 0, 0],+ [0, -60, 40],+ [100, 0, 0],+ ],+ radius: 14,+ tubularSegments: 32,+ radialSegments: 12,+ });+ expect(solidTube.bounds.size[0]).toBeGreaterThan(200);++ const hollowPipe = generatePrimitiveGeometry({+ type: "tube",+ path: {+ kind: "helix",+ radius: 60,+ pitch: 40,+ turns: 1.5,+ },+ radius: 14,+ innerRadius: 9,+ tubularSegments: 48,+ radialSegments: 12,+ });+ const mesh = hollowPipe.meshes[0]!;+ const p = mesh.positions;+ const n = mesh.normals;+ const at = (i: number): V => [p[i * 3]!, p[i * 3 + 1]!, p[i * 3 + 2]!];+ const normalAt = (i: number): V => [+ n[i * 3]!,+ n[i * 3 + 1]!,+ n[i * 3 + 2]!,+ ];+ for (let t = 0; t < mesh.indices.length; t += 3) {+ const [i0, i1, i2] = [+ mesh.indices[t]!,+ mesh.indices[t + 1]!,+ mesh.indices[t + 2]!,+ ];+ const a = at(i0);+ const face = cross(sub(at(i1), a), sub(at(i2), a));+ if (Math.hypot(...face) < 1e-6) continue;+ expect(dot(face, normalAt(i0))).toBeGreaterThan(0);+ }+ });++ it("builds 3D line-list and point-list / spherical point geometries", () => {+ const line = generatePrimitiveGeometry({+ type: "line3d",+ points: [+ [0, 0, 0],+ [100, 0, 0],+ [100, 100, 0],+ ],+ dashSize: 10,+ gapSize: 5,+ colors: ["#ff0000", "#00ff00", "#0000ff"],+ });+ expect(line.meshes[0]!.topology).toBe("line-list");+ expect(line.meshes[0]!.colors).toBeDefined();++ const pixelPoints = generatePrimitiveGeometry({+ type: "points3d",+ points: [+ [0, 0, 0],+ [50, 50, 50],+ ],+ });+ expect(pixelPoints.meshes[0]!.topology).toBe("point-list");++ const spherePoints = generatePrimitiveGeometry({+ type: "points3d",+ points: [+ [0, 0, 0],+ [50, 50, 50],+ ],+ pointSize: 6,+ });+ expect(spherePoints.meshes[0]!.topology).toBeUndefined();+ expect(spherePoints.meshes[0]!.indices.length).toBeGreaterThan(100);+ });});diff --git a/packages/webgpu-renderers/src/renderer3d/primitive-geometry.ts b/packages/webgpu-renderers/src/renderer3d/primitive-geometry.tsindex 8d5a95ab..f674d6ea 100644--- a/packages/webgpu-renderers/src/renderer3d/primitive-geometry.ts+++ b/packages/webgpu-renderers/src/renderer3d/primitive-geometry.ts@@ -1,5 +1,16 @@+import earcut from "earcut";import type { Material3D, Mesh3DData, Model3DData } from "../loaders/types.js";-import { parseHexOrRgbColor } from "./text-extruder.js";+import { Path3D } from "../math3d/path3d.js";+import type { Vec3 } from "../math3d/vector3.js";+import { sampleSvgArc } from "../renderer2d/path-geometry.js";+import {+ type Contour,+ type CurveFlattening,+ computeContourSignedArea,+ organizeGlyphPolygons,+ type Point2D,+ parseHexOrRgbColor,+} from "./text-extruder.js";/*** Procedural solids built as real meshes (one draw call each), centered on@@ -48,8 +59,197 @@ export interface CylinderGeometryOptions extends PrimitiveSurface {height: number;/** Segments around (default 32). */segments?: number;- /** Leave the caps off (a tube). */+ /** Leave the caps off (a thin open cylinder). */openEnded?: boolean;+ /** Render each lateral side as a flat-shaded facet instead of smooth-shaded (default false). */+ flatShaded?: boolean;+}++export interface TorusGeometryOptions extends PrimitiveSurface {+ type: "torus";+ /** Major radius from the torus center to the center of the tube (default 60). */+ radius?: number;+ /** Minor radius of the circular tube cross-section (default 20). */+ tube?: number;+ /** Segments around the tube cross-section (default 24). */+ radialSegments?: number;+ /** Segments around the main ring (default 48). */+ tubularSegments?: number;+ /** Central sweep angle in degrees (default 360). */+ arc?: number;+}++export interface CapsuleGeometryOptions extends PrimitiveSurface {+ type: "capsule";+ /** Radius of the cylinder body and hemispherical end caps (default 30). */+ radius?: number;+ /** Straight cylinder length between the hemisphere centers; total height is `length + 2 * radius` (default 60). */+ length?: number;+ /** Latitude rings per hemisphere cap (default 12). */+ capSegments?: number;+ /** Segments around the circumference (default 32). */+ radialSegments?: number;+}++export interface RingGeometryOptions extends PrimitiveSurface {+ type: "ring";+ /** Inner hole radius (default 30). */+ innerRadius?: number;+ /** Outer rim radius (default 60). */+ outerRadius?: number;+ /** Thick-walled depth along z (or y when `extrude` > 0); 0 or omitted builds a 2-sided flat annulus with front/back faces. */+ depth?: number;+ /** Segments around the ring (default 48). */+ thetaSegments?: number;+ /** Concentric radial subdivisions across the ring face (default 1). */+ phiSegments?: number;+ /** Start angle in degrees (default 0). */+ thetaStart?: number;+ /** Sweep angle in degrees (default 360). */+ thetaLength?: number;+}++export interface PolyhedronGeometryOptions extends PrimitiveSurface {+ type: "polyhedron";+ /** Base Platonic solid. Default "icosahedron". */+ shape?:+ | "tetrahedron"+ | "octahedron"+ | "dodecahedron"+ | "icosahedron"+ | "icosphere";+ /** Bounding sphere radius (default 50). */+ radius?: number;+ /** Geodesic subdivision levels (0..5): 0 keeps the base solid, >0 subdivides and projects onto the sphere. */+ detail?: number;+ /** Flat-shade each triangle facet (default true for polyhedra, false when `shape` is "icosphere" and `flatShaded` is omitted). */+ flatShaded?: boolean;+}++export interface ExtrudeShapeGeometryOptions extends PrimitiveSurface {+ type: "extrude";+ /** SVG path string (`M ... Z`, including holes/multiple subpaths) or one or more 2D point contours (`[x, y]` or `{x, y}`). */+ shape:+ | string+ | Array<[number, number] | Point2D>+ | Array<Array<[number, number] | Point2D>>;+ /** Extrusion thickness along Z (default 20). */+ depth?: number;+ /** Optional bevel thickness along Z at front and back caps (default 0). */+ bevelThickness?: number;+ /** Optional bevel radial inset/outset in XY (default `bevelThickness`). */+ bevelSize?: number;+ /** Bevel steps (default 1 when bevelThickness > 0). */+ bevelSegments?: number;+ /** Color of the side walls and bevels; defaults to `color`. */+ bevelColor?: string;+ /** Fixed straight segments per curve. */+ curveSegments?: number;+ /** Max curve chord error in px (default 0.25). */+ curveTolerance?: number;+ /** Center the extruded 2D outline around (0, 0) in local XY (default true). */+ center?: boolean;+}++export interface LatheGeometryOptions extends PrimitiveSurface {+ type: "lathe";+ /**+ * Profile curve in the XY plane revolved around the Y axis, as `[[r, y], ...]`+ * (or `{x, y}`) or an SVG path string. `x` (radius >= 0) is distance from the Y axis.+ */+ points: string | Array<[number, number] | Point2D>;+ /** Circumferential segments around the Y axis (default 32). */+ segments?: number;+ /** Start angle in degrees (default 0). */+ phiStart?: number;+ /** Sweep angle in degrees (default 360). */+ phiLength?: number;+ /** Cap the top and bottom openings when the profile starts/ends away from r = 0 (default false). */+ capped?: boolean;+ /** Flat-shade longitudinal segments (default false). */+ flatShaded?: boolean;+}++export type TubePathSpec =+ | {+ kind: "catmullRom";+ points: Vec3[];+ tension?: number;+ closed?: boolean;+ samplesPerSegment?: number;+ }+ | {+ kind: "bezier";+ segments: Array<{ p0: Vec3; p1: Vec3; p2: Vec3; p3: Vec3 }>;+ samplesPerSegment?: number;+ }+ | {+ kind: "helix";+ center?: Vec3;+ radius: number;+ pitch: number;+ turns: number;+ axis?: "x" | "y" | "z";+ samplesPerTurn?: number;+ }+ | {+ kind: "circle";+ center?: Vec3;+ radius: number;+ startAngleDeg?: number;+ endAngleDeg?: number;+ samples?: number;+ }+ | Vec3[];++export interface TubeGeometryOptions extends PrimitiveSurface {+ type: "tube";+ /** 3D path specification or array of 3D waypoints `[x, y, z]`. */+ path: TubePathSpec;+ /** Outer radius of the tube (default 12). */+ radius?: number;+ /** Optional inner radius for a thick-walled hollow pipe (0 = solid tube with end caps). */+ innerRadius?: number;+ /** Optional end-to-end radius taper `[radiusStart, radiusEnd]`. */+ radiusTaper?: [number, number];+ /** Segments along the 3D path (default 64). */+ tubularSegments?: number;+ /** Segments around the circular cross-section (default 16). */+ radialSegments?: number;+ /** Close the tube loop smoothly from end to start (default false). */+ closed?: boolean;+ /** Cap the ends when not closed (default true). */+ capped?: boolean;+}++export interface Line3DGeometryOptions extends PrimitiveSurface {+ type: "line3d";+ /** 3D polyline points `[x, y, z]` or a `TubePathSpec` curve. */+ points: TubePathSpec;+ /** Optional per-vertex CSS colors matching `points`. */+ colors?: string[];+ /** Connect consecutive points (`"strip"`, default) or pairs `(0,1), (2,3), ...` (`"segments"`). */+ mode?: "strip" | "segments";+ /** Close the polyline back to point 0 (default false). */+ closed?: boolean;+ /** Optional dash length in world px for dashed 3D diagram lines. */+ dashSize?: number;+ /** Gap length between dashes in world px (default `dashSize`). */+ gapSize?: number;+}++export interface Points3DGeometryOptions extends PrimitiveSurface {+ type: "points3d";+ /** 3D point coordinates `[x, y, z]` or a `TubePathSpec` curve. */+ points: TubePathSpec;+ /** Optional per-point CSS colors. */+ colors?: string[];+ /**+ * Point radius in world px. When > 0 (default 0 = native GPU `point-list` pixels),+ * each point is tessellated into a low-poly icosahedral dot of radius `pointSize`+ * so diagram nodes have real 3D thickness and perspective size.+ */+ pointSize?: number;}export interface ShardGeometryOptions extends PrimitiveSurface {@@ -70,18 +270,37 @@ export type PrimitiveGeometryOptions =| RoundedBoxGeometryOptions| SphereGeometryOptions| CylinderGeometryOptions+ | TorusGeometryOptions+ | CapsuleGeometryOptions+ | RingGeometryOptions+ | PolyhedronGeometryOptions+ | ExtrudeShapeGeometryOptions+ | LatheGeometryOptions+ | TubeGeometryOptions+ | Line3DGeometryOptions+ | Points3DGeometryOptions| ShardGeometryOptions;class MeshBuilder {positions: number[] = [];normals: number[] = [];uvs: number[] = [];+ colors: number[] = [];indices: number[] = [];+ topology?: "triangle-list" | "line-list" | "point-list";- vertex(p: number[], n: number[], uv: [number, number]): number {+ vertex(+ p: number[],+ n: number[],+ uv: [number, number],+ color?: [number, number, number, number],+ ): number {this.positions.push(p[0]!, p[1]!, p[2]!);this.normals.push(n[0]!, n[1]!, n[2]!);this.uvs.push(uv[0], uv[1]);+ if (color) {+ this.colors.push(color[0], color[1], color[2], color[3]);+ }return this.positions.length / 3 - 1;}@@ -105,7 +324,7 @@ class MeshBuilder {build(name: string): Mesh3DData {const count = this.positions.length / 3;- return {+ const mesh: Mesh3DData = {id: `${name}-mesh`,name,positions: new Float32Array(this.positions),@@ -117,14 +336,37 @@ class MeshBuilder {: new Uint16Array(this.indices),materialName: `${name}-material`,};+ if (this.topology) mesh.topology = this.topology;+ if (this.colors.length === count * 4 && this.colors.length > 0) {+ mesh.colors = new Float32Array(this.colors);+ }+ return mesh;}}-function normalize(v: number[]): number[] {+type V3 = [number, number, number];++function normalize(v: number[]): V3 {const len = Math.hypot(v[0]!, v[1]!, v[2]!);return len > 1e-12 ? [v[0]! / len, v[1]! / len, v[2]! / len] : [0, 0, 0];}+function sub3(a: V3, b: V3): V3 {+ return [a[0] - b[0], a[1] - b[1], a[2] - b[2]];+}++function dot3(a: V3, b: V3): number {+ return a[0] * b[0] + a[1] * b[1] + a[2] * b[2];+}++function cross3(a: V3, b: V3): V3 {+ return [+ a[1] * b[2] - a[2] * b[1],+ a[2] * b[0] - a[0] * b[2],+ a[0] * b[1] - a[1] * b[0],+ ];+}+/*** 1D samples across a side of half-extent `e` whose ends round off with* radius `r`: arc-spaced through each rounded zone, nothing in between, so@@ -167,7 +409,7 @@ function roundedBox(o: RoundedBoxGeometryOptions, mb: MeshBuilder): void {Math.max(-iy, Math.min(iy, surface[1]!)),Math.max(-iz, Math.min(iz, surface[2]!)),];- let n =+ let n: number[] =r > 0? normalize([surface[0]! - inner[0]!,@@ -258,28 +500,71 @@ function sphere(o: SphereGeometryOptions, mb: MeshBuilder): void {function cylinder(o: CylinderGeometryOptions, mb: MeshBuilder): void {const seg = Math.max(3, Math.round(o.segments ?? 32));- const rTop = o.radiusTop ?? o.radius ?? 50;- const rBottom = o.radiusBottom ?? o.radius ?? 50;+ const rTop = Math.max(0, o.radiusTop ?? o.radius ?? 50);+ const rBottom = Math.max(0, o.radiusBottom ?? o.radius ?? 50);const hy = o.height / 2;- // Side normals lean by the cone's slope.- const lean = o.height > 0 ? (rBottom - rTop) / o.height : 0;- for (let j = 0; j <= 1; j++) {- const rr = j === 0 ? rTop : rBottom;- const y = j === 0 ? -hy : hy;- for (let i = 0; i <= seg; i++) {- const theta = (i / seg) * Math.PI * 2;- const c = Math.cos(theta);- const s = Math.sin(theta);- mb.vertex([c * rr, y, s * rr], normalize([c, -lean, s]), [i / seg, j]);++ if (o.flatShaded) {+ for (let i = 0; i < seg; i++) {+ const theta0 = (i / seg) * Math.PI * 2;+ const theta1 = ((i + 1) / seg) * Math.PI * 2;+ const c0 = Math.cos(theta0);+ const s0 = Math.sin(theta0);+ const c1 = Math.cos(theta1);+ const s1 = Math.sin(theta1);++ const t0: V3 = [c0 * rTop, -hy, s0 * rTop];+ const t1: V3 = [c1 * rTop, -hy, s1 * rTop];+ const b0: V3 = [c0 * rBottom, hy, s0 * rBottom];+ const b1: V3 = [c1 * rBottom, hy, s1 * rBottom];++ // Outward normal of the quad facet (or triangle when rTop === 0).+ const edgeV = sub3(b0, t0);+ const edgeU = rBottom >= rTop ? sub3(b1, b0) : sub3(t1, t0);+ const fn = normalize(cross3(edgeV, edgeU));++ const u0 = i / seg;+ const u1 = (i + 1) / seg;+ if (rTop <= 1e-6) {+ const apex = mb.vertex([0, -hy, 0], fn, [(u0 + u1) / 2, 0]);+ const vB0 = mb.vertex(b0, fn, [u0, 1]);+ const vB1 = mb.vertex(b1, fn, [u1, 1]);+ mb.indices.push(apex, vB0, vB1);+ } else if (rBottom <= 1e-6) {+ const vT0 = mb.vertex(t0, fn, [u0, 0]);+ const vT1 = mb.vertex(t1, fn, [u1, 0]);+ const apex = mb.vertex([0, hy, 0], fn, [(u0 + u1) / 2, 1]);+ mb.indices.push(vT0, apex, vT1);+ } else {+ const base = mb.vertex(t0, fn, [u0, 0]);+ mb.vertex(t1, fn, [u1, 0]);+ mb.vertex(b0, fn, [u0, 1]);+ mb.vertex(b1, fn, [u1, 1]);+ mb.indices.push(base, base + 2, base + 1, base + 1, base + 2, base + 3);+ }+ }+ } else {+ // Side normals lean by the cone's slope.+ const lean = o.height > 0 ? (rBottom - rTop) / o.height : 0;+ for (let j = 0; j <= 1; j++) {+ const rr = j === 0 ? rTop : rBottom;+ const y = j === 0 ? -hy : hy;+ for (let i = 0; i <= seg; i++) {+ const theta = (i / seg) * Math.PI * 2;+ const c = Math.cos(theta);+ const s = Math.sin(theta);+ mb.vertex([c * rr, y, s * rr], normalize([c, -lean, s]), [i / seg, j]);+ }}+ mb.grid(0, seg, 1);}- mb.grid(0, seg, 1);+if (o.openEnded) return;for (const [y, rr, ny] of [[-hy, rTop, -1],[hy, rBottom, 1],] as const) {- if (rr <= 0) continue;+ if (rr <= 1e-6) continue;const center = mb.vertex([0, y, 0], [0, ny, 0], [0.5, 0.5]);const ring = mb.positions.length / 3;for (let i = 0; i <= seg; i++) {@@ -296,6 +581,1649 @@ function cylinder(o: CylinderGeometryOptions, mb: MeshBuilder): void {}}+/**+ * Torus centered at origin lying in the XY plane (so its hole faces a default+ * camera looking along +Z), with major radius `radius` and tube radius `tube`.+ */+function torus(o: TorusGeometryOptions, mb: MeshBuilder): void {+ const R = Math.max(1e-3, o.radius ?? 60);+ const r = Math.max(1e-3, o.tube ?? 20);+ const radialSegments = Math.max(3, Math.round(o.radialSegments ?? 24));+ const tubularSegments = Math.max(3, Math.round(o.tubularSegments ?? 48));+ const arcDeg = o.arc ?? 360;+ const arcRad = (arcDeg * Math.PI) / 180;+ const base = mb.positions.length / 3;++ for (let j = 0; j <= radialSegments; j++) {+ const v = (j / radialSegments) * Math.PI * 2;+ const cv = Math.cos(v);+ const sv = Math.sin(v);+ for (let i = 0; i <= tubularSegments; i++) {+ const u = (i / tubularSegments) * arcRad;+ const cu = Math.cos(u);+ const su = Math.sin(u);+ const x = (R + r * cv) * cu;+ const y = (R + r * cv) * su;+ const z = r * sv;+ const nx = cv * cu;+ const ny = cv * su;+ const nz = sv;+ mb.vertex([x, y, z], normalize([nx, ny, nz]), [+ i / tubularSegments,+ j / radialSegments,+ ]);+ }+ }+ // ∂p/∂v × ∂p/∂u points along (-cv cu, -cv su, -sv), so flip = true winds outward.+ mb.grid(base, tubularSegments, radialSegments, true);++ // Cap open ends when arc < 360°.+ if (Math.abs(arcRad) < Math.PI * 2 - 1e-4) {+ for (const [u, sign] of [+ [0, -1],+ [arcRad, 1],+ ] as const) {+ const cu = Math.cos(u);+ const su = Math.sin(u);+ // Tangent at angle u is (-su, cu, 0); cap normal points in sign * tangent.+ const capN: V3 = [-su * sign, cu * sign, 0];+ const center = mb.vertex([R * cu, R * su, 0], capN, [0.5, 0.5]);+ const ring = mb.positions.length / 3;+ for (let j = 0; j <= radialSegments; j++) {+ const v = (j / radialSegments) * Math.PI * 2;+ const cv = Math.cos(v);+ const sv = Math.sin(v);+ mb.vertex([(R + r * cv) * cu, (R + r * cv) * su, r * sv], capN, [+ (cv + 1) / 2,+ (sv + 1) / 2,+ ]);+ }+ for (let j = 0; j < radialSegments; j++) {+ if (sign > 0) mb.indices.push(center, ring + j, ring + j + 1);+ else mb.indices.push(center, ring + j + 1, ring + j);+ }+ }+ }+}++/**+ * Capsule aligned along the Y axis: a cylinder of height `length` and radius `radius`+ * capped by top (-y) and bottom (+y) hemispheres of radius `radius`.+ */+function capsule(o: CapsuleGeometryOptions, mb: MeshBuilder): void {+ const r = Math.max(1e-3, o.radius ?? 30);+ const length = Math.max(0, o.length ?? 60);+ const hy = length / 2;+ const capSeg = Math.max(2, Math.round(o.capSegments ?? 12));+ const radSeg = Math.max(3, Math.round(o.radialSegments ?? 32));++ // Build profile rings from top pole (y = -hy - r) down to bottom pole (y = +hy + r).+ const rings: Array<{+ y: number;+ rRing: number;+ ny: number;+ nr: number;+ v: number;+ }> = [];+ const totalArc = Math.PI * r + length;++ for (let j = 0; j <= capSeg; j++) {+ const phi = ((j / capSeg) * Math.PI) / 2; // 0 at top pole, pi/2 at top equator+ const s = Math.sin(phi);+ const c = Math.cos(phi);+ rings.push({+ y: -hy - r * c,+ rRing: r * s,+ ny: -c,+ nr: s,+ v: (phi * r) / (totalArc || 1),+ });+ }+ for (let j = 0; j <= capSeg; j++) {+ if (j === 0 && length <= 1e-6) continue;+ const phi = Math.PI / 2 + ((j / capSeg) * Math.PI) / 2; // pi/2 at bottom equator, pi at bottom pole+ const s = Math.sin(phi);+ const c = Math.cos(phi);+ rings.push({+ y: hy - r * c,+ rRing: r * s,+ ny: -c,+ nr: s,+ v:+ ((Math.PI / 2) * r + length + (phi - Math.PI / 2) * r) /+ (totalArc || 1),+ });+ }++ const base = mb.positions.length / 3;+ for (const ring of rings) {+ for (let i = 0; i <= radSeg; i++) {+ const theta = (i / radSeg) * Math.PI * 2;+ const ct = Math.cos(theta);+ const st = Math.sin(theta);+ const n = normalize([ring.nr * ct, ring.ny, ring.nr * st]);+ mb.vertex([ring.rRing * ct, ring.y, ring.rRing * st], n, [+ i / radSeg,+ ring.v,+ ]);+ }+ }+ mb.grid(base, radSeg, rings.length - 1, false);+}++/**+ * Flat or thick-walled annulus (ring) in the XY plane facing -Z (front) and +Z (back).+ * Always builds a closed two-sided or solid manifold so it works with single-sided culling.+ */+function ring(o: RingGeometryOptions, mb: MeshBuilder): void {+ const rInner = Math.max(0, o.innerRadius ?? 30);+ const rOuter = Math.max(rInner + 1e-3, o.outerRadius ?? 60);+ const hz = Math.max(0, o.depth ?? 0) / 2;+ const thetaSeg = Math.max(3, Math.round(o.thetaSegments ?? 48));+ const phiSeg = Math.max(1, Math.round(o.phiSegments ?? 1));+ const thetaStart = ((o.thetaStart ?? 0) * Math.PI) / 180;+ const thetaLength = ((o.thetaLength ?? 360) * Math.PI) / 180;++ // Front face (-z, normal [0, 0, -1]) and back face (+z, normal [0, 0, 1])+ for (const [z, nz, flip] of [+ [-hz, -1, false],+ [hz, 1, true],+ ] as const) {+ const base = mb.positions.length / 3;+ for (let j = 0; j <= phiSeg; j++) {+ const radius = rInner + ((rOuter - rInner) * j) / phiSeg;+ for (let i = 0; i <= thetaSeg; i++) {+ const theta = thetaStart + (i / thetaSeg) * thetaLength;+ const c = Math.cos(theta);+ const s = Math.sin(theta);+ const x = radius * c;+ const y = radius * s;+ mb.vertex(+ [x, y, z],+ [0, 0, nz],+ [(x / rOuter + 1) / 2, (y / rOuter + 1) / 2],+ );+ }+ }+ // ∂p/∂j = (c, s, 0), ∂p/∂i = (-s, c, 0) -> ∂p/∂j × ∂p/∂i = (0, 0, +1).+ // So for front face (nz = -1) we need flip = true, for back face (nz = +1) flip = false.+ mb.grid(base, thetaSeg, phiSeg, !flip);+ }++ // If depth > 0, stitch outer rim, inner hole wall, and any open sector ends.+ if (hz > 0) {+ // Outer rim (outward normal [cos θ, sin θ, 0])+ const outerBase = mb.positions.length / 3;+ for (const [z, v] of [+ [-hz, 0],+ [hz, 1],+ ] as const) {+ for (let i = 0; i <= thetaSeg; i++) {+ const theta = thetaStart + (i / thetaSeg) * thetaLength;+ const c = Math.cos(theta);+ const s = Math.sin(theta);+ mb.vertex([rOuter * c, rOuter * s, z], [c, s, 0], [i / thetaSeg, v]);+ }+ }+ mb.grid(outerBase, thetaSeg, 1, true);++ // Inner hole wall (outward normal [-cos θ, -sin θ, 0])+ if (rInner > 1e-6) {+ const innerBase = mb.positions.length / 3;+ for (const [z, v] of [+ [-hz, 0],+ [hz, 1],+ ] as const) {+ for (let i = 0; i <= thetaSeg; i++) {+ const theta = thetaStart + (i / thetaSeg) * thetaLength;+ const c = Math.cos(theta);+ const s = Math.sin(theta);+ mb.vertex(+ [rInner * c, rInner * s, z],+ [-c, -s, 0],+ [i / thetaSeg, v],+ );+ }+ }+ mb.grid(innerBase, thetaSeg, 1, false);+ }++ // Sector end caps when thetaLength < 360°+ if (Math.abs(thetaLength) < Math.PI * 2 - 1e-4) {+ for (const [theta, sign] of [+ [thetaStart, -1],+ [thetaStart + thetaLength, 1],+ ] as const) {+ const c = Math.cos(theta);+ const s = Math.sin(theta);+ const capN: V3 = [-s * sign, c * sign, 0];+ const p0 = mb.vertex([rInner * c, rInner * s, -hz], capN, [0, 0]);+ const p1 = mb.vertex([rOuter * c, rOuter * s, -hz], capN, [1, 0]);+ const p2 = mb.vertex([rInner * c, rInner * s, hz], capN, [0, 1]);+ const p3 = mb.vertex([rOuter * c, rOuter * s, hz], capN, [1, 1]);+ if (sign > 0) mb.indices.push(p0, p2, p1, p1, p2, p3);+ else mb.indices.push(p0, p1, p2, p1, p3, p2);+ }+ }+ }+}++/**+ * Platonic solids (tetrahedron, octahedron, dodecahedron, icosahedron) and+ * geodesic icosphere with configurable subdivision `detail`.+ */+function polyhedron(o: PolyhedronGeometryOptions, mb: MeshBuilder): void {+ const shape = o.shape ?? "icosahedron";+ const radius = Math.max(1e-3, o.radius ?? 50);+ const detail = Math.max(+ 0,+ Math.min(5, Math.round(o.detail ?? (shape === "icosphere" ? 2 : 0))),+ );+ const flatShaded = o.flatShaded ?? shape !== "icosphere";++ let baseVerts: V3[] = [];+ let baseFaces: number[][] = [];++ if (shape === "tetrahedron") {+ baseVerts = [+ [1, 1, 1],+ [-1, -1, 1],+ [-1, 1, -1],+ [1, -1, -1],+ ];+ baseFaces = [+ [2, 1, 0],+ [0, 3, 2],+ [1, 3, 0],+ [2, 3, 1],+ ];+ } else if (shape === "octahedron") {+ baseVerts = [+ [1, 0, 0],+ [-1, 0, 0],+ [0, 1, 0],+ [0, -1, 0],+ [0, 0, 1],+ [0, 0, -1],+ ];+ baseFaces = [+ [0, 2, 4],+ [0, 4, 3],+ [0, 3, 5],+ [0, 5, 2],+ [1, 2, 5],+ [1, 5, 3],+ [1, 3, 4],+ [1, 4, 2],+ ];+ } else if (shape === "dodecahedron") {+ const t = (1 + Math.sqrt(5)) / 2;+ const r = 1 / t;+ baseVerts = [+ // (±1, ±1, ±1)+ [-1, -1, -1],+ [-1, -1, 1],+ [-1, 1, -1],+ [-1, 1, 1],+ [1, -1, -1],+ [1, -1, 1],+ [1, 1, -1],+ [1, 1, 1],+ // (0, ±1/φ, ±φ)+ [0, -r, -t],+ [0, -r, t],+ [0, r, -t],+ [0, r, t],+ // (±1/φ, ±φ, 0)+ [-r, -t, 0],+ [-r, t, 0],+ [r, -t, 0],+ [r, t, 0],+ // (±φ, 0, ±1/φ)+ [-t, 0, -r],+ [t, 0, -r],+ [-t, 0, r],+ [t, 0, r],+ ];+ // 12 pentagonal faces (when detail === 0 and flatShaded, keep each pentagon planar!)+ const pentagons: number[][] = [+ [3, 11, 7, 15, 13],+ [7, 19, 17, 6, 15],+ [17, 4, 8, 10, 6],+ [8, 0, 16, 2, 10],+ [0, 12, 1, 18, 16],+ [6, 10, 2, 13, 15],+ [2, 16, 18, 3, 13],+ [18, 1, 9, 11, 3],+ [4, 14, 12, 0, 8],+ [11, 9, 5, 19, 7],+ [19, 5, 14, 4, 17],+ [1, 12, 14, 5, 9],+ ];+ if (detail === 0 && flatShaded) {+ const unitVerts = baseVerts.map((v) => normalize(v));+ for (const pent of pentagons) {+ const pts = pent.map((idx) => unitVerts[idx]!);+ const center: V3 = [+ pts.reduce((s, p) => s + p[0], 0) / 5,+ pts.reduce((s, p) => s + p[1], 0) / 5,+ pts.reduce((s, p) => s + p[2], 0) / 5,+ ];+ let fn = normalize(+ cross3(sub3(pts[1]!, pts[0]!), sub3(pts[2]!, pts[0]!)),+ );+ if (dot3(fn, center) < 0) {+ pts.reverse();+ fn = [-fn[0], -fn[1], -fn[2]];+ }+ const base = mb.positions.length / 3;+ for (const p of pts) {+ const u = 0.5 + Math.atan2(p[2], p[0]) / (2 * Math.PI);+ const v = Math.acos(Math.max(-1, Math.min(1, -p[1]))) / Math.PI;+ mb.vertex([p[0] * radius, p[1] * radius, p[2] * radius], fn, [u, v]);+ }+ for (let k = 1; k < pts.length - 1; k++) {+ mb.indices.push(base, base + k, base + k + 1);+ }+ }+ return;+ }+ for (const p of pentagons) {+ baseFaces.push(+ [p[0]!, p[1]!, p[2]!],+ [p[0]!, p[2]!, p[3]!],+ [p[0]!, p[3]!, p[4]!],+ );+ }+ } else {+ // icosahedron or icosphere+ const t = (1 + Math.sqrt(5)) / 2;+ baseVerts = [+ [-1, t, 0],+ [1, t, 0],+ [-1, -t, 0],+ [1, -t, 0],+ [0, -1, t],+ [0, 1, t],+ [0, -1, -t],+ [0, 1, -t],+ [t, 0, -1],+ [t, 0, 1],+ [-t, 0, -1],+ [-t, 0, 1],+ ];+ baseFaces = [+ [0, 11, 5],+ [0, 5, 1],+ [0, 1, 7],+ [0, 7, 10],+ [0, 10, 11],+ [1, 5, 9],+ [5, 11, 4],+ [11, 10, 2],+ [10, 7, 6],+ [7, 1, 8],+ [3, 9, 4],+ [3, 4, 2],+ [3, 2, 6],+ [3, 6, 8],+ [3, 8, 9],+ [4, 9, 5],+ [2, 4, 11],+ [6, 2, 10],+ [8, 6, 7],+ [9, 8, 1],+ ];+ }++ const verts: V3[] = baseVerts.map((v) => normalize(v));+ let tris: [number, number, number][] = baseFaces.map((f) => [+ f[0]!,+ f[1]!,+ f[2]!,+ ]);++ // Subdivide each triangle into 4 per level and project onto unit sphere.+ for (let d = 0; d < detail; d++) {+ const midCache = new Map<string, number>();+ const midpoint = (a: number, b: number): number => {+ const key = a < b ? `${a}_${b}` : `${b}_${a}`;+ const existing = midCache.get(key);+ if (existing !== undefined) return existing;+ const va = verts[a]!;+ const vb = verts[b]!;+ const idx = verts.length;+ verts.push(normalize([va[0] + vb[0], va[1] + vb[1], va[2] + vb[2]]));+ midCache.set(key, idx);+ return idx;+ };+ const nextTris: [number, number, number][] = [];+ for (const [i0, i1, i2] of tris) {+ const m01 = midpoint(i0, i1);+ const m12 = midpoint(i1, i2);+ const m20 = midpoint(i2, i0);+ nextTris.push(+ [i0, m01, m20],+ [i1, m12, m01],+ [i2, m20, m12],+ [m01, m12, m20],+ );+ }+ tris = nextTris;+ }++ const uvOf = (n: V3): [number, number] => [+ 0.5 + Math.atan2(n[2], n[0]) / (2 * Math.PI),+ Math.acos(Math.max(-1, Math.min(1, -n[1]))) / Math.PI,+ ];++ if (flatShaded) {+ for (const [i0, i1, i2] of tris) {+ const a = verts[i0]!;+ let b = verts[i1]!;+ let c = verts[i2]!;+ const centroid: V3 = [+ (a[0] + b[0] + c[0]) / 3,+ (a[1] + b[1] + c[1]) / 3,+ (a[2] + b[2] + c[2]) / 3,+ ];+ let fn = normalize(cross3(sub3(b, a), sub3(c, a)));+ if (dot3(fn, centroid) < 0) {+ const tmp = b;+ b = c;+ c = tmp;+ fn = [-fn[0], -fn[1], -fn[2]];+ }+ const base = mb.positions.length / 3;+ mb.vertex([a[0] * radius, a[1] * radius, a[2] * radius], fn, uvOf(a));+ mb.vertex([b[0] * radius, b[1] * radius, b[2] * radius], fn, uvOf(b));+ mb.vertex([c[0] * radius, c[1] * radius, c[2] * radius], fn, uvOf(c));+ mb.indices.push(base, base + 1, base + 2);+ }+ } else {+ const base = mb.positions.length / 3;+ for (const n of verts) {+ mb.vertex([n[0] * radius, n[1] * radius, n[2] * radius], n, uvOf(n));+ }+ for (const [i0, i1, i2] of tris) {+ const a = verts[i0]!;+ const b = verts[i1]!;+ const c = verts[i2]!;+ const centroid: V3 = [+ (a[0] + b[0] + c[0]) / 3,+ (a[1] + b[1] + c[1]) / 3,+ (a[2] + b[2] + c[2]) / 3,+ ];+ const fn = cross3(sub3(b, a), sub3(c, a));+ if (dot3(fn, centroid) < 0) {+ mb.indices.push(base + i0, base + i2, base + i1);+ } else {+ mb.indices.push(base + i0, base + i1, base + i2);+ }+ }+ }+}++/**+ * Parses an SVG path string (supporting M, L, H, V, C, S, Q, T, A, Z and multiple subpaths)+ * into closed 2D contours with adaptive or fixed curve flattening.+ */+function parseSvgPathToContours(+ d: string,+ flattening: CurveFlattening,+): Contour[] {+ const contours: Contour[] = [];+ if (!d || typeof d !== "string") return contours;++ const tokens: Array<string | number> = [];+ const regex = /([a-df-z])|([-+]?(?:\d*\.\d+|\d+)(?:[eE][-+]?\d+)?)/gi;+ let match: RegExpExecArray | null = regex.exec(d);+ while (match !== null) {+ if (match[1]) tokens.push(match[1]);+ else if (match[2]) tokens.push(Number.parseFloat(match[2]));+ match = regex.exec(d);+ }++ let cursor = 0;+ let current: Point2D = { x: 0, y: 0 };+ let subpathStart: Point2D = { x: 0, y: 0 };+ let lastCubicControl: Point2D | null = null;+ let lastQuadControl: Point2D | null = null;+ let contour: Contour = [];++ const finishContour = () => {+ if (contour.length >= 2) {+ const first = contour[0]!;+ const last = contour[contour.length - 1]!;+ if (Math.hypot(last.x - first.x, last.y - first.y) < 1e-4) {+ contour.pop();+ }+ if (contour.length >= 2) {+ contours.push(contour);+ }+ }+ contour = [];+ };++ const segCount = (maxSecondDeriv: number): number => {+ if (flattening.segments !== undefined)+ return Math.max(1, flattening.segments);+ const n = Math.ceil(+ Math.sqrt(maxSecondDeriv / (8 * Math.max(1e-3, flattening.tolerance))),+ );+ return Math.min(64, Math.max(1, n));+ };++ const addQuad = (p0: Point2D, cp: Point2D, end: Point2D) => {+ const n = segCount(+ 2 * Math.hypot(p0.x - 2 * cp.x + end.x, p0.y - 2 * cp.y + end.y),+ );+ for (let s = 1; s <= n; s++) {+ const t = s / n;+ const mt = 1 - t;+ contour.push({+ x: mt * mt * p0.x + 2 * mt * t * cp.x + t * t * end.x,+ y: mt * mt * p0.y + 2 * mt * t * cp.y + t * t * end.y,+ });+ }+ };++ const addCubic = (p0: Point2D, cp1: Point2D, cp2: Point2D, end: Point2D) => {+ const n = segCount(+ 6 *+ Math.max(+ Math.hypot(p0.x - 2 * cp1.x + cp2.x, p0.y - 2 * cp1.y + cp2.y),+ Math.hypot(cp1.x - 2 * cp2.x + end.x, cp1.y - 2 * cp2.y + end.y),+ ),+ );+ for (let s = 1; s <= n; s++) {+ const t = s / n;+ const mt = 1 - t;+ contour.push({+ x:+ mt * mt * mt * p0.x ++ 3 * mt * mt * t * cp1.x ++ 3 * mt * t * t * cp2.x ++ t * t * t * end.x,+ y:+ mt * mt * mt * p0.y ++ 3 * mt * mt * t * cp1.y ++ 3 * mt * t * t * cp2.y ++ t * t * t * end.y,+ });+ }+ };++ const getNum = (): number =>+ cursor < tokens.length && typeof tokens[cursor] === "number"+ ? (tokens[cursor++] as number)+ : 0;++ while (cursor < tokens.length) {+ const cmdToken = tokens[cursor++];+ if (typeof cmdToken !== "string") continue;+ const isRel = cmdToken === cmdToken.toLowerCase();+ const upper = cmdToken.toUpperCase();++ switch (upper) {+ case "M": {+ finishContour();+ let first = true;+ while (cursor < tokens.length && typeof tokens[cursor] === "number") {+ let x = getNum();+ let y = getNum();+ if (isRel) {+ x += current.x;+ y += current.y;+ }+ current = { x, y };+ if (first) {+ subpathStart = current;+ contour = [current];+ first = false;+ } else {+ contour.push(current);+ }+ }+ lastCubicControl = null;+ lastQuadControl = null;+ break;+ }+ case "L": {+ while (cursor < tokens.length && typeof tokens[cursor] === "number") {+ let x = getNum();+ let y = getNum();+ if (isRel) {+ x += current.x;+ y += current.y;+ }+ current = { x, y };+ contour.push(current);+ }+ lastCubicControl = null;+ lastQuadControl = null;+ break;+ }+ case "H": {+ while (cursor < tokens.length && typeof tokens[cursor] === "number") {+ let x = getNum();+ if (isRel) x += current.x;+ current = { x, y: current.y };+ contour.push(current);+ }+ lastCubicControl = null;+ lastQuadControl = null;+ break;+ }+ case "V": {+ while (cursor < tokens.length && typeof tokens[cursor] === "number") {+ let y = getNum();+ if (isRel) y += current.y;+ current = { x: current.x, y };+ contour.push(current);+ }+ lastCubicControl = null;+ lastQuadControl = null;+ break;+ }+ case "C": {+ while (cursor < tokens.length && typeof tokens[cursor] === "number") {+ let x1 = getNum();+ let y1 = getNum();+ let x2 = getNum();+ let y2 = getNum();+ let x = getNum();+ let y = getNum();+ if (isRel) {+ x1 += current.x;+ y1 += current.y;+ x2 += current.x;+ y2 += current.y;+ x += current.x;+ y += current.y;+ }+ const cp1 = { x: x1, y: y1 };+ const cp2 = { x: x2, y: y2 };+ const end = { x, y };+ addCubic(current, cp1, cp2, end);+ current = end;+ lastCubicControl = cp2;+ }+ lastQuadControl = null;+ break;+ }+ case "S": {+ while (cursor < tokens.length && typeof tokens[cursor] === "number") {+ let x2 = getNum();+ let y2 = getNum();+ let x = getNum();+ let y = getNum();+ if (isRel) {+ x2 += current.x;+ y2 += current.y;+ x += current.x;+ y += current.y;+ }+ const cp1: Point2D = lastCubicControl+ ? {+ x: 2 * current.x - lastCubicControl.x,+ y: 2 * current.y - lastCubicControl.y,+ }+ : current;+ const cp2 = { x: x2, y: y2 };+ const end = { x, y };+ addCubic(current, cp1, cp2, end);+ current = end;+ lastCubicControl = cp2;+ }+ lastQuadControl = null;+ break;+ }+ case "Q": {+ while (cursor < tokens.length && typeof tokens[cursor] === "number") {+ let x1 = getNum();+ let y1 = getNum();+ let x = getNum();+ let y = getNum();+ if (isRel) {+ x1 += current.x;+ y1 += current.y;+ x += current.x;+ y += current.y;+ }+ const cp = { x: x1, y: y1 };+ const end = { x, y };+ addQuad(current, cp, end);+ current = end;+ lastQuadControl = cp;+ }+ lastCubicControl = null;+ break;+ }+ case "T": {+ while (cursor < tokens.length && typeof tokens[cursor] === "number") {+ let x = getNum();+ let y = getNum();+ if (isRel) {+ x += current.x;+ y += current.y;+ }+ const cp: Point2D = lastQuadControl+ ? {+ x: 2 * current.x - lastQuadControl.x,+ y: 2 * current.y - lastQuadControl.y,+ }+ : current;+ const end = { x, y };+ addQuad(current, cp, end);+ current = end;+ lastQuadControl = cp;+ }+ lastCubicControl = null;+ break;+ }+ case "A": {+ while (cursor < tokens.length && typeof tokens[cursor] === "number") {+ const rx = getNum();+ const ry = getNum();+ const rot = getNum();+ const largeArc = getNum() !== 0;+ const sweep = getNum() !== 0;+ let x = getNum();+ let y = getNum();+ if (isRel) {+ x += current.x;+ y += current.y;+ }+ const end = { x, y };+ const segs = sampleSvgArc(current, rx, ry, rot, largeArc, sweep, end);+ for (const s of segs) {+ contour.push(s.p1);+ }+ current = end;+ }+ lastCubicControl = null;+ lastQuadControl = null;+ break;+ }+ case "Z": {+ finishContour();+ current = subpathStart;+ lastCubicControl = null;+ lastQuadControl = null;+ break;+ }+ }+ }+ finishContour();+ return contours;+}++function toPoint2D(p: [number, number] | Point2D): Point2D {+ return Array.isArray(p) ? { x: p[0], y: p[1] } : { x: p.x, y: p.y };+}++function normalizeContoursInput(+ shape: ExtrudeShapeGeometryOptions["shape"],+ flattening: CurveFlattening,+): Contour[] {+ if (typeof shape === "string") {+ return parseSvgPathToContours(shape, flattening).filter(+ (c) => c.length >= 3,+ );+ }+ if (!Array.isArray(shape) || shape.length === 0) return [];+ const first = shape[0];+ const isNested =+ Array.isArray(first) &&+ first.length > 0 &&+ (Array.isArray(first[0]) ||+ (typeof first[0] === "object" && first[0] !== null && "x" in first[0]));+ if (isNested) {+ return (shape as Array<Array<[number, number] | Point2D>>)+ .map((c) => c.map(toPoint2D))+ .filter((c) => c.length >= 3);+ }+ const single = (shape as Array<[number, number] | Point2D>).map(toPoint2D);+ return single.length >= 3 ? [single] : [];+}++/** Side-wall segments meeting at more than 30° keep a crisp hard edge. */+const SIDE_CREASE_COS = Math.cos((30 * Math.PI) / 180);++/**+ * Extrudes any 2D outline (SVG path string with subpaths/holes, or polygon contour arrays)+ * into a 3D solid mesh with optional front/back bevels and crease-aware smooth/hard side normals.+ */+function buildExtrudedShapeModel(o: ExtrudeShapeGeometryOptions): Model3DData {+ const depth = Math.max(1e-3, o.depth ?? 20);+ const halfDepth = depth / 2;+ const bevelThickness = Math.max(+ 0,+ Math.min(halfDepth * 0.49, o.bevelThickness ?? 0),+ );+ const bevelSize = Math.max(0, o.bevelSize ?? bevelThickness);+ const bevelSegments =+ bevelThickness > 0 || bevelSize > 0+ ? Math.max(1, Math.round(o.bevelSegments ?? 2))+ : 0;+ const flattening: CurveFlattening = {+ segments: o.curveSegments,+ tolerance: Math.max(1e-3, o.curveTolerance ?? 0.25),+ };++ const rawContours = normalizeContoursInput(o.shape, flattening);+ const polygons = organizeGlyphPolygons({+ contours: rawContours,+ simplified: false,+ });++ let minX = Number.POSITIVE_INFINITY;+ let maxX = Number.NEGATIVE_INFINITY;+ let minY = Number.POSITIVE_INFINITY;+ let maxY = Number.NEGATIVE_INFINITY;+ for (const poly of polygons) {+ for (const p of poly.outer) {+ if (p.x < minX) minX = p.x;+ if (p.x > maxX) maxX = p.x;+ if (p.y < minY) minY = p.y;+ if (p.y > maxY) maxY = p.y;+ }+ for (const hole of poly.holes) {+ for (const p of hole) {+ if (p.x < minX) minX = p.x;+ if (p.x > maxX) maxX = p.x;+ if (p.y < minY) minY = p.y;+ if (p.y > maxY) maxY = p.y;+ }+ }+ }+ if (!Number.isFinite(minX)) {+ minX = maxX = minY = maxY = 0;+ }+ if (o.center ?? true) {+ const cx = (minX + maxX) / 2;+ const cy = (minY + maxY) / 2;+ for (const poly of polygons) {+ for (const p of poly.outer) {+ p.x -= cx;+ p.y -= cy;+ }+ for (const hole of poly.holes) {+ for (const p of hole) {+ p.x -= cx;+ p.y -= cy;+ }+ }+ }+ minX -= cx;+ maxX -= cx;+ minY -= cy;+ maxY -= cy;+ }+ const w = maxX - minX;+ const h = maxY - minY;++ const frontMb = new MeshBuilder();+ const sideMb = new MeshBuilder();+ const useSeparateSideMaterial =+ o.bevelColor !== undefined && o.bevelColor !== o.color;+ const wallMb = useSeparateSideMaterial ? sideMb : frontMb;++ // Clean contour and compute outward 2D edge & vertex miter normals+ const cleanContour = (contour: Contour) => {+ const pts = contour.filter((p, k) => {+ const next = contour[(k + 1) % contour.length]!;+ return Math.hypot(next.x - p.x, next.y - p.y) >= 1e-5;+ });+ const count = pts.length;+ if (count < 3) return null;+ const edgeLengths: number[] = [];+ const edgeNormals = pts.map((p, k) => {+ const next = pts[(k + 1) % count]!;+ const len = Math.hypot(next.x - p.x, next.y - p.y);+ edgeLengths.push(len);+ // For CCW outer contour (signedArea > 0) or CW hole (signedArea < 0),+ // (dy, -dx)/len points outward from the filled solid.+ return { x: (next.y - p.y) / len, y: -(next.x - p.x) / len };+ });+ const miterNormals = pts.map((_, k) => {+ const nPrev = edgeNormals[(k - 1 + count) % count]!;+ const nNext = edgeNormals[k]!;+ const sx = nPrev.x + nNext.x;+ const sy = nPrev.y + nNext.y;+ const len = Math.hypot(sx, sy);+ if (len < 1e-6) return nNext;+ // Clamp miter length so acute corners don't shoot out+ const dot = (sx / len) * nNext.x + (sy / len) * nNext.y;+ const scale = Math.min(2.0, 1 / Math.max(0.35, dot));+ return { x: (sx / len) * scale, y: (sy / len) * scale };+ });+ return { pts, edgeLengths, edgeNormals, miterNormals };+ };++ const addSideWallWithProfile = (contour: Contour) => {+ const info = cleanContour(contour);+ if (!info) return;+ const { pts, edgeLengths, edgeNormals, miterNormals } = info;+ const count = pts.length;+ const perimeter = edgeLengths.reduce((a, b) => a + b, 0) || 1;++ // Build Z-profile slices from front (-halfDepth) to back (+halfDepth):+ // Each slice has z, outset (radial offset along 2D outward normal), and (nr, nz) normal tilt.+ interface Slice {+ z: number;+ inset: number; // radial shift along outward normal (negative = inset at cap)+ nr: number;+ nz: number;+ v: number;+ }+ const slices: Slice[] = [];+ if (bevelSegments <= 0) {+ slices.push(+ { z: -halfDepth, inset: 0, nr: 1, nz: 0, v: 0 },+ { z: halfDepth, inset: 0, nr: 1, nz: 0, v: 1 },+ );+ } else {+ const totalRows = bevelSegments * 2 + 1;+ let row = 0;+ for (let b = 0; b <= bevelSegments; b++) {+ const a = ((b / bevelSegments) * Math.PI) / 2; // 0 at cap, pi/2 at wall+ slices.push({+ z: -halfDepth + bevelThickness * (1 - Math.cos(a)),+ inset: -bevelSize * (1 - Math.sin(a)),+ nr: Math.sin(a),+ nz: -Math.cos(a),+ v: row++ / totalRows,+ });+ }+ for (let b = 0; b <= bevelSegments; b++) {+ const a = ((b / bevelSegments) * Math.PI) / 2; // 0 at wall, pi/2 at back cap+ slices.push({+ z: halfDepth - bevelThickness * (1 - Math.sin(a)),+ inset: -bevelSize * (1 - Math.cos(a)),+ nr: Math.cos(a),+ nz: Math.sin(a),+ v: row++ / totalRows,+ });+ }+ }++ const numSlices = slices.length;+ const addColumn = (+ p: Point2D,+ miter: Point2D,+ n2d: Point2D,+ u: number,+ ): number => {+ const base = wallMb.positions.length / 3;+ for (const s of slices) {+ const px = p.x + miter.x * s.inset;+ const py = p.y + miter.y * s.inset;+ const n3 = normalize([n2d.x * s.nr, n2d.y * s.nr, s.nz]);+ wallMb.vertex([px, py, s.z], n3, [u, s.v]);+ }+ return base;+ };++ const startColumn: number[] = [];+ const endColumn: number[] = [];+ let along = 0;+ for (let k = 0; k < count; k++) {+ const incoming = edgeNormals[(k - 1 + count) % count]!;+ const outgoing = edgeNormals[k]!;+ const miter = miterNormals[k]!;+ const u = along / perimeter;+ const sx = incoming.x + outgoing.x;+ const sy = incoming.y + outgoing.y;+ const smooth =+ incoming.x * outgoing.x + incoming.y * outgoing.y >= SIDE_CREASE_COS;+ const averaged = smooth+ ? { x: sx / Math.hypot(sx, sy), y: sy / Math.hypot(sx, sy) }+ : null;+ if (averaged && k > 0) {+ startColumn[k] = endColumn[k] = addColumn(pts[k]!, miter, averaged, u);+ } else {+ endColumn[k] = addColumn(+ pts[k]!,+ miter,+ averaged ?? incoming,+ k === 0 ? 1 : u,+ );+ startColumn[k] = addColumn(pts[k]!, miter, averaged ?? outgoing, u);+ }+ along += edgeLengths[k]!;+ }++ for (let k = 0; k < count; k++) {+ const colA = startColumn[k]!;+ const colB = endColumn[(k + 1) % count]!;+ for (let s = 0; s < numSlices - 1; s++) {+ const a0 = colA + s;+ const a1 = colA + s + 1;+ const b0 = colB + s;+ const b1 = colB + s + 1;+ wallMb.indices.push(a0, b0, a1, b0, b1, a1);+ }+ }+ };++ for (const poly of polygons) {+ const outer = poly.outer;+ if (computeContourSignedArea(outer) < 0) outer.reverse();+ for (const hole of poly.holes) {+ if (computeContourSignedArea(hole) > 0) hole.reverse();+ }++ const outerInfo = cleanContour(outer);+ if (!outerInfo) continue;+ const holeInfos = poly.holes+ .map(cleanContour)+ .filter((x): x is NonNullable<typeof x> => x !== null);++ const capInset = -bevelSize;+ const earcutCoords: number[] = [];+ const holeIndices: number[] = [];++ for (let k = 0; k < outerInfo.pts.length; k++) {+ const p = outerInfo.pts[k]!;+ const m = outerInfo.miterNormals[k]!;+ earcutCoords.push(p.x + m.x * capInset, p.y + m.y * capInset);+ }+ for (const hInfo of holeInfos) {+ holeIndices.push(earcutCoords.length / 2);+ for (let k = 0; k < hInfo.pts.length; k++) {+ const p = hInfo.pts[k]!;+ const m = hInfo.miterNormals[k]!;+ earcutCoords.push(p.x + m.x * capInset, p.y + m.y * capInset);+ }+ }++ const triangles = earcut(earcutCoords, holeIndices, 2);+ const vertCount = earcutCoords.length / 2;++ // Front cap (-halfDepth, normal -z)+ const frontBase = frontMb.positions.length / 3;+ for (let v = 0; v < vertCount; v++) {+ const vx = earcutCoords[v * 2]!;+ const vy = earcutCoords[v * 2 + 1]!;+ frontMb.vertex(+ [vx, vy, -halfDepth],+ [0, 0, -1],+ [(vx - minX) / (w || 1), (vy - minY) / (h || 1)],+ );+ }+ for (let t = 0; t < triangles.length; t += 3) {+ frontMb.indices.push(+ frontBase + triangles[t]!,+ frontBase + triangles[t + 2]!,+ frontBase + triangles[t + 1]!,+ );+ }++ // Back cap (+halfDepth, normal +z)+ const backBase = frontMb.positions.length / 3;+ for (let v = 0; v < vertCount; v++) {+ const vx = earcutCoords[v * 2]!;+ const vy = earcutCoords[v * 2 + 1]!;+ frontMb.vertex(+ [vx, vy, halfDepth],+ [0, 0, 1],+ [(vx - minX) / (w || 1), (vy - minY) / (h || 1)],+ );+ }+ for (let t = 0; t < triangles.length; t += 3) {+ frontMb.indices.push(+ backBase + triangles[t]!,+ backBase + triangles[t + 1]!,+ backBase + triangles[t + 2]!,+ );+ }++ addSideWallWithProfile(outer);+ for (const hole of poly.holes) {+ addSideWallWithProfile(hole);+ }+ }++ const meshes: Mesh3DData[] = [];+ const materials: Record<string, Material3D> = {};++ const frontMesh = frontMb.build("extrude-front");+ frontMesh.materialName = "extrude-front-material";+ meshes.push(frontMesh);+ materials["extrude-front-material"] = {+ name: "extrude-front-material",+ diffuseColor: parseHexOrRgbColor(o.color ?? "#ffffff"),+ shading: o.material ?? "lit",+ shininess: o.shininess ?? 32,+ roughness: o.roughness,+ metallic: o.metallic,+ };++ if (useSeparateSideMaterial && sideMb.indices.length > 0) {+ const sideMesh = sideMb.build("extrude-side");+ sideMesh.materialName = "extrude-side-material";+ meshes.push(sideMesh);+ materials["extrude-side-material"] = {+ name: "extrude-side-material",+ diffuseColor: parseHexOrRgbColor(o.bevelColor ?? o.color ?? "#ffffff"),+ shading: o.material ?? "lit",+ shininess: o.shininess ?? 32,+ roughness: o.roughness,+ metallic: o.metallic,+ };+ }++ return finalizeModel3DData("extrude", meshes, materials);+}++/**+ * Revolves a 2D profile `(r, y)` around the Y axis (`x = r cos φ, y = y, z = r sin φ`).+ */+function lathe(o: LatheGeometryOptions, mb: MeshBuilder): void {+ const rawPoints: Point2D[] =+ typeof o.points === "string"+ ? (parseSvgPathToContours(o.points, { tolerance: 0.25 })[0] ?? [])+ : o.points.map(toPoint2D);+ if (rawPoints.length < 2) return;++ // Ensure profile runs so outward normal points away from the Y axis:+ // If the profile goes bottom (+y) to top (-y) without closing, reverse it so it runs top (-y) to bottom (+y),+ // or compute outward orientation from the profile centroid.+ const pts = rawPoints.map((p) => ({ x: Math.max(0, p.x), y: p.y }));+ const isClosedLoop =+ pts.length >= 3 &&+ Math.hypot(+ pts[pts.length - 1]!.x - pts[0]!.x,+ pts[pts.length - 1]!.y - pts[0]!.y,+ ) < 1e-4;++ if (isClosedLoop) {+ // In (r, y) plane, outward normal for segment (dr, dy) is (dy, -dr); for that to point outward+ // from the loop interior, signedArea in (r, y) must be > 0.+ if (computeContourSignedArea(pts) < 0) pts.reverse();+ } else if (pts[0]!.y > pts[pts.length - 1]!.y) {+ // Open profile: ensure it runs from top (-y) to bottom (+y) so (dy, -dr) has nr = dy >= 0 (outward +r).+ pts.reverse();+ }++ const seg = Math.max(3, Math.round(o.segments ?? 32));+ const phiStart = ((o.phiStart ?? 0) * Math.PI) / 180;+ const phiLength = ((o.phiLength ?? 360) * Math.PI) / 180;+ const count = pts.length;++ // Arc length along profile for V coordinate and 2D profile normals (nr, ny)+ const segLens: number[] = [];+ const segNormals: Point2D[] = [];+ let totalLen = 0;+ for (let j = 0; j < count - 1; j++) {+ const a = pts[j]!;+ const b = pts[j + 1]!;+ const dr = b.x - a.x;+ const dy = b.y - a.y;+ const len = Math.hypot(dr, dy);+ segLens.push(len);+ totalLen += len;+ segNormals.push(+ len > 1e-8 ? { x: dy / len, y: -dr / len } : { x: 1, y: 0 },+ );+ }++ const vCoords: number[] = [0];+ let acc = 0;+ for (const len of segLens) {+ acc += len;+ vCoords.push(totalLen > 0 ? acc / totalLen : 0);+ }++ if (o.flatShaded) {+ for (let j = 0; j < count - 1; j++) {+ const pA = pts[j]!;+ const pB = pts[j + 1]!;+ const n2 = segNormals[j]!;+ for (let i = 0; i < seg; i++) {+ const phi0 = phiStart + (i / seg) * phiLength;+ const phi1 = phiStart + ((i + 1) / seg) * phiLength;+ const phiMid = (phi0 + phi1) / 2;+ const fn = normalize([+ n2.x * Math.cos(phiMid),+ n2.y,+ n2.x * Math.sin(phiMid),+ ]);+ const c0 = Math.cos(phi0);+ const s0 = Math.sin(phi0);+ const c1 = Math.cos(phi1);+ const s1 = Math.sin(phi1);+ const base = mb.positions.length / 3;+ mb.vertex([pA.x * c0, pA.y, pA.x * s0], fn, [i / seg, vCoords[j]!]);+ mb.vertex([pA.x * c1, pA.y, pA.x * s1], fn, [+ (i + 1) / seg,+ vCoords[j]!,+ ]);+ mb.vertex([pB.x * c0, pB.y, pB.x * s0], fn, [i / seg, vCoords[j + 1]!]);+ mb.vertex([pB.x * c1, pB.y, pB.x * s1], fn, [+ (i + 1) / seg,+ vCoords[j + 1]!,+ ]);+ mb.indices.push(base, base + 2, base + 1, base + 1, base + 2, base + 3);+ }+ }+ } else {+ // Smooth-shaded vertex normals along the profile with crease splitting at sharp corners (> 30°)+ const base = mb.positions.length / 3;+ for (let j = 0; j < count; j++) {+ const p = pts[j]!;+ const nPrev =+ j > 0+ ? segNormals[j - 1]!+ : isClosedLoop+ ? segNormals[count - 2]!+ : segNormals[0]!;+ const nNext =+ j < count - 1+ ? segNormals[j]!+ : isClosedLoop+ ? segNormals[0]!+ : segNormals[count - 2]!;+ const nx = nPrev.x + nNext.x;+ const ny = nPrev.y + nNext.y;+ const nLen = Math.hypot(nx, ny);+ const n2 = nLen > 1e-8 ? { x: nx / nLen, y: ny / nLen } : { x: 1, y: 0 };++ for (let i = 0; i <= seg; i++) {+ const phi = phiStart + (i / seg) * phiLength;+ const c = Math.cos(phi);+ const s = Math.sin(phi);+ mb.vertex(+ [p.x * c, p.y, p.x * s],+ normalize([n2.x * c, n2.y, n2.x * s]),+ [i / seg, vCoords[j]!],+ );+ }+ }+ mb.grid(base, seg, count - 1, false);+ }++ // Optional end caps when not closed and r > 0+ if (o.capped && !isClosedLoop) {+ const first = pts[0]!;+ const last = pts[count - 1]!;+ for (const [pt, ny] of [+ [first, -1],+ [last, 1],+ ] as const) {+ if (pt.x <= 1e-5) continue;+ const center = mb.vertex([0, pt.y, 0], [0, ny, 0], [0.5, 0.5]);+ const ring = mb.positions.length / 3;+ for (let i = 0; i <= seg; i++) {+ const phi = phiStart + (i / seg) * phiLength;+ const c = Math.cos(phi);+ const s = Math.sin(phi);+ mb.vertex(+ [pt.x * c, pt.y, pt.x * s],+ [0, ny, 0],+ [(c + 1) / 2, (s + 1) / 2],+ );+ }+ for (let i = 0; i < seg; i++) {+ if (ny < 0) mb.indices.push(center, ring + i, ring + i + 1);+ else mb.indices.push(center, ring + i + 1, ring + i);+ }+ }+ }+}++function buildPath3DFromSpec(+ spec: TubePathSpec,+ closedDefault = false,+): Path3D {+ if (Array.isArray(spec)) {+ if (spec.length < 2) {+ throw new Error("3D path requires at least 2 points");+ }+ return Path3D.catmullRom(spec, { closed: closedDefault });+ }+ if (spec.kind === "catmullRom") {+ return Path3D.catmullRom(spec.points, {+ tension: spec.tension,+ closed: spec.closed ?? closedDefault,+ samplesPerSegment: spec.samplesPerSegment,+ });+ }+ if (spec.kind === "bezier") {+ return Path3D.bezier(spec.segments, spec.samplesPerSegment);+ }+ if (spec.kind === "helix") {+ return Path3D.helix({+ center: spec.center ?? [0, 0, 0],+ radius: spec.radius,+ pitch: spec.pitch,+ turns: spec.turns,+ axis: spec.axis,+ samplesPerTurn: spec.samplesPerTurn,+ });+ }+ return Path3D.circle({+ center: spec.center ?? [0, 0, 0],+ radius: spec.radius,+ startAngleDeg: spec.startAngleDeg,+ endAngleDeg: spec.endAngleDeg,+ samples: spec.samples,+ });+}++/**+ * Sweeps a circular (or thick-walled hollow pipe) cross-section along a 3D path+ * using Rotation-Minimizing Frames (RMF) so the tube never kinks or gimbal-flips.+ */+function tube(o: TubeGeometryOptions, mb: MeshBuilder): void {+ const closed =+ o.closed ??+ (!Array.isArray(o.path) &&+ o.path.kind === "catmullRom" &&+ Boolean(o.path.closed));+ const path = buildPath3DFromSpec(o.path, closed);+ const tubSeg = Math.max(2, Math.round(o.tubularSegments ?? 64));+ const radSeg = Math.max(3, Math.round(o.radialSegments ?? 16));+ const rDefault = Math.max(1e-3, o.radius ?? 12);+ const rStart = o.radiusTaper ? Math.max(0, o.radiusTaper[0]) : rDefault;+ const rEnd = o.radiusTaper ? Math.max(0, o.radiusTaper[1]) : rDefault;+ const rInnerBase = Math.max(0, Math.min(rDefault - 1e-3, o.innerRadius ?? 0));+ const capped = o.capped ?? true;++ const frames = [];+ for (let j = 0; j <= tubSeg; j++) {+ frames.push(path.getPointAt(j / tubSeg));+ }++ // Outer wall: ∂p/∂j = T, ∂p/∂i = -sin(θ) N + cos(θ) B -> ∂p/∂j × ∂p/∂i = T × (-sin N + cos B) = -sin B - cos N = -(cos N + sin B).+ // Outward normal is +(cos N + sin B), so flip = true.+ const outerBase = mb.positions.length / 3;+ for (let j = 0; j <= tubSeg; j++) {+ const u = j / tubSeg;+ const r = rStart + (rEnd - rStart) * u;+ const f = frames[j]!;+ const [px, py, pz] = f.position;+ const [nx, ny, nz] = f.normal;+ const [bx, by, bz] = f.binormal;+ for (let i = 0; i <= radSeg; i++) {+ const v = i / radSeg;+ const theta = v * Math.PI * 2;+ const c = Math.cos(theta);+ const s = Math.sin(theta);+ const dirX = c * nx + s * bx;+ const dirY = c * ny + s * by;+ const dirZ = c * nz + s * bz;+ mb.vertex(+ [px + r * dirX, py + r * dirY, pz + r * dirZ],+ normalize([dirX, dirY, dirZ]),+ [u, v],+ );+ }+ }+ mb.grid(outerBase, radSeg, tubSeg, true);++ if (rInnerBase > 1e-6) {+ // Hollow thick-walled pipe: inner wall + annular end caps+ const innerRatio = rInnerBase / rDefault;+ const innerBase = mb.positions.length / 3;+ for (let j = 0; j <= tubSeg; j++) {+ const u = j / tubSeg;+ const r = (rStart + (rEnd - rStart) * u) * innerRatio;+ const f = frames[j]!;+ const [px, py, pz] = f.position;+ const [nx, ny, nz] = f.normal;+ const [bx, by, bz] = f.binormal;+ for (let i = 0; i <= radSeg; i++) {+ const v = i / radSeg;+ const theta = v * Math.PI * 2;+ const c = Math.cos(theta);+ const s = Math.sin(theta);+ const dirX = c * nx + s * bx;+ const dirY = c * ny + s * by;+ const dirZ = c * nz + s * bz;+ mb.vertex(+ [px + r * dirX, py + r * dirY, pz + r * dirZ],+ normalize([-dirX, -dirY, -dirZ]),+ [u, v],+ );+ }+ }+ mb.grid(innerBase, radSeg, tubSeg, false);++ if (!closed && capped) {+ for (const [j, sign] of [+ [0, -1],+ [tubSeg, 1],+ ] as const) {+ const u = j / tubSeg;+ const rOut = rStart + (rEnd - rStart) * u;+ const rIn = rOut * innerRatio;+ const f = frames[j]!;+ const [px, py, pz] = f.position;+ const [nx, ny, nz] = f.normal;+ const [bx, by, bz] = f.binormal;+ const capN = normalize([+ f.tangent[0] * sign,+ f.tangent[1] * sign,+ f.tangent[2] * sign,+ ]);+ const base = mb.positions.length / 3;+ for (const rr of [rIn, rOut]) {+ for (let i = 0; i <= radSeg; i++) {+ const theta = (i / radSeg) * Math.PI * 2;+ const c = Math.cos(theta);+ const s = Math.sin(theta);+ const dirX = c * nx + s * bx;+ const dirY = c * ny + s * by;+ const dirZ = c * nz + s * bz;+ mb.vertex([px + rr * dirX, py + rr * dirY, pz + rr * dirZ], capN, [+ (c * (rr / rOut) + 1) / 2,+ (s * (rr / rOut) + 1) / 2,+ ]);+ }+ }+ // ∂p/∂rr × ∂p/∂i = (cos N + sin B) × (-sin N + cos B) = N × B = T.+ mb.grid(base, radSeg, 1, sign < 0);+ }+ }+ } else if (!closed && capped) {+ // Solid circular end caps+ for (const [j, sign] of [+ [0, -1],+ [tubSeg, 1],+ ] as const) {+ const u = j / tubSeg;+ const r = rStart + (rEnd - rStart) * u;+ if (r <= 1e-6) continue;+ const f = frames[j]!;+ const [px, py, pz] = f.position;+ const [nx, ny, nz] = f.normal;+ const [bx, by, bz] = f.binormal;+ const capN = normalize([+ f.tangent[0] * sign,+ f.tangent[1] * sign,+ f.tangent[2] * sign,+ ]);+ const center = mb.vertex([px, py, pz], capN, [0.5, 0.5]);+ const ring = mb.positions.length / 3;+ for (let i = 0; i <= radSeg; i++) {+ const theta = (i / radSeg) * Math.PI * 2;+ const c = Math.cos(theta);+ const s = Math.sin(theta);+ const dirX = c * nx + s * bx;+ const dirY = c * ny + s * by;+ const dirZ = c * nz + s * bz;+ mb.vertex([px + r * dirX, py + r * dirY, pz + r * dirZ], capN, [+ (c + 1) / 2,+ (s + 1) / 2,+ ]);+ }+ for (let i = 0; i < radSeg; i++) {+ // (p_{i+1} - center) × (p_i - center) = -N × B = -T; for +T (sign > 0) wind (center, ring+i, ring+i+1).+ if (sign > 0) mb.indices.push(center, ring + i, ring + i + 1);+ else mb.indices.push(center, ring + i + 1, ring + i);+ }+ }+ }+}++function resolvePointArray(spec: TubePathSpec): Vec3[] {+ if (Array.isArray(spec)) return spec;+ const path = buildPath3DFromSpec(spec);+ const count = 96;+ const out: Vec3[] = [];+ for (let i = 0; i <= count; i++) {+ out.push(path.getPointAt(i / count).position);+ }+ return out;+}++/**+ * Native 3D line geometry (`line-list` topology) with optional dashing and per-vertex colors.+ */+function line3d(o: Line3DGeometryOptions, mb: MeshBuilder): void {+ mb.topology = "line-list";+ const pts = resolvePointArray(o.points);+ if (pts.length < 2) return;++ const parsedColors = o.colors?.map((c) => parseHexOrRgbColor(c));+ const mode = o.mode ?? "strip";++ if (o.dashSize && o.dashSize > 0 && mode === "strip") {+ const dash = o.dashSize;+ const gap = o.gapSize ?? dash;+ const cycle = dash + gap;+ const workPts = o.closed ? [...pts, pts[0]!] : pts;+ let dist = 0;+ for (let i = 0; i < workPts.length - 1; i++) {+ const a = workPts[i]!;+ const b = workPts[i + 1]!;+ const segLen = Math.hypot(b[0] - a[0], b[1] - a[1], b[2] - a[2]);+ if (segLen < 1e-6) continue;+ const dir: V3 = [+ (b[0] - a[0]) / segLen,+ (b[1] - a[1]) / segLen,+ (b[2] - a[2]) / segLen,+ ];+ const colA = parsedColors?.[i % parsedColors.length];+ let local = 0;+ while (local < segLen) {+ const phase = (dist + local) % cycle;+ if (phase < dash) {+ const step = Math.min(dash - phase, segLen - local);+ const p0: V3 = [+ a[0] + dir[0] * local,+ a[1] + dir[1] * local,+ a[2] + dir[2] * local,+ ];+ const p1: V3 = [+ a[0] + dir[0] * (local + step),+ a[1] + dir[1] * (local + step),+ a[2] + dir[2] * (local + step),+ ];+ const idx0 = mb.vertex(p0, [0, -1, 0], [0, 0], colA);+ const idx1 = mb.vertex(p1, [0, -1, 0], [1, 0], colA);+ mb.indices.push(idx0, idx1);+ local += step;+ } else {+ local += cycle - phase;+ }+ }+ dist += segLen;+ }+ return;+ }++ for (let i = 0; i < pts.length; i++) {+ const u = pts.length > 1 ? i / (pts.length - 1) : 0;+ mb.vertex(+ pts[i]!,+ [0, -1, 0],+ [u, 0],+ parsedColors ? parsedColors[i % parsedColors.length] : undefined,+ );+ }+ if (mode === "segments") {+ for (let i = 0; i + 1 < pts.length; i += 2) {+ mb.indices.push(i, i + 1);+ }+ } else {+ for (let i = 0; i < pts.length - 1; i++) {+ mb.indices.push(i, i + 1);+ }+ if (o.closed && pts.length >= 3) {+ mb.indices.push(pts.length - 1, 0);+ }+ }+}++/**+ * 3D point cloud geometry: either native GPU `point-list` topology (`pointSize <= 0` or omitted)+ * or icosahedral 3D dots of radius `pointSize` for diagram vertices that scale with perspective.+ */+function points3d(o: Points3DGeometryOptions, mb: MeshBuilder): void {+ const pts = resolvePointArray(o.points);+ if (pts.length === 0) return;+ const parsedColors = o.colors?.map((c) => parseHexOrRgbColor(c));+ const pointSize = o.pointSize ?? 0;++ if (pointSize > 0) {+ const dotMb = new MeshBuilder();+ polyhedron(+ {+ type: "polyhedron",+ shape: "icosphere",+ radius: pointSize,+ detail: 1,+ flatShaded: false,+ },+ dotMb,+ );+ const dotVerts = dotMb.positions.length / 3;+ for (let pIdx = 0; pIdx < pts.length; pIdx++) {+ const [px, py, pz] = pts[pIdx]!;+ const col = parsedColors+ ? parsedColors[pIdx % parsedColors.length]+ : undefined;+ const base = mb.positions.length / 3;+ for (let v = 0; v < dotVerts; v++) {+ mb.vertex(+ [+ px + dotMb.positions[v * 3]!,+ py + dotMb.positions[v * 3 + 1]!,+ pz + dotMb.positions[v * 3 + 2]!,+ ],+ [+ dotMb.normals[v * 3]!,+ dotMb.normals[v * 3 + 1]!,+ dotMb.normals[v * 3 + 2]!,+ ],+ [dotMb.uvs[v * 2]!, dotMb.uvs[v * 2 + 1]!],+ col,+ );+ }+ for (const idx of dotMb.indices) {+ mb.indices.push(base + idx);+ }+ }+ return;+ }++ mb.topology = "point-list";+ for (let i = 0; i < pts.length; i++) {+ const u = pts.length > 1 ? i / (pts.length - 1) : 0;+ const idx = mb.vertex(+ pts[i]!,+ [0, -1, 0],+ [u, 0],+ parsedColors ? parsedColors[i % parsedColors.length] : undefined,+ );+ mb.indices.push(idx);+ }+}+function shard(o: ShardGeometryOptions, mb: MeshBuilder): void {const r = o.radius ?? 50;const hx = (o.size ? o.size[0] : r) || 50;@@ -316,18 +2244,8 @@ function shard(o: ShardGeometryOptions, mb: MeshBuilder): void {return (res >>> 0) / 4294967296;};- type V3 = [number, number, number];type Polygon = V3[];- const sub3 = (a: V3, b: V3): V3 => [a[0] - b[0], a[1] - b[1], a[2] - b[2]];- const dot3 = (a: V3, b: V3): number =>- a[0] * b[0] + a[1] * b[1] + a[2] * b[2];- const cross3 = (a: V3, b: V3): V3 => [- a[1] * b[2] - a[2] * b[1],- a[2] * b[0] - a[0] * b[2],- a[0] * b[1] - a[1] * b[0],- ];-// Start with bounding box of size [2*hx, 2*hy, 2*hz] as 6 rectangular faces// Each face is an array of CCW vertices facing outwardlet faces: Polygon[] = [@@ -460,7 +2378,7 @@ function shard(o: ShardGeometryOptions, mb: MeshBuilder): void {// Tangent vectors on cutting planeconst up: V3 = Math.abs(n[1]) < 0.9 ? [0, 1, 0] : [1, 0, 0];- const tangentX = normalize(cross3(up, n)) as V3;+ const tangentX = normalize(cross3(up, n));const tangentY = cross3(n, tangentX);// Sort vertices CCW with respect to outward normal n@@ -543,7 +2461,7 @@ function shard(o: ShardGeometryOptions, mb: MeshBuilder): void {// Local face UV basisconst up: V3 = Math.abs(fn[1]) < 0.9 ? [0, 1, 0] : [1, 0, 0];- const tx = normalize(cross3(up, fn)) as V3;+ const tx = normalize(cross3(up, fn));const ty = cross3(fn, tx);// Project face vertices to [0, 1] UVs@@ -564,32 +2482,11 @@ function shard(o: ShardGeometryOptions, mb: MeshBuilder): void {}}-/** Builds a procedural solid as a single-mesh Model3DData. */-export function generatePrimitiveGeometry(- options: PrimitiveGeometryOptions,+function finalizeModel3DData(+ name: string,+ meshes: Mesh3DData[],+ materials: Record<string, Material3D>,): Model3DData {- const mb = new MeshBuilder();- if (options.type === "roundedBox") roundedBox(options, mb);- else if (options.type === "sphere") sphere(options, mb);- else if (options.type === "cylinder") cylinder(options, mb);- else if (options.type === "shard") shard(options, mb);- else {- throw new Error(- `Unknown 3D primitive: ${(options as { type?: string }).type}`,- );- }-- const name = options.type;- const mesh = mb.build(name);- const material: Material3D = {- name: `${name}-material`,- diffuseColor: parseHexOrRgbColor(options.color ?? "#ffffff"),- shading: options.material ?? "lit",- shininess: options.shininess ?? 32,- roughness: options.roughness,- metallic: options.metallic,- };-const min: [number, number, number] = [Number.POSITIVE_INFINITY,Number.POSITIVE_INFINITY,@@ -600,14 +2497,20 @@ export function generatePrimitiveGeometry(Number.NEGATIVE_INFINITY,Number.NEGATIVE_INFINITY,];- const pos = mesh.positions;- for (let i = 0; i < pos.length; i += 3) {- for (let k = 0; k < 3; k++) {- const v = pos[i + k]!;- if (v < min[k]!) min[k] = v;- if (v > max[k]!) max[k] = v;+ for (const mesh of meshes) {+ const pos = mesh.positions;+ for (let i = 0; i < pos.length; i += 3) {+ for (let k = 0; k < 3; k++) {+ const v = pos[i + k]!;+ if (v < min[k]!) min[k] = v;+ if (v > max[k]!) max[k] = v;+ }}}+ if (!Number.isFinite(min[0])) {+ min[0] = min[1] = min[2] = 0;+ max[0] = max[1] = max[2] = 0;+ }const size: [number, number, number] = [max[0] - min[0],max[1] - min[1],@@ -615,8 +2518,8 @@ export function generatePrimitiveGeometry(];return {name: `primitive-${name}`,- meshes: [mesh],- materials: { [material.name]: material },+ meshes,+ materials,animations: [],bounds: {min,@@ -632,6 +2535,52 @@ export function generatePrimitiveGeometry(};}+/** Builds a procedural solid as a Model3DData. */+export function generatePrimitiveGeometry(+ options: PrimitiveGeometryOptions,+): Model3DData {+ if (options.type === "extrude") {+ return buildExtrudedShapeModel(options);+ }++ const mb = new MeshBuilder();+ if (options.type === "roundedBox") roundedBox(options, mb);+ else if (options.type === "sphere") sphere(options, mb);+ else if (options.type === "cylinder") cylinder(options, mb);+ else if (options.type === "torus") torus(options, mb);+ else if (options.type === "capsule") capsule(options, mb);+ else if (options.type === "ring") ring(options, mb);+ else if (options.type === "polyhedron") polyhedron(options, mb);+ else if (options.type === "lathe") lathe(options, mb);+ else if (options.type === "tube") tube(options, mb);+ else if (options.type === "line3d") line3d(options, mb);+ else if (options.type === "points3d") points3d(options, mb);+ else if (options.type === "shard") shard(options, mb);+ else {+ throw new Error(+ `Unknown 3D primitive: ${(options as { type?: string }).type}`,+ );+ }++ const name = options.type;+ const mesh = mb.build(name);+ const defaultShading =+ options.type === "line3d" ||+ (options.type === "points3d" && (options.pointSize ?? 0) <= 0)+ ? "unlit"+ : "lit";+ const material: Material3D = {+ name: `${name}-material`,+ diffuseColor: parseHexOrRgbColor(options.color ?? "#ffffff"),+ shading: options.material ?? defaultShading,+ shininess: options.shininess ?? 32,+ roughness: options.roughness,+ metallic: options.metallic,+ };++ return finalizeModel3DData(name, [mesh], { [material.name]: material });+}+const primitiveCache = new Map<string, Model3DData>();/**diff --git a/packages/webgpu-renderers/src/renderer3d/text-extruder.ts b/packages/webgpu-renderers/src/renderer3d/text-extruder.tsindex 53e69292..bf4517b9 100644--- a/packages/webgpu-renderers/src/renderer3d/text-extruder.ts+++ b/packages/webgpu-renderers/src/renderer3d/text-extruder.ts@@ -1,6 +1,7 @@import earcut from "earcut";import type * as fontkit from "fontkit";import { Path2D } from "skia-canvas";+import { parseColor } from "../color.js";import type { Material3D, Mesh3DData, Model3DData } from "../loaders/types.js";import type { FontkitFont } from "../slug/slug-generator.js";import { shapeLineFromFont } from "../slug/text-shaping.js";@@ -57,40 +58,9 @@ export interface ExtrudedTextResult {export function parseHexOrRgbColor(colorStr: string,): [number, number, number, number] {- const c = colorStr.trim();- if (c.startsWith("#")) {- const hex = c.slice(1);- if (hex.length === 3) {- const r = Number.parseInt(hex[0]! + hex[0]!, 16) / 255;- const g = Number.parseInt(hex[1]! + hex[1]!, 16) / 255;- const b = Number.parseInt(hex[2]! + hex[2]!, 16) / 255;- return [r, g, b, 1];- }- if (hex.length === 6) {- const r = Number.parseInt(hex.slice(0, 2), 16) / 255;- const g = Number.parseInt(hex.slice(2, 4), 16) / 255;- const b = Number.parseInt(hex.slice(4, 6), 16) / 255;- return [r, g, b, 1];- }- if (hex.length === 8) {- const r = Number.parseInt(hex.slice(0, 2), 16) / 255;- const g = Number.parseInt(hex.slice(2, 4), 16) / 255;- const b = Number.parseInt(hex.slice(4, 6), 16) / 255;- const a = Number.parseInt(hex.slice(6, 8), 16) / 255;- return [r, g, b, a];- }- }- if (c.startsWith("rgb")) {- const parts = c- .replace(/rgba?\(/, "")- .replace(/\)/, "")- .split(",")- .map((p) => Number.parseFloat(p.trim()));- const r = (parts[0] ?? 0) / 255;- const g = (parts[1] ?? 0) / 255;- const b = (parts[2] ?? 0) / 255;- const a = parts[3] !== undefined ? parts[3] : 1;- return [r, g, b, a];+ const c = parseColor(colorStr);+ if (c.a > 0 || colorStr.trim().toLowerCase() === "transparent") {+ return [c.r, c.g, c.b, c.a];}return [1, 1, 1, 1];}diff --git a/plugins/framefields/skills/framefields-compose/SKILL.md b/plugins/framefields/skills/framefields-compose/SKILL.mdindex c6eec60f..68fabdba 100644--- a/plugins/framefields/skills/framefields-compose/SKILL.md+++ b/plugins/framefields/skills/framefields-compose/SKILL.md@@ -104,7 +104,8 @@ All `Layer.*` builders return `AnimatableNode<T>` instances with chainable `.ani| `Layer.environment(preset, options)` | `"light"` | The 3D scene's world: studio image-based light, exposure, tone mapping, fog, bloom. **Adding one switches the scene to physically based shading.** See *3D Look* below. || `Layer.sequence(entries, options)` | `"box"` | Scenes back to back with `Transition`s between them; returns a box whose `totalFrames` is the length. See *Scenes & Transitions*. || `Layer.model(options)` | `"model3d"` | 3D mesh loader (`.gltf`, `.glb`, `.obj`, `.fbx`, `.stl`, `.ply`). Supports skinning and audio deformation compute shaders. |-| `Layer3D.roundedBox / sphere / cylinder / shard(options)` | `"model3d"` | Procedural solid meshes, centered on `x`/`y`/`z` (y is down, so "top" is -y). `roundedBox`: `width`, `height`, `depth`, `radius`, `segments`, `taper`. `sphere`: `radius`. `cylinder`: `radius` or `radiusTop`/`radiusBottom`, `height`. `shard`: procedural flat-faceted polyhedron rock/crystal clipped against Fibonacci lattice normals (`radius`, `cuts`, `irregularity`, seed); builds automatic UVs and Rapier 3D hull collider. Surface: `color`, `tint`, `roughness`, `metallic`, `emissive`, `emissiveIntensity`, `castShadow`, `wireframe`. Shared GPU buffers cache identical shapes. |+| `Layer3D.roundedBox / sphere / cylinder / capsule / torus / ring / prism / pyramid / polyhedron / icosahedron / icosphere / shard(options)` | `"model3d"` | Procedural solid meshes, centered on `x`/`y`/`z` (y is down, so "top" is -y). `roundedBox`: `width`, `height`, `depth`, `radius`, `segments`, `taper`. `sphere`: `radius`. `cylinder`: `radius` or `radiusTop`/`radiusBottom`, `height`, `openEnded`, `flatShaded`. `capsule`: `radius`, `height` (cylindrical shaft) or `totalHeight`. `torus`: `radius`, `tubeRadius`, `arc`. `ring`: flat annulus (`innerRadius`, `outerRadius`). `prism` / `pyramid`: solid capped flat-shaded N-gon prism or pyramid (`sides`, `radius`, `height`). `polyhedron` (`type: "tetrahedron" \| "octahedron" \| "dodecahedron" \| "icosahedron"`), `icosahedron`, `icosphere` (`radius`, `detail`, `flatShaded`). `shard`: procedural flat-faceted polyhedron rock/crystal (`radius`, `cuts`, `irregularity`, `seed`). Surface: `color`, `tint`, `roughness`, `metallic`, `emissive`, `emissiveIntensity`, `material` (`"lit" \| "glass" \| "acrylic" \| "frosted"`), `castShadow`, `wireframe`. Shared GPU buffers cache identical shapes. |+| `Layer3D.extrude / lathe / tube / line / points(options)` | `"model3d"` | Custom & path-driven 3D geometry. `extrude`: extrude a 2D SVG path `d` (with holes) or `contour`/`holes` (`depth`, `bevelThickness`, `bevelSize`, `bevelSegments`, `bevelColor`). `lathe`: revolve a 2D `points` profile `[r, y][]` around the Y axis (`segments`, `phiStart`, `phiLength`, `closed`, `flatShaded`). `tube`: sweep a solid or thick-walled hollow pipe (`radius`, `innerRadius`, `radiusTaper`, `closed`, `capped`) along a `Path3D` or 3D control `points` using rotation-minimizing frames. `line`: 3D polyline (`points` or `Path3D`, `dashSize`, `gapSize`, per-vertex `colors`). `points`: 3D point cloud (`points`, `pointSize` for lit sphere dots or `0` for `point-list`, per-point `colors`). || `Layer3D.instances(options)` | `"model3d"` | Hardware-instanced single or multi-variant mesh rendering in 1 GPU draw call. Options: `count`, `mesh` / `meshes` (array of Layer3D primitives or meshes), `instanceAt(index, frame): { position, rotation, scale, color, emissive }`, or bind directly to Rapier `Physics.world3d` bodies via `bodies: Body3D[]` with `emissiveBySpeed` and `colorRamp`. || `Layer3D.swarm(options)` | `"model3d"` | Continuous 3D GPU particle swarm with compute-driven physics, 3D curl turbulence, vortex/cyclone field (`swirl`, `pull`, `axial`), ground plane collisions with Coulomb sliding friction and rotational roll torque, kinetic heat accumulation/cooling, and zero-copy packing directly into GPU instance buffers. |@@ -494,7 +495,7 @@ stage.animate(LayerAnimation.create().signal("y", world.impact, { multiplier: 14- Live worlds bind signals only (no `bakeKeyframes()`); `await world.advanceTo(frame)` steps one without rendering (e.g. to read `collisions`).- **Particles:** for clouds, dust, sparks, fluids and flow fields use `Layer.particles` (GPU, below), not hundreds of physics bodies. Keep physics bodies for a few dozen things that must collide and stack (cards, letters, products).- **Keyframes instead of signals:** `world.bakeKeyframes({ tolerance: 0.25 })` in place of `simulate()` writes plain, simplified linear keyframes (editable, plain JSON).-- **3D:** `Physics.world3d` takes `Layer3D.roundedBox / sphere / cylinder / shard` and models (convex hull of the mesh); same options with 3-vectors, `world.hinge(a, b, at, axis)`, `world.walls({ width, height, depth })`. Use `Layer3D.instances({ count: bodies.length, mesh: Layer3D.shard({ radius: 24 }), bodies, emissiveBySpeed: { speedThreshold: 200, maxSpeed: 1200, color: "#ff5511", intensity: 4 } })` to render hundreds of physics bodies in a single GPU draw call.+- **3D:** `Physics.world3d` takes `Layer3D` solids (`roundedBox`, `sphere`, `cylinder`, `capsule`, `torus`, `ring`, `prism`, `pyramid`, `polyhedron`, `icosahedron`, `icosphere`, `shard`) and models (convex hull of the mesh); same options with 3-vectors, `world.hinge(a, b, at, axis)`, `world.walls({ width, height, depth })`. Use `Layer3D.instances({ count: bodies.length, mesh: Layer3D.shard({ radius: 24 }), bodies, emissiveBySpeed: { speedThreshold: 200, maxSpeed: 1200, color: "#ff5511", intensity: 4 } })` to render hundreds of physics bodies in a single GPU draw call.- **Timing:** signals are on the composition clock. In a scene that starts at frame `S`, pass `startFrame: S` to the world. Before it and after `frames` the signals hold their first/last value. Add every body, joint and force before `simulate()` (or before reading any signal): the world then locks.- **Feel:** gravity 2400 px/s² reads snappy on a 1080p canvas; `pixelsPerMeter` (100) scales how heavy things feel. Raise `substeps` (4) for tall stacks or thin, fast bodies.- Install note: physics uses the optional dependency `@dimforge/rapier2d-deterministic-compat` / `rapier3d-deterministic-compat` (installed by default with framefields).