diff --git a/src/cpp/bindings/python/bind_core.cpp b/src/cpp/bindings/python/bind_core.cpp index 7f5dbc87..a6532f92 100644 --- a/src/cpp/bindings/python/bind_core.cpp +++ b/src/cpp/bindings/python/bind_core.cpp @@ -80,14 +80,37 @@ void bind_core(py::module_& m) { // The world frame as a module constant, like simplecadapi.WORLD_CS. m.attr("WORLD_CS") = py::cast(scad::world_cs()); - py::class_(m, "SimpleWorkplane") + const auto tuple3 = [](const scad::Vec3& v) { return py::make_tuple(v.x, v.y, v.z); }; + py::class_(m, "SimpleWorkplane", + "A workplane: a frame in world coordinates, and the context manager that makes it the current " + "coordinate system (`with wp:`). A value: it can be entered again, pickled, and given to " + "make_sketch_rsketch(plane=wp).") .def(py::init([](const py::object& origin, const py::object& normal, const py::object& x_dir) { return std::make_unique(vec_from_python(origin), vec_from_python(normal), vec_from_python(x_dir)); }), py::arg("origin") = py::make_tuple(0, 0, 0), py::arg("normal") = py::make_tuple(0, 0, 1), py::arg("x_dir") = py::make_tuple(1, 0, 0)) + .def_static( + "_from_frame", + [](const py::object& origin, const py::object& x_axis, const py::object& y_axis) { + return Workplane::from_frame( + CoordinateSystem(vec_from_python(origin), vec_from_python(x_axis), vec_from_python(y_axis))); + }, + py::arg("origin"), py::arg("x_axis"), py::arg("y_axis")) .def_property_readonly("cs", &Workplane::cs, py::return_value_policy::reference_internal) + .def_property_readonly( + "origin", [tuple3](const Workplane& w) { return tuple3(w.origin()); }, "The origin in world coordinates.") + .def_property_readonly( + "normal", [tuple3](const Workplane& w) { return tuple3(w.normal()); }, + "The unit normal (the local z axis) in world coordinates.") + .def_property_readonly( + "x_dir", [tuple3](const Workplane& w) { return tuple3(w.x_dir()); }, "The unit x axis in world coordinates.") + .def_property_readonly( + "y_dir", [tuple3](const Workplane& w) { return tuple3(w.y_dir()); }, "The unit y axis in world coordinates.") + .def_property_readonly( + "plane", [](const Workplane& w) { return scad::pybind::value_to_python(w.plane_value()); }, + "The frame as a sketch plane mapping {'origin', 'x_axis', 'y_axis'} (world coordinates).") .def( "__enter__", [](Workplane& w) -> Workplane& { @@ -96,12 +119,63 @@ void bind_core(py::module_& m) { }, py::return_value_policy::reference) .def("__exit__", [](Workplane& w, const py::object&, const py::object&, const py::object&) { w.exit(); }) + .def("set_metadata", + [](const Workplane& w, const std::string& key, const scad::Value& value) { w.set_metadata(key, value); }) + .def( + "get_metadata", + [](const Workplane& w, const std::string& key, const scad::Value& fallback) { + return w.get_metadata(key, fallback); + }, + py::arg("key"), py::arg("default") = scad::Value()) + .def("_set_runtime", + [](const Workplane& w, const std::string& key, const scad::Value& value) { w.set_runtime(key, value); }) + .def( + "_get_runtime", + [](const Workplane& w, const std::string& key, const scad::Value& fallback) { + return w.get_runtime(key, fallback); + }, + py::arg("key"), py::arg("default") = scad::Value()) + .def("_metadata_dict", [](const Workplane& w) { return scad::pybind::value_to_python(w.metadata()); }) + .def("_runtime_dict", [](const Workplane& w) { return scad::pybind::value_to_python(w.runtime()); }) + .def("__copy__", [](const Workplane& w) { return Workplane(w); }) + .def( + "__deepcopy__", [](const Workplane& w, const py::object&) { return Workplane(w); }, py::arg("memo")) + // The cell cache pickles cell outputs: the exact frame, then the dictionaries (the graph lineage is in + // the runtime one, so a restored workplane is still the output of the node that made it). + .def(py::pickle( + [tuple3](const Workplane& w) { + return py::make_tuple(tuple3(w.origin()), tuple3(w.x_dir()), tuple3(w.y_dir()), + scad::pybind::value_to_python(w.metadata()), + scad::pybind::value_to_python(w.runtime())); + }, + [](const py::tuple& state) { + if (state.size() != 5) + throw std::runtime_error("Invalid SimpleWorkplane state"); + Workplane w = Workplane::from_frame( + CoordinateSystem(vec_from_python(state[0]), vec_from_python(state[1]), vec_from_python(state[2]))); + for (const auto& [key, value] : state[3].cast()) + w.set_metadata(key.cast(), scad::pybind::value_from_python(value)); + for (const auto& [key, value] : state[4].cast()) + w.set_runtime(key.cast(), scad::pybind::value_from_python(value)); + return w; + })) .def("_format_string", &Workplane::to_string, py::arg("indent") = 0, py::arg("show_coordinate_system") = true) .def("__str__", [](const Workplane& w) { return w.to_string(0, true); }) .def("__repr__", &Workplane::repr); m.attr("Workplane") = m.attr("SimpleWorkplane"); m.def("get_current_cs", [] { return scad::current_cs(); }); + // The recorded workplane the innermost frame comes from: {"graph_id", "node_id", "output_slot"} or None. + m.def("get_current_frame_source", []() -> py::object { + const scad::FrameSource* source = scad::current_frame_source(); + if (source == nullptr) + return py::none(); + py::dict out; + out["graph_id"] = source->graph_id; + out["node_id"] = source->node_id; + out["output_slot"] = source->output_slot; + return std::move(out); + }); // use_coordinate_system(cs): context manager over the same stack. struct CsScope { diff --git a/src/cpp/bindings/python/bind_ops_geometry.cpp b/src/cpp/bindings/python/bind_ops_geometry.cpp index 03320430..c8ceef87 100644 --- a/src/cpp/bindings/python/bind_ops_geometry.cpp +++ b/src/cpp/bindings/python/bind_ops_geometry.cpp @@ -14,6 +14,7 @@ #include #include "scad/ops/geometry/geometry.hpp" +#include "scad/ops/geometry/workplanes.hpp" #include "scad/reactive/registry.hpp" namespace { @@ -360,6 +361,80 @@ void bind_primitives(py::module_& m) { py::arg("center") = origin(), "Create a sphere solid."); } +// A point of a workplane: a vertex of the model or numbers. +struct PointOrVertexTag { + static constexpr auto name = py::detail::const_name("Vertex | simplecadapi.types.Point3"); +}; +struct EdgeOrWireTag { + static constexpr auto name = py::detail::const_name("Edge | Wire"); +}; + +PointOrVertex point_or_vertex(const AnyOf& point, const char* name) { + if (py::isinstance(point.value)) + return point.value.cast(); + if (py::isinstance(point.value)) + throw py::type_error(std::string(name) + " must be a Vertex or a point (x, y, z)"); + return Scalar3(point.value.cast()); +} + +EdgeOrWire edge_or_wire(const AnyOf& curve) { + if (py::isinstance(curve.value)) + return curve.value.cast(); + if (py::isinstance(curve.value)) + return curve.value.cast(); + throw py::type_error("curve must be an Edge or a Wire"); +} + +std::optional optional_point(const std::optional& point) { + return point ? std::optional(*point) : std::nullopt; +} +std::optional optional_direction(const std::optional& direction) { + return direction ? std::optional(*direction) : std::nullopt; +} + +void bind_workplanes(py::module_& m) { + m.def( + "make_workplane_rworkplane", + [](const Point3& origin, const Direction3& normal, const Direction3& x_dir) { + return make_workplane_rworkplane(origin, normal, x_dir); + }, + py::arg("origin") = origin(), py::arg("normal") = unit_z(), py::arg("x_dir") = py::make_tuple(1, 0, 0), + "Create a recorded workplane from an origin, a normal and an x direction in the current coordinate system."); + m.def( + "make_workplane_from_face_rworkplane", + [](const Face& face, const std::optional& origin, const std::optional& x_edge, + const std::optional& x_dir, const Length& offset, bool flip) { + return make_workplane_from_face_rworkplane(face, optional_point(origin), x_edge, optional_direction(x_dir), + offset, flip); + }, + py::arg("face"), py::kw_only(), py::arg("origin") = py::none(), py::arg("x_edge") = py::none(), + py::arg("x_dir") = py::none(), py::arg("offset") = 0.0, py::arg("flip") = false, + "Create a workplane on a planar face (its normal, its centre or a given origin, x along an edge)."); + m.def( + "make_workplane_from_points_rworkplane", + [](const AnyOf& a, const AnyOf& b, const AnyOf& c) { + return make_workplane_from_points_rworkplane(point_or_vertex(a, "a"), point_or_vertex(b, "b"), + point_or_vertex(c, "c")); + }, + py::arg("a"), py::arg("b"), py::arg("c"), "Create a workplane through three points (origin a, x towards b)."); + m.def( + "make_workplane_from_axis_rworkplane", + [](const Edge& axis, const Angle& angle, const std::optional& face) { + return make_workplane_from_axis_rworkplane(axis, angle, face); + }, + py::arg("axis"), py::arg("angle") = 0.0, py::kw_only(), py::arg("face") = py::none(), + "Create a workplane through a straight edge or a circle's axis, turned about it by an angle."); + m.def("make_workplane_midplane_rworkplane", &make_workplane_midplane_rworkplane, py::arg("face_a"), py::arg("face_b"), + "Create the workplane halfway between two parallel planar faces."); + m.def( + "make_workplane_normal_to_curve_rworkplane", + [](const AnyOf& curve, const Scalar& at, const std::optional& x_dir) { + return make_workplane_normal_to_curve_rworkplane(edge_or_wire(curve), at, optional_direction(x_dir)); + }, + py::arg("curve"), py::arg("at") = 0.0, py::kw_only(), py::arg("x_dir") = py::none(), + "Create a workplane normal to a curve at a fraction of its length (a sweep profile's plane)."); +} + void bind_brep_region(py::module_& m) { m.def( "load_brep_region_rsolid", @@ -468,6 +543,7 @@ void bind_ops_geometry(py::module_& m) { bind_wires_and_faces(m); bind_primitives(m); bind_brep_region(m); + bind_workplanes(m); bind_aliases(m); bind_testing(m); scad::register_geometry_executors(scad::reactive::ExecutorRegistry::global()); diff --git a/src/cpp/bindings/python/bind_sketch.cpp b/src/cpp/bindings/python/bind_sketch.cpp index 884d5d96..e9afcfbe 100644 --- a/src/cpp/bindings/python/bind_sketch.cpp +++ b/src/cpp/bindings/python/bind_sketch.cpp @@ -133,7 +133,7 @@ using scad::pybind::Choice; using scad::pybind::Length; // The names the signatures show. -struct PlaneTag { // read by make_sketch_rsketch: a named plane or {"origin", "x_axis", "y_axis"} +struct PlaneTag { // read by make_sketch_rsketch: a named plane, {"origin", "x_axis", "y_axis"} or a Workplane static constexpr auto name = py::detail::const_name("simplecadapi.types.Plane"); }; struct EndTag { @@ -597,6 +597,8 @@ void bind_entity_operators(py::module_& m) { "make_sketch_rsketch", [](const std::optional& name, const AnyOf& plane, const std::optional& sketch_id) { + if (py::isinstance(plane.value)) + return make_sketch_rsketch(name, plane.value.cast(), sketch_id); return make_sketch_rsketch(name, value_from_python(plane.value), sketch_id); }, py::arg("name") = py::none(), py::kw_only(), py::arg("plane") = "XY", py::arg("sketch_id") = py::none()); diff --git a/src/cpp/include/scad/core/coordinate_system.hpp b/src/cpp/include/scad/core/coordinate_system.hpp index 069756bb..9393c3d5 100644 --- a/src/cpp/include/scad/core/coordinate_system.hpp +++ b/src/cpp/include/scad/core/coordinate_system.hpp @@ -7,7 +7,9 @@ #pragma once #include +#include +#include "scad/core/value.hpp" #include "scad/core/vec.hpp" namespace scad { @@ -58,27 +60,69 @@ class CoordinateSystemScope { CoordinateSystem cs_; }; -// The workplane context manager: builds the frame from (origin, normal, x_dir) -// expressed in the *current* system, then pushes it. +// Where the innermost active frame came from: the recorded node of the Workplane value that pushed it +// (its runtime "graph.id" / "graph.node_id" / "graph.output_slot"). A recorder writes it into the context of +// every operation made inside the workplane, so a replay can take the frame from the replayed workplane +// instead of the numbers frozen at recording time. +struct FrameSource { + std::string graph_id; + std::string node_id; + int output_slot = 0; +}; + +// The source of the innermost active frame; nullptr for the world frame, a CoordinateSystemScope or a +// workplane that no recorder saw. +const FrameSource* current_frame_source(); + +// A workplane: a frame in world coordinates that is also the context manager making it the current system. +// +// It is a value: copies share nothing but the frame, it can be entered again after it is left (`with wp:` +// in several places), and it carries metadata / runtime dictionaries like the other recorded values, so the +// operation that made it (make_workplane_*_rworkplane) is its graph lineage. class Workplane { public: + // The frame from (origin, normal, x_dir) expressed in the *current* system. Workplane(const Vec3& origin = {0, 0, 0}, const Vec3& normal = {0, 0, 1}, const Vec3& x_dir = {1, 0, 0}); - // The stack holds the address of cs_, so a Workplane never moves. - Workplane(const Workplane&) = delete; + // A workplane on an exact world frame (no current-system transform). + static Workplane from_frame(const CoordinateSystem& cs); + + // A copy has the same frame, its own copies of the dictionaries, and is not entered. + Workplane(const Workplane& other); Workplane& operator=(const Workplane&) = delete; ~Workplane(); const CoordinateSystem& cs() const noexcept { return cs_; } + const Vec3& origin() const noexcept { return cs_.origin(); } + const Vec3& normal() const noexcept { return cs_.z_axis(); } + const Vec3& x_dir() const noexcept { return cs_.x_axis(); } + const Vec3& y_dir() const noexcept { return cs_.y_axis(); } + // {"origin", "x_axis", "y_axis"}: the frame as a sketch plane mapping (world coordinates). + Value plane_value() const; + std::string repr() const; std::string to_string(int indent = 0, bool show_coordinate_system = true) const; - // Python `with` support: push on enter, pop on exit. enter()/exit() must pair. + // Python `with` support: push on enter, pop on exit. enter()/exit() must pair; entering a workplane + // that is already entered is a RuntimeError. void enter(); void exit() noexcept; + bool entered() const noexcept { return entered_; } + + void set_metadata(std::string key, Value value) const { metadata_.set(std::move(key), std::move(value)); } + Value get_metadata(std::string_view key, Value fallback = {}) const; + void set_runtime(std::string key, Value value) const { runtime_.set(std::move(key), std::move(value)); } + Value get_runtime(std::string_view key, Value fallback = {}) const; + const Value& metadata() const noexcept { return metadata_; } + const Value& runtime() const noexcept { return runtime_; } private: + struct Exact {}; + Workplane(Exact, const CoordinateSystem& cs); + CoordinateSystem cs_; bool entered_ = false; + mutable Value metadata_ = Value::object(); + mutable Value runtime_ = Value::object(); }; } // namespace scad diff --git a/src/cpp/include/scad/ops/geometry/workplanes.hpp b/src/cpp/include/scad/ops/geometry/workplanes.hpp new file mode 100644 index 00000000..41726b41 --- /dev/null +++ b/src/cpp/include/scad/ops/geometry/workplanes.hpp @@ -0,0 +1,66 @@ +// Workplanes made from the model: recorded operations whose result is a Workplane value. +// +// A Workplane (scad/core/coordinate_system.hpp) is a frame in world coordinates and the context manager that +// makes it the current system. These operators build one from geometry -- a planar face, three points, an +// axis, two parallel faces, a curve -- and record the operation with its inputs as ordered `input_refs`, so a +// replay of the graph builds the frame again from the geometry as it is then (a sketch on a face's workplane +// follows the face). The result takes the lineage of the recorded node, like a Sketch or a Part. +// +// Points and directions given as numbers are read in the current coordinate system, like every operator's; +// geometry inputs are world-space already. The parameter `frame` of each record holds the frame that was made +// (world coordinates): what a reader that cannot rebuild the inputs falls back to. +#pragma once + +#include +#include + +#include "scad/core/coordinate_system.hpp" +#include "scad/core/scalar.hpp" +#include "scad/ops/geometry/types.hpp" +#include "scad/topo/shape.hpp" + +namespace scad { + +// A point given as numbers (current system) or as a vertex of the model. +using PointOrVertex = std::variant; +// A curve: one edge or a wire. +using EdgeOrWire = std::variant; + +// The recorded spelling of SimpleWorkplane(origin, normal, x_dir): a frame in the current system. +Workplane make_workplane_rworkplane(const Scalar3& origin = scalar3(0, 0, 0), const Scalar3& normal = scalar3(0, 0, 1), + const Scalar3& x_dir = scalar3(1, 0, 0)); + +// On a planar face: normal = the face's outward normal (`flip` reverses it), origin = the face's centre or +// `origin` projected onto the face's plane, x = along `x_edge` (its direction at its start, projected onto the +// plane), or along `x_dir` (projected), or the x direction of the face's own plane. `offset` moves the origin +// along the normal. ValueError for a face that is not planar, both `x_edge` and `x_dir`, or an x direction +// normal to the plane. +Workplane make_workplane_from_face_rworkplane(const Face& face, const std::optional& origin = std::nullopt, + const std::optional& x_edge = std::nullopt, + const std::optional& x_dir = std::nullopt, + const Scalar& offset = Scalar(0.0), bool flip = false); + +// Through three points: origin = a, x towards b, normal = (b - a) x (c - a). ValueError when they are collinear. +Workplane make_workplane_from_points_rworkplane(const PointOrVertex& a, const PointOrVertex& b, const PointOrVertex& c); + +// Through an axis, turned by `angle` (degrees, right-handed about the axis): the axis is a straight edge (from +// its start, along it) or a circular edge (its centre, along the circle's normal). x = the axis direction. At +// angle 0 the plane is the plane of `face` (a planar face containing the axis direction, usually one the edge +// bounds), or without one, the plane whose normal is the global Z (or X for an axis along Z) made square to the +// axis. ValueError for an edge that is neither straight nor circular, or a face whose normal is along the axis. +Workplane make_workplane_from_axis_rworkplane(const Edge& axis, const Scalar& angle = Scalar(0.0), + const std::optional& face = std::nullopt); + +// Halfway between two parallel planar faces: normal and x from `face_a`, origin = the middle between the centre +// of `face_a` and its projection onto the plane of `face_b`. ValueError when a face is not planar or the faces +// are not parallel. +Workplane make_workplane_midplane_rworkplane(const Face& face_a, const Face& face_b); + +// Normal to a curve, for a sweep profile: origin = the point at `at` (a fraction of the curve's length, 0 = +// start, 1 = end), normal = the direction of travel there, x = `x_dir` projected onto the plane, or the global Z +// made square to the normal (the global X when the tangent is near Z; orthonormal_plane_axes). ValueError for `at` +// outside [0, 1] or an x direction along the tangent. +Workplane make_workplane_normal_to_curve_rworkplane(const EdgeOrWire& curve, const Scalar& at = Scalar(0.0), + const std::optional& x_dir = std::nullopt); + +} // namespace scad diff --git a/src/cpp/include/scad/sketch/operators.hpp b/src/cpp/include/scad/sketch/operators.hpp index 6fbcbc04..2bf636eb 100644 --- a/src/cpp/include/scad/sketch/operators.hpp +++ b/src/cpp/include/scad/sketch/operators.hpp @@ -12,6 +12,7 @@ #include #include "scad/core/scalar.hpp" +#include "scad/core/coordinate_system.hpp" #include "scad/core/value.hpp" #include "scad/sketch/profile.hpp" #include "scad/sketch/sketch.hpp" @@ -24,9 +25,15 @@ using SketchConstraintId = std::optional; // ---- documents and entities ------------------------------------------------ // `plane`: "XY" | "XZ" | "YZ" or {"origin", "x_axis", "y_axis"}, read in the -// *current* coordinate system (the sketch stores it in world coordinates). +// *current* coordinate system (the sketch stores it in world coordinates). A mapping that also says +// "workplane": true is a world frame already (what a sketch on a workplane records) and is not transformed. Sketch make_sketch_rsketch(const std::optional& name = std::nullopt, const Value& plane = Value("XY"), const std::optional& sketch_id = std::nullopt); +// On a workplane: its frame, in world coordinates whatever the current system. The workplane's node (when it +// was recorded) is an input of the sketch's, and `plane` is recorded as {"workplane": true, origin, x_axis, +// y_axis}, so a replay takes the frame from the replayed workplane. +Sketch make_sketch_rsketch(const std::optional& name, const Workplane& plane, + const std::optional& sketch_id = std::nullopt); Sketch add_point_rsketch(const Sketch& sketch, const std::string& point_id, const Scalar& x, const Scalar& y); Sketch add_line_rsketch(const Sketch& sketch, const std::string& entity_id, const SketchTarget& start, diff --git a/src/cpp/src/core/coordinate_system.cpp b/src/cpp/src/core/coordinate_system.cpp index 5c4b6492..61880c91 100644 --- a/src/cpp/src/core/coordinate_system.cpp +++ b/src/cpp/src/core/coordinate_system.cpp @@ -65,10 +65,17 @@ std::string fixed3(const Vec3& v) { return buf; } +// One active system and, for a recorded workplane, the node that made it. +struct StackEntry { + const CoordinateSystem* cs; + FrameSource source; + bool has_source = false; +}; + // Thread-local stack of active systems. The bottom entry (the world frame) // is never popped. -std::vector& cs_stack() { - thread_local std::vector stack; +std::vector& cs_stack() { + thread_local std::vector stack; return stack; } @@ -124,11 +131,18 @@ const CoordinateSystem& world_cs() { const CoordinateSystem& current_cs() { const auto& stack = cs_stack(); - return stack.empty() ? world_cs() : *stack.back(); + return stack.empty() ? world_cs() : *stack.back().cs; +} + +const FrameSource* current_frame_source() { + const auto& stack = cs_stack(); + if (stack.empty() || !stack.back().has_source) + return nullptr; + return &stack.back().source; } CoordinateSystemScope::CoordinateSystemScope(CoordinateSystem cs) : cs_(std::move(cs)) { - cs_stack().push_back(&cs_); + cs_stack().push_back(StackEntry{&cs_, {}, false}); } CoordinateSystemScope::~CoordinateSystemScope() { @@ -168,14 +182,59 @@ CoordinateSystem workplane_frame(const Vec3& origin, const Vec3& normal, const V Workplane::Workplane(const Vec3& origin, const Vec3& normal, const Vec3& x_dir) : cs_(workplane_frame(origin, normal, x_dir)) {} +Workplane::Workplane(Exact, const CoordinateSystem& cs) : cs_(cs) {} + +Workplane Workplane::from_frame(const CoordinateSystem& cs) { + return Workplane(Exact{}, cs); +} + +Workplane::Workplane(const Workplane& other) + : cs_(other.cs_), entered_(false), metadata_(other.metadata_), runtime_(other.runtime_) {} + Workplane::~Workplane() { exit(); } +namespace { +Value lookup(const Value& dict, std::string_view key, Value fallback) { + const Value* found = dict.find(key); + return found != nullptr ? *found : std::move(fallback); +} +Value vec_value(const Vec3& v) { + return Value(Value::Array{Value(v.x), Value(v.y), Value(v.z)}); +} +} // namespace + +Value Workplane::get_metadata(std::string_view key, Value fallback) const { + return lookup(metadata_, key, std::move(fallback)); +} + +Value Workplane::get_runtime(std::string_view key, Value fallback) const { + return lookup(runtime_, key, std::move(fallback)); +} + +Value Workplane::plane_value() const { + Value out = Value::object(); + out.set("origin", vec_value(cs_.origin())); + out.set("x_axis", vec_value(cs_.x_axis())); + out.set("y_axis", vec_value(cs_.y_axis())); + return out; +} + void Workplane::enter() { if (entered_) throw RuntimeError("Workplane is already entered"); - cs_stack().push_back(&cs_); + StackEntry entry{&cs_, {}, false}; + const Value* node = runtime_.find("graph.node_id"); + if (node != nullptr && node->is_string() && !node->as_string().empty()) { + entry.has_source = true; + entry.source.node_id = node->as_string(); + if (const Value* graph = runtime_.find("graph.id"); graph != nullptr && graph->is_string()) + entry.source.graph_id = graph->as_string(); + if (const Value* slot = runtime_.find("graph.output_slot"); slot != nullptr && slot->is_int()) + entry.source.output_slot = static_cast(slot->as_int()); + } + cs_stack().push_back(std::move(entry)); entered_ = true; } diff --git a/src/cpp/src/ops/geometry/executors.cpp b/src/cpp/src/ops/geometry/executors.cpp index 15b27efa..c0a4a693 100644 --- a/src/cpp/src/ops/geometry/executors.cpp +++ b/src/cpp/src/ops/geometry/executors.cpp @@ -189,10 +189,21 @@ void register_primitives(reactive::ExecutorRegistry& registry) { }); } +// The workplane constructors make a value, not a shape: like the product values, they have nothing to +// recompute here (a model-JSON replay rebuilds the frame from the recorded inputs). +void register_workplanes(reactive::ExecutorRegistry& registry) { + for (const char* operation : {"make_workplane_rworkplane", "make_workplane_from_face_rworkplane", + "make_workplane_from_points_rworkplane", "make_workplane_from_axis_rworkplane", + "make_workplane_midplane_rworkplane", "make_workplane_normal_to_curve_rworkplane"}) { + registry.add(operation, [](Params, Inputs, const ScalarValues&) { return std::vector{}; }); + } +} + } // namespace void register_geometry_executors(reactive::ExecutorRegistry& registry) { register_curves(registry); + register_workplanes(registry); register_splines(registry); register_assemblies(registry); register_primitives(registry); diff --git a/src/cpp/src/ops/geometry/workplanes.cpp b/src/cpp/src/ops/geometry/workplanes.cpp new file mode 100644 index 00000000..c1206cea --- /dev/null +++ b/src/cpp/src/ops/geometry/workplanes.cpp @@ -0,0 +1,395 @@ +// make_workplane_*_rworkplane: workplanes from the model (see scad/ops/geometry/workplanes.hpp). +#include "scad/ops/geometry/workplanes.hpp" + +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "internal.hpp" +#include "scad/kernel/convert.hpp" +#include "scad/kernel/properties.hpp" +#include "scad/ops/geometry/plane.hpp" +#include "scad/topo/value_lineage.hpp" + +namespace scad { + +using namespace geometry_detail; + +namespace { + +constexpr double kSquareTolerance = 1e-9; // |cross| below this: parallel; |projection| below this: degenerate +constexpr double kParallelFaces = 1e-6; // |n_a x n_b| above this: the faces are not parallel + +// Round-off of a centroid or a rotation (|v| < 1e-12): a frame of exact zeros reads better in a cell and a report. +Vec3 clean(const Vec3& v) { + const auto snap = [](double c) { return std::abs(c) < 1e-12 ? 0.0 : c; }; + return {snap(v.x), snap(v.y), snap(v.z)}; +} + +// The workplane on (origin, normal, x): x is projected onto the plane first. +Workplane frame(const Vec3& origin_in, const Vec3& normal_in, const Vec3& x_in, const char* x_what) { + const Vec3 origin = clean(origin_in); + const Vec3 normal = clean(normal_in); + const Vec3 x = clean(x_in); + const double n_norm = normal.norm(); + if (!(n_norm > kSquareTolerance)) + throw ValueError("The workplane normal is a zero vector"); + const Vec3 n = normal / n_norm; + Vec3 in_plane = x - n * x.dot(n); + const double x_norm = in_plane.norm(); + if (!(x_norm > kSquareTolerance)) + throw ValueError(std::string("The ") + x_what + " is normal to the workplane: it gives no direction in the plane"); + in_plane = in_plane / x_norm; + return Workplane::from_frame(CoordinateSystem(origin, in_plane, n.cross(in_plane))); +} + +// A planar face: its outward normal, the x direction of its plane, its centre. +struct PlanarFace { + Vec3 normal; + Vec3 x_axis; + Vec3 center; +}; + +PlanarFace planar_face(const Face& face, const char* what) { + const TopoDS_Face& f = TopoDS::Face(face.wrapped()); + const BRepAdaptor_Surface surface(f, false); + if (surface.GetType() != GeomAbs_Plane) + throw ValueError(std::string(what) + " must be a planar face; a workplane lies on a plane"); + return occt_guard([&] { + const gp_Pln plane = surface.Plane(); + gp_Dir normal = plane.Axis().Direction(); + if (f.Orientation() == TopAbs_REVERSED) + normal.Reverse(); + return PlanarFace{kernel::from_dir(normal), kernel::from_dir(plane.XAxis().Direction()), kernel::center_of_mass(f)}; + }); +} + +// An edge's direction of travel at its start (its orientation counts). +Vec3 edge_start_direction(const Edge& edge) { + return occt_guard([&] { + const TopoDS_Edge& e = TopoDS::Edge(edge.wrapped()); + const BRepAdaptor_Curve curve(e); + const bool reversed = e.Orientation() == TopAbs_REVERSED; + gp_Pnt point; + gp_Vec tangent; + curve.D1(reversed ? curve.LastParameter() : curve.FirstParameter(), point, tangent); + if (reversed) + tangent.Reverse(); + return kernel::from_vec(tangent); + }); +} + +// A line through `origin` along `direction`: a straight edge or the axis of a circular one. +struct Axis { + Vec3 origin; + Vec3 direction; +}; + +Axis edge_axis(const Edge& edge) { + const TopoDS_Edge& e = TopoDS::Edge(edge.wrapped()); + const BRepAdaptor_Curve curve(e); + const bool reversed = e.Orientation() == TopAbs_REVERSED; + if (curve.GetType() == GeomAbs_Line) { + return occt_guard([&] { + const gp_Pnt start = curve.Value(reversed ? curve.LastParameter() : curve.FirstParameter()); + gp_Dir direction = curve.Line().Direction(); + if (reversed) + direction.Reverse(); + return Axis{kernel::from_pnt(start), kernel::from_dir(direction)}; + }); + } + if (curve.GetType() == GeomAbs_Circle) { + return occt_guard([&] { + const gp_Circ circle = curve.Circle(); + return Axis{kernel::from_pnt(circle.Location()), kernel::from_dir(circle.Axis().Direction())}; + }); + } + throw ValueError("The axis must be a straight edge or a circular edge (its centre line)"); +} + +// `v` turned by `radians` about the unit axis `k` (right-handed). +Vec3 rotate_about(const Vec3& v, const Vec3& k, double radians) { + const double c = std::cos(radians); + const double s = std::sin(radians); + return v * c + k.cross(v) * s + k * (k.dot(v) * (1.0 - c)); +} + +Vec3 point_of(const PointOrVertex& point, const char* label) { + if (const auto* numbers = std::get_if(&point)) + return place_point(*numbers, label); + return std::get(point).coordinates(); +} + +// The wire a curve argument walks along. +TopoDS_Wire curve_wire(const EdgeOrWire& curve) { + if (const auto* wire = std::get_if(&curve)) + return TopoDS::Wire(wire->wrapped()); + return occt_guard([&] { return BRepBuilderAPI_MakeWire(TopoDS::Edge(std::get(curve).wrapped())).Wire(); }); +} + +const Shape& curve_shape(const EdgeOrWire& curve) { + if (const auto* wire = std::get_if(&curve)) + return *wire; + return std::get(curve); +} + +// Hands the operation to the recorder: the inputs as ordered input_refs (a replay rebuilds the frame from +// them), the frame made as `frame`, and the workplane takes the lineage of the node. +// Call it only when current_recorder() is set. +void record_workplane(const Workplane& workplane, OpRecord record) { + Recorder* recorder = current_recorder(); + if (recorder == nullptr) + return; + record.params.set("frame", workplane.plane_value()); + if (!record.inputs.empty()) { + std::vector shapes; + for (const OpInput& input : record.inputs) + shapes.push_back(input.shape); + if (std::optional refs = recorder->input_refs(shapes); + refs && refs->is_array() && refs->as_array().size() == shapes.size()) + record.params.set("input_refs", std::move(*refs)); + } + if (const auto lineage = recorder->record_value_op(record, {})) + attach_value_lineage(workplane, *lineage, record.op); +} + +std::vector workplane_labels() { + return {"datum", "workplane"}; +} + +// {"input": index}: a parameter given as the input at `index` of input_refs. +Value input_param(int index) { + Value out = Value::object(); + out.set("input", static_cast(index)); + return out; +} + +} // namespace + +Workplane make_workplane_rworkplane(const Scalar3& origin, const Scalar3& normal, const Scalar3& x_dir) { + static constexpr const char* kOp = "make_workplane_rworkplane"; + static const ErrorSpec kSpec{ + kOp, + "Failed to create a workplane.", + {"The origin, normal, or x direction is not a finite 3D vector.", "The normal is a zero vector."}, + {"Pass origin, normal, and x_dir as 3-element numeric tuples or expressions.", + "Use a non-zero normal; an x_dir along the normal is replaced by a perpendicular."}}; + return guarded(kSpec, [&] { + Workplane workplane(evaluate_point(origin, "origin"), evaluate_point(normal, "normal"), + evaluate_point(x_dir, "x_dir")); + if (current_recorder() != nullptr) + record_workplane(workplane, OpParams(kOp, workplane_labels()) + .point("origin", origin) + .point("normal", normal) + .point("x_dir", x_dir) + .take()); + return workplane; + }); +} + +Workplane make_workplane_from_face_rworkplane(const Face& face, const std::optional& origin, + const std::optional& x_edge, const std::optional& x_dir, + const Scalar& offset, bool flip) { + static constexpr const char* kOp = "make_workplane_from_face_rworkplane"; + static const ErrorSpec kSpec{ + kOp, + "Failed to create a workplane on the face.", + {"The face is not planar.", "Both x_edge and x_dir were given.", + "The x edge or x direction is normal to the face, so it gives no direction in the plane.", + "The origin, x direction, or offset is not finite."}, + {"Pick a planar face (a cylinder or a B-spline face has no single plane).", + "Give the x direction once: an edge of the face (x_edge) or a vector (x_dir).", + "Use an edge that lies in the face or a direction along the face."}}; + return guarded(kSpec, [&] { + if (x_edge && x_dir) + throw ValueError("Give x_edge or x_dir, not both"); + const PlanarFace plane = planar_face(face, "face"); + const Vec3 normal = flip ? plane.normal * -1.0 : plane.normal; + Vec3 at = plane.center; + if (origin) { + const Vec3 given = place_point(*origin, "origin"); + at = given - plane.normal * (given - plane.center).dot(plane.normal); + } + at = at + normal * evaluate_scalar(offset, "offset"); + Vec3 x = plane.x_axis; + const char* x_what = "face's x direction"; + if (x_edge) { + x = edge_start_direction(*x_edge); + x_what = "x edge"; + } else if (x_dir) { + x = place_vector(*x_dir, "x_dir"); + x_what = "x direction"; + } + Workplane workplane = frame(at, normal, x, x_what); + if (current_recorder() != nullptr) { + OpParams params(kOp, workplane_labels()); + params.optional_point("origin", origin).optional_point("x_dir", x_dir).scalar("offset", offset); + params.boolean("flip", flip).input(face, "face"); + if (x_edge) + params.input(*x_edge, "x_edge"); + OpRecord record = params.take(); + record.params.set("x_edge", x_edge ? input_param(1) : Value()); + record_workplane(workplane, std::move(record)); + } + return workplane; + }); +} + +Workplane make_workplane_from_points_rworkplane(const PointOrVertex& a, const PointOrVertex& b, + const PointOrVertex& c) { + static constexpr const char* kOp = "make_workplane_from_points_rworkplane"; + static const ErrorSpec kSpec{kOp, + "Failed to create a workplane through three points.", + {"Two of the points coincide or the three points lie on one line.", + "A point is not a finite 3D point or a vertex."}, + {"Pick three points that span a plane (not on one line).", + "Pass each point as a Vertex of the model or a 3-element tuple."}}; + return guarded(kSpec, [&] { + const Vec3 pa = point_of(a, "a"); + const Vec3 pb = point_of(b, "b"); + const Vec3 pc = point_of(c, "c"); + const Vec3 x = pb - pa; + const Vec3 normal = x.cross(pc - pa); + const double scale = std::max({x.norm(), (pc - pa).norm(), 1.0}); + if (!(normal.norm() > kSquareTolerance * scale * scale)) + throw ValueError("The three points lie on one line (or two coincide): they do not span a plane"); + Workplane workplane = frame(pa, normal, x, "direction from a to b"); + if (current_recorder() != nullptr) { + OpParams params(kOp, workplane_labels()); + std::vector> by_input; + int index = 0; + for (const auto& [name, point] : {std::pair{"a", &a}, {"b", &b}, {"c", &c}}) { + if (const auto* numbers = std::get_if(point)) { + params.point(name, *numbers); + } else { + params.input(std::get(*point), name); + by_input.emplace_back(name, input_param(index++)); + } + } + OpRecord record = params.take(); + for (auto& [name, value] : by_input) + record.params.set(name, std::move(value)); + record_workplane(workplane, std::move(record)); + } + return workplane; + }); +} + +Workplane make_workplane_from_axis_rworkplane(const Edge& axis, const Scalar& angle, const std::optional& face) { + static constexpr const char* kOp = "make_workplane_from_axis_rworkplane"; + static const ErrorSpec kSpec{ + kOp, + "Failed to create a workplane through the axis.", + {"The edge is neither straight nor circular.", "The reference face is not planar.", + "The reference face's normal is along the axis, so the axis does not lie in its plane."}, + {"Use a straight edge, or a circular edge for its centre line.", + "Give a planar face that contains the axis direction (a face the edge bounds), or no face."}}; + return guarded(kSpec, [&] { + const Axis line = edge_axis(axis); + const Vec3 k = line.direction / line.direction.norm(); + Vec3 start_normal = orthonormal_plane_axes(k).x_axis; + if (face) { + const Vec3 n = planar_face(*face, "face").normal; + start_normal = n - k * n.dot(k); + if (!(start_normal.norm() > kSquareTolerance)) + throw ValueError("The face's normal is along the axis: the axis does not lie in the face's plane"); + start_normal = start_normal / start_normal.norm(); + } + const double radians = evaluate_scalar(angle, "angle") * kPi / 180.0; + Workplane workplane = frame(line.origin, rotate_about(start_normal, k, radians), k, "axis"); + if (current_recorder() != nullptr) { + OpParams params(kOp, workplane_labels()); + params.scalar("angle", angle).input(axis, "axis"); + if (face) + params.input(*face, "face"); + OpRecord record = params.take(); + record.params.set("face", face ? input_param(1) : Value()); + record_workplane(workplane, std::move(record)); + } + return workplane; + }); +} + +Workplane make_workplane_midplane_rworkplane(const Face& face_a, const Face& face_b) { + static constexpr const char* kOp = "make_workplane_midplane_rworkplane"; + static const ErrorSpec kSpec{kOp, + "Failed to create the workplane halfway between two faces.", + {"A face is not planar.", "The two faces are not parallel."}, + {"Pick two parallel planar faces (the two sides of a plate, a slot's walls)."}}; + return guarded(kSpec, [&] { + const PlanarFace a = planar_face(face_a, "face_a"); + const PlanarFace b = planar_face(face_b, "face_b"); + if (a.normal.cross(b.normal).norm() > kParallelFaces) + throw ValueError("The two faces are not parallel: a midplane needs parallel planar faces"); + const Vec3 on_b = a.center - b.normal * (a.center - b.center).dot(b.normal); + Workplane workplane = frame((a.center + on_b) * 0.5, a.normal, a.x_axis, "face's x direction"); + if (current_recorder() != nullptr) { + OpParams params(kOp, workplane_labels()); + params.input(face_a, "face_a").input(face_b, "face_b"); + record_workplane(workplane, params.take()); + } + return workplane; + }); +} + +Workplane make_workplane_normal_to_curve_rworkplane(const EdgeOrWire& curve, const Scalar& at, + const std::optional& x_dir) { + static constexpr const char* kOp = "make_workplane_normal_to_curve_rworkplane"; + static const ErrorSpec kSpec{ + kOp, + "Failed to create a workplane normal to the curve.", + {"`at` is outside [0, 1].", "The curve has no length.", "The x direction is along the curve's tangent there."}, + {"Pass at as a fraction of the curve's length: 0 = start, 1 = end.", + "Use an x_dir that is not along the curve at that point."}}; + return guarded(kSpec, [&] { + const double fraction = evaluate_scalar(at, "at"); + if (fraction < 0.0 || fraction > 1.0) + throw ValueError("at must be a fraction of the curve's length in [0, 1]"); + const TopoDS_Wire wire = curve_wire(curve); + const auto [point, tangent] = occt_guard([&] { + const BRepAdaptor_CompCurve adaptor(wire); + const double first = adaptor.FirstParameter(); + const double last = adaptor.LastParameter(); + double parameter = first; + if (fraction >= 1.0) { + parameter = last; + } else if (fraction > 0.0) { + const double length = GCPnts_AbscissaPoint::Length(adaptor); + if (!(length > 0.0)) + throw ValueError("The curve has no length"); + const GCPnts_AbscissaPoint abscissa(adaptor, fraction * length, first); + if (!abscissa.IsDone()) + throw ValueError("Could not find the point at that fraction of the curve's length"); + parameter = abscissa.Parameter(); + } + gp_Pnt p; + gp_Vec d; + adaptor.D1(parameter, p, d); + return std::pair{kernel::from_pnt(p), kernel::from_vec(d)}; + }); + if (!(tangent.norm() > kSquareTolerance)) + throw ValueError("The curve has no direction at that point"); + const Vec3 x = x_dir ? place_vector(*x_dir, "x_dir") : orthonormal_plane_axes(tangent).x_axis; + Workplane workplane = frame(point, tangent, x, "x direction"); + if (current_recorder() != nullptr) { + OpParams params(kOp, workplane_labels()); + params.scalar("at", at).optional_point("x_dir", x_dir).input(curve_shape(curve), "curve"); + record_workplane(workplane, params.take()); + } + return workplane; + }); +} + +} // namespace scad diff --git a/src/cpp/src/reactive/session.cpp b/src/cpp/src/reactive/session.cpp index 3a66f516..8686aeea 100644 --- a/src/cpp/src/reactive/session.cpp +++ b/src/cpp/src/reactive/session.cpp @@ -718,7 +718,18 @@ NodePtr Session::record_impl(const OpRecord& record, const std::vector& o graph_.graph_id(), node_id); } spec.tags.insert(record.labels.begin(), record.labels.end()); - spec.context = context_snapshot(cs); + Value context = context_snapshot(cs); + // Inside `with wp:` of a recorded workplane, the context names its node: a replay takes the frame from + // the replayed workplane (it may have moved with the geometry it was made from), not from these numbers. + if (const FrameSource* source = current_frame_source()) { + if (const NodePtr workplane = active_node_for(Lineage{source->graph_id, source->node_id, source->output_slot})) { + Value ref = Value::object(); + ref.set("node_id", workplane->node_id); + ref.set("output_slot", static_cast(source->output_slot)); + context.set("workplane", std::move(ref)); + } + } + spec.context = std::move(context); if (options_.source_provider) spec.source = options_.source_provider(); spec.expressions = referenced_expressions(spec.param_exprs, expressions_); diff --git a/src/cpp/src/sketch/finalize.cpp b/src/cpp/src/sketch/finalize.cpp index 3b7dd65d..c20dcaa6 100644 --- a/src/cpp/src/sketch/finalize.cpp +++ b/src/cpp/src/sketch/finalize.cpp @@ -8,12 +8,12 @@ namespace scad::sketch_detail { // The only place the sketch library hands an operation to the semantic pipeline. void finalize_sketch_object(const std::string& op, Value params, SymbolicArgs symbolic, const Sketch& output, - const Sketch* input) { + const Sketch* input, std::vector values) { OpRecord record; record.op = op; record.params = std::move(params); record.symbolic = std::move(symbolic); - std::vector inputs; + std::vector inputs = std::move(values); if (input != nullptr) if (auto lineage = value_lineage_of(*input)) inputs.push_back(std::move(*lineage)); diff --git a/src/cpp/src/sketch/finalize.hpp b/src/cpp/src/sketch/finalize.hpp index 5bb9cd7f..902d33c3 100644 --- a/src/cpp/src/sketch/finalize.hpp +++ b/src/cpp/src/sketch/finalize.hpp @@ -9,6 +9,7 @@ #include "scad/core/scalar.hpp" #include "scad/core/value.hpp" #include "scad/sketch/sketch.hpp" +#include "scad/topo/recorder.hpp" #include "scad/topo/shape.hpp" namespace scad::sketch_detail { @@ -18,8 +19,9 @@ using SymbolicArgs = std::vector>; // _finalize_runtime_object for Sketch outputs: the operation is reported with its // parameters (symbolic ones kept) and no shape output. // The result sketch takes the lineage of the node recorded; `input` (the sketch it was made from) links to it. +// `values`: the lineages of other value inputs (the workplane a sketch is made on). void finalize_sketch_object(const std::string& op, Value params, SymbolicArgs symbolic, const Sketch& output, - const Sketch* input = nullptr); + const Sketch* input = nullptr, std::vector values = {}); // _finalize_derived_shape for a promoted Wire / Face. Returns the handle the // operator must hand back (the finalize pipeline may return a detached view). diff --git a/src/cpp/src/sketch/operators_entities.cpp b/src/cpp/src/sketch/operators_entities.cpp index cbdd0883..e37835a2 100644 --- a/src/cpp/src/sketch/operators_entities.cpp +++ b/src/cpp/src/sketch/operators_entities.cpp @@ -6,6 +6,7 @@ #include "scad/core/coordinate_system.hpp" #include "scad/core/error.hpp" #include "scad/sketch/operators.hpp" +#include "scad/topo/value_lineage.hpp" namespace scad { @@ -69,6 +70,13 @@ Value plane_in_current_coordinates(const Value& plane) { origin = vec_from_value(plane.find("origin"), origin); x_axis = vec_from_value(plane.find("x_axis"), x_axis); y_axis = vec_from_value(plane.find("y_axis"), y_axis); + if (const Value* world = plane.find("workplane"); world != nullptr && world->is_bool() && world->as_bool()) { + Value out = Value::object(); // a workplane's frame: world coordinates already + out.set("origin", vec_value(origin)); + out.set("x_axis", vec_value(x_axis)); + out.set("y_axis", vec_value(y_axis)); + return out; + } } else { throw ValueError("Sketch plane must be 'XY', 'XZ', 'YZ', or a plane mapping"); } @@ -99,6 +107,28 @@ Sketch make_sketch_rsketch(const std::optional& name, const Value& }); } +Sketch make_sketch_rsketch(const std::optional& name, const Workplane& plane, + const std::optional& sketch_id) { + static const ErrorSpec kSpec{"make_sketch_rsketch", + "Failed to create a sketch document on the workplane.", + {"The sketch name is invalid."}, + {"Pass a Workplane made by SimpleWorkplane(...) or a make_workplane_*_rworkplane op."}}; + return guarded(kSpec, [&] { + Sketch sketch(name, plane.plane_value(), sketch_id); + Value recorded = plane.plane_value(); + recorded.set("workplane", true); + Value params = Value::object(); + params.set("name", name ? Value(*name) : Value()); + params.set("plane", std::move(recorded)); + params.set("sketch_id", sketch.sketch_id()); + std::vector values; + if (auto lineage = value_lineage_of(plane)) + values.push_back(std::move(*lineage)); + finalize_sketch_object("make_sketch_rsketch", std::move(params), {}, sketch, nullptr, std::move(values)); + return sketch; + }); +} + Sketch add_point_rsketch(const Sketch& sketch, const std::string& point_id, const Scalar& x, const Scalar& y) { static const ErrorSpec kSpec{ "add_point_rsketch", diff --git a/src/cpp/tests/cpp/core/test_core.cpp b/src/cpp/tests/cpp/core/test_core.cpp index 568f5b8e..d76e745b 100644 --- a/src/cpp/tests/cpp/core/test_core.cpp +++ b/src/cpp/tests/cpp/core/test_core.cpp @@ -69,3 +69,33 @@ TEST_CASE("Value keeps object insertion order and dumps JSON") { CHECK(v.dump() == R"({"b":2.5,"a":"x"})"); CHECK(Value(1) == Value(1.0)); } + +TEST_CASE("a Workplane is a value: copied, entered again, and on an exact frame") { + Workplane wp({0, 0, 5}, {0, 1, 0}, {1, 0, 0}); + wp.set_runtime("graph.node_id", Value("node_7")); + const Workplane copy(wp); + CHECK(copy.origin() == Vec3{0, 0, 5}); + CHECK(copy.normal() == Vec3{0, 1, 0}); + CHECK(copy.get_runtime("graph.node_id").as_string() == "node_7"); + CHECK_FALSE(copy.entered()); + for (int round = 0; round < 2; ++round) { // `with wp:` twice + wp.enter(); + CHECK(current_cs().origin() == Vec3{0, 0, 5}); + REQUIRE(current_frame_source() != nullptr); + CHECK(current_frame_source()->node_id == "node_7"); + wp.exit(); + CHECK(current_frame_source() == nullptr); + } + { + CoordinateSystemScope plain(CoordinateSystem({1, 2, 3}, {1, 0, 0}, {0, 1, 0})); + CHECK(current_frame_source() == nullptr); // a plain scope has no recorded source + const Workplane exact = Workplane::from_frame(CoordinateSystem({9, 0, 0}, {0, 1, 0}, {0, 0, 1})); + CHECK(exact.origin() == Vec3{9, 0, 0}); // not moved by the current system + CHECK(exact.normal() == Vec3{1, 0, 0}); + const Value plane = exact.plane_value(); + CHECK(plane.find("x_axis")->dump() == "[0,1,0]"); + } + wp.enter(); + CHECK_THROWS_AS(wp.enter(), RuntimeError); + wp.exit(); +} diff --git a/src/cpp/tests/cpp/ops_geometry/test_workplanes.cpp b/src/cpp/tests/cpp/ops_geometry/test_workplanes.cpp new file mode 100644 index 00000000..af4af5ad --- /dev/null +++ b/src/cpp/tests/cpp/ops_geometry/test_workplanes.cpp @@ -0,0 +1,123 @@ +// The workplane constructors: frames from faces, points, axes, two faces and curves; what they record. +#include "support.hpp" + +#include "scad/kernel/properties.hpp" +#include "scad/ops/geometry/executors.hpp" +#include "scad/ops/geometry/workplanes.hpp" +#include "scad/reactive/registry.hpp" + +using namespace scad; +using namespace scad::geometry_test; + +namespace { + +void check_vec(const Vec3& actual, const Vec3& expected) { + CHECK(actual.x == doctest::Approx(expected.x).epsilon(1e-9)); + CHECK(actual.y == doctest::Approx(expected.y).epsilon(1e-9)); + CHECK(actual.z == doctest::Approx(expected.z).epsilon(1e-9)); +} + +Face face_with_normal(const Solid& solid, const Vec3& normal) { + for (const Face& face : solid.faces()) + if (face.normal_at().dot(normal) > 0.999) + return face; + FAIL("no face with that normal"); + return solid.faces().front(); +} + +} // namespace + +TEST_CASE("a workplane on a planar face: its centre, its outward normal, an offset, an x edge") { + const Solid box = make_box_rsolid(10.0, 20.0, 5.0); + const Face top = face_with_normal(box, {0, 0, 1}); + const Workplane on_top = make_workplane_from_face_rworkplane(top); + check_vec(on_top.origin(), {0, 0, 5}); + check_vec(on_top.normal(), {0, 0, 1}); + + const Workplane lifted = make_workplane_from_face_rworkplane(top, scalar3(3, 4, 99), std::nullopt, std::nullopt, 2.0); + check_vec(lifted.origin(), {3, 4, 7}); // the given origin, projected onto the face, then moved along the normal + + const Face bottom = face_with_normal(box, {0, 0, -1}); + check_vec(make_workplane_from_face_rworkplane(bottom).normal(), {0, 0, -1}); + check_vec(make_workplane_from_face_rworkplane(bottom, std::nullopt, std::nullopt, std::nullopt, 0.0, true).normal(), + {0, 0, 1}); + + const Edge along_y = make_line_redge(scalar3(0, 0, 5), scalar3(0, 1, 5)); + const Workplane turned = make_workplane_from_face_rworkplane(top, std::nullopt, along_y); + check_vec(turned.x_dir(), {0, 1, 0}); + check_vec(turned.y_dir(), {-1, 0, 0}); + CHECK_THROWS_AS(make_workplane_from_face_rworkplane(top, std::nullopt, along_y, scalar3(1, 0, 0)), Error); + + const Solid cylinder = make_cylinder_rsolid(2.0, 4.0); + for (const Face& face : cylinder.faces()) { + if (std::abs(face.normal_at().z) < 0.5) { + CHECK_THROWS_AS(make_workplane_from_face_rworkplane(face), Error); // not planar + } + } +} + +TEST_CASE("three points, an axis turned by an angle, a midplane, a curve's normal plane") { + const Workplane through = make_workplane_from_points_rworkplane(scalar3(1, 1, 1), scalar3(2, 1, 1), scalar3(1, 1, 3)); + check_vec(through.origin(), {1, 1, 1}); + check_vec(through.x_dir(), {1, 0, 0}); + check_vec(through.normal(), {0, -1, 0}); + CHECK_THROWS_AS(make_workplane_from_points_rworkplane(scalar3(0, 0, 0), scalar3(1, 0, 0), scalar3(2, 0, 0)), Error); + const Vertex v(make_point_rvertex(0.0, 0.0, 7.0)); + check_vec(make_workplane_from_points_rworkplane(v, scalar3(1, 0, 7), scalar3(0, 1, 7)).origin(), {0, 0, 7}); + + const Edge x_axis = make_line_redge(scalar3(0, 0, 0), scalar3(10, 0, 0)); + const Workplane flat = make_workplane_from_axis_rworkplane(x_axis); + check_vec(flat.normal(), {0, 0, 1}); // global Z made square to the axis + const Workplane tilted = make_workplane_from_axis_rworkplane(x_axis, 90.0); + check_vec(tilted.normal(), {0, -1, 0}); // Z turned 90 degrees about +X + check_vec(tilted.x_dir(), {1, 0, 0}); + const Edge ring = make_circle_redge(scalar3(0, 0, 3), 2.0, scalar3(0, 0, 1)); + const Workplane through_axis = make_workplane_from_axis_rworkplane(ring); + check_vec(through_axis.origin(), {0, 0, 3}); + check_vec(through_axis.x_dir(), {0, 0, 1}); + + const Solid box = make_box_rsolid(10.0, 20.0, 5.0); + const Workplane middle = + make_workplane_midplane_rworkplane(face_with_normal(box, {1, 0, 0}), face_with_normal(box, {-1, 0, 0})); + check_vec(middle.origin(), {0, 0, 2.5}); + check_vec(middle.normal(), {1, 0, 0}); + CHECK_THROWS_AS( + make_workplane_midplane_rworkplane(face_with_normal(box, {1, 0, 0}), face_with_normal(box, {0, 0, 1})), Error); + + const Workplane halfway = make_workplane_normal_to_curve_rworkplane(x_axis, 0.25); + check_vec(halfway.origin(), {2.5, 0, 0}); + check_vec(halfway.normal(), {1, 0, 0}); + check_vec(make_workplane_normal_to_curve_rworkplane(x_axis, 1.0).origin(), {10, 0, 0}); + CHECK_THROWS_AS(make_workplane_normal_to_curve_rworkplane(x_axis, 1.5), Error); +} + +TEST_CASE("a workplane is recorded with its inputs; an operation inside it names its node") { + Recording recording; + const Face face = make_rectangle_rface(4.0, 2.0, scalar3(0, 0, 3)); + const Workplane wp = make_workplane_from_face_rworkplane(face); + const auto& nodes = recording.session.graph().nodes(); + const auto& made = *nodes.back(); + CHECK(made.op == "make_workplane_from_face_rworkplane"); + CHECK(made.params.find("input_refs")->size() == 1); + CHECK(made.params.find("frame")->find("origin")->dump() == "[0,0,3]"); + CHECK(wp.get_runtime("graph.node_id").as_string() == made.node_id); + + Workplane entered(wp); + entered.enter(); + make_box_rsolid(1.0, 1.0, 1.0); + entered.exit(); + const auto& inside = *recording.session.graph().nodes().back(); + REQUIRE(inside.context); + CHECK(inside.context->find("workplane")->find("node_id")->as_string() == made.node_id); + CHECK(inside.context->find("origin")->dump() == "[0,0,3]"); +} + +TEST_CASE("the workplane constructors have (value) executors") { + reactive::ExecutorRegistry registry(false); + register_geometry_executors(registry); + for (const char* op : {"make_workplane_rworkplane", "make_workplane_from_face_rworkplane", + "make_workplane_from_points_rworkplane", "make_workplane_from_axis_rworkplane", + "make_workplane_midplane_rworkplane", "make_workplane_normal_to_curve_rworkplane"}) { + CHECK_MESSAGE(registry.contains(op), op); + } +} diff --git a/src/cpp/tests/cpp/sketch/test_operators.cpp b/src/cpp/tests/cpp/sketch/test_operators.cpp index dbd18381..92bccb33 100644 --- a/src/cpp/tests/cpp/sketch/test_operators.cpp +++ b/src/cpp/tests/cpp/sketch/test_operators.cpp @@ -387,3 +387,46 @@ TEST_CASE("backends are pluggable and the default is the native solver") { } CHECK(get_default_sketch_solver_backend()->name() == "scad-native"); } + +namespace { +class ValueRecorder : public Recorder { + public: + void record(const OpRecord& record, const std::vector&) override { params.push_back(record.params); } + std::optional record_value_op(const OpRecord& record, + const std::vector& value_inputs) override { + params.push_back(record.params); + inputs = value_inputs; + return std::nullopt; + } + std::vector params; + std::vector inputs; +}; +} // namespace + +TEST_CASE("a sketch on a workplane takes its frame whatever the current system, and records the workplane") { + Workplane wp({0, 0, 4}, {1, 0, 0}, {0, 1, 0}); // the YZ plane through (0, 0, 4): x = +Y + wp.set_runtime("graph.node_id", Value("node_wp")); + ValueRecorder recorder; + RecorderScope scope(&recorder); + Workplane other({100, 0, 0}); + other.enter(); + const Sketch sketch = make_sketch_rsketch(std::string("on_wp"), wp); + other.exit(); + const SketchPlaneFrame frame = sketch.plane_frame(); + CHECK(frame.origin.z == doctest::Approx(4.0)); + CHECK(frame.origin.x == doctest::Approx(0.0)); // not moved by the entered workplane + CHECK(frame.normal.x == doctest::Approx(1.0)); + REQUIRE_FALSE(recorder.params.empty()); + const Value* plane = recorder.params.back().find("plane"); + REQUIRE(plane != nullptr); + CHECK(plane->find("workplane")->as_bool()); + REQUIRE(recorder.inputs.size() == 1); + CHECK(recorder.inputs.front().node_id == "node_wp"); + + // Its recorded plane read back as a mapping: a world frame, not transformed again. + Workplane moved({0, 0, 50}); + moved.enter(); + const Sketch again = make_sketch_rsketch(std::string("again"), *plane); + moved.exit(); + CHECK(again.plane_frame().origin.z == doctest::Approx(4.0)); +} diff --git a/src/simplecadapi/__init__.py b/src/simplecadapi/__init__.py index ac6a2746..7f9a5433 100644 --- a/src/simplecadapi/__init__.py +++ b/src/simplecadapi/__init__.py @@ -209,6 +209,12 @@ from simplecadapi._cpp import ( make_angle_arc_redge, make_angle_arc_rwire, make_box_rsolid, + make_workplane_rworkplane, + make_workplane_from_face_rworkplane, + make_workplane_from_points_rworkplane, + make_workplane_from_axis_rworkplane, + make_workplane_midplane_rworkplane, + make_workplane_normal_to_curve_rworkplane, make_circle_redge, make_circle_rface, make_circle_rwire, @@ -578,6 +584,12 @@ __all__ = [ "make_angle_arc_redge", "make_angle_arc_rwire", "make_box_rsolid", + "make_workplane_rworkplane", + "make_workplane_from_face_rworkplane", + "make_workplane_from_points_rworkplane", + "make_workplane_from_axis_rworkplane", + "make_workplane_midplane_rworkplane", + "make_workplane_normal_to_curve_rworkplane", "load_brep_region_rsolid", "load_brep_region_rshell", "make_circle_redge", diff --git a/src/simplecadapi/_glue/docstrings.json b/src/simplecadapi/_glue/docstrings.json index f6ee8e48..fd630954 100644 --- a/src/simplecadapi/_glue/docstrings.json +++ b/src/simplecadapi/_glue/docstrings.json @@ -40,7 +40,7 @@ "Shell": "OCP-native connected surface shell with face and edge topology.", "SimpleCADError": "Structured ValueError variant for LLM-oriented repair guidance.", "SimpleCADMessageError": "Message-first SDK error that still carries the structured payload.\n\nSole sanctioned base for message-style error families: raise sites keep\ntheir legacy ``Error(\"message\")`` call shape and plain ``str()`` display\nwhile the structured channel (guidance, ``to_dict``) becomes available\nfamily-wide. Guidance fields beyond ``what_happened`` stay empty until\neach family's designed guidance lands.", - "SimpleWorkplane": "Workplane context manager defining a local coordinate system.", + "SimpleWorkplane": "Workplane: a frame in world coordinates and the context manager that makes it the current coordinate system.\n\n``SimpleWorkplane(origin, normal, x_dir)`` (alias ``Workplane``) reads the three vectors in the current coordinate system;\nthe recorded constructors ``make_workplane_*_rworkplane`` build one from the model (a face, three points, an axis, two\nparallel faces, a curve). Inside ``with wp:`` point and vector parameters are local to it, and every recorded operation\nnotes the workplane's node, so a replay follows it. ``make_sketch_rsketch(plane=wp)`` draws a sketch on it.\n\nA value: enter it again later (``with wp:`` in another cell), copy or pickle it (the notebook cell cache does).\nAttributes (world coordinates): ``origin``, ``normal``, ``x_dir``, ``y_dir``, ``plane`` (the sketch-plane mapping),\n``cs`` (its CoordinateSystem).", "Sketch": "Declarative constrained sketch container.\n\nUse `make_sketch_rsketch(...)`, `add_point_rsketch(...)`,\n`add_line_rsketch(...)`, `add_circle_rsketch(...)`, and\n`constrain_*_rsketch(...)` as the canonical API for building sketch\nprofiles. Public sketch construction APIs are functional and return an\nupdated `Sketch` document. The legacy `curves` constructor remains only for\nreading already-built wire/edge containers.", "SketchConstraint": "Serializable constraint inside a declarative sketch.", "SketchConstraintDiagnostic": "Diagnostic emitted by the sketch solver.", @@ -245,7 +245,7 @@ "make_scalar_limit_rscalarlimit": "Create a closed scalar limit for driven constraint coordinates.", "make_segment_redge": "Alias of `make_line_redge` that returns a straight edge.", "make_segment_rwire": "Create a wire containing a single straight segment.", - "make_sketch_rsketch": "Create an empty declarative sketch document.\n\nUse this API, not concrete edge/wire constructors, when the intent is to\nbuild a sketch profile with constraints.", + "make_sketch_rsketch": "Create an empty declarative sketch document.\n\nUse this API, not concrete edge/wire constructors, when the intent is to\nbuild a sketch profile with constraints.\n\n``plane`` is ``\"XY\"``, ``\"XZ\"``, ``\"YZ\"`` or a frame mapping ``{origin, x_axis, y_axis}`` (read in the current\ncoordinate system), or a Workplane value (``make_workplane_*_rworkplane`` / ``SimpleWorkplane``), whose world frame is used\nas it is. A sketch on a recorded workplane names its node: a replay takes the frame from the replayed workplane, so a\nsketch on a face's workplane follows the face.", "make_solid_from_shell_rsolid": "Create an oriented Solid from one valid closed Shell.", "make_sphere_rsolid": "Create a sphere solid.", "make_spline_redge": "Create an exact B-spline edge from named control-point parameters.\n\nPass sampled curve points through `fit_cubic_bspline_control_points(...)` first,\nthen pass the result fields explicitly as `control_points=...`, `knots=...`,\nand `multiplicities=...`. `control_points` are poles, not interpolation\npoints; the curve generally does not pass through interior poles.", @@ -365,5 +365,11 @@ "rebuild_surface_rface": "Refit a face's surface as a B-spline of the given degrees and pole counts, or with the fewest poles that keep within ``tolerance``.\n\nGive both pole counts or neither. A least-squares fit in the face's own (u, v) parametrisation (over the surface's domain for a B-spline, over the face's bounds otherwise), so the face keeps its trimming. Works on any face. Returns a new Face; the input is not changed. Recorded: the Face and its boundary edges continue in the node's history, so tags and references follow.", "sample_curve_rcurvature": "Sample an edge for a curvature comb: ``count`` points evenly in its parameter range.\n\nReturns ``{parameters, points, tangents, normals, curvatures, max_curvature}`` in the current coordinate system; a normal points to the centre of curvature and is zero where the curve is straight. Not recorded in the graph.", "sample_surface_risocurves": "Sample isocurves of a face, clipped to its trimming.\n\n``u_count`` lines of constant u and ``v_count`` of constant v, evenly inside the face's (u, v) bounds, each sampled at ``samples`` points. Returns ``{u: [{parameter, segments}], v: [...], uv_bounds}``; ``segments`` are the runs of points that lie on the face. Not recorded in the graph.", - "set_body_appearance_rpart": "Set the display colour, opacity and display name of one body of a Part.\n\nA Part is a value: the result is a new Part, the input is unchanged. The colour is an\nappearance only. A body without a colour shows its Part's material colour\n(``Material.color``), and without either it shows the default grey: the body colour\noverrides the material colour for display (the live preview, the package scene, the STEP\nsurface colour of that solid). Mass, density and geometry never read it.\n\nArgs:\n part: The Part (one body or several).\n body_id: The body to change: an id from ``part.body_ids()``. A one-body Part has\n the one body ``\"body\"`` (the default).\n color: Display colour as RGB floats in [0.0, 1.0], e.g. ``(0.8, 0.2, 0.2)``;\n linear RGB, as ``Material.color``, OpenCASCADE (so STEP) and three.js read\n it (the editor's colour picker converts its sRGB ``#rrggbb``). ``None``\n keeps the body's colour.\n opacity: Display opacity in [0.0, 1.0] (1 is opaque). ``None`` keeps it. STEP\n export writes the colour, not the opacity.\n name: Display name of the body (the editor's bodies list, the scene node,\n the STEP solid). ``None`` keeps it. The ``body_id`` never changes.\n reset: Clear the colour, opacity and name first, so the body shows the material\n colour, opaque, under its id; then apply what is given.\n\nReturns:\n Part: The Part with that body's appearance changed; ``part.get_body(body_id).color``,\n ``.opacity`` and ``.name`` read it back.\n\nRaises:\n SimpleCADError: The value is not a Part, the part has no such body, the colour is\n not three numbers in [0, 1], the opacity is outside [0, 1], or the name is empty.\n\nUsage:\n ``case = scad.set_body_appearance_rpart(case, \"lid\", color=(0.9, 0.3, 0.2), name=\"Lid\")``\n paints the lid body of a multi-body part; ``scad.set_body_appearance_rpart(part,\n color=(0.2, 0.4, 0.8))`` paints a one-body part. Recorded and replayed like\n ``assign_material_rpart``. To name a face or an edge for people, tag it\n (``scad.apply_tag_rselection`` / ``ql.tag``): a tag is the name." -} + "set_body_appearance_rpart": "Set the display colour, opacity and display name of one body of a Part.\n\nA Part is a value: the result is a new Part, the input is unchanged. The colour is an\nappearance only. A body without a colour shows its Part's material colour\n(``Material.color``), and without either it shows the default grey: the body colour\noverrides the material colour for display (the live preview, the package scene, the STEP\nsurface colour of that solid). Mass, density and geometry never read it.\n\nArgs:\n part: The Part (one body or several).\n body_id: The body to change: an id from ``part.body_ids()``. A one-body Part has\n the one body ``\"body\"`` (the default).\n color: Display colour as RGB floats in [0.0, 1.0], e.g. ``(0.8, 0.2, 0.2)``;\n linear RGB, as ``Material.color``, OpenCASCADE (so STEP) and three.js read\n it (the editor's colour picker converts its sRGB ``#rrggbb``). ``None``\n keeps the body's colour.\n opacity: Display opacity in [0.0, 1.0] (1 is opaque). ``None`` keeps it. STEP\n export writes the colour, not the opacity.\n name: Display name of the body (the editor's bodies list, the scene node,\n the STEP solid). ``None`` keeps it. The ``body_id`` never changes.\n reset: Clear the colour, opacity and name first, so the body shows the material\n colour, opaque, under its id; then apply what is given.\n\nReturns:\n Part: The Part with that body's appearance changed; ``part.get_body(body_id).color``,\n ``.opacity`` and ``.name`` read it back.\n\nRaises:\n SimpleCADError: The value is not a Part, the part has no such body, the colour is\n not three numbers in [0, 1], the opacity is outside [0, 1], or the name is empty.\n\nUsage:\n ``case = scad.set_body_appearance_rpart(case, \"lid\", color=(0.9, 0.3, 0.2), name=\"Lid\")``\n paints the lid body of a multi-body part; ``scad.set_body_appearance_rpart(part,\n color=(0.2, 0.4, 0.8))`` paints a one-body part. Recorded and replayed like\n ``assign_material_rpart``. To name a face or an edge for people, tag it\n (``scad.apply_tag_rselection`` / ``ql.tag``): a tag is the name.", + "make_workplane_rworkplane": "Create a recorded workplane from an origin, a normal and an x direction.\n\nThe recorded spelling of ``SimpleWorkplane(origin, normal, x_dir)``: the three vectors are read in the current\ncoordinate system (inside ``with other_wp:`` they are local to it). An ``x_dir`` along the normal is replaced by a\nperpendicular; otherwise x is ``x_dir`` made square to the normal.\n\nArgs:\n origin: The origin of the plane.\n normal: The plane's normal (its local z axis); its length does not matter.\n x_dir: The direction of the local x axis, projected onto the plane.\n\nReturns:\n SimpleWorkplane: a frame in world coordinates (``origin``, ``normal``, ``x_dir``, ``y_dir``, ``plane``) that is\n also a context manager: ``with wp:`` makes it the current coordinate system, ``make_sketch_rsketch(plane=wp)``\n draws on it. It is a value: enter it again in later code, pickle it (the notebook cell cache does).\n\nRaises:\n SimpleCADError: The normal is zero or a value is not finite.\n\nUsage:\n ``wp = scad.make_workplane_rworkplane((0, 0, 40), (0, 1, 0))`` then ``with wp: ...`` or\n ``scad.make_sketch_rsketch(\"rib\", plane=wp)``.\n", + "make_workplane_from_face_rworkplane": "Create a workplane on a planar face of the model.\n\nnormal = the face's outward normal (``flip=True`` reverses it); origin = the face's centre, or ``origin``\nprojected onto the face's plane; x = along ``x_edge`` (its direction at its start, projected onto the plane), or\nalong ``x_dir`` (projected), or the x direction of the face's own plane. ``offset`` then moves the origin along\nthe normal (an offset datum plane).\n\nArgs:\n face: A planar Face (picked with ``ql``, ``get_faces(i)`` or a tag).\n origin: A point (current coordinate system) projected onto the face; ``None`` = the face's centre.\n x_edge: An Edge giving the x direction (usually an edge of the face).\n x_dir: A direction giving x; give ``x_edge`` or ``x_dir``, not both.\n offset: Distance along the normal from the face (mm).\n flip: Reverse the normal (draw from inside the body).\n\nReturns:\n SimpleWorkplane: a frame in world coordinates (``origin``, ``normal``, ``x_dir``, ``y_dir``, ``plane``) that is\n also a context manager: ``with wp:`` makes it the current coordinate system, ``make_sketch_rsketch(plane=wp)``\n draws on it. It is a value: enter it again in later code, pickle it (the notebook cell cache does).\n\nRaises:\n SimpleCADError: The face is not planar, both ``x_edge`` and ``x_dir`` were given, or the x direction is normal\n to the face.\n\nRecorded: the node takes the inputs as ordered references, so a model-JSON replay builds the frame again from the\ngeometry as it is then, and a sketch on the workplane (``plane=wp``) or an operation inside ``with wp:`` follows it.\n\nUsage:\n ``top = scad.ql.faces().where(scad.ql.tag(\"base.face.top\")).exactly(1).resolve(base)[0]``;\n ``wp = scad.make_workplane_from_face_rworkplane(top, offset=2)``.\n", + "make_workplane_from_points_rworkplane": "Create a workplane through three points: origin at ``a``, x towards ``b``, normal = (b - a) x (c - a).\n\nArgs:\n a: A Vertex of the model or a point (current coordinate system): the origin.\n b: A Vertex or a point: x points from ``a`` towards it.\n c: A Vertex or a point on the positive-y side of the plane.\n\nReturns:\n SimpleWorkplane: a frame in world coordinates (``origin``, ``normal``, ``x_dir``, ``y_dir``, ``plane``) that is\n also a context manager: ``with wp:`` makes it the current coordinate system, ``make_sketch_rsketch(plane=wp)``\n draws on it. It is a value: enter it again in later code, pickle it (the notebook cell cache does).\n\nRaises:\n SimpleCADError: The three points lie on one line or two coincide.\n\nRecorded: the node takes the inputs as ordered references, so a model-JSON replay builds the frame again from the\ngeometry as it is then, and a sketch on the workplane (``plane=wp``) or an operation inside ``with wp:`` follows it.\n\nUsage:\n ``scad.make_workplane_from_points_rworkplane(v0, v1, v2)`` with three picked vertices; points given as\n numbers are recorded as numbers.\n", + "make_workplane_from_axis_rworkplane": "Create a workplane through an axis, turned about it by an angle.\n\nThe axis is a straight edge (from its start, along it) or a circular edge (its centre line: through the centre,\nalong the circle's normal). x = the axis direction. At ``angle=0`` the plane is the plane of ``face`` (a planar face\ncontaining the axis direction, usually one the edge bounds) or, without one, the plane whose normal is global Z\n(global X for an axis along Z) made square to the axis; ``angle`` turns it right-handed about the axis.\n\nArgs:\n axis: A straight or circular Edge.\n angle: The turn about the axis, in degrees.\n face: The planar Face the plane starts from at angle 0.\n\nReturns:\n SimpleWorkplane: a frame in world coordinates (``origin``, ``normal``, ``x_dir``, ``y_dir``, ``plane``) that is\n also a context manager: ``with wp:`` makes it the current coordinate system, ``make_sketch_rsketch(plane=wp)``\n draws on it. It is a value: enter it again in later code, pickle it (the notebook cell cache does).\n\nRaises:\n SimpleCADError: The edge is neither straight nor circular, the face is not planar, or the face's normal is\n along the axis.\n\nRecorded: the node takes the inputs as ordered references, so a model-JSON replay builds the frame again from the\ngeometry as it is then, and a sketch on the workplane (``plane=wp``) or an operation inside ``with wp:`` follows it.\n\nUsage:\n ``scad.make_workplane_from_axis_rworkplane(edge, 30, face=top)``: a plane hinged on an edge of the top\n face, tilted 30 degrees.\n", + "make_workplane_midplane_rworkplane": "Create the workplane halfway between two parallel planar faces (a symmetry plane).\n\nnormal and x come from ``face_a``; origin = the middle between the centre of ``face_a`` and its projection onto the\nplane of ``face_b``.\n\nArgs:\n face_a: A planar Face; it gives the normal and x.\n face_b: A planar Face parallel to it.\n\nReturns:\n SimpleWorkplane: a frame in world coordinates (``origin``, ``normal``, ``x_dir``, ``y_dir``, ``plane``) that is\n also a context manager: ``with wp:`` makes it the current coordinate system, ``make_sketch_rsketch(plane=wp)``\n draws on it. It is a value: enter it again in later code, pickle it (the notebook cell cache does).\n\nRaises:\n SimpleCADError: A face is not planar or the faces are not parallel.\n\nRecorded: the node takes the inputs as ordered references, so a model-JSON replay builds the frame again from the\ngeometry as it is then, and a sketch on the workplane (``plane=wp``) or an operation inside ``with wp:`` follows it.\n\nUsage:\n ``mid = scad.make_workplane_midplane_rworkplane(left_wall, right_wall)``; mirror or sketch on it.\n", + "make_workplane_normal_to_curve_rworkplane": "Create a workplane normal to a curve: the plane of a sweep profile.\n\norigin = the point at ``at`` (a fraction of the curve's length: 0 = start, 1 = end); normal = the direction of\ntravel there; x = ``x_dir`` projected onto the plane, or global Z made square to the normal (global X when the\ntangent is near Z).\n\nArgs:\n curve: An Edge or a Wire (the sweep path).\n at: The fraction of the length, in [0, 1].\n x_dir: The direction of x, projected onto the plane.\n\nReturns:\n SimpleWorkplane: a frame in world coordinates (``origin``, ``normal``, ``x_dir``, ``y_dir``, ``plane``) that is\n also a context manager: ``with wp:`` makes it the current coordinate system, ``make_sketch_rsketch(plane=wp)``\n draws on it. It is a value: enter it again in later code, pickle it (the notebook cell cache does).\n\nRaises:\n SimpleCADError: ``at`` is outside [0, 1], the curve has no length, or ``x_dir`` is along the tangent.\n\nRecorded: the node takes the inputs as ordered references, so a model-JSON replay builds the frame again from the\ngeometry as it is then, and a sketch on the workplane (``plane=wp``) or an operation inside ``with wp:`` follows it.\n\nUsage:\n ``start = scad.make_workplane_normal_to_curve_rworkplane(path, 0)``;\n ``profile = ... make_sketch_rsketch(\"profile\", plane=start) ...``; ``sweep_rsolid(profile, path)``.\n" +} \ No newline at end of file diff --git a/src/simplecadapi/_glue/modules.json b/src/simplecadapi/_glue/modules.json index be031433..fe310f3e 100644 --- a/src/simplecadapi/_glue/modules.json +++ b/src/simplecadapi/_glue/modules.json @@ -287,6 +287,12 @@ "set_surface_weights_rface": "simplecadapi.operators.geometry", "make_bolt_rsolid": "simplecadapi.std.fastener", "make_box_rsolid": "simplecadapi.operators.geometry", +"make_workplane_rworkplane": "simplecadapi.operators.geometry", +"make_workplane_from_face_rworkplane": "simplecadapi.operators.geometry", +"make_workplane_from_points_rworkplane": "simplecadapi.operators.geometry", +"make_workplane_from_axis_rworkplane": "simplecadapi.operators.geometry", +"make_workplane_midplane_rworkplane": "simplecadapi.operators.geometry", +"make_workplane_normal_to_curve_rworkplane": "simplecadapi.operators.geometry", "make_bspline_edge": "simplecadapi.kernel.ocp_curves", "make_circle_edge": "simplecadapi.kernel.ocp_curves", "make_circle_redge": "simplecadapi.operators.geometry", diff --git a/src/simplecadapi/_glue/session.py b/src/simplecadapi/_glue/session.py index c9c25b77..7b0fa38b 100644 --- a/src/simplecadapi/_glue/session.py +++ b/src/simplecadapi/_glue/session.py @@ -464,14 +464,25 @@ def _frame(node_id: str) -> Any: ) -def _context() -> Dict[str, Any]: +def _context(session: Any = None) -> Dict[str, Any]: cs = _n.get_current_cs() - return { + out: Dict[str, Any] = { "origin": tuple(float(v) for v in cs.origin), "x_axis": tuple(float(v) for v in cs.x_axis), "y_axis": tuple(float(v) for v in cs.y_axis), "z_axis": tuple(float(v) for v in cs.z_axis), } + # Inside `with wp:` of a recorded workplane: its node, as the C++ recorder writes it (a replay takes the frame + # from the replayed workplane). + source = _n.get_current_frame_source() + if source is not None and session is not None: + try: + node = session._node_of(source["graph_id"], source["node_id"]) + except ValueError: + node = None + if node is not None: + out["workplane"] = {"node_id": node.node_id, "output_slot": int(source["output_slot"])} + return out def record_operation_if_active( @@ -510,7 +521,7 @@ def record_operation_if_active( node_id=node_id, output_count=1 if outputs is None else len(output_list), # a value op holds one output; an empty list result none semantic_delta=semantic_delta, - context=context or _context(), + context=context or _context(session), tags=tags, source=(source if source is not None else capture_source_provenance()), expressions=_n.referenced_expressions(exprs, session.expression_graph), diff --git a/src/simplecadapi/catalog.py b/src/simplecadapi/catalog.py index b24018cf..14c41907 100644 --- a/src/simplecadapi/catalog.py +++ b/src/simplecadapi/catalog.py @@ -12,7 +12,7 @@ functions with the same annotations. The catalog parses both, so a GUI, an agen A parameter's ``kind`` is one of: the meanings of :mod:`simplecadapi.types` (``length``, ``angle``, ``point3``, ``direction3``, ``vector3``, ``count``, ``point2``, ``plane``, ``sketch_profile``, ``color``), ``number`` (a unitless ``float | Expr``), ``int``, ``bool``, ``text``, ``path`` (``str | os.PathLike``), ``enum`` (``Literal[...]``, with ``choices``), a value type (``solid``, ``face``, ``wire``, -``edge``, ``vertex``, ``shell``, ``shape``, ``sketch``, ``part``, ``assembly``, ``scalar_limit``, ...), ``query`` (a +``edge``, ``vertex``, ``shell``, ``shape``, ``sketch``, ``part``, ``assembly``, ``scalar_limit``, ``workplane``, ...), ``query`` (a ``ql`` selection), ``points`` / ``numbers`` (sequences), ``grid`` (rows of points), ``_map`` (``dict[str, ]``: a value per id), ``|`` (a union of kinds, e.g. ``enum|numbers`` or ``query|shape``), or ``unknown`` when the signature says no more than ``object``. ``many`` marks a sequence of the kind, ``optional`` a @@ -61,6 +61,8 @@ _VALUE_KINDS = { "SurfaceBoundary": "surface_boundary", "SurfaceFillingSettings": "filling_settings", "ScalarLimit": "scalar_limit", + "SimpleWorkplane": "workplane", + "Workplane": "workplane", "PathLike": "path", "Path": "path", } diff --git a/src/simplecadapi/operators/__init__.py b/src/simplecadapi/operators/__init__.py index 2ab4d2f6..00a51a4b 100644 --- a/src/simplecadapi/operators/__init__.py +++ b/src/simplecadapi/operators/__init__.py @@ -56,6 +56,12 @@ from simplecadapi._cpp import ( make_angle_arc_redge, make_angle_arc_rwire, make_box_rsolid, + make_workplane_rworkplane, + make_workplane_from_face_rworkplane, + make_workplane_from_points_rworkplane, + make_workplane_from_axis_rworkplane, + make_workplane_midplane_rworkplane, + make_workplane_normal_to_curve_rworkplane, make_circle_redge, make_circle_rface, make_circle_rwire, @@ -350,6 +356,12 @@ __all__ = [ "make_assembly_rassembly", "make_bezier_surface_rface", "make_box_rsolid", + "make_workplane_rworkplane", + "make_workplane_from_face_rworkplane", + "make_workplane_from_points_rworkplane", + "make_workplane_from_axis_rworkplane", + "make_workplane_midplane_rworkplane", + "make_workplane_normal_to_curve_rworkplane", "make_circle_redge", "make_circle_rface", "make_circle_rwire", diff --git a/src/simplecadapi/operators/geometry.py b/src/simplecadapi/operators/geometry.py index 311c246b..a0132c07 100644 --- a/src/simplecadapi/operators/geometry.py +++ b/src/simplecadapi/operators/geometry.py @@ -25,6 +25,12 @@ from simplecadapi._cpp import ( make_angle_arc_redge, make_angle_arc_rwire, make_box_rsolid, + make_workplane_rworkplane, + make_workplane_from_face_rworkplane, + make_workplane_from_points_rworkplane, + make_workplane_from_axis_rworkplane, + make_workplane_midplane_rworkplane, + make_workplane_normal_to_curve_rworkplane, make_circle_redge, make_circle_rface, make_circle_rwire, @@ -116,6 +122,12 @@ __all__ = [ "make_angle_arc_rwire", "make_bezier_surface_rface", "make_box_rsolid", + "make_workplane_rworkplane", + "make_workplane_from_face_rworkplane", + "make_workplane_from_points_rworkplane", + "make_workplane_from_axis_rworkplane", + "make_workplane_midplane_rworkplane", + "make_workplane_normal_to_curve_rworkplane", "make_circle_redge", "make_circle_rface", "make_circle_rwire", diff --git a/src/simplecadapi/recording/serializer.py b/src/simplecadapi/recording/serializer.py index ab92a62f..af2dbc9b 100644 --- a/src/simplecadapi/recording/serializer.py +++ b/src/simplecadapi/recording/serializer.py @@ -42,6 +42,7 @@ from simplecadapi._cpp import ( Material, Part, ScalarLimit, + SimpleWorkplane, Shell, Sketch, Solid, @@ -112,6 +113,12 @@ PUBLIC_API_COVERAGE: Dict[str, Dict[str, str]] = { "status": "replayable", "op": "make_wire_from_edges_rwire", }, + "make_workplane_rworkplane": {"status": "replayable", "op": "make_workplane_rworkplane"}, + "make_workplane_from_face_rworkplane": {"status": "replayable", "op": "make_workplane_from_face_rworkplane"}, + "make_workplane_from_points_rworkplane": {"status": "replayable", "op": "make_workplane_from_points_rworkplane"}, + "make_workplane_from_axis_rworkplane": {"status": "replayable", "op": "make_workplane_from_axis_rworkplane"}, + "make_workplane_midplane_rworkplane": {"status": "replayable", "op": "make_workplane_midplane_rworkplane"}, + "make_workplane_normal_to_curve_rworkplane": {"status": "replayable", "op": "make_workplane_normal_to_curve_rworkplane"}, "make_sketch_rsketch": {"status": "replayable", "op": "make_sketch_rsketch"}, "add_point_rsketch": {"status": "replayable", "op": "add_point_rsketch"}, "add_line_rsketch": {"status": "replayable", "op": "add_line_rsketch"}, @@ -590,6 +597,12 @@ CANONICAL_CORE_OP_SET: Tuple[str, ...] = ( "make_wire_from_edges_rwire", "make_face_from_wire_rface", "make_face_from_wires_rface", + "make_workplane_rworkplane", + "make_workplane_from_face_rworkplane", + "make_workplane_from_points_rworkplane", + "make_workplane_from_axis_rworkplane", + "make_workplane_midplane_rworkplane", + "make_workplane_normal_to_curve_rworkplane", "make_sketch_rsketch", "add_point_rsketch", "add_line_rsketch", @@ -743,6 +756,12 @@ _CANONICAL_2_1_ONLY_OPS = { "fillet_corner_rsketch", "chamfer_corner_rsketch", "project_rsketch", + "make_workplane_rworkplane", + "make_workplane_from_face_rworkplane", + "make_workplane_from_points_rworkplane", + "make_workplane_from_axis_rworkplane", + "make_workplane_midplane_rworkplane", + "make_workplane_normal_to_curve_rworkplane", "explode_rassembly", "convert_to_bspline_redge", "convert_to_bspline_rface", @@ -2366,6 +2385,136 @@ def _replay_shape_edit( _optional_int(params["v_pole_count"]), tolerance=float(params["tolerance"]), tag_prefix=tag_prefix) +_WORKPLANE_OPS = frozenset( + { + "make_workplane_rworkplane", + "make_workplane_from_face_rworkplane", + "make_workplane_from_points_rworkplane", + "make_workplane_from_axis_rworkplane", + "make_workplane_midplane_rworkplane", + "make_workplane_normal_to_curve_rworkplane", + } +) +"""The workplane constructors: a Workplane value made from numbers or from ordered geometry inputs.""" + + +def _replay_workplane( + ctx: _ReplayContext, + graph: OperationGraph, + outputs: Dict[str, List[Any]], + node: Any, + params: Dict[str, Any], +) -> Any: + """Build the workplane again from its recorded op: from the replayed geometry, so it follows a moved face.""" + + op_name = node.op + fn = getattr(ops, op_name) + if op_name == "make_workplane_rworkplane": + ctx.require_params(node.node_id, op_name, params, ("origin", "normal", "x_dir")) + return fn(tuple(params["origin"]), tuple(params["normal"]), tuple(params["x_dir"])) + if not isinstance(params.get("input_refs"), list): + # Made from geometry no recorder could name: the frame it made is all there is. + ctx.require_params(node.node_id, op_name, params, ("frame",)) + frame = params["frame"] + return SimpleWorkplane._from_frame(frame["origin"], frame["x_axis"], frame["y_axis"]) + shapes = _ordered_input_shapes(ctx, graph, outputs, node, params) + + def value(name: str) -> Any: + item = params.get(name) + if isinstance(item, dict) and "input" in item: + index = int(item["input"]) + if index < 0 or index >= len(shapes): + ctx.fail(f"Graph node '{node.node_id}' ({op_name}) parameter '{name}' names a missing input") + return shapes[index] + if isinstance(item, (list, tuple)): + return tuple(item) + return item + + if op_name == "make_workplane_from_face_rworkplane": + return fn( + shapes[0], + origin=value("origin"), + x_edge=value("x_edge"), + x_dir=value("x_dir"), + offset=params.get("offset", 0.0), + flip=bool(params.get("flip", False)), + ) + if op_name == "make_workplane_from_points_rworkplane": + ctx.require_params(node.node_id, op_name, params, ("a", "b", "c")) + return fn(value("a"), value("b"), value("c")) + if op_name == "make_workplane_from_axis_rworkplane": + return fn(shapes[0], params.get("angle", 0.0), face=value("face")) + if op_name == "make_workplane_midplane_rworkplane": + if len(shapes) != 2: + ctx.fail(f"Graph node '{node.node_id}' ({op_name}) requires two face inputs") + return fn(shapes[0], shapes[1]) + return fn(shapes[0], params.get("at", 0.0), x_dir=value("x_dir")) + + +def _input_workplane(outputs: Dict[str, List[Any]], node: Any) -> Any: + """The replayed Workplane among a node's inputs (a sketch made on one), or None.""" + + for input_node in node.inputs: + for item in outputs.get(input_node.node_id, ()): + if isinstance(item, SimpleWorkplane): + return item + return None + + +def _context_workplane(outputs: Dict[str, List[Any]], context: Any) -> Any: + """The replayed Workplane a node's context names (the node was made inside ``with wp:``), or None.""" + + if not isinstance(context, dict): + return None + ref = context.get("workplane") + if not isinstance(ref, dict): + return None + made = outputs.get(str(ref.get("node_id", "")), []) + slot = int(ref.get("output_slot", 0) or 0) + item = made[slot] if 0 <= slot < len(made) else None + return item if isinstance(item, SimpleWorkplane) else None + + +def _frame_ordered(order: List[Any]) -> List[Any]: + """*order* with every node made inside ``with wp:`` after the node that made ``wp``. + + The context names the workplane node without an input edge, so the graph's own order may put the node first. + Kahn's algorithm over the inputs plus those links, taking the earliest node of *order* first. + """ + + import heapq + + index = {node.node_id: position for position, node in enumerate(order)} + extra: Dict[str, str] = {} + for node in order: + context = node.context if isinstance(node.context, dict) else {} + ref = context.get("workplane") + source = str(ref.get("node_id", "")) if isinstance(ref, dict) else "" + if source in index and index[source] > index[node.node_id]: + extra[node.node_id] = source + if not extra: + return order + deps = {node.node_id: {item.node_id for item in node.inputs if item.node_id in index} for node in order} + for node_id, source in extra.items(): + deps[node_id].add(source) + users: Dict[str, List[str]] = {} + for node_id, sources in deps.items(): + for source in sources: + users.setdefault(source, []).append(node_id) + remaining = {node_id: len(sources) for node_id, sources in deps.items()} + heap = [index[node_id] for node_id, count in remaining.items() if count == 0] + heapq.heapify(heap) + out: List[Any] = [] + while heap: + node = order[heapq.heappop(heap)] + out.append(node) + for user in users.get(node.node_id, ()): + remaining[user] -= 1 + if remaining[user] == 0: + heapq.heappush(heap, index[user]) + return out if len(out) == len(order) else order + + def _feature_input_shapes(ctx, graph, outputs, node, params): # New features preserve order and output slots, including repeated inputs. # Older graphs only carried distinct upstream nodes. @@ -2689,7 +2838,7 @@ def _execute_graph( if graph.node_count == 0: return [] - topo_order = graph.topological_order() + topo_order = _frame_ordered(list(graph.topological_order())) # Store per-node outputs outputs: Dict[str, List[Any]] = {} @@ -2731,8 +2880,11 @@ def _execute_graph( for node in topo_order: op_name = node.op params = node.params + context_workplane = _context_workplane(outputs, node.context) context_manager = ( - use_coordinate_system(node.context) + use_coordinate_system(context_workplane.cs) + if context_workplane is not None + else use_coordinate_system(node.context) if isinstance(node.context, dict) else nullcontext() ) @@ -3918,6 +4070,27 @@ def _execute_graph( _store_outputs(node, result) continue + if op_name in _WORKPLANE_OPS: + _store_outputs(node, _replay_workplane(ctx, graph, outputs, node, params)) + continue + + if op_name == "make_sketch_rsketch": + plane = params.get("plane") + workplane = ( + _input_workplane(outputs, node) + if isinstance(plane, dict) and plane.get("workplane") is True + else None + ) + if workplane is not None: + ctx.require_params(node.node_id, op_name, params, ("sketch_id",)) + _store_outputs( + node, + ops.make_sketch_rsketch( + params.get("name"), plane=workplane, sketch_id=str(params["sketch_id"]) + ), + ) + continue + if op_name in _SHAPE_EDIT_OPS: _store_outputs(node, _replay_shape_edit(ctx, graph, outputs, node, params)) continue diff --git a/src/simplecadapi/types.py b/src/simplecadapi/types.py index 615f4624..8550ae93 100644 --- a/src/simplecadapi/types.py +++ b/src/simplecadapi/types.py @@ -11,7 +11,8 @@ the meaning from there. Each alias is the type a caller may pass (``Annotated`` - ``Vector3``: an offset; direction and length both matter. - ``Count``: a whole number of things (copies, teeth, segments). - ``Point2``: a position ``(x, y)`` in a sketch plane (lengths). -- ``Plane``: a sketch plane, ``"XY"`` / ``"XZ"`` / ``"YZ"`` or ``{"origin": Point3, "x_axis": Direction3, "y_axis": Direction3}``. +- ``Plane``: a sketch plane, ``"XY"`` / ``"XZ"`` / ``"YZ"``, ``{"origin": Point3, "x_axis": Direction3, "y_axis": Direction3}``, + or a ``Workplane`` value (``make_workplane_*_rworkplane`` / ``SimpleWorkplane``), whose frame is used as it is. - ``SketchProfile``: a closed profile of a sketch, by index or by id. - ``Color``: a display colour ``(r, g, b)``, each component a float in [0, 1] (``Material.color``, a body colour). @@ -23,7 +24,7 @@ from __future__ import annotations from collections.abc import Mapping, Sequence from typing import Annotated, Literal, Union -from simplecadapi._cpp import Expr +from simplecadapi._cpp import Expr, SimpleWorkplane _Number = Union[float, Expr] @@ -34,7 +35,7 @@ Direction3 = Annotated[Sequence[_Number], "direction3"] Vector3 = Annotated[Sequence[_Number], "vector3"] Count = Annotated[int, "count"] Point2 = Annotated[Sequence[_Number], "point2"] -Plane = Annotated[Union[Literal["XY", "XZ", "YZ"], Mapping[str, Sequence[_Number]]], "plane"] +Plane = Annotated[Union[Literal["XY", "XZ", "YZ"], Mapping[str, Sequence[_Number]], SimpleWorkplane], "plane"] SketchProfile = Annotated[Union[int, str], "sketch_profile"] Color = Annotated[Sequence[float], "color"] diff --git a/test/test_serialization.py b/test/test_serialization.py index 9d32e0f5..2df0845b 100644 --- a/test/test_serialization.py +++ b/test/test_serialization.py @@ -280,6 +280,12 @@ class TestCoverageMatrix(unittest.TestCase): "make_wire_from_edges_rwire", "make_face_from_wire_rface", "make_face_from_wires_rface", + "make_workplane_rworkplane", + "make_workplane_from_face_rworkplane", + "make_workplane_from_points_rworkplane", + "make_workplane_from_axis_rworkplane", + "make_workplane_midplane_rworkplane", + "make_workplane_normal_to_curve_rworkplane", "make_sketch_rsketch", "add_point_rsketch", "add_line_rsketch", diff --git a/test/test_workplanes.py b/test/test_workplanes.py new file mode 100644 index 00000000..f6a85fb4 --- /dev/null +++ b/test/test_workplanes.py @@ -0,0 +1,282 @@ +"""Workplanes as values: the recorded constructors, ``with wp:`` and ``plane=wp``, replay, pickling and the cell cache.""" + +from __future__ import annotations + +import copy +import json +import pickle +import textwrap +import typing +from pathlib import Path + +import pytest + +import simplecadapi as scad +from simplecadapi import catalog +from simplecadapi.runtime import run_notebook + +ql = scad.ql + + +def _close(actual, expected, tol: float = 1e-9) -> bool: + return all(abs(float(a) - float(b)) <= tol for a, b in zip(actual, expected)) + + +def _face(shape, tag: str): + return ql.faces().where(ql.tag(tag)).exactly(1).resolve(shape)[0] + + +def _centre(shape) -> tuple[float, float, float]: + """The centre of the bounding box (``get_center`` of a round shape is not its axis).""" + x0, y0, z0, x1, y1, z1 = shape._bounds() + return ((x0 + x1) / 2, (y0 + y1) / 2, (z0 + z1) / 2) + + +# --------------------------------------------------------------------------- +# The constructors +# --------------------------------------------------------------------------- + + +def test_a_workplane_on_a_face_sits_at_its_centre_along_its_outward_normal(): + box = scad.make_box_rsolid(10, 20, 5, tag_prefix="base") + top = _face(box, "base.face.top") + wp = scad.make_workplane_from_face_rworkplane(top) + assert isinstance(wp, scad.Workplane) + assert _close(wp.origin, (0, 0, 5)) and _close(wp.normal, (0, 0, 1)) + assert _close(scad.make_workplane_from_face_rworkplane(top, offset=3).origin, (0, 0, 8)) + assert _close(scad.make_workplane_from_face_rworkplane(top, origin=(2, 3, 40)).origin, (2, 3, 5)) + bottom = _face(box, "base.face.bottom") + assert _close(scad.make_workplane_from_face_rworkplane(bottom).normal, (0, 0, -1)) + assert _close(scad.make_workplane_from_face_rworkplane(bottom, flip=True).normal, (0, 0, 1)) + edge = scad.make_line_redge((0, 0, 5), (0, 1, 5)) + along = scad.make_workplane_from_face_rworkplane(top, x_edge=edge) + assert _close(along.x_dir, (0, 1, 0)) and _close(along.y_dir, (-1, 0, 0)) + assert _close(scad.make_workplane_from_face_rworkplane(top, x_dir=(0, -1, 0)).x_dir, (0, -1, 0)) + with pytest.raises(scad.SimpleCADError): + scad.make_workplane_from_face_rworkplane(top, x_edge=edge, x_dir=(1, 0, 0)) + side = ql.faces().where(ql.prop("geom.type", "==", "CYLINDER")).exactly(1).resolve(scad.make_cylinder_rsolid(2, 4))[0] + with pytest.raises(scad.SimpleCADError, match="planar"): + scad.make_workplane_from_face_rworkplane(side) + + +def test_three_points_an_axis_a_midplane_and_a_curve(): + wp = scad.make_workplane_from_points_rworkplane((1, 1, 1), (2, 1, 1), (1, 1, 3)) + assert _close(wp.origin, (1, 1, 1)) and _close(wp.normal, (0, -1, 0)) + corner = scad.make_point_rvertex(0, 0, 7) + assert _close(scad.make_workplane_from_points_rworkplane(corner, (1, 0, 7), (0, 1, 7)).origin, (0, 0, 7)) + with pytest.raises(scad.SimpleCADError, match="one line"): + scad.make_workplane_from_points_rworkplane((0, 0, 0), (1, 0, 0), (3, 0, 0)) + + axis = scad.make_line_redge((0, 0, 0), (10, 0, 0)) + assert _close(scad.make_workplane_from_axis_rworkplane(axis).normal, (0, 0, 1)) + tilted = scad.make_workplane_from_axis_rworkplane(axis, 90) + assert _close(tilted.normal, (0, -1, 0)) and _close(tilted.x_dir, (1, 0, 0)) + box = scad.make_box_rsolid(10, 20, 5, tag_prefix="base") + long_edge = ql.edges().where( + ql.and_(ql.prop("geom.length", ">", 19), ql.prop("geom.center.z", ">", 4), ql.prop("geom.center.x", ">", 4)) + ).exactly(1).resolve(box)[0] + hinged = scad.make_workplane_from_axis_rworkplane(long_edge, 0, face=_face(box, "base.face.top")) + assert _close(hinged.normal, (0, 0, 1)) # at angle 0: the plane of the face + ring = scad.make_circle_redge((0, 0, 3), 2) + assert _close(scad.make_workplane_from_axis_rworkplane(ring).origin, (0, 0, 3)) + + mid = scad.make_workplane_midplane_rworkplane(_face(box, "base.face.left"), _face(box, "base.face.right")) + assert _close(mid.origin, (0, 0, 2.5)) + assert _close(mid.normal, scad.make_workplane_from_face_rworkplane(_face(box, "base.face.left")).normal) + with pytest.raises(scad.SimpleCADError, match="parallel"): + scad.make_workplane_midplane_rworkplane(_face(box, "base.face.left"), _face(box, "base.face.top")) + + path = scad.make_polyline_rwire([(0, 0, 0), (10, 0, 0), (10, 10, 0)]) + start = scad.make_workplane_normal_to_curve_rworkplane(path, 0) + assert _close(start.origin, (0, 0, 0)) and _close(start.normal, (1, 0, 0)) + end = scad.make_workplane_normal_to_curve_rworkplane(path, 1) + assert _close(end.origin, (10, 10, 0)) and _close(end.normal, (0, 1, 0)) + assert _close(scad.make_workplane_normal_to_curve_rworkplane(path, 0.25).origin, (5, 0, 0)) + with pytest.raises(scad.SimpleCADError): + scad.make_workplane_normal_to_curve_rworkplane(path, 2) + + +def test_the_plain_constructor_reads_the_current_system(): + outer = scad.make_workplane_rworkplane((0, 0, 10)) + with outer: + inner = scad.make_workplane_rworkplane((1, 0, 0), (0, 1, 0)) + assert _close(inner.origin, (1, 0, 10)) and _close(inner.normal, (0, 1, 0)) + assert _close(scad.SimpleWorkplane((0, 0, 4)).origin, (0, 0, 4)) + + +# --------------------------------------------------------------------------- +# A value +# --------------------------------------------------------------------------- + + +def test_a_workplane_is_a_value_entered_again_copied_and_pickled(): + wp = scad.make_workplane_rworkplane((0, 0, 5), (1, 0, 0), (0, 1, 0)) + for _ in range(2): # `with wp:` in one cell, then again in a later one + with wp: + assert _close(scad.get_current_cs().origin, (0, 0, 5)) + assert _close(scad.get_current_cs().origin, (0, 0, 0)) + for twin in (pickle.loads(pickle.dumps(wp)), copy.copy(wp), copy.deepcopy(wp)): + assert _close(twin.origin, wp.origin) and _close(twin.normal, wp.normal) and _close(twin.x_dir, wp.x_dir) + with twin: + assert _close(scad.get_current_cs().z_axis, (1, 0, 0)) + with scad.GraphSession(graph_id="pickled") as session: + recorded = scad.make_workplane_rworkplane((0, 0, 5)) + restored = pickle.loads(pickle.dumps(recorded)) + assert restored._get_runtime("graph.node_id") == recorded._get_runtime("graph.node_id") + assert session.graph.get_node(restored._get_runtime("graph.node_id")).op == "make_workplane_rworkplane" + assert set(wp.plane) == {"origin", "x_axis", "y_axis"} + + +def test_a_sketch_on_a_workplane_uses_its_frame_wherever_it_is_made(): + wp = scad.make_workplane_rworkplane((0, 0, 4), (1, 0, 0), (0, 1, 0)) + with scad.SimpleWorkplane((100, 0, 0)): + sketch = scad.make_sketch_rsketch("rib", plane=wp) # not moved by the entered workplane + sketch = scad.add_point_rsketch(sketch, "c", 0, 0) + sketch = scad.add_circle_rsketch(sketch, "circle", "c", 1) + face = scad.make_face_from_sketch_rface(sketch) + assert _close(_centre(face), (0, 0, 4), 1e-6) + assert scad.SimpleWorkplane in typing.get_args(typing.get_args(scad.types.Plane)[0]) + + +def test_the_constructors_are_typed_operations_in_the_catalog(): + names = { + "make_workplane_rworkplane", + "make_workplane_from_face_rworkplane", + "make_workplane_from_points_rworkplane", + "make_workplane_from_axis_rworkplane", + "make_workplane_midplane_rworkplane", + "make_workplane_normal_to_curve_rworkplane", + } + for name in names: + op = catalog.operation(name) + assert op.returns == "workplane", (name, op.returns) + assert all(p.kind != "unknown" for p in op.params), (name, op.params) + face = {p.name: p.kind for p in catalog.operation("make_workplane_from_face_rworkplane").params} + assert face == {"face": "face", "origin": "point3", "x_edge": "edge", "x_dir": "direction3", "offset": "length", "flip": "bool"} + assert catalog.operation("make_workplane_from_axis_rworkplane").params[1].kind == "angle" + plane = next(p for p in catalog.operation("make_sketch_rsketch").params if p.name == "plane") + assert plane.kind == "plane" + + +# --------------------------------------------------------------------------- +# Recording and replay +# --------------------------------------------------------------------------- + + +def _recorded_model(): + with scad.GraphSession(graph_id="wp_replay") as session: + top = scad.make_rectangle_rface(10, 20, center=(0, 0, 5)) + wp = scad.make_workplane_from_face_rworkplane(top, offset=1) + sketch = scad.make_sketch_rsketch("disc", plane=wp) + sketch = scad.add_point_rsketch(sketch, "c", 0, 0) + sketch = scad.add_circle_rsketch(sketch, "circle", "c", 2) + disc = scad.make_face_from_sketch_rface(sketch) + with wp: + pin = scad.make_box_rsolid(1, 1, 1) + return session, wp, disc, pin + + +def test_the_graph_records_the_workplane_op_its_inputs_and_who_uses_it(): + session, wp, _disc, pin = _recorded_model() + node = session.graph.get_node(wp._get_runtime("graph.node_id")) + assert node.op == "make_workplane_from_face_rworkplane" + assert len(node.params["input_refs"]) == 1 and node.params["offset"] == 1 + sketch_node = next(n for n in session.graph.nodes if n.op == "make_sketch_rsketch") + assert sketch_node.params["plane"]["workplane"] is True + assert [n.node_id for n in sketch_node.inputs] == [node.node_id] + pin_node = session.graph.get_node(pin._get_runtime("graph.node_id")) + assert pin_node.context["workplane"]["node_id"] == node.node_id + + +def test_replay_rebuilds_the_frame_from_the_recorded_op_so_it_follows_the_face(): + session, _wp, disc, pin = _recorded_model() + payload = scad.export_model_json(session) + replayed = scad.replay_model_json(payload) + centres = sorted((type(item).__name__, _centre(item)) for item in replayed if hasattr(item, "_bounds")) + assert _close(dict(centres)["Face"], _centre(disc), 1e-6) and _close(dict(centres)["Solid"], _centre(pin), 1e-6) + + data = json.loads(payload) + for node in data["graph"]["nodes"]: # move the face: the sides of the rectangle from z = 5 to z = 12 + if node["op"] == "make_line_redge": + node["params"]["start"][2] = 12 + node["params"]["end"][2] = 12 + moved = {type(item).__name__: _centre(item) for item in scad.replay_model_json(json.dumps(data)) if hasattr(item, "_bounds")} + assert _close(moved["Face"], (0, 0, 13), 1e-6) # the sketch on the workplane: face + offset 1 + assert _close(moved["Solid"], (0, 0, 13.5), 1e-6) # the box made inside `with wp:` + + +def test_a_workplane_from_a_vertex_replays_from_its_input(): + with scad.GraphSession(graph_id="wp_points") as session: + corner = scad.make_point_rvertex(0, 0, 7) + wp = scad.make_workplane_from_points_rworkplane(corner, (1, 0, 7), (0, 1, 7)) + node = session.graph.get_node(wp._get_runtime("graph.node_id")) + assert node.params["a"] == {"input": 0} and list(node.params["b"]) == [1, 0, 7] + data = json.loads(scad.export_model_json(session)) + for item in data["graph"]["nodes"]: + if item["op"] == "make_point_rvertex": + item["params"]["z"] = 9 + (replayed,) = [v for v in scad.replay_model_json(json.dumps(data)) if isinstance(v, scad.Workplane)] + assert _close(replayed.origin, (0, 0, 9)) + assert abs(replayed.normal[2]) < 1 # the plane through (0,0,9), (1,0,7), (0,1,7) tilts + + +# --------------------------------------------------------------------------- +# The notebook: cell cache and a parameter change +# --------------------------------------------------------------------------- + + +def _notebook(tmp_path: Path) -> Path: + def cell(body: str, reads: str, returns: str) -> str: + code = textwrap.indent(textwrap.dedent(body).strip(), " ") + return f"@app.cell\ndef _({reads}):\n{code}\n return ({returns},)\n" + + cells = [ + cell("height = 5.0", "", "height"), + cell('base = scad.make_box_rsolid(10.0, 20.0, height, tag_prefix="base")', "height", "base"), + cell( + """ + _top = scad.ql.faces().where(scad.ql.tag("base.face.top")).exactly(1).resolve(base)[0] + wp_top = scad.make_workplane_from_face_rworkplane(_top) + """, + "base", + "wp_top", + ), + cell( + """ + _sketch = scad.make_sketch_rsketch("boss", plane=wp_top) + _sketch = scad.add_point_rsketch(_sketch, "c", 0, 0) + _sketch = scad.add_circle_rsketch(_sketch, "circle", "c", 2) + boss = scad.extrude_rsolid(scad.make_face_from_sketch_rface(_sketch), (0, 0, 1), 3) + with wp_top: + peg = scad.make_cylinder_rsolid(0.5, 2) + part = scad.Part(part_id="plate", body=scad.union_rsolid(base, boss)) + """, + "wp_top", + "boss, peg, part", + ), + ] + text = ( + '# /// script\n# [tool.simplecadapi]\n# id = "plate"\n# ///\nimport marimo\n\napp = marimo.App()\n\n' + "with app.setup:\n import simplecadapi as scad\n\n\n" + "\n\n".join(cells) + '\n\nif __name__ == "__main__":\n app.run()\n' + ) + path = tmp_path / "plate.py" + path.write_text(text, encoding="utf-8") + return path + + +def test_a_workplane_cell_is_cached_and_a_sketch_on_it_follows_a_parameter_change(tmp_path): + path = _notebook(tmp_path) + first = run_notebook(path) + second = run_notebook(path) + assert [c.status for c in second.cells] == ["ran", "cached", "cached", "cached", "cached"] + for run in (first, second): + assert isinstance(run.values["wp_top"], scad.Workplane) + assert _close(run.values["wp_top"].origin, (0, 0, 5)) + assert _close(_centre(run.values["boss"]), (0, 0, 6.5), 1e-6) + with second.values["wp_top"]: # the restored value is a context manager again + assert _close(scad.get_current_cs().origin, (0, 0, 5)) + + taller = run_notebook(path, overrides={"height": 9.0}) + assert _close(taller.values["wp_top"].origin, (0, 0, 9)) + assert _close(_centre(taller.values["boss"]), (0, 0, 10.5), 1e-6) + assert _close(_centre(taller.values["peg"]), (0, 0, 10), 1e-6)