From 28ad167b4ba69acd5a69d43aedf8c5026dd7288c Mon Sep 17 00:00:00 2001 From: vishwajeet mane Date: Wed, 18 Nov 2026 13:27:49 +0100 Subject: [PATCH] feat(revolve): build exact capped partial revolutions with signed angles --- CHANGELOG.md | 8 + README.md | 4 +- docs/opengeometry/api/constants.mdx | 2 +- docs/opengeometry/api/solid.mdx | 2 +- docs/opengeometry/guides/revolve.mdx | 10 +- docs/opengeometry/what-is-opengeometry.mdx | 2 +- .../src/constants/operations.ts | 13 +- .../tests/node/revolve.test.mjs | 47 +++ .../src/operations/creating/revolve.rs | 23 +- .../src/primitives/internal/mod.rs | 2 +- .../primitives/internal/revolved_profile.rs | 3 + .../internal/revolved_profile/partial.rs | 389 ++++++++++++++++++ main/opengeometry/src/primitives/mod.rs | 6 +- main/opengeometry/src/world_graph/creating.rs | 17 +- main/opengeometry/tests/golden/half_space.rs | 1 + main/opengeometry/tests/primitives.rs | 97 ++++- 16 files changed, 603 insertions(+), 23 deletions(-) create mode 100644 main/opengeometry/src/primitives/internal/revolved_profile/partial.rs diff --git a/CHANGELOG.md b/CHANGELOG.md index 43c6f6f0..b585c737 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,14 @@ All notable changes to the `opengeometry` package are in this file. The format f [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and the package follows [Semantic Versioning](https://semver.org/spec/v2.0.0.html). +## [Unreleased] + +### Added + +- Revolve accepts an optional signed `angle` in radians for exact capped partial turns. + Line-and-arc profiles retain analytic plane, cylinder, cone, sphere and torus faces. + Omitting the angle preserves the existing full-turn behavior. + ## [3.0.1] - 2026-11-17 Some booleans that threw in 3.0.0 now build, and some refused pairs throw a different error. diff --git a/README.md b/README.md index d4b00699..1d63a3c1 100644 --- a/README.md +++ b/README.md @@ -59,7 +59,7 @@ Floorkit, a toolkit for building design, is one application built on OpenGeometr | Area | What 3.0 has | | --- | --- | | **Primitives** | Wires: rectangle, circle, polyline (open or closed), line-and-arc profile, arc, regular polygon, slot, rounded rectangle. Solids: cuboid, cylinder, cylinder sector, sphere, cone or frustum, ring torus, planar polyhedron, slot prism, rounded box, pipe segment, polysolid wall along a path of straight legs and tangent arcs. Each can be placed on any plane. | -| **Operations** | Extrude a closed wire into a solid, with holes. Sweep a profile along an open or closed path of lines and arcs, each arc an exact bend, capped into a solid, open-ended into a sheet, or closed into a ring. Revolve a closed line-and-arc profile a full turn about an axis in its plane. Shell a solid into a hollow one with walls of one thickness. Union, subtract and intersect, with one to a hundred tool solids in one call. | +| **Operations** | Extrude a closed wire into a solid, with holes. Sweep a profile along an open or closed path of lines and arcs, each arc an exact bend, capped into a solid, open-ended into a sheet, or closed into a ring. Revolve a closed line-and-arc profile a full or partial turn about an axis in its plane. Shell a solid into a hollow one with walls of one thickness. Union, subtract and intersect, with one to a hundred tool solids in one call. | | **Parametric edits** | `rebuild` gives an existing body new parameters in place. `mirror` rebuilds a body as its reflection across a plane. | | **Assemblies** | Assemblies with parent and child placement; translate, rotate, scale and place; independent copies and shared instances. | | **History** | Marks with rollback and release; transactions, with a dry-run option. | @@ -152,7 +152,7 @@ This is a compact reference for writing OpenGeometry 3.0 code, by hand or with a | `Wire` | `new Wire(kind, params, options?)`. `OG_PRIMITIVE_RECTANGLE` `{ width, breadth }`, `OG_PRIMITIVE_CIRCLE` `{ radius }`, `OG_PRIMITIVE_POLYLINE` `{ points, closed? }`, `OG_PRIMITIVE_REGULAR_POLYGON` `{ sides, radius }` (3 to 1024 corners on a circle about the `plane` origin, the first on the x direction), `OG_PRIMITIVE_SLOT` `{ length, width }` (the outline of `OG_PRIMITIVE_SLOT_PRISM`), `OG_PRIMITIVE_ROUNDED_RECTANGLE` `{ width, breadth, radius }` (a rectangle with rounded corners; `radius` below half the width and half the breadth). | | Profile wire | `new Wire(OG_PRIMITIVE_PROFILE, { start, segments, closed }, options?)`. Points are `[u, v]` in `plane`; a segment is `{ to }` for a line or `{ to, arc: { center, counterClockwise } }` for an arc. A closed profile is an extrude profile or hole. | | Arc wire | `new Wire(OG_PRIMITIVE_ARC, { radius, startAngle, sweepAngle }, options?)`. Angles in radians from the `plane` x direction, centred on the `plane` origin; the sweep is nonzero and less than one turn. | -| `Solid` | `new Solid(kind, params, options?)`. `OG_PRIMITIVE_CUBOID` `{ width, height, depth }`, `OG_PRIMITIVE_CYLINDER` `{ radius, height }`, `OG_PRIMITIVE_CYLINDER_SECTOR` `{ radius, height, startAngle, sweepAngle }` (radians from the `plane` x direction, counter-clockwise seen from the side the normal points to; sweep nonzero and less than one turn), `OG_PRIMITIVE_POLYHEDRON` `{ points, faces }` (planar faces as rings of point indices, counter-clockwise seen from outside), `OG_PRIMITIVE_SPHERE` `{ radius }` (centred on the `plane` origin), `OG_PRIMITIVE_CONE` `{ radiusBottom, radiusTop, height }` (standing on the `plane`; one radius may be zero, equal radii make a cylinder), `OG_PRIMITIVE_TORUS` `{ majorRadius, minorRadius }` (lying on the `plane`; minor below major), `OG_OPERATION_EXTRUDE` `{ profile, holes?, distance }`, `OG_OPERATION_SWEEP` `{ profile, path, caps? }`, `OG_OPERATION_REVOLVE` `{ profile, axis? }` (a full turn about `axis` `{ point: [u, v], direction: [du, dv] }` in the profile's `[u, v]`, by default its v axis), `OG_PRIMITIVE_SLOT_PRISM` `{ length, width, height }` (a stadium standing on the `plane`, centred on its origin; `length` between the arc centres along the x direction), `OG_PRIMITIVE_ROUNDED_BOX` `{ width, height, depth, radius }` (a cuboid with its four upright edges rounded; `radius` below half the width and half the depth), `OG_PRIMITIVE_PIPE_SEGMENT` `{ outerRadius, innerRadius, height, startAngle, sweepAngle }` (a ring sector placed and angled like the cylinder sector), `OG_PRIMITIVE_POLYSOLID` `{ path, width, height, justify? }` (a wall of constant width along `path`, a `{ start, segments, closed }` of straight legs and tangent arcs in the `plane`'s `[u, v]`, standing on the `plane` and rising along its normal; `justify` is `'centre'` (default), `'left'` or `'right'` of the path direction); `profile`, `holes` and `path` are wires. | +| `Solid` | `new Solid(kind, params, options?)`. `OG_PRIMITIVE_CUBOID` `{ width, height, depth }`, `OG_PRIMITIVE_CYLINDER` `{ radius, height }`, `OG_PRIMITIVE_CYLINDER_SECTOR` `{ radius, height, startAngle, sweepAngle }` (radians from the `plane` x direction, counter-clockwise seen from the side the normal points to; sweep nonzero and less than one turn), `OG_PRIMITIVE_POLYHEDRON` `{ points, faces }` (planar faces as rings of point indices, counter-clockwise seen from outside), `OG_PRIMITIVE_SPHERE` `{ radius }` (centred on the `plane` origin), `OG_PRIMITIVE_CONE` `{ radiusBottom, radiusTop, height }` (standing on the `plane`; one radius may be zero, equal radii make a cylinder), `OG_PRIMITIVE_TORUS` `{ majorRadius, minorRadius }` (lying on the `plane`; minor below major), `OG_OPERATION_EXTRUDE` `{ profile, holes?, distance }`, `OG_OPERATION_SWEEP` `{ profile, path, caps? }`, `OG_OPERATION_REVOLVE` `{ profile, axis?, angle? }` (`angle` is signed radians with magnitude up to one turn, defaults to `2 * Math.PI`, and follows the right-hand rule about `axis` `{ point: [u, v], direction: [du, dv] }` in the profile's `[u, v]`, by default its v axis), `OG_PRIMITIVE_SLOT_PRISM` `{ length, width, height }` (a stadium standing on the `plane`, centred on its origin; `length` between the arc centres along the x direction), `OG_PRIMITIVE_ROUNDED_BOX` `{ width, height, depth, radius }` (a cuboid with its four upright edges rounded; `radius` below half the width and half the depth), `OG_PRIMITIVE_PIPE_SEGMENT` `{ outerRadius, innerRadius, height, startAngle, sweepAngle }` (a ring sector placed and angled like the cylinder sector), `OG_PRIMITIVE_POLYSOLID` `{ path, width, height, justify? }` (a wall of constant width along `path`, a `{ start, segments, closed }` of straight legs and tangent arcs in the `plane`'s `[u, v]`, standing on the `plane` and rising along its normal; `justify` is `'centre'` (default), `'left'` or `'right'` of the path direction); `profile`, `holes` and `path` are wires. | | `Sheet` | `new Sheet(OG_OPERATION_SWEEP, { profile, path, caps: false })`: an open-ended sweep, faces that enclose no volume. It shows its surface, from the front only, and its outline; `OpenGeometry.exportStep` refuses it. | | Body options | `{ ogId?, parent?, appearance?, plane? }`. `plane` is `{ origin?, normal?, xDirection? }` and applies to primitives only; by default it is the ground plane through the origin, normal `[0, 1, 0]`, x direction `[1, 0, 0]`. | | Booleans | `solid.operate(kind, { tools, instances? })` with `OG_OPERATION_SUBTRACT`, `OG_OPERATION_UNION` or `OG_OPERATION_INTERSECT`; `tools` is one to a hundred solids. | diff --git a/docs/opengeometry/api/constants.mdx b/docs/opengeometry/api/constants.mdx index 0e3d5d56..2142b5f2 100644 --- a/docs/opengeometry/api/constants.mdx +++ b/docs/opengeometry/api/constants.mdx @@ -73,7 +73,7 @@ Each helper returns its argument unchanged. It only gives the object a type, so | `OG_PRIMITIVE_PARAMS_POLYSOLID` | `PolysolidParams` | | `OG_OPERATION_PARAMS_EXTRUDE` | `{ profile, holes?, distance }` | | `OG_OPERATION_PARAMS_SWEEP` | `{ profile, path, caps? }` | -| `OG_OPERATION_PARAMS_REVOLVE` | `{ profile, axis? }` | +| `OG_OPERATION_PARAMS_REVOLVE` | `{ profile, axis?, angle? }` | | `OG_PRIMITIVE_PARAMS_SLOT_PRISM` | `SlotPrismParams` | | `OG_PRIMITIVE_PARAMS_ROUNDED_BOX` | `RoundedBoxParams` | | `OG_PRIMITIVE_PARAMS_PIPE_SEGMENT` | `PipeSegmentParams` | diff --git a/docs/opengeometry/api/solid.mdx b/docs/opengeometry/api/solid.mdx index 2059e8cb..298498ff 100644 --- a/docs/opengeometry/api/solid.mdx +++ b/docs/opengeometry/api/solid.mdx @@ -45,7 +45,7 @@ console.log(base.getReport()?.report.operation); | `OG_PRIMITIVE_POLYHEDRON` | `{ points, faces }` | | `OG_OPERATION_EXTRUDE` | `{ profile, holes?, distance }` | | `OG_OPERATION_SWEEP` | `{ profile, path, caps? }` | -| `OG_OPERATION_REVOLVE` | `{ profile, axis? }` | +| `OG_OPERATION_REVOLVE` | `{ profile, axis?, angle? }` | | `OG_PRIMITIVE_SLOT_PRISM` | `{ length, width, height }` | | `OG_PRIMITIVE_ROUNDED_BOX` | `{ width, height, depth, radius }` | | `OG_PRIMITIVE_PIPE_SEGMENT` | `{ outerRadius, innerRadius, height, startAngle, sweepAngle }` | diff --git a/docs/opengeometry/guides/revolve.mdx b/docs/opengeometry/guides/revolve.mdx index 88a2c755..98e02eb9 100644 --- a/docs/opengeometry/guides/revolve.mdx +++ b/docs/opengeometry/guides/revolve.mdx @@ -1,16 +1,19 @@ --- title: Revolve -description: Turn a closed line-and-arc profile a full turn about an axis in its plane. +description: Turn a closed line-and-arc profile a full or partial turn about an axis in its plane. icon: rotate --- -`OG_OPERATION_REVOLVE` turns a closed profile a full turn into a solid. The parameters are `{ profile, axis? }`: +`OG_OPERATION_REVOLVE` turns a closed profile into a solid. The parameters are `{ profile, axis?, angle? }`: +- `angle`: signed radians, nonzero and at most one full turn in magnitude. The default is `2 * Math.PI`. Positive angles follow the right-hand rule about the axis direction; negative angles reverse it. Partial turns retain the start profile and add exact planar end caps. - `profile`: a closed `OG_PRIMITIVE_PROFILE` wire. - `axis`: `{ point: [u, v], direction: [du, dv] }` in the profile's own `[u, v]`. By default it is `{ point: [0, 0], direction: [0, 1] }`, the profile plane's v axis. Each profile edge off the axis becomes one plane, cylinder, cone, sphere or ring torus face. An edge on the axis makes no face. +`OG_SUPPORTS_PARTIAL_REVOLVE` is `true` in SDK builds with this angle parameter. Older builds lack the flag. Pair the SDK with its matching WASM: an older kernel rejects an angle parameter instead of building a full turn. + ## A bowl On the default ground plane, the v axis runs along −Z, so the solid would lie on its side. Draw the profile on an upright plane instead, with u as the radius and v as the height. The bowl then stands upright about the Y axis: @@ -57,9 +60,10 @@ These throw `InvalidParameter`: - A profile that crosses the axis, touches it at a single point, or meets it along two separate stretches. - An arc whose circle meets the axis. - A zero `direction`. +- A zero, nonfinite or greater-than-one-turn `angle`. +- A partial angle whose start/end cap separation is below the kernel geometric accuracy. Such an angle is refused rather than rounded to zero or a full turn. Not built: -- A partial turn. There is no sweep angle; every revolve is a full turn. - A profile with holes. `OG_OPERATION_REVOLVE` takes no `holes`. - The shell of a full-turn revolve throws `CoverageGap`. diff --git a/docs/opengeometry/what-is-opengeometry.mdx b/docs/opengeometry/what-is-opengeometry.mdx index caab7ade..0ef91895 100644 --- a/docs/opengeometry/what-is-opengeometry.mdx +++ b/docs/opengeometry/what-is-opengeometry.mdx @@ -19,7 +19,7 @@ It also fits AI-assisted CAD. An assistant or an agent proposes the modelling st | Area | What you get | | -------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | Primitives | Wires: rectangle, circle, polyline, line-and-arc profile, arc. Solids: cuboid, cylinder, cylinder sector, sphere, cone or frustum, ring torus, planar polyhedron. Each goes on any plane. | -| Operations | Extrude with holes. Sweep along lines and arcs into a solid, an open sheet or a closed ring. Revolve a full turn. Shell a solid. Union, subtract and intersect with one to a hundred tools. | +| Operations | Extrude with holes. Sweep along lines and arcs into a solid, an open sheet or a closed ring. Revolve a full or partial turn. Shell a solid. Union, subtract and intersect with one to a hundred tools. | | Parametric edits | `rebuild` gives a body new parameters in place. `mirror` reflects a body across a plane. | | Assemblies | Parent and child placement, translate, rotate, scale and place, independent copies and shared instances. | | History | Marks with rollback and release, and transactions with a dry run. | diff --git a/main/opengeometry-three/src/constants/operations.ts b/main/opengeometry-three/src/constants/operations.ts index 01178b12..c55229ce 100644 --- a/main/opengeometry-three/src/constants/operations.ts +++ b/main/opengeometry-three/src/constants/operations.ts @@ -1,6 +1,7 @@ export const OG_OPERATION_EXTRUDE = 'Extrude' as const; export const OG_OPERATION_SWEEP = 'Sweep' as const; export const OG_OPERATION_REVOLVE = 'Revolve' as const; +export const OG_SUPPORTS_PARTIAL_REVOLVE = true as const; export const OG_OPERATION_UNION = 'Union' as const; export const OG_OPERATION_SUBTRACT = 'Subtract' as const; export const OG_OPERATION_INTERSECT = 'Intersect' as const; @@ -13,5 +14,13 @@ export const OG_OPERATION_PARAMS_SWEEP = ( value: { profile: { ogId: string }; path: { ogId: string }; caps?: boolean }, ): { profile: { ogId: string }; path: { ogId: string }; caps?: boolean } => value; export const OG_OPERATION_PARAMS_REVOLVE = ( - value: { profile: { ogId: string }; axis?: { point: [number, number]; direction: [number, number] } }, -): { profile: { ogId: string }; axis?: { point: [number, number]; direction: [number, number] } } => value; + value: { + profile: { ogId: string }; + angle?: number; + axis?: { point: [number, number]; direction: [number, number] }; + }, +): { + profile: { ogId: string }; + angle?: number; + axis?: { point: [number, number]; direction: [number, number] }; +} => value; diff --git a/main/opengeometry-three/tests/node/revolve.test.mjs b/main/opengeometry-three/tests/node/revolve.test.mjs index c5f53d5e..bc61b703 100644 --- a/main/opengeometry-three/tests/node/revolve.test.mjs +++ b/main/opengeometry-three/tests/node/revolve.test.mjs @@ -2,6 +2,7 @@ import assert from 'node:assert/strict'; import { test } from 'node:test'; import { OpenGeometry, Solid, Wire, OG_OPERATION_PARAMS_REVOLVE, OG_OPERATION_REVOLVE, OG_PRIMITIVE_PROFILE, + OG_SUPPORTS_PARTIAL_REVOLVE, } from '../../../dist/index.js'; import { boot, failsWith } from './support.mjs'; @@ -92,3 +93,49 @@ test('a revolve with holes is refused as InvalidParameter', async () => { const hole = upright(polygon([[1.5, 0.5], [2.5, 0.5], [2.5, 1.5], [1.5, 1.5]])); assert.throws(() => new Solid(OG_OPERATION_REVOLVE, { profile, holes: [hole] }), failsWith('InvalidParameter')); }); + +test('signed partial revolutions retain exact rounded sides, caps and STEP topology', async () => { + await boot(); + assert.equal(OG_SUPPORTS_PARTIAL_REVOLVE, true); + const profile = upright({ + start: [1.025, 0], + segments: [ + { to: [1, 0] }, + { to: [0.99, -0.01], arc: { center: [1, -0.01], counterClockwise: true } }, + { to: [0.99, -0.03] }, + { to: [1, -0.04], arc: { center: [1, -0.03], counterClockwise: true } }, + { to: [1.025, -0.04] }, + { to: [1.025, 0] }, + ], + closed: true, + }); + for (const degrees of [90, 270, 360, -90, -270, -360]) { + const angle = degrees * Math.PI / 180; + const part = new Solid( + OG_OPERATION_REVOLVE, OG_OPERATION_PARAMS_REVOLVE({ profile, angle }), { ogId: `round-${degrees}` }, + ); + const brep = part.getBrep(); + assert.equal(brep.topology.faces.length, Math.abs(degrees) === 360 ? 6 : 8); + const { text, report } = await OpenGeometry.exportStep({ nodes: [part], unit: 'metre' }); + assert.equal(report.solids, 1); + assert.equal(report.pcurvelessEdges, 0); + assert.equal(surfaces(text, 'TOROIDAL_SURFACE('), 2); + assert.equal(part.lastInfo.bodyType, 'Solid'); + } +}); + +test('partial revolve sign chooses the intended side and rejected edits preserve the old solid', async () => { + await boot(); + const profile = upright(polygon([[1, 0], [2, 0], [2, 1], [1, 1]])); + const quarter = new Solid(OG_OPERATION_REVOLVE, { profile, angle: Math.PI / 2 }); + assert.equal(quarter.classifyPoint([1, -1, -0.5]), 'Inside'); + assert.equal(quarter.classifyPoint([1, 1, -0.5]), 'Outside'); + const negative = new Solid(OG_OPERATION_REVOLVE, { profile, angle: -Math.PI / 2 }); + assert.equal(negative.classifyPoint([1, 1, -0.5]), 'Inside'); + assert.equal(negative.classifyPoint([1, -1, -0.5]), 'Outside'); + const old = quarter.getBrep(); + for (const angle of [0, 2 * Math.PI + 0.1, -2 * Math.PI - 0.1, 1e-12, 2 * Math.PI - 1e-12]) { + assert.throws(() => quarter.rebuild(OG_OPERATION_REVOLVE, { profile, angle }), failsWith('InvalidParameter')); + assert.deepEqual(quarter.getBrep(), old); + } +}); diff --git a/main/opengeometry/src/operations/creating/revolve.rs b/main/opengeometry/src/operations/creating/revolve.rs index 2935af2f..fe5a45d7 100644 --- a/main/opengeometry/src/operations/creating/revolve.rs +++ b/main/opengeometry/src/operations/creating/revolve.rs @@ -12,18 +12,29 @@ pub(crate) struct Axis { pub(crate) fn build( id: String, profile: ProfileLoop, - axis: Axis, + mut axis: Axis, + angle: f64, accuracy: Accuracy, ) -> Result { + if !angle.is_finite() || angle == 0.0 || angle.abs() > std::f64::consts::TAU { + return Err(invalid( + "revolve angle must be nonzero, finite, and no greater than a full turn", + )); + } + if angle < 0.0 { + axis.direction = scale(axis.direction, -1.0); + } let g = accuracy.geometric; let plane = profile_frame(&profile, g)?; let frame = revolve_frame(&profile, plane, axis)?; let profile_edges = edges(&profile, meridian(frame.origin, frame.x, frame.z)); - primitives::revolved_profile(id, frame, profile_edges, accuracy).map_err(|error| match error { - GeometryError::InvalidGeometry(message) - | GeometryError::UnresolvedIntersection(message) => invalid(message), - other => other.into(), - }) + primitives::partially_revolved_profile(id, frame, profile_edges, angle.abs(), accuracy).map_err( + |error| match error { + GeometryError::InvalidGeometry(message) + | GeometryError::UnresolvedIntersection(message) => invalid(message), + other => other.into(), + }, + ) } fn revolve_frame( diff --git a/main/opengeometry/src/primitives/internal/mod.rs b/main/opengeometry/src/primitives/internal/mod.rs index e3164dc8..7467b714 100644 --- a/main/opengeometry/src/primitives/internal/mod.rs +++ b/main/opengeometry/src/primitives/internal/mod.rs @@ -21,6 +21,6 @@ pub use frustum::frustum; pub use linear_extrusion::linear_extrusion; pub use outlines::{ring_sector_outline, rounded_rectangle_outline, slot_outline}; pub use polysolid::{polysolid, PolysolidError, PolysolidJustify, PolysolidPath}; -pub use revolved_profile::revolved_profile; +pub use revolved_profile::{partially_revolved_profile, revolved_profile}; pub use sphere::sphere; pub use torus::torus; diff --git a/main/opengeometry/src/primitives/internal/revolved_profile.rs b/main/opengeometry/src/primitives/internal/revolved_profile.rs index 9eb030c3..0b0eb780 100644 --- a/main/opengeometry/src/primitives/internal/revolved_profile.rs +++ b/main/opengeometry/src/primitives/internal/revolved_profile.rs @@ -1,3 +1,6 @@ +mod partial; +pub use partial::partially_revolved_profile; + use crate::brep::{ boundary, plane_boundary, unit, uv_line, Accuracy, BrepEnvelope, Builder, CurveGeometry, EdgeGeometry, Frame3, GeometryError, Orientation, Surface, SurfaceGeometry, Use, diff --git a/main/opengeometry/src/primitives/internal/revolved_profile/partial.rs b/main/opengeometry/src/primitives/internal/revolved_profile/partial.rs new file mode 100644 index 00000000..ea1e0da2 --- /dev/null +++ b/main/opengeometry/src/primitives/internal/revolved_profile/partial.rs @@ -0,0 +1,389 @@ +use super::{check_axis_contact, generator, revolved_profile, stations, Generator, Lateral}; +use crate::brep::{ + boundary, plane_boundary, unit, uv_line, Accuracy, BrepEnvelope, Builder, CurveGeometry, + EdgeGeometry, Frame3, GeometryError, Orientation, Surface, SurfaceGeometry, Use, +}; +use crate::math::add; +use crate::math::{dot, norm, scale, sub, Interval, Point3}; +use crate::primitives::profile::{validate_arc_profile_loop, ProfileEdge}; +use std::f64::consts::TAU; + +#[derive(Clone, Copy)] +struct Ends { + vertices: [u32; 2], + ring: Option, + collapsed: bool, +} + +pub fn partially_revolved_profile( + id: String, + frame: Frame3, + mut edges: Vec, + angle: f64, + accuracy: Accuracy, +) -> Result { + frame.validate()?; + accuracy.validate()?; + if !angle.is_finite() || angle <= 0.0 || angle > TAU { + return Err(GeometryError::InvalidGeometry( + "revolve angle must be positive and no greater than a full turn".into(), + )); + } + if angle == TAU { + return revolved_profile(id, frame, edges, accuracy); + } + let g = accuracy.geometric; + let mut keys = (0..edges.len()).collect::>(); + if validate_arc_profile_loop(&edges, g)? < 0.0 { + edges = edges.iter().rev().map(ProfileEdge::reversed).collect(); + keys.reverse(); + } + let stations = stations(&edges, g)?; + let mut radius = stations + .iter() + .filter(|station| station.r > 0.0) + .map(|station| station.r) + .fold(f64::INFINITY, f64::min); + if !radius.is_finite() { + radius = edges.iter().fold(0.0_f64, |reach, edge| match edge { + ProfileEdge::Arc { center, radius, .. } => reach.max(center[0] + radius), + ProfileEdge::Line { from, to } => reach.max(from[0]).max(to[0]), + }); + } + if 2.0 * radius * (angle.min(TAU - angle) / 2.0).sin() <= g { + return Err(GeometryError::InvalidGeometry( + "partial revolve cap separation is below geometric accuracy".into(), + )); + } + let count = edges.len(); + let generators = (0..count) + .map(|i| { + generator( + frame, + &edges[i], + [stations[i], stations[(i + 1) % count]], + g, + ) + }) + .collect::, _>>()?; + check_axis_contact(&stations, &generators)?; + let end_frame = rotated(frame, frame, angle); + let mut b = Builder::new(id, accuracy)?; + let ends = stations + .iter() + .enumerate() + .map(|(i, station)| { + let start = b.vertex(frame.point([station.r, 0.0, station.z])); + if station.r == 0.0 { + let lateral = matches!(generators[i], Generator::Lateral(_)) + || matches!(generators[(i + count - 1) % count], Generator::Lateral(_)); + let ring = lateral + .then(|| b.edge_geometry(EdgeGeometry::Collapsed { vertex: start }, true)); + Ok(Ends { + vertices: [start, start], + ring, + collapsed: true, + }) + } else { + let end = b.vertex(end_frame.point([station.r, 0.0, station.z])); + let circle = CurveGeometry::Circle { + frame: Frame3 { + origin: frame.point([0.0, 0.0, station.z]), + ..frame + }, + radius: station.r, + }; + let ring = b.edge(circle, Interval::new(0.0, angle)?, false); + Ok(Ends { + vertices: [start, end], + ring: Some(ring), + collapsed: false, + }) + } + }) + .collect::, GeometryError>>()?; + let mut meridians = Vec::with_capacity(count); + for (i, generator) in generators.iter().enumerate() { + let (curve, range, forward) = match generator { + Generator::Lateral(lateral) => { + (lateral.seam.clone(), lateral.seam_range, lateral.forward) + } + _ => { + let from = frame.point([stations[i].r, 0.0, stations[i].z]); + let next = stations[(i + 1) % count]; + let delta = sub(frame.point([next.r, 0.0, next.z]), from); + ( + CurveGeometry::Line { + origin: from, + direction: unit(delta)?, + }, + Interval::new(0.0, norm(delta))?, + true, + ) + } + }; + let start = b.edge(curve.clone(), range, false); + let end = if matches!(generator, Generator::Axis) { + start + } else { + b.edge(rotate_curve(curve, frame, angle)?, range, false) + }; + meridians.push(([start, end], forward)); + } + for (i, generator) in generators.iter().enumerate() { + let next = (i + 1) % count; + let pair = [ends[i], ends[next]]; + let key = format!("edge-{}", keys[i]); + match generator { + Generator::Axis => {} + Generator::Plane => { + let facing = if stations[next].r > stations[i].r { + -1.0 + } else { + 1.0 + }; + let plane = Frame3 { + origin: frame.point([0.0, 0.0, stations[i].z]), + x: frame.x, + y: scale(frame.y, facing), + z: scale(frame.z, facing), + }; + let mut uses = Vec::new(); + if let Some(edge) = pair[0].ring { + uses.push(plane_boundary( + &b, + plane, + edge, + pair[0].vertices[0], + pair[0].vertices[1], + Orientation::Forward, + )?); + } + uses.push(plane_boundary( + &b, + plane, + meridians[i].0[1], + pair[0].vertices[1], + pair[1].vertices[1], + Orientation::Forward, + )?); + if let Some(edge) = pair[1].ring { + uses.push(plane_boundary( + &b, + plane, + edge, + pair[1].vertices[1], + pair[1].vertices[0], + Orientation::Reverse, + )?); + } + uses.push(plane_boundary( + &b, + plane, + meridians[i].0[0], + pair[1].vertices[0], + pair[0].vertices[0], + Orientation::Reverse, + )?); + let radius = stations[i].r.max(stations[next].r); + b.face( + &key, + SurfaceGeometry::Plane { frame: plane }, + [[-radius, radius]; 2], + uses, + )?; + } + Generator::Lateral(lateral) => { + add_lateral(&mut b, &key, lateral, pair, meridians[i].0, angle)? + } + } + } + for side in 0..2 { + let radial = if side == 0 { frame } else { end_frame }; + let sign = if side == 0 { 1.0 } else { -1.0 }; + let plane = Frame3 { + origin: frame.origin, + x: radial.x, + y: scale(frame.z, sign), + z: scale(radial.y, -sign), + }; + let mut uses = Vec::with_capacity(count); + for i in 0..count { + let next = (i + 1) % count; + let (edge, forward) = (meridians[i].0[side], meridians[i].1); + let (from, to) = if side == 0 { + (ends[i].vertices[side], ends[next].vertices[side]) + } else { + (ends[next].vertices[side], ends[i].vertices[side]) + }; + let sense = if forward == (side == 0) { + Orientation::Forward + } else { + Orientation::Reverse + }; + uses.push(plane_boundary(&b, plane, edge, from, to, sense)?); + } + if side == 1 { + uses.reverse(); + } + let extent = edges + .iter() + .fold(0.0_f64, |extent, edge| match edge { + ProfileEdge::Line { from, to } => from + .iter() + .chain(to.iter()) + .fold(extent, |n, v| n.max(v.abs())), + ProfileEdge::Arc { center, radius, .. } => extent + .max(center[0].abs() + radius) + .max(center[1].abs() + radius), + }) + .max(g); + b.face( + if side == 0 { "start-cap" } else { "end-cap" }, + SurfaceGeometry::Plane { frame: plane }, + [[-extent, extent]; 2], + uses, + )?; + } + b.finish_solid() +} + +fn add_lateral( + b: &mut Builder, + key: &str, + lateral: &Lateral, + ends: [Ends; 2], + meridians: [u32; 2], + angle: f64, +) -> Result<(), GeometryError> { + let turn = lateral.turn; + let u0 = if turn > 0.0 { 0.0 } else { TAU }; + let u1 = u0 + turn * angle; + let ring = |end: Ends, v: f64, leading: bool| -> Result { + let edge = end.ring.ok_or_else(|| { + GeometryError::InvalidTopology("partial revolve lateral face misses a ring".into()) + })?; + let (from, to) = if leading { + (end.vertices[0], end.vertices[1]) + } else { + (end.vertices[1], end.vertices[0]) + }; + let (sense, pcurve) = if end.collapsed { + ( + Orientation::Forward, + uv_line( + [if leading { u0 } else { u1 }, v], + [if leading { turn * angle } else { -turn * angle }, 0.0], + ), + ) + } else { + ( + if leading { + Orientation::Forward + } else { + Orientation::Reverse + }, + uv_line([u0, v], [turn, 0.0]), + ) + }; + Ok(boundary(edge, from, to, sense, pcurve)) + }; + let along = if lateral.forward { + Orientation::Forward + } else { + Orientation::Reverse + }; + let back = if lateral.forward { + Orientation::Reverse + } else { + Orientation::Forward + }; + let [origin, rate] = lateral.seam_v; + let uses = vec![ + ring(ends[0], lateral.v[0], true)?, + boundary( + meridians[1], + ends[0].vertices[1], + ends[1].vertices[1], + along, + uv_line([u1, origin], [0.0, rate]), + ), + ring(ends[1], lateral.v[1], false)?, + boundary( + meridians[0], + ends[1].vertices[0], + ends[0].vertices[0], + back, + uv_line([u0, origin], [0.0, rate]), + ), + ]; + let face = b.brep.topology.faces.len(); + b.face( + key, + lateral.surface.clone(), + [ + [u0.min(u1), u0.max(u1)], + [ + lateral.v[0].min(lateral.v[1]), + lateral.v[0].max(lateral.v[1]), + ], + ], + uses, + )?; + if dot( + lateral + .surface + .normal_at([0.0, (lateral.v[0] + lateral.v[1]) / 2.0])?, + lateral.outward, + ) < 0.0 + { + b.brep.topology.faces[face].sense = Orientation::Reverse; + } + Ok(()) +} + +fn rotate_vector(v: Point3, axis: Frame3, angle: f64) -> Point3 { + let x = dot(v, axis.x); + let y = dot(v, axis.y); + let z = dot(v, axis.z); + axis.vector([ + x * angle.cos() - y * angle.sin(), + x * angle.sin() + y * angle.cos(), + z, + ]) +} +fn rotated(frame: Frame3, axis: Frame3, angle: f64) -> Frame3 { + Frame3 { + origin: add( + axis.origin, + rotate_vector(sub(frame.origin, axis.origin), axis, angle), + ), + x: rotate_vector(frame.x, axis, angle), + y: rotate_vector(frame.y, axis, angle), + z: rotate_vector(frame.z, axis, angle), + } +} +fn rotate_curve( + curve: CurveGeometry, + axis: Frame3, + angle: f64, +) -> Result { + Ok(match curve { + CurveGeometry::Line { origin, direction } => CurveGeometry::Line { + origin: add( + axis.origin, + rotate_vector(sub(origin, axis.origin), axis, angle), + ), + direction: rotate_vector(direction, axis, angle), + }, + CurveGeometry::Circle { frame, radius } => CurveGeometry::Circle { + frame: rotated(frame, axis, angle), + radius, + }, + _ => { + return Err(GeometryError::UnsupportedGeometry( + "partial revolve meridian curve".into(), + )) + } + }) +} diff --git a/main/opengeometry/src/primitives/mod.rs b/main/opengeometry/src/primitives/mod.rs index 815d4276..049236dc 100644 --- a/main/opengeometry/src/primitives/mod.rs +++ b/main/opengeometry/src/primitives/mod.rs @@ -21,9 +21,9 @@ pub use cuboid::cuboid; pub use cylinder::cylinder; pub use internal::{ annular_cylinder, arc_edged_extrusion, arc_edged_extrusion_with_holes, cone, cylinder_sector, - cylinder_with_circular_hole, frustum, linear_extrusion, polysolid, revolved_profile, - ring_sector_outline, rounded_rectangle_outline, slot_outline, sphere, torus, PolysolidError, - PolysolidJustify, PolysolidPath, + cylinder_with_circular_hole, frustum, linear_extrusion, partially_revolved_profile, polysolid, + revolved_profile, ring_sector_outline, rounded_rectangle_outline, slot_outline, sphere, torus, + PolysolidError, PolysolidJustify, PolysolidPath, }; pub use polyhedron::polyhedron; pub use polyline::{polyline, polyline_with_keys}; diff --git a/main/opengeometry/src/world_graph/creating.rs b/main/opengeometry/src/world_graph/creating.rs index 6c10e555..2d4b9dfc 100644 --- a/main/opengeometry/src/world_graph/creating.rs +++ b/main/opengeometry/src/world_graph/creating.rs @@ -29,6 +29,8 @@ pub enum CreatingOperation { profile: String, #[serde(default)] axis: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + angle: Option, }, } @@ -95,10 +97,21 @@ impl WorldGraph { sweep::build(id, profile, path, caps.unwrap_or(true), self.accuracy) .map_err(GraphError::from) } - CreatingOperation::Revolve { profile, axis } => { + CreatingOperation::Revolve { + profile, + axis, + angle, + } => { let outer = profile_loop(self, profile, target)?; let axis = self.revolve_axis(profile, target, *axis)?; - revolve::build(id, outer, axis, self.accuracy).map_err(GraphError::from) + revolve::build( + id, + outer, + axis, + angle.unwrap_or(std::f64::consts::TAU), + self.accuracy, + ) + .map_err(GraphError::from) } } } diff --git a/main/opengeometry/tests/golden/half_space.rs b/main/opengeometry/tests/golden/half_space.rs index fdbf2be0..8e69cb76 100644 --- a/main/opengeometry/tests/golden/half_space.rs +++ b/main/opengeometry/tests/golden/half_space.rs @@ -183,6 +183,7 @@ fn revolved_bowl(graph: &mut WorldGraph) -> Result<(), Failure> { }; create(graph, "profile", profile, upright())?; let revolve = CreatingOperation::Revolve { + angle: None, profile: "profile".into(), axis: None, }; diff --git a/main/opengeometry/tests/primitives.rs b/main/opengeometry/tests/primitives.rs index e6a03995..436fa537 100644 --- a/main/opengeometry/tests/primitives.rs +++ b/main/opengeometry/tests/primitives.rs @@ -3,7 +3,7 @@ use opengeometry::primitives::{self, ProfileEdge}; use opengeometry::query::{classify_point, PointClassification}; use opengeometry_test_support::accuracy::accuracy; use opengeometry_test_support::volume::estimate; -use std::f64::consts::{FRAC_PI_2, PI}; +use std::f64::consts::{FRAC_PI_2, PI, TAU}; #[test] fn independent_volumes_match_analytic_formulas() { @@ -431,3 +431,98 @@ fn revolve_refuses_sub_resolution_edges() { GeometryError::InvalidGeometry("profile arc is unresolved".into()) ); } + +#[test] +fn partial_revolved_profiles_are_closed_and_match_analytic_sector_volumes() { + for angle in [PI / 3.0, PI, 1.5 * PI, TAU] { + for (name, edges, full_volume) in revolved_volume_cases() { + let body = primitives::partially_revolved_profile( + format!("partial-{name}"), + Frame3::IDENTITY, + edges, + angle, + accuracy(1e-6), + ) + .unwrap_or_else(|error| panic!("{name} at {angle}: {error:?}")); + body.validate().unwrap(); + let measured = estimate(&body, 0.01); + let expected = full_volume * angle / TAU; + assert!( + (measured.value - expected).abs() <= measured.error_bound, + "{name} at {angle}: {} versus {expected} bound {}", + measured.value, + measured.error_bound + ); + let restored = BrepEnvelope::from_json(&body.to_json().unwrap()).unwrap(); + restored.validate().unwrap(); + let (step, report) = opengeometry::exchange::export_step(&body, "metre").unwrap(); + assert_eq!(serde_json::to_value(report).unwrap()["solids"], 1); + assert!(step.contains("ADVANCED_FACE")); + } + } +} + +#[test] +fn partial_revolve_is_equivariant_under_rotated_translated_frames() { + let a = 0.71_f64; + let frame = Frame3 { + origin: [7.3, -5.2, 11.9], + x: [a.cos(), 0.0, a.sin()], + y: [0.0, -1.0, 0.0], + z: [a.sin(), 0.0, -a.cos()], + }; + for (name, edges, full_volume) in revolved_volume_cases() { + let body = primitives::partially_revolved_profile( + format!("placed-{name}"), + frame, + edges, + PI * 1.5, + accuracy(1e-6), + ) + .unwrap(); + body.validate().unwrap(); + let measured = estimate(&body, 0.01); + assert!( + (measured.value - full_volume * 0.75).abs() <= measured.error_bound, + "{name}" + ); + opengeometry::exchange::export_step(&body, "metre").unwrap(); + } +} + +#[test] +fn partial_revolve_refuses_unresolved_cap_separation_without_rounding_the_angle() { + for angle in [1e-12, 1e-9, TAU - 1e-12, TAU - 1e-9] { + let pole_result = primitives::partially_revolved_profile( + "unresolved-poles".into(), + Frame3::IDENTITY, + semicircle(), + angle, + accuracy(1e-6), + ); + assert!(matches!( + pole_result, + Err(GeometryError::InvalidGeometry(_)) + )); + let result = primitives::partially_revolved_profile( + "unresolved".into(), + Frame3::IDENTITY, + off_axis_circle(), + angle, + accuracy(1e-6), + ); + assert!(matches!(result, Err(GeometryError::InvalidGeometry(_)))); + } + for angle in [0.0001, TAU - 0.0001] { + primitives::partially_revolved_profile( + "resolved".into(), + Frame3::IDENTITY, + off_axis_circle(), + angle, + accuracy(1e-6), + ) + .unwrap() + .validate() + .unwrap(); + } +}