forked from 1b-agent/opencadstudio-upstream
Add ocs_doc_api: object-oriented CAD entity API (v2)
New crate crates/ocs_doc_api: object-centric facade (DocApi -> Document -> collections -> typed handles), transport-agnostic wire layer (DocApiEnvelope = single op | read-only query batch), per-op autocommit (no write transactions), bulk ops with upfront-validation all-or-nothing, structured ApiError, and build-time codegen (spec/entities.toml -> ops/query enums, api_reference.md, binding_schema.json). ocs_plugin_api: append-only PluginRequest::DocApiRequest / PluginResponse:: DocApiResponse (serde_bytes payload) + defaulted HostApi::doc_api_dispatch. Host: DocApiBackend impl for HostSession (src/app/doc_api.rs) mapping to scene primitives (solid_models lift-on-miss, register_prepared_solid_model, meshes metrics), entity conversions (doc_api_convert.rs), HostSession accessors + doc_api_dispatch override. Tests: 592 host lib (incl. 7 DocApi integration tests: create/boolean/query, unknown-id, transform-many all-or-nothing, query-batch cap, 2D/geometric/DWG roundtrips), 8 crate unit tests. Examples + README/ARCHITECTURE/IMPLEMENTATION docs.
This commit is contained in:
1 parent
9129c85f97
commit
e41086b058
44 files changed
+4837
-12
No files matched your search
@@ -0,0 +1,194 @@
|
||||
//! Shared in-memory `DocApiBackend` for the runnable examples.
|
||||
//!
|
||||
//! Lets the examples run without the host binary: an in-process mock document
|
||||
//! (HashMap<ObjectId, Body> + a kind table) behind the `InProcess` transport.
|
||||
//! Not for production use — the real backend lives in the host (`src/app/doc_api.rs`).
|
||||
|
||||
use std::collections::HashMap;
|
||||
|
||||
use ocs_doc_api::backend::{DocApiBackend, KernelBody};
|
||||
use ocs_doc_api::{
|
||||
Aabb, ApiError, ApiResult, Curve2Spec, EntityView, GeometryErrorKind, GeometryRevision, ObjectId,
|
||||
PlacementSpec,
|
||||
};
|
||||
|
||||
#[derive(Default)]
|
||||
pub struct MockBackend {
|
||||
next_id: u64,
|
||||
revision: u64,
|
||||
undo_steps: u32,
|
||||
bodies: HashMap<ObjectId, KernelBody>,
|
||||
kinds: HashMap<ObjectId, String>,
|
||||
/// Stored 2D curve specs so `bounds()` works on non-solid entities too.
|
||||
curves: HashMap<ObjectId, Curve2Spec>,
|
||||
}
|
||||
|
||||
impl MockBackend {
|
||||
fn alloc(&mut self, kind: &str) -> ObjectId {
|
||||
self.next_id += 1;
|
||||
let id = ObjectId::from_u64(self.next_id);
|
||||
self.kinds.insert(id, kind.to_string());
|
||||
id
|
||||
}
|
||||
fn body(&self, id: ObjectId) -> ApiResult<&KernelBody> {
|
||||
self.bodies.get(&id).ok_or(ApiError::UnknownId(id))
|
||||
}
|
||||
#[allow(dead_code)]
|
||||
pub fn undo_steps(&self) -> u32 {
|
||||
self.undo_steps
|
||||
}
|
||||
}
|
||||
|
||||
/// Coarse bounds for a stored 2D curve spec (mirrors the host's entity_bounds).
|
||||
fn curve_bounds(spec: &Curve2Spec) -> Aabb {
|
||||
match spec {
|
||||
Curve2Spec::Line { start, end } => Aabb {
|
||||
min: [
|
||||
start[0].min(end[0]),
|
||||
start[1].min(end[1]),
|
||||
start[2].min(end[2]),
|
||||
],
|
||||
max: [
|
||||
start[0].max(end[0]),
|
||||
start[1].max(end[1]),
|
||||
start[2].max(end[2]),
|
||||
],
|
||||
},
|
||||
Curve2Spec::Circle { centre, radius } => Aabb {
|
||||
min: [centre[0] - radius, centre[1] - radius, centre[2]],
|
||||
max: [centre[0] + radius, centre[1] + radius, centre[2]],
|
||||
},
|
||||
Curve2Spec::Point { position } => Aabb { min: *position, max: *position },
|
||||
Curve2Spec::Polyline { points, .. } => {
|
||||
let mut min = [f64::INFINITY; 3];
|
||||
let mut max = [f64::NEG_INFINITY; 3];
|
||||
for p in points {
|
||||
for i in 0..3 {
|
||||
min[i] = min[i].min(p[i]);
|
||||
max[i] = max[i].max(p[i]);
|
||||
}
|
||||
}
|
||||
Aabb { min, max }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl DocApiBackend for MockBackend {
|
||||
fn resolve_body(&mut self, id: ObjectId) -> ApiResult<KernelBody> {
|
||||
Ok(self.body(id)?.clone())
|
||||
}
|
||||
fn store_solid(&mut self, body: &KernelBody) -> ApiResult<ObjectId> {
|
||||
let id = self.alloc("Solid3D");
|
||||
self.bodies.insert(id, body.clone());
|
||||
Ok(id)
|
||||
}
|
||||
fn update_solid(&mut self, id: ObjectId, body: &KernelBody) -> ApiResult<()> {
|
||||
if self.bodies.insert(id, body.clone()).is_none() {
|
||||
return Err(ApiError::UnknownId(id));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
fn add_curve(&mut self, spec: &Curve2Spec) -> ApiResult<ObjectId> {
|
||||
let kind = match spec {
|
||||
Curve2Spec::Line { .. } => "Line",
|
||||
Curve2Spec::Circle { .. } => "Circle",
|
||||
Curve2Spec::Polyline { .. } => "LwPolyline",
|
||||
Curve2Spec::Point { .. } => "Point",
|
||||
};
|
||||
let id = self.alloc(kind);
|
||||
self.curves.insert(id, spec.clone());
|
||||
Ok(id)
|
||||
}
|
||||
fn add_vertex(&mut self, id: ObjectId, _at: usize, _point: [f64; 3]) -> ApiResult<()> {
|
||||
if self.entity_exists(id) {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(ApiError::UnknownId(id))
|
||||
}
|
||||
}
|
||||
fn remove_entity(&mut self, id: ObjectId) -> ApiResult<bool> {
|
||||
self.bodies.remove(&id);
|
||||
Ok(self.kinds.remove(&id).is_some())
|
||||
}
|
||||
fn get_entity(&mut self, id: ObjectId) -> ApiResult<EntityView> {
|
||||
let kind = self.kinds.get(&id).ok_or(ApiError::UnknownId(id))?.clone();
|
||||
let bounds = self.bodies.get(&id).and_then(|b| {
|
||||
cadkernel::brep::body_bounds(b).map(|bb| Aabb { min: bb.min, max: bb.max })
|
||||
});
|
||||
Ok(EntityView { id, kind, bounds })
|
||||
}
|
||||
fn transform_entity(&mut self, id: ObjectId, placement: &PlacementSpec) -> ApiResult<()> {
|
||||
if !self.entity_exists(id) {
|
||||
return Err(ApiError::UnknownId(id));
|
||||
}
|
||||
if let Some(body) = self.bodies.get(&id).cloned() {
|
||||
let place = cadkernel::brep::Placement {
|
||||
x_axis: placement.x_axis,
|
||||
y_axis: placement.y_axis,
|
||||
z_axis: placement.z_axis,
|
||||
origin: placement.origin,
|
||||
};
|
||||
let moved = cadkernel::brep::transform(&body, &place)
|
||||
.ok_or_else(|| ApiError::geometry(GeometryErrorKind::InvalidInput, "transform failed"))?;
|
||||
self.bodies.insert(id, moved);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
fn profile_curves(&self, _id: ObjectId) -> ApiResult<Vec<cadkernel::geom2d::Curve>> {
|
||||
Err(ApiError::Unsupported("profiles not mocked".into()))
|
||||
}
|
||||
fn bounds(&mut self, id: ObjectId) -> ApiResult<Aabb> {
|
||||
// Solids via the kernel body; 2D curves from their stored spec.
|
||||
if let Some(body) = self.bodies.get(&id) {
|
||||
let bb = cadkernel::brep::body_bounds(body)
|
||||
.ok_or_else(|| ApiError::geometry(GeometryErrorKind::Empty, "no bounds"))?;
|
||||
return Ok(Aabb { min: bb.min, max: bb.max });
|
||||
}
|
||||
if let Some(spec) = self.curves.get(&id) {
|
||||
return Ok(curve_bounds(spec));
|
||||
}
|
||||
Err(ApiError::UnknownId(id))
|
||||
}
|
||||
fn centroid(&mut self, id: ObjectId) -> ApiResult<[f64; 3]> {
|
||||
let body = self.body(id)?;
|
||||
Ok(mesh_vc(&cadkernel::brep::mesh_body(body, 0.5, 1e-3)).1)
|
||||
}
|
||||
fn volume(&mut self, id: ObjectId) -> ApiResult<f64> {
|
||||
let body = self.body(id)?;
|
||||
Ok(mesh_vc(&cadkernel::brep::mesh_body(body, 0.5, 1e-3)).0)
|
||||
}
|
||||
fn entity_exists(&self, id: ObjectId) -> bool {
|
||||
self.kinds.contains_key(&id)
|
||||
}
|
||||
fn revision(&self) -> GeometryRevision {
|
||||
GeometryRevision(self.revision)
|
||||
}
|
||||
fn push_undo(&mut self, _label: &str) {}
|
||||
fn finalize_op(&mut self) {
|
||||
self.undo_steps += 1;
|
||||
self.revision += 1;
|
||||
}
|
||||
}
|
||||
|
||||
/// Signed volume + centroid of a closed mesh via the divergence theorem.
|
||||
fn mesh_vc(mesh: &cadkernel::brep::Mesh) -> (f64, [f64; 3]) {
|
||||
let mut vol = 0.0;
|
||||
let mut c = [0.0; 3];
|
||||
for t in &mesh.triangles {
|
||||
let (v0, v1, v2) = (mesh.positions[t[0]], mesh.positions[t[1]], mesh.positions[t[2]]);
|
||||
let cross = [
|
||||
v1[1] * v2[2] - v1[2] * v2[1],
|
||||
v1[2] * v2[0] - v1[0] * v2[2],
|
||||
v1[0] * v2[1] - v1[1] * v2[0],
|
||||
];
|
||||
let tet = (v0[0] * cross[0] + v0[1] * cross[1] + v0[2] * cross[2]) / 6.0;
|
||||
vol += tet;
|
||||
for i in 0..3 {
|
||||
c[i] += (v0[i] + v1[i] + v2[i]) * tet;
|
||||
}
|
||||
}
|
||||
if vol.abs() < 1e-12 {
|
||||
return (0.0, [0.0; 3]);
|
||||
}
|
||||
(vol, [c[0] / (4.0 * vol), c[1] / (4.0 * vol), c[2] / (4.0 * vol)])
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
//! Example 1 — Create solid primitives and query their geometry.
|
||||
//!
|
||||
//! Run: `cargo run --example e1_primitives_and_queries --features host`
|
||||
//!
|
||||
//! Shows: `doc.solids().create_*` for the supported primitives, and the read
|
||||
//! queries `bounds()` / `volume()` / `centroid()` on a `Solid`.
|
||||
|
||||
mod common;
|
||||
|
||||
use ocs_doc_api::DocApi;
|
||||
|
||||
fn main() -> ocs_doc_api::ApiResult<()> {
|
||||
// In-process document over the mock backend (no host binary needed).
|
||||
let api = DocApi::in_process(common::MockBackend::default(), 0);
|
||||
let doc = api.document(api.active_tab());
|
||||
|
||||
// The supported solid primitives.
|
||||
let block = doc.solids().create_cuboid([0.0, 0.0, 0.0], [10.0, 10.0, 10.0])?;
|
||||
let ball = doc.solids().create_sphere([5.0, 5.0, 5.0], 6.0)?;
|
||||
let cyl = doc.solids().create_cylinder([0.0, 0.0, 0.0], 4.0, 12.0)?;
|
||||
|
||||
// Geometric queries are entity methods — one host call each.
|
||||
let bb = block.bounds()?;
|
||||
let vol = ball.volume()?;
|
||||
let cg = cyl.centroid()?;
|
||||
|
||||
println!("cuboid bounds : {bb:?}");
|
||||
println!("sphere volume : {vol:.2} (analytic ~904.78)");
|
||||
println!("cylinder centroid: {cg:?}");
|
||||
|
||||
// Read-only batching: same queries, ONE round-trip.
|
||||
let res = doc.query_batch(|q| {
|
||||
q.bounds(&block);
|
||||
q.volume(&ball);
|
||||
q.centroid(&cyl);
|
||||
})?;
|
||||
let (bb2, vol2, cg2) = (res.bounds(0)?, res.volume(1)?, res.centroid(2)?);
|
||||
assert_eq!(bb, bb2);
|
||||
assert!((vol - vol2).abs() < 1e-9);
|
||||
assert_eq!(cg, cg2);
|
||||
println!("query_batch matches the per-call results");
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
//! Example 2 — Construct two solids and intersect them (the canonical boolean).
|
||||
//!
|
||||
//! Run: `cargo run --example e2_intersect_two_solids --features host`
|
||||
//!
|
||||
//! Shows: `intersect` / `union` / `subtract` on `Solid`, `erase_sources`
|
||||
//! semantics (the result lives at the first input's id, the second is erased),
|
||||
//! and `OpGroup` cleanup on failure.
|
||||
|
||||
mod common;
|
||||
|
||||
use ocs_doc_api::{DocApi, HasId, OpGroup};
|
||||
|
||||
fn main() -> ocs_doc_api::ApiResult<()> {
|
||||
let api = DocApi::in_process(common::MockBackend::default(), 0);
|
||||
let doc = api.document(api.active_tab());
|
||||
let mut grp = OpGroup::new();
|
||||
|
||||
// Two overlapping boxes: [0,10]^3 and [5,15]^3.
|
||||
let a = grp.track(doc.solids().create_cuboid([0.0, 0.0, 0.0], [10.0; 3]))?;
|
||||
let b = grp.track(doc.solids().create_cuboid([5.0, 5.0, 5.0], [10.0; 3]))?;
|
||||
|
||||
// intersect -> SolidBoolean{Intersection, erase_sources:true}. The result is
|
||||
// returned AT `a`'s id; `b` is erased. [5,10]^3 = volume 125.
|
||||
let lens = match a.intersect(&b) {
|
||||
Ok(l) => {
|
||||
grp.commit(); // keep everything
|
||||
l
|
||||
}
|
||||
Err(e) => {
|
||||
grp.compensate(&doc)?; // best-effort: delete the two boxes
|
||||
return Err(e);
|
||||
}
|
||||
};
|
||||
|
||||
assert_eq!(lens.id(), a.id(), "result lives at the first input's id");
|
||||
let vol = lens.volume()?;
|
||||
let bb = lens.bounds()?;
|
||||
println!("intersection volume = {vol:.2} (expected 125)");
|
||||
println!("intersection bounds = {bb:?}");
|
||||
|
||||
// union / subtract follow the same shape. Fresh inputs (b was erased above).
|
||||
let c = doc.solids().create_cuboid([0.0, 0.0, 0.0], [10.0; 3])?;
|
||||
let d = doc.solids().create_cuboid([5.0, 5.0, 5.0], [10.0; 3])?;
|
||||
let uni = c.union(&d)?;
|
||||
// union volume = 1000 + 1000 - 125 (overlap) = 1875.
|
||||
println!("union volume = {:.2} (expected 1875)", uni.volume()?);
|
||||
|
||||
let e = doc.solids().create_cuboid([0.0, 0.0, 0.0], [10.0; 3])?;
|
||||
let f = doc.solids().create_cuboid([5.0, 5.0, 5.0], [10.0; 3])?;
|
||||
let diff = e.subtract(&f)?;
|
||||
println!("difference volume = {:.2} (expected 875)", diff.volume()?);
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
//! Example 3 — Transform a solid and chain geometric operations.
|
||||
//!
|
||||
//! Run: `cargo run --example e3_transform_and_chain --features host`
|
||||
//!
|
||||
//! Shows: `transform(PlacementSpec)` (in-place, same ObjectId), how bounds shift
|
||||
//! exactly by the translation, and chaining intersect -> transform.
|
||||
|
||||
mod common;
|
||||
|
||||
use ocs_doc_api::{DocApi, PlacementSpec};
|
||||
|
||||
fn main() -> ocs_doc_api::ApiResult<()> {
|
||||
let api = DocApi::in_process(common::MockBackend::default(), 0);
|
||||
let doc = api.document(api.active_tab());
|
||||
|
||||
let a = doc.solids().create_cuboid([0.0, 0.0, 0.0], [10.0; 3])?;
|
||||
let b = doc.solids().create_cuboid([5.0, 5.0, 5.0], [10.0; 3])?;
|
||||
|
||||
// Boolean first: lens = [5,10]^3.
|
||||
let lens = a.intersect(&b)?;
|
||||
let before = lens.bounds()?;
|
||||
println!("lens bounds before transform: {before:?}");
|
||||
|
||||
// Transform is in-place: the SAME ObjectId is preserved; bounds shift by the
|
||||
// translation. [5,10]^3 moved +100 in X -> [105,110] x [5,10] x [5,10].
|
||||
lens.transform(PlacementSpec::at([100.0, 0.0, 0.0]))?;
|
||||
let after = lens.bounds()?;
|
||||
println!("lens bounds after +100 X : {after:?}");
|
||||
assert!((after.min[0] - 105.0).abs() < 1e-4);
|
||||
assert!((after.max[0] - 110.0).abs() < 1e-4);
|
||||
assert_eq!(after.min[1], before.min[1], "Y unchanged");
|
||||
|
||||
// Volume is invariant under a rigid transform.
|
||||
let vol = lens.volume()?;
|
||||
println!("lens volume after transform = {vol:.2} (still ~125)");
|
||||
assert!((vol - 125.0).abs() < 1.0);
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
//! Example 4 — 2D entities and bulk creation.
|
||||
//!
|
||||
//! Run: `cargo run --example e4_2d_entities_and_bulk --features host`
|
||||
//!
|
||||
//! Shows: the minimal-2D constructors (`create_line`/`create_circle`/
|
||||
//! `create_polyline`/`create_point`), `bounds()` on 2D entities, and the bulk op
|
||||
//! `create_points` (one op, all-or-nothing, one undo step).
|
||||
|
||||
mod common;
|
||||
|
||||
use ocs_doc_api::{DocApi, HasId};
|
||||
|
||||
fn main() -> ocs_doc_api::ApiResult<()> {
|
||||
let api = DocApi::in_process(common::MockBackend::default(), 0);
|
||||
let doc = api.document(api.active_tab());
|
||||
|
||||
// Individual 2D constructors.
|
||||
let line = doc.curves().create_line([0.0, 0.0, 0.0], [10.0, 0.0, 0.0])?;
|
||||
let circle = doc.curves().create_circle([5.0, 5.0, 0.0], 3.0)?;
|
||||
let poly = doc.curves().create_polyline(
|
||||
&[[0.0, 0.0, 0.0], [1.0, 0.0, 0.0], [1.0, 1.0, 0.0], [0.0, 1.0, 0.0]],
|
||||
true,
|
||||
)?;
|
||||
|
||||
println!("line bounds: {:?}", line.bounds()?); // [0,10] in X
|
||||
println!("circle bounds: {:?}", circle.bounds()?); // centre ± radius
|
||||
println!("poly bounds: {:?}", poly.bounds()?); // unit square
|
||||
|
||||
// Bulk: 1000 points in ONE op (all-or-nothing, one undo step — not 1000).
|
||||
let coords: Vec<[f64; 3]> = (0..1000).map(|i| [i as f64, (i % 10) as f64, 0.0]).collect();
|
||||
let pts = doc.curves().create_points(&coords)?;
|
||||
println!("created {} points in one bulk op", pts.len());
|
||||
assert_eq!(pts.len(), 1000);
|
||||
|
||||
// Generic lookup: any id -> Entity -> kind.
|
||||
let e = doc.entities().get(line.id())?;
|
||||
println!("line entity kind: {}", e.view()?.kind);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
//! Example 5 — Failure semantics: atomicity, OpGroup compensation, revision guard.
|
||||
//!
|
||||
//! Run: `cargo run --example e5_failure_and_guards --features host`
|
||||
//!
|
||||
//! Shows: per-op atomicity (a failed op applies nothing and moves no revision),
|
||||
//! `OpGroup` best-effort cleanup, `ApiError` handling, and the `assert_revision`
|
||||
//! read-guard.
|
||||
|
||||
mod common;
|
||||
|
||||
use ocs_doc_api::{ApiError, DocApi, HasId, OpGroup, ObjectId};
|
||||
|
||||
fn main() -> ocs_doc_api::ApiResult<()> {
|
||||
let api = DocApi::in_process(common::MockBackend::default(), 0);
|
||||
let doc = api.document(api.active_tab());
|
||||
|
||||
// ── Per-op atomicity: a boolean against a deleted id fails cleanly ──
|
||||
let a = doc.solids().create_cuboid([0.0, 0.0, 0.0], [10.0; 3])?;
|
||||
let ghost = doc.solids().create_sphere([5.0, 5.0, 5.0], 4.0)?;
|
||||
ghost.delete()?; // now a stale handle
|
||||
|
||||
let rev_before = doc.revision()?;
|
||||
match a.intersect(&ghost) {
|
||||
Err(ApiError::UnknownId(id)) => println!("boolean failed as expected: unknown id {id:?}"),
|
||||
Err(e) => println!("boolean failed: {e}"),
|
||||
Ok(_) => panic!("expected the boolean to fail"),
|
||||
}
|
||||
// `a` is still live (failed op mutated nothing) and the revision did not move.
|
||||
assert!(a.bounds().is_ok(), "input solid survives a failed boolean");
|
||||
assert_eq!(doc.revision()?, rev_before, "failed op records no revision bump");
|
||||
|
||||
// ── OpGroup: clean up a partially-built logical operation on failure ──
|
||||
let mut grp = OpGroup::new();
|
||||
let p1 = grp.track(doc.solids().create_cuboid([0.0, 0.0, 0.0], [4.0; 3]))?;
|
||||
let p2 = grp.track(doc.solids().create_sphere([2.0, 2.0, 2.0], 3.0))?;
|
||||
// Simulate a downstream failure: abandon the group and delete what we made.
|
||||
grp.compensate(&doc)?;
|
||||
for h in [p1.id(), p2.id()] {
|
||||
assert!(doc.entities().get(h).is_err(), "compensated entity is gone");
|
||||
}
|
||||
println!("OpGroup compensated: created entities deleted");
|
||||
|
||||
// ── assert_revision: read-modify-write guard ──
|
||||
let rev = doc.revision()?;
|
||||
doc.assert_revision(rev)?; // unchanged -> ok
|
||||
doc.solids().create_cuboid([0.0, 0.0, 0.0], [1.0; 3])?; // moves the revision
|
||||
match doc.assert_revision(rev) {
|
||||
Err(ApiError::Validation { reason, .. }) => println!("revision guard caught: {reason}"),
|
||||
other => panic!("expected the revision guard to fail, got {other:?}"),
|
||||
}
|
||||
|
||||
// A totally unknown id also surfaces a structured error.
|
||||
assert!(matches!(
|
||||
doc.entities().get(ObjectId::from_u64(0xDEAD)),
|
||||
Err(_)
|
||||
));
|
||||
println!("failure semantics verified");
|
||||
Ok(())
|
||||
}
|
||||
Reference in new issue
Block a user