diff --git a/src/cpp/bindings/python/bind_io.cpp b/src/cpp/bindings/python/bind_io.cpp index d5bf27a7..0e3d14f5 100644 --- a/src/cpp/bindings/python/bind_io.cpp +++ b/src/cpp/bindings/python/bind_io.cpp @@ -389,6 +389,20 @@ std::vector definitions_from(const py::sequence& items) { const Vec3 c = vec3_from(d["color"]); def.color = std::array{c.x, c.y, c.z}; } + if (d.contains("bodies")) { + for (const py::handle bh : d["bodies"]) { + const py::dict b = py::reinterpret_borrow(bh); + io::StepBody body; + body.shape = b["shape"].cast().wrapped(); + if (b.contains("name") && !b["name"].is_none()) + body.name = b["name"].cast(); + if (b.contains("color") && !b["color"].is_none()) { + const Vec3 c = vec3_from(b["color"]); + body.color = std::array{c.x, c.y, c.z}; + } + def.bodies.push_back(std::move(body)); + } + } if (d.contains("material") && !d["material"].is_none()) { const py::dict m = d["material"].cast(); io::StepMaterial material; diff --git a/src/cpp/bindings/python/bind_product.cpp b/src/cpp/bindings/python/bind_product.cpp index 2751c404..8de0ab1f 100644 --- a/src/cpp/bindings/python/bind_product.cpp +++ b/src/cpp/bindings/python/bind_product.cpp @@ -27,7 +27,7 @@ SCAD_SIGNATURE_NAME(TextOrNone, const_name("str | None")); SCAD_SIGNATURE_NAME(Number, const_name("float | Expr")); SCAD_SIGNATURE_NAME(NumberOrNone, const_name("float | Expr | None")); SCAD_SIGNATURE_NAME(Bool, const_name("bool")); -SCAD_SIGNATURE_NAME(Color, const_name("collections.abc.Sequence[float] | None")); +SCAD_SIGNATURE_NAME(Color, scad::pybind::ColorTag::name + kOrNone); SCAD_SIGNATURE_NAME(Length, scad::pybind::LengthTag::name); SCAD_SIGNATURE_NAME(LengthOrNone, scad::pybind::LengthTag::name + kOrNone); SCAD_SIGNATURE_NAME(AngleOrNone, scad::pybind::AngleTag::name + kOrNone); @@ -165,9 +165,9 @@ void bind_structure(py::module_& m) { return sp::make_part_rpart(text(part_id, "part_id"), pieces, optional_name(name)); } if (is_pieces(body)) - return sp::make_part_rpart(text(part_id, "part_id"), - typed(py::reinterpret_borrow(body.value[py::int_(0)]), "body"), - optional_name(name)); + return sp::make_part_rpart( + text(part_id, "part_id"), + typed(py::reinterpret_borrow(body.value[py::int_(0)]), "body"), optional_name(name)); return sp::make_part_rpart(text(part_id, "part_id"), typed(body, "body must be a Solid"), optional_name(name)); }); @@ -183,6 +183,20 @@ void bind_structure(py::module_& m) { }); }, py::arg("part"), py::arg("material"), "Assign a Material to a Part and return the updated Part."); + m.def( + "set_body_appearance_rpart", + [](const PartArg& part, const TextArg& body_id, const ColorArg& color, const NumberOrNoneArg& opacity, + const NameArg& name, const BoolArg& reset) { + return guard_operation("set_body_appearance_rpart", [&] { + return sp::set_body_appearance_rpart( + part_arg(part), text(body_id, "body_id"), optional_vec3(color, "color"), + opacity.is_none() ? sp::OptionalDouble{} : sp::OptionalDouble{number(opacity, "opacity")}, + optional_name(name), truthy(reset)); + }); + }, + py::arg("part"), py::arg("body_id") = sp::kDefaultBodyId, py::kw_only(), py::arg("color") = py::none(), + py::arg("opacity") = py::none(), py::arg("name") = py::none(), py::arg("reset") = false, + "Set the display colour, opacity and display name of one body of a Part and return the updated Part."); m.def( "make_assembly_rassembly", diff --git a/src/cpp/bindings/python/bind_product_values.cpp b/src/cpp/bindings/python/bind_product_values.cpp index f26823fa..cd8d2f3f 100644 --- a/src/cpp/bindings/python/bind_product_values.cpp +++ b/src/cpp/bindings/python/bind_product_values.cpp @@ -425,17 +425,33 @@ void bind_constraints(py::module_& m) { void bind_part(py::module_& m) { using namespace sp; py::class_(m, "Body", "One named solid of a Part; a multi-body Part keeps several apart.") - .def(py::init([](const py::object& body_id, const py::object& solid, const py::object& name) { + .def(py::init([](const py::object& body_id, const py::object& solid, const py::object& name, + const py::object& color, const py::object& opacity) { + std::optional opacity_value; + if (!opacity.is_none()) + opacity_value = number(opacity, "opacity"); return std::make_shared(text(body_id, "body_id"), typed(solid, "solid must be a Solid"), - optional_name(name)); + optional_name(name), optional_vec3(color, "color"), opacity_value); }), - py::arg("body_id"), py::arg("solid"), py::arg("name") = py::none()) + py::arg("body_id"), py::arg("solid"), py::arg("name") = py::none(), py::arg("color") = py::none(), + py::arg("opacity") = py::none()) .def_property_readonly("body_id", &Body::body_id) .def_property_readonly("solid", &Body::solid) .def_property_readonly("name", [](const Body& self) { return optional_object(self.name()); }) + .def_property_readonly( + "color", [](const Body& self) -> py::object { return self.color() ? py::cast(*self.color()) : py::none(); }, + "The display colour of this body (RGB in [0, 1]), or None to show the material colour.") + .def_property_readonly( + "opacity", [](const Body& self) { return optional_float(self.opacity()); }, + "The display opacity of this body in [0, 1], or None (opaque).") .def("to_dict", [](const Body& self) { return self.to_dict(); }) .def("__repr__", [](const Body& self) { - return "Body(body_id=" + str_repr(self.body_id()) + ", name=" + opt_str_repr(self.name()) + ")"; + std::string out = "Body(body_id=" + str_repr(self.body_id()) + ", name=" + opt_str_repr(self.name()); + if (self.color()) + out += ", color=" + tuple_repr(*self.color()); + if (self.opacity()) + out += ", opacity=" + opt_float_repr(self.opacity()); + return out + ")"; }); py::class_ cls( diff --git a/src/cpp/bindings/python/semantic_types.hpp b/src/cpp/bindings/python/semantic_types.hpp index 3bf3fa60..e819a028 100644 --- a/src/cpp/bindings/python/semantic_types.hpp +++ b/src/cpp/bindings/python/semantic_types.hpp @@ -19,6 +19,7 @@ // PointVec3 / DirectionVec a position / a direction read as a plain Vec3 (no expressions) // PlainQuantity a meaning above read as a plain double (no expressions) // Count a whole number of things +// Color a display colour, RGB components in [0, 1] 3 x float // Choice text with fixed choices; Tag::name is the Literal[...] that lists them // // Plain `Scalar` stays for numbers without a unit (a factor, a tolerance); plain `Scalar3` for anything else. A tag is @@ -74,6 +75,9 @@ struct VectorTag { struct CountTag { static constexpr auto name = pybind11::detail::const_name("simplecadapi.types.Count"); }; +struct ColorTag { + static constexpr auto name = pybind11::detail::const_name("simplecadapi.types.Color"); +}; using Length = Renamed; using Angle = Renamed; diff --git a/src/cpp/include/scad/io/step_assembly.hpp b/src/cpp/include/scad/io/step_assembly.hpp index d27122d6..87cde37b 100644 --- a/src/cpp/include/scad/io/step_assembly.hpp +++ b/src/cpp/include/scad/io/step_assembly.hpp @@ -54,6 +54,14 @@ struct StepComponent { Value metadata = Value::object(); // occurrence record (written as comment + property item) }; +// One solid of a part's shape that carries its own name or colour (a body of a multi-body part): written as an XCAF +// sub-shape label of the part. `shape` must be a sub-shape of the part's shape. +struct StepBody { + TopoDS_Shape shape; + std::string name; // empty: no name + std::optional> color; // linear RGB in [0, 1], the surface colour of this solid +}; + struct StepDefinition { std::string id; std::string kind = "single_solid"; // "single_solid" or "assembly": part of the metadata record's name @@ -61,6 +69,7 @@ struct StepDefinition { TopoDS_Shape shape; // a part's body; null for an assembly std::vector components; std::optional> color; // linear RGB in [0, 1], applied as the surface colour + std::vector bodies; // named or coloured solids of the part's shape std::optional material; Value metadata = Value::object(); // definition record }; diff --git a/src/cpp/include/scad/product/operators.hpp b/src/cpp/include/scad/product/operators.hpp index 05e30063..e56d8c81 100644 --- a/src/cpp/include/scad/product/operators.hpp +++ b/src/cpp/include/scad/product/operators.hpp @@ -42,6 +42,12 @@ PartPtr make_part_rpart(const std::string& part_id, const Solid& body, const Opt // A Part of several named bodies, kept apart (no boolean between them), in this order. PartPtr make_part_rpart(const std::string& part_id, const std::vector& bodies, const OptionalString& name = {}); PartPtr assign_material_rpart(const Part& part, const Material& material); +// The Part with the display colour, opacity and display name of one body set. An argument left empty keeps what +// the body has; `reset` first clears all three (the body then shows the material colour, opaque, under its id). +// The colour overrides the material colour for display only. KeyError for an unknown body id. +PartPtr set_body_appearance_rpart(const Part& part, const std::string& body_id = kDefaultBodyId, + const std::optional& color = {}, const OptionalDouble& opacity = {}, + const OptionalString& name = {}, bool reset = false); // ---- connectors ------------------------------------------------------------------------------------- // Z follows the face normal, the origin is the face center; `flip` negates Z. diff --git a/src/cpp/include/scad/product/part.hpp b/src/cpp/include/scad/product/part.hpp index ac83ce51..b3b5faa6 100644 --- a/src/cpp/include/scad/product/part.hpp +++ b/src/cpp/include/scad/product/part.hpp @@ -21,21 +21,36 @@ namespace scad::product { // One named solid of a Part. The body id is a stable identifier within its Part ("base", "lid"). +// +// A body may carry a display colour (RGB in [0, 1], like Material::color) and an opacity in [0, 1]. They are an +// appearance only: the material colour is the default, a body colour overrides it for display (preview, package +// scene, STEP surface colour). Mass and density never read them. class Body { public: - // ValueError for a malformed id or an empty name. - Body(std::string body_id, Solid solid, OptionalString name = {}); + // ValueError for a malformed id, an empty name, a colour outside [0, 1] or an opacity outside [0, 1]. + Body(std::string body_id, Solid solid, OptionalString name = {}, std::optional color = {}, + OptionalDouble opacity = {}); const std::string& body_id() const noexcept { return body_id_; } const Solid& solid() const noexcept { return solid_; } const OptionalString& name() const noexcept { return name_; } + const std::optional& color() const noexcept { return color_; } + const OptionalDouble& opacity() const noexcept { return opacity_; } + // True when the body has a colour or an opacity of its own. + bool has_appearance() const noexcept { return color_.has_value() || opacity_.has_value(); } - Value to_dict() const; // {"body_id", "name"} (the solid is geometry, not a dict field) + // A copy with another display name, colour and opacity (same id and solid). + Body with_appearance(OptionalString name, std::optional color, OptionalDouble opacity) const; + + // {"body_id", "name"}, plus "color" / "opacity" when set (the solid is geometry, not a dict field). + Value to_dict() const; private: std::string body_id_; Solid solid_; OptionalString name_; + std::optional color_; + OptionalDouble opacity_; }; // The body id of a Part made from one Solid. @@ -64,6 +79,8 @@ class Part : public SemanticValue { const std::vector& connectors() const noexcept { return connectors_; } Part with_material(const Material& material) const; + // The Part with `body` in place of the body of the same id. KeyError for an unknown id. + Part with_body(const Body& body) const; // ValueError when the Part already has a connector with that id. Part with_connector(const Connector& connector) const; diff --git a/src/cpp/src/io/step_assembly.cpp b/src/cpp/src/io/step_assembly.cpp index 0c4959f4..876ccdd5 100644 --- a/src/cpp/src/io/step_assembly.cpp +++ b/src/cpp/src/io/step_assembly.cpp @@ -218,6 +218,18 @@ class AssemblyBuilder { color_tool_->SetColor(label, Quantity_Color((*d.color)[0], (*d.color)[1], (*d.color)[2], Quantity_TOC_RGB), XCAFDoc_ColorSurf); } + for (const StepBody& body : d.bodies) { + const TDF_Label sub = shape_tool_->AddSubShape(label, body.shape); + if (sub.IsNull()) + throw ValueError("a body of definition '" + d.id + "' is not a solid of its shape"); + if (!body.name.empty()) + set_name(sub, body.name); + if (body.color) { + color_tool_->SetColor(sub, + Quantity_Color((*body.color)[0], (*body.color)[1], (*body.color)[2], Quantity_TOC_RGB), + XCAFDoc_ColorSurf); + } + } } else { for (const StepComponent& c : d.components) { require_rigid(c.placement, "component '" + c.id + "' of '" + d.id + "'"); @@ -318,6 +330,19 @@ class SchemaScope { int prior_; }; +// Sub-shape names on (the names of the bodies of a multi-body part), restored afterwards. +class SubshapeNamesScope { + public: + SubshapeNamesScope() : prior_(Interface_Static::IVal(kKey)) { Interface_Static::SetIVal(kKey, 1); } + ~SubshapeNamesScope() { Interface_Static::SetIVal(kKey, prior_); } + SubshapeNamesScope(const SubshapeNamesScope&) = delete; + SubshapeNamesScope& operator=(const SubshapeNamesScope&) = delete; + + private: + static constexpr const char* kKey = "write.stepcaf.subshapes.name"; + int prior_; +}; + } // namespace Bytes step_assembly_bytes(const std::vector& definitions, std::string_view root_id, @@ -335,6 +360,7 @@ Bytes step_assembly_bytes(const std::vector& definitions, std::s writer.SetMaterialMode(Standard_True); writer.SetPropsMode(Standard_True); const SchemaScope schema(options.schema); + const SubshapeNamesScope subshape_names; if (!writer.Transfer(root)) throw RuntimeError("STEPCAF transfer failed: " + messages.text()); if (options.metadata_properties) diff --git a/src/cpp/src/product/executors.cpp b/src/cpp/src/product/executors.cpp index 6e75e01d..48234be3 100644 --- a/src/cpp/src/product/executors.cpp +++ b/src/cpp/src/product/executors.cpp @@ -11,6 +11,7 @@ void register_product_executors(reactive::ExecutorRegistry& registry) { "make_identity_placement_rplacement", "make_part_rpart", "make_assign_material_rpart", + "make_set_body_appearance_rpart", "make_assembly_rassembly", "make_add_component_rassembly", "make_place_component_rassembly", diff --git a/src/cpp/src/product/ops_structure.cpp b/src/cpp/src/product/ops_structure.cpp index 899e3279..9d4f72ff 100644 --- a/src/cpp/src/product/ops_structure.cpp +++ b/src/cpp/src/product/ops_structure.cpp @@ -172,6 +172,32 @@ PartPtr assign_material_rpart(const Part& part, const Material& material) { }); } +PartPtr set_body_appearance_rpart(const Part& part, const std::string& body_id, const std::optional& color, + const OptionalDouble& opacity, const OptionalString& name, bool reset) { + return guard_operation("set_body_appearance_rpart", [&] { + const Body& body = part.get_body(body_id); + const Body updated = body.with_appearance(name ? name : (reset ? OptionalString{} : body.name()), + color ? color : (reset ? std::optional{} : body.color()), + opacity ? opacity : (reset ? OptionalDouble{} : body.opacity())); + auto result = std::make_shared(part.with_body(updated)); + record_value( + [&] { + Value params = Value::object(); + params.set("part_id", part.part_id()); + params.set("body_id", updated.body_id()); + params.set("color", color ? to_array(*updated.color()) : Value()); + params.set("opacity", opacity ? Value(*updated.opacity()) : Value()); + params.set("name", name ? Value(*updated.name()) : Value()); + params.set("reset", reset); + OpRecord record = op_record("make_set_body_appearance_rpart", std::move(params)); + record.semantic_delta = semantic_modified("Part", part.part_id(), updated.to_dict()); + return record; + }, + result, part); + return result; + }); +} + AssemblyPtr make_assembly_rassembly(const std::string& assembly_id, const OptionalString& name) { return guard_operation("make_assembly_rassembly", [&] { auto assembly = std::make_shared(assembly_id, name); diff --git a/src/cpp/src/product/part.cpp b/src/cpp/src/product/part.cpp index daf5d78a..fa8cbdba 100644 --- a/src/cpp/src/product/part.cpp +++ b/src/cpp/src/product/part.cpp @@ -46,18 +46,57 @@ std::string joined_ids(const std::vector& bodies) { return out; } +std::optional checked_color(const std::optional& color) { + if (!color) + return color; + const Vec3 rgb = finite_vec3(*color, "color"); + for (double c : {rgb.x, rgb.y, rgb.z}) { + if (c < 0.0 || c > 1.0) + throw ValueError("color components must be in [0.0, 1.0]"); + } + return rgb; +} + +OptionalDouble checked_opacity(OptionalDouble opacity) { + opacity = optional_float(opacity, "opacity"); + if (opacity && (*opacity < 0.0 || *opacity > 1.0)) + throw ValueError("opacity must be in [0.0, 1.0]"); + return opacity; +} + } // namespace -Body::Body(std::string body_id, Solid solid, OptionalString name) - : body_id_(validate_identifier(body_id, "body_id")), solid_(std::move(solid)), name_(clean_name(name)) {} +Body::Body(std::string body_id, Solid solid, OptionalString name, std::optional color, OptionalDouble opacity) + : body_id_(validate_identifier(body_id, "body_id")), + solid_(std::move(solid)), + name_(clean_name(name)), + color_(checked_color(color)), + opacity_(checked_opacity(opacity)) {} + +Body Body::with_appearance(OptionalString name, std::optional color, OptionalDouble opacity) const { + return Body(body_id_, solid_, std::move(name), color, opacity); +} Value Body::to_dict() const { Value out = Value::object(); out.set("body_id", body_id_); out.set("name", name_ ? Value(*name_) : Value()); + if (color_) // a body without an appearance keeps the dict it always had + out.set("color", to_array(*color_)); + if (opacity_) + out.set("opacity", *opacity_); return out; } +namespace { + +// A one-body Part writes its body in to_dict only when the body says more than its solid. +bool plain_default_body(const Body& body) { + return body.body_id() == kDefaultBodyId && !body.name() && !body.has_appearance(); +} + +} // namespace + Part::Part(std::string part_id, Solid body, OptionalString name, std::optional material, std::vector connectors) : Part(std::move(part_id), std::vector{Body(kDefaultBodyId, std::move(body))}, std::move(name), @@ -105,6 +144,22 @@ Part Part::with_material(const Material& material) const { return result; } +Part Part::with_body(const Body& body) const { + std::vector bodies = bodies_; + bool found = false; + for (Body& item : bodies) { + if (item.body_id() == body.body_id()) { + item = body; + found = true; + } + } + if (!found) + throw LookupError("part has no body_id '" + body.body_id() + "'"); + Part result(part_id_, std::move(bodies), name_, material_, connectors_); + result.inherit_metadata(*this); + return result; +} + Part Part::with_connector(const Connector& connector) const { const std::vector ids = connector_ids(); if (std::find(ids.begin(), ids.end(), connector.connector_id()) != ids.end()) { @@ -143,7 +198,8 @@ Value Part::to_dict() const { for (const Connector& connector : connectors_) rows.push_back(connector.to_dict()); out.set("connectors", std::move(rows)); - if (bodies_.size() > 1) { // a one-body Part keeps the dict it always had + // a one-body Part keeps the dict it always had, unless its body has a name or an appearance + if (bodies_.size() > 1 || !plain_default_body(bodies_.front())) { Value bodies = Value::array(); for (const Body& body : bodies_) bodies.push_back(body.to_dict()); diff --git a/src/cpp/src/product/specs.cpp b/src/cpp/src/product/specs.cpp index 620646fe..0fbf29ef 100644 --- a/src/cpp/src/product/specs.cpp +++ b/src/cpp/src/product/specs.cpp @@ -46,6 +46,14 @@ void add_structure(Specs& s) { "Failed to assign the material to the Part.", {"The part input is not a Part.", "The material input is not a Material."}, {"Create parts with make_part_rpart(...).", "Create materials with make_material_rmaterial(...)."}}); + add(s, {"set_body_appearance_rpart", + "Failed to set the appearance of the body.", + {"The part input is not a Part.", "The part has no body with that body_id.", + "The color is not three numbers in the [0.0, 1.0] range, or the opacity is outside [0.0, 1.0].", + "The name is empty."}, + {"Use an id from part.body_ids() (a one-body Part has the body 'body').", + "Pass color as an RGB tuple of floats between 0.0 and 1.0, e.g. (0.8, 0.2, 0.2).", + "Leave an argument out (None) to keep what the body has; pass reset=True to clear the appearance."}}); add(s, {"make_assembly_rassembly", "Failed to create the assembly.", {"The assembly_id is empty or uses unsupported characters.", diff --git a/src/simplecadapi/__init__.py b/src/simplecadapi/__init__.py index fc4b561a..1ef80106 100644 --- a/src/simplecadapi/__init__.py +++ b/src/simplecadapi/__init__.py @@ -264,6 +264,7 @@ from simplecadapi._cpp import ( make_vertex_connector_rconnector, measure_constraint_residual_rconstraintresidual, place_component_rassembly, + set_body_appearance_rpart, set_public_connector_rassembly, solve_assembly_constraints_rassembly, unground_component_rassembly, @@ -587,6 +588,7 @@ __all__ = [ "make_vertex_connector_rconnector", "make_placement_connector_rconnector", "add_connector_rpart", + "set_body_appearance_rpart", "set_public_connector_rassembly", "make_connector_ref_rconnectorref", "make_scalar_limit_rscalarlimit", diff --git a/src/simplecadapi/_glue/docstrings.json b/src/simplecadapi/_glue/docstrings.json index 2f302053..5759951f 100644 --- a/src/simplecadapi/_glue/docstrings.json +++ b/src/simplecadapi/_glue/docstrings.json @@ -346,5 +346,6 @@ "cut_rsolid_list": "Compute the boolean difference of solids and keep every piece.\n\nA cut can split the body (a slot through a bar leaves two parts) or consume it\n(a tool that encloses the whole body leaves nothing). ``cut_rsolid`` refuses\nsuch a result because it returns exactly one ``Solid``; this operator returns\nthem all. A tool is cut from every piece it meets, so several tools may split\na body into several parts.\n\nArgs:\n solids: One or more Solid objects or sequences of Solid. Nested sequences are\n flattened before processing; the first solid is the base, the rest are\n subtracted in order.\n skip_non_intersecting: When True, a tool that meets none of the current\n pieces is ignored; when False it raises.\n tracking_policy: FULL computes topology history and lineage. GRAPH keeps\n the replayable operation node without computing a TopoDelta.\n\nReturns:\n list[Solid]: Every piece of the cut, in kernel order; empty when the tools\n consume the base.\n\nRaises:\n SimpleCADError: An input is not a valid Solid, or the kernel could not\n compute the cut.\n\nUsage:\n ``pieces = cut_rsolid_list(bar, slot)`` returns both halves of a bar cut by\n a through slot. Use ``cut_rsolid`` when the result must be one solid.\n", "Body": "One named solid of a Part.\n\n``Body(body_id, solid, name=None)``: ``body_id`` is an identifier unique within\nthe part, ``solid`` the body's Solid, ``name`` an optional display name. A\none-body Part has one Body with the id ``\"body\"``.", "measure_part_mass_rmassreport": "Measure the volume, mass and centre of mass of every body of a Part, and of the Part as a whole.\n\nArgs:\n part: The Part to measure (one body or several).\n density: Density to use instead of the material's; ``None`` uses the\n Part's material, and without a material density every mass is ``None``.\n density_unit: Unit of ``density``: ``kg/m^3`` (default), ``g/cm^3``,\n ``kg/mm^3`` or ``g/mm^3``.\n\nReturns:\n MassReport: ``bodies`` (one ``BodyMass`` per body, in body order: ``body_id``,\n ``volume_mm3``, ``mass_kg``, ``centroid_mm``) and the totals of the part\n (``volume_mm3``, ``mass_kg``, volume-weighted ``centroid_mm``).\n\nRaises:\n SimpleCADError: The value is not a Part, or the density or its unit is invalid.\n\nUsage:\n ``scad.measure_part_mass_rmassreport(case).body(\"lid\").mass_kg`` is the mass of\n the lid body; ``.mass_kg`` the mass of the whole part. Every body has the\n Part's material.", - "inspect_body_overlaps_rlist": "List the pairs of bodies of a Part that share volume.\n\nOverlapping bodies are allowed (a Part does not fuse them), but mass counts the\nshared volume once per body and STEP holds both copies. Bodies that only touch\n(a face, an edge or a point in common) do not overlap.\n\nArgs:\n part: The Part to inspect; a one-body Part has no overlaps.\n min_volume_mm3: Shared volume below which a pair is not reported.\n\nReturns:\n list[BodyOverlap]: ``(first, second, volume_mm3)`` per overlapping pair, in body order.\n\nRaises:\n SimpleCADError: The value is not a Part.\n\nUsage:\n ``scad.inspect_body_overlaps_rlist(case)`` before export. Building the part's\n definition (a notebook run, ``@part``, a package) warns with ``BodyOverlapWarning``\n for the same pairs." + "inspect_body_overlaps_rlist": "List the pairs of bodies of a Part that share volume.\n\nOverlapping bodies are allowed (a Part does not fuse them), but mass counts the\nshared volume once per body and STEP holds both copies. Bodies that only touch\n(a face, an edge or a point in common) do not overlap.\n\nArgs:\n part: The Part to inspect; a one-body Part has no overlaps.\n min_volume_mm3: Shared volume below which a pair is not reported.\n\nReturns:\n list[BodyOverlap]: ``(first, second, volume_mm3)`` per overlapping pair, in body order.\n\nRaises:\n SimpleCADError: The value is not a Part.\n\nUsage:\n ``scad.inspect_body_overlaps_rlist(case)`` before export. Building the part's\n definition (a notebook run, ``@part``, a package) warns with ``BodyOverlapWarning``\n for the same pairs.", + "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 ``None`` 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." } diff --git a/src/simplecadapi/_glue/modules.json b/src/simplecadapi/_glue/modules.json index 57657ca2..c4b135ab 100644 --- a/src/simplecadapi/_glue/modules.json +++ b/src/simplecadapi/_glue/modules.json @@ -476,5 +476,6 @@ "vertices": "simplecadapi.ql", "vertices_of": "simplecadapi.kernel.ocp_topology", "volume": "simplecadapi.kernel.ocp_properties", -"wires": "simplecadapi.ql" +"wires": "simplecadapi.ql", +"set_body_appearance_rpart": "simplecadapi.operators.product" } \ No newline at end of file diff --git a/src/simplecadapi/_glue/session.py b/src/simplecadapi/_glue/session.py index 77e4ef0c..c9c25b77 100644 --- a/src/simplecadapi/_glue/session.py +++ b/src/simplecadapi/_glue/session.py @@ -587,6 +587,7 @@ _PRODUCT_OPS = ( "make_vertex_connector_rconnector", "make_placement_connector_rconnector", "add_connector_rpart", + "set_body_appearance_rpart", "set_public_connector_rassembly", "make_connector_ref_rconnectorref", "make_scalar_limit_rscalarlimit", diff --git a/src/simplecadapi/_glue/values.py b/src/simplecadapi/_glue/values.py index 17e2847c..010d6f95 100644 --- a/src/simplecadapi/_glue/values.py +++ b/src/simplecadapi/_glue/values.py @@ -94,12 +94,22 @@ def _token_for(key: str, item: Any) -> str: return f"{_TOKEN}{key}:{id(item):x}" +def _plain_body(part: Any) -> bool: + """A one-body Part whose body is just its Solid: no name, colour or opacity, and the default id.""" + + if part.multi_body: + return False + body = part.bodies[0] + return body.body_id == "body" and body.name is None and body.color is None and body.opacity is None + + # Constructor arguments that are not read back by the attribute of the same name. A Part holds one ``body`` or -# several ``bodies``, and is rebuilt from exactly one of them (``Part.body`` raises for a multi-body Part). +# several ``bodies``, and is rebuilt from exactly one of them (``Part.body`` raises for a multi-body Part). A one-body +# Part whose body carries a name or an appearance is rebuilt from its ``Body`` so they survive. _ARGUMENTS: Dict[str, Dict[str, Any]] = { "Part": { - "body": lambda value: None if value.multi_body else value.body, - "bodies": lambda value: value.bodies if value.multi_body else None, + "body": lambda value: value.body if _plain_body(value) else None, + "bodies": lambda value: None if _plain_body(value) else value.bodies, }, } diff --git a/src/simplecadapi/artifacts/assembly_io.py b/src/simplecadapi/artifacts/assembly_io.py index 6cd00f4a..a9ad01ff 100644 --- a/src/simplecadapi/artifacts/assembly_io.py +++ b/src/simplecadapi/artifacts/assembly_io.py @@ -42,6 +42,7 @@ from .part_definition import ( PartDefinition, mark_part_definition_validated, take_validated_part_body, + with_definition_appearance, ) from .part_io import encode_part_definition, load_part_definition, read_part_bodies from .references import ConnectorInterface, PartRef @@ -761,7 +762,8 @@ def materialize_definition( validate_artifact_blobs(node.to_dict(), node.blobs) body = read_part_bodies(node) mark_part_definition_validated(node) - multi = isinstance(body, tuple) # the Body values of a multi-body part + body = with_definition_appearance(node, body) # body colours, opacity and names, when any + multi = isinstance(body, tuple) # the Body values of a multi-body part (or of a one-body part with an appearance) value: Part | Assembly = Part( part_id=node.definition_id, name=node.metadata.get("name"), diff --git a/src/simplecadapi/artifacts/part_definition.py b/src/simplecadapi/artifacts/part_definition.py index e254017d..6b8437a2 100644 --- a/src/simplecadapi/artifacts/part_definition.py +++ b/src/simplecadapi/artifacts/part_definition.py @@ -7,6 +7,11 @@ one :class:`BodyRef` per body (its own BRep and topology snapshot, so each body that expects exactly one Solid refuses), and ``topology_snapshot_ref`` repeats the first body's snapshot. A multi-body definition has profile ``simplecad-part-definition-3`` (``contracts/part-definition-3.schema.json``), so a reader that knows only profile 2 refuses it; a one-body definition keeps profile 2 and its bytes. + +``appearance`` (optional, both profiles) holds the display appearance of the bodies that have one +(``set_body_appearance_rpart``): ``{"bodies": [{"body_id", "color", "opacity"}]}``, plus ``name`` on the row of a +one-body part (a multi-body part's body names live in ``solid_cache.bodies``). A definition whose bodies have no +appearance writes no ``appearance`` key, so its bytes and content hash are what they always were. """ from __future__ import annotations @@ -70,6 +75,62 @@ class BodyRef: ) +def _color(value: Any, path: str) -> tuple[float, float, float] | None: + if value is None: + return None + if ( + not isinstance(value, (list, tuple)) + or len(value) != 3 + or not all(isinstance(c, (int, float)) and not isinstance(c, bool) and 0.0 <= float(c) <= 1.0 for c in value) + ): + raise ArtifactValidationError("appearance_invalid", path, "expected three numbers in [0, 1] or null") + return (float(value[0]), float(value[1]), float(value[2])) + + +@dataclass(frozen=True, slots=True) +class BodyAppearance: + """The display appearance of one body of a PartDefinition: colour (RGB in [0, 1]), opacity and, for the body of + a one-body part, its display name. ``None`` fields are unset (the material colour, opaque, the body id).""" + + body_id: str + color: tuple[float, float, float] | None = None + opacity: float | None = None + name: str | None = None + + def __post_init__(self) -> None: + object.__setattr__(self, "body_id", validate_logical_id(self.body_id, "/appearance/bodies/body_id")) + object.__setattr__(self, "color", _color(self.color, "/appearance/bodies/color")) + if self.opacity is not None: + if isinstance(self.opacity, bool) or not isinstance(self.opacity, (int, float)) or not 0.0 <= float(self.opacity) <= 1.0: + raise ArtifactValidationError("appearance_invalid", "/appearance/bodies/opacity", "expected a number in [0, 1] or null") + object.__setattr__(self, "opacity", float(self.opacity)) + if self.name is not None and (not isinstance(self.name, str) or not self.name): + raise ArtifactValidationError("name_invalid", "/appearance/bodies/name", "expected a name or null") + + @classmethod + def of_body(cls, body: Any, *, with_name: bool) -> "BodyAppearance | None": + """The appearance of a runtime ``Body``, or ``None`` when it has nothing to record.""" + + name = body.name if with_name else None + if body.color is None and body.opacity is None and name is None: + return None + return cls(body_id=body.body_id, color=body.color, opacity=body.opacity, name=name) + + def to_dict(self) -> dict[str, Any]: + out: dict[str, Any] = { + "body_id": self.body_id, + "color": list(self.color) if self.color is not None else None, + "opacity": self.opacity, + } + if self.name is not None: + out["name"] = self.name + return out + + @classmethod + def from_dict(cls, data: Mapping[str, Any]) -> "BodyAppearance": + return cls(body_id=str(data["body_id"]), color=data.get("color"), opacity=data.get("opacity"), name=data.get("name")) + + @dataclass(frozen=True, slots=True) class PartDefinition: """Validated durable definition for exactly one evaluated Solid.""" @@ -89,6 +150,7 @@ class PartDefinition: content_hash: str = "" blobs: Mapping[str, bytes] = field(default_factory=dict, compare=False, repr=False) bodies: tuple[BodyRef, ...] = () # empty for a one-body part; else every body, in order (at least two) + appearance: tuple[BodyAppearance, ...] = () # the bodies that have a display appearance (usually none) _validated_manifest: bytes | None = field( default=None, init=False, @@ -166,6 +228,23 @@ class PartDefinition: "bodies_invalid", "/connectors", "connectors on a multi-body part are not supported yet" ) object.__setattr__(self, "bodies", bodies) + appearance = tuple(self.appearance) + if not all(isinstance(item, BodyAppearance) for item in appearance): + raise ArtifactValidationError("appearance_invalid", "/appearance/bodies", "expected BodyAppearance values") + known = [item.body_id for item in bodies] if bodies else None + seen = [item.body_id for item in appearance] + if len(set(seen)) != len(seen): + raise ArtifactValidationError("appearance_invalid", "/appearance/bodies", "body IDs must be unique") + for item in appearance: + if known is not None and item.body_id not in known: + raise ArtifactValidationError("appearance_invalid", "/appearance/bodies", f"no body {item.body_id!r}") + if known is None and len(appearance) > 1: + raise ArtifactValidationError("appearance_invalid", "/appearance/bodies", "a one-body part has one body") + if known is not None and item.name is not None: + raise ArtifactValidationError( + "appearance_invalid", "/appearance/bodies/name", "a multi-body part names its bodies in solid_cache.bodies" + ) + object.__setattr__(self, "appearance", appearance) # a multi-body part is profile 3, so a profile-2 reader refuses it (one-body parts keep profile 2 and their bytes) object.__setattr__(self, "profile", MULTI_BODY_PART_DEFINITION_PROFILE if bodies else PART_DEFINITION_PROFILE) if self.material_ref is not None and not isinstance( @@ -275,6 +354,8 @@ class PartDefinition: "file_inputs": [item.to_dict() for item in self.file_inputs], "interface_hashes": self.interface_hashes.to_dict(), "metadata": dict(self.metadata), + # only when a body has an appearance: every other definition keeps its bytes + **({"appearance": {"bodies": [item.to_dict() for item in self.appearance]}} if self.appearance else {}), } def to_dict(self) -> dict[str, Any]: @@ -331,6 +412,9 @@ class PartDefinition: BodyRef.from_dict(item, f"/solid_cache/bodies/{index}") for index, item in enumerate(cache.get("bodies") or ()) ), + appearance=tuple( + BodyAppearance.from_dict(item) for item in ((data.get("appearance") or {}).get("bodies") or ()) + ), ) @@ -366,4 +450,24 @@ def validated_part_feature_graph(definition: PartDefinition) -> Any: return definition._validated_feature_graph -__all__ = ["BodyRef", "PartDefinition"] +def with_definition_appearance(definition: PartDefinition, body: Any) -> Any: + """The bodies of *definition* with their appearance: *body* is what ``read_part_bodies`` gives (a Solid, or the + ``Body`` values of a multi-body part). Without an appearance it is returned as is; a one-body part with one + becomes a one-element tuple of ``Body`` (``Part(bodies=...)`` takes it).""" + + if not definition.appearance: + return body + from simplecadapi._cpp import Body + + rows = {item.body_id: item for item in definition.appearance} + if not isinstance(body, tuple): + row = definition.appearance[0] + return (Body(row.body_id, body, row.name, row.color, row.opacity),) + out = [] + for item in body: + row = rows.get(item.body_id) + out.append(item if row is None else Body(item.body_id, item.solid, item.name, row.color, row.opacity)) + return tuple(out) + + +__all__ = ["BodyAppearance", "BodyRef", "PartDefinition", "with_definition_appearance"] diff --git a/src/simplecadapi/build/definition.py b/src/simplecadapi/build/definition.py index a28b3b1b..f2bb7f6b 100644 --- a/src/simplecadapi/build/definition.py +++ b/src/simplecadapi/build/definition.py @@ -39,7 +39,7 @@ from ..artifacts.feature_graph import ( encode_feature_graph_artifact, ) from ..artifacts.geometry_interface import geometry_interface_fingerprint -from ..artifacts.part_definition import BodyRef, PartDefinition, mark_part_definition_validated +from ..artifacts.part_definition import BodyAppearance, BodyRef, PartDefinition, mark_part_definition_validated from ..artifacts.references import ( BlobRef, ConnectorInterface, @@ -248,6 +248,11 @@ def _part_definition( metadata={"name": part.name}, blobs=blobs, bodies=body_refs, + appearance=tuple( + row + for item in part.bodies + if (row := BodyAppearance.of_body(item, with_name=not part.multi_body)) is not None + ), ) validate_artifact_blobs(definition.to_dict(), definition.blobs) if not part.multi_body: # a multi-body part has no connectors yet diff --git a/src/simplecadapi/catalog.py b/src/simplecadapi/catalog.py index cf844b9b..b24018cf 100644 --- a/src/simplecadapi/catalog.py +++ b/src/simplecadapi/catalog.py @@ -10,7 +10,7 @@ functions with the same annotations. The catalog parses both, so a GUI, an agen [('radius', 'length'), ('height', 'length'), ('bottom_face_center', 'point3'), ('axis', 'direction3')] A parameter's ``kind`` is one of: the meanings of :mod:`simplecadapi.types` (``length``, ``angle``, ``point3``, -``direction3``, ``vector3``, ``count``, ``point2``, ``plane``, ``sketch_profile``), ``number`` (a unitless ``float | Expr``), ``int``, ``bool``, ``text``, ``path`` +``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 ``ql`` selection), ``points`` / ``numbers`` (sequences), ``grid`` (rows of points), ``_map`` (``dict[str, ]``: a value per id), diff --git a/src/simplecadapi/contracts/part-definition-2.schema.json b/src/simplecadapi/contracts/part-definition-2.schema.json index 0e2b0a9a..76335d37 100644 --- a/src/simplecadapi/contracts/part-definition-2.schema.json +++ b/src/simplecadapi/contracts/part-definition-2.schema.json @@ -39,7 +39,30 @@ "material_ref": {"oneOf": [{"type": "null"}, {"$ref": "#/$defs/materialRef"}]}, "file_inputs": {"type": "array", "maxItems": 1024, "items": {"$ref": "#/$defs/fileInput"}}, "interface_hashes": {"$ref": "#/$defs/interfaceHashes"}, - "metadata": {"type": "object"} + "metadata": {"type": "object"}, + "appearance": { + "type": "object", + "additionalProperties": false, + "required": ["bodies"], + "properties": { + "bodies": { + "type": "array", + "minItems": 1, + "maxItems": 10000, + "items": { + "type": "object", + "additionalProperties": false, + "required": ["body_id", "color", "opacity"], + "properties": { + "body_id": {"type": "string", "minLength": 1, "maxLength": 128}, + "color": {"oneOf": [{"type": "null"}, {"type": "array", "minItems": 3, "maxItems": 3, "items": {"type": "number", "minimum": 0, "maximum": 1}}]}, + "opacity": {"oneOf": [{"type": "null"}, {"type": "number", "minimum": 0, "maximum": 1}]}, + "name": {"type": "string", "minLength": 1} + } + } + } + } + } }, "$defs": { "id": {"type": "string", "minLength": 1, "maxLength": 256, "pattern": "^[A-Za-z][A-Za-z0-9_.:-]*$"}, diff --git a/src/simplecadapi/contracts/part-definition-3.schema.json b/src/simplecadapi/contracts/part-definition-3.schema.json index 8c65b26f..956d72dc 100644 --- a/src/simplecadapi/contracts/part-definition-3.schema.json +++ b/src/simplecadapi/contracts/part-definition-3.schema.json @@ -55,7 +55,30 @@ "material_ref": {"oneOf": [{"type": "null"}, {"$ref": "#/$defs/materialRef"}]}, "file_inputs": {"type": "array", "maxItems": 1024, "items": {"$ref": "#/$defs/fileInput"}}, "interface_hashes": {"$ref": "#/$defs/interfaceHashes"}, - "metadata": {"type": "object"} + "metadata": {"type": "object"}, + "appearance": { + "type": "object", + "additionalProperties": false, + "required": ["bodies"], + "properties": { + "bodies": { + "type": "array", + "minItems": 1, + "maxItems": 10000, + "items": { + "type": "object", + "additionalProperties": false, + "required": ["body_id", "color", "opacity"], + "properties": { + "body_id": {"type": "string", "minLength": 1, "maxLength": 128}, + "color": {"oneOf": [{"type": "null"}, {"type": "array", "minItems": 3, "maxItems": 3, "items": {"type": "number", "minimum": 0, "maximum": 1}}]}, + "opacity": {"oneOf": [{"type": "null"}, {"type": "number", "minimum": 0, "maximum": 1}]}, + "name": {"type": "string", "minLength": 1} + } + } + } + } + } }, "$defs": { "id": {"type": "string", "minLength": 1, "maxLength": 256, "pattern": "^[A-Za-z][A-Za-z0-9_.:-]*$"}, diff --git a/src/simplecadapi/exporter/step.py b/src/simplecadapi/exporter/step.py index 79e83881..231891f0 100644 --- a/src/simplecadapi/exporter/step.py +++ b/src/simplecadapi/exporter/step.py @@ -97,6 +97,23 @@ def _native_definitions(root_value: Part | Assembly, units: Any) -> list[dict[st } if material.color is not None: entry["color"] = tuple(float(c) for c in material.color) + if not value.multi_body: + own = value.bodies[0].color # a body colour overrides the material colour + if own is not None: + entry["color"] = tuple(float(c) for c in own) + else: + # each body with a name or a colour of its own is a named / coloured solid of the product's shape + shape = entry["shape"] + solids = shape.solids() + entry["bodies"] = [ + { + "shape": solid, + "name": body.name, + "color": None if body.color is None else tuple(float(c) for c in body.color), + } + for body, solid in zip(value.bodies, solids) + if body.name is not None or body.color is not None + ] out[key] = entry return definition_id entry = { diff --git a/src/simplecadapi/operators/__init__.py b/src/simplecadapi/operators/__init__.py index d974f9bd..f89ec614 100644 --- a/src/simplecadapi/operators/__init__.py +++ b/src/simplecadapi/operators/__init__.py @@ -111,6 +111,7 @@ from simplecadapi._cpp import ( make_vertex_connector_rconnector, measure_constraint_residual_rconstraintresidual, place_component_rassembly, + set_body_appearance_rpart, set_public_connector_rassembly, solve_assembly_constraints_rassembly, unground_component_rassembly, @@ -385,6 +386,7 @@ __all__ = [ "select_edges_by_tag", "select_faces_by_tag", "selection", + "set_body_appearance_rpart", "set_public_connector_rassembly", "sew_faces_rshell", "shell_rsolid", diff --git a/src/simplecadapi/operators/product.py b/src/simplecadapi/operators/product.py index afbe9ff3..36111443 100644 --- a/src/simplecadapi/operators/product.py +++ b/src/simplecadapi/operators/product.py @@ -38,6 +38,7 @@ from simplecadapi._cpp import ( make_vertex_connector_rconnector, measure_constraint_residual_rconstraintresidual, place_component_rassembly, + set_body_appearance_rpart, set_public_connector_rassembly, solve_assembly_constraints_rassembly, unground_component_rassembly, @@ -73,6 +74,7 @@ __all__ = [ "measure_part_mass_rmassreport", "inspect_body_overlaps_rlist", "place_component_rassembly", + "set_body_appearance_rpart", "set_public_connector_rassembly", "solve_assembly_constraints_rassembly", "unground_component_rassembly", diff --git a/src/simplecadapi/product/bodies.py b/src/simplecadapi/product/bodies.py index b2ac68b5..6867f592 100644 --- a/src/simplecadapi/product/bodies.py +++ b/src/simplecadapi/product/bodies.py @@ -27,6 +27,32 @@ _DENSITY_TO_KG_MM3 = { } +def body_display_color(part: Part, body: Any) -> tuple[float, float, float] | None: + """The colour a viewer shows *body* of *part* in: the body's own colour, else the Part's material colour, else + ``None`` (the viewer's default grey). + + A body colour (``set_body_appearance_rpart``) overrides the material colour for display only. + """ + + if body.color is not None: + return tuple(float(c) for c in body.color) # type: ignore[return-value] + material = part.material + if material is not None and material.color is not None: + return tuple(float(c) for c in material.color) # type: ignore[return-value] + return None + + +def body_appearance_fields(body: Any) -> dict[str, Any]: + """The appearance a body sets itself, as plain data: ``color`` (RGB list) and ``opacity`` when set, else ``{}``.""" + + out: dict[str, Any] = {} + if body.color is not None: + out["color"] = [float(c) for c in body.color] + if body.opacity is not None: + out["opacity"] = float(body.opacity) + return out + + def part_shape(part: Part) -> Solid | Compound: """The Solid of a one-body Part, or a Compound of every body of a multi-body Part (in body order). diff --git a/src/simplecadapi/recording/serializer.py b/src/simplecadapi/recording/serializer.py index ad2dbeb7..1c5fd181 100644 --- a/src/simplecadapi/recording/serializer.py +++ b/src/simplecadapi/recording/serializer.py @@ -285,6 +285,10 @@ PUBLIC_API_COVERAGE: Dict[str, Dict[str, str]] = { "status": "replayable", "op": "make_assign_material_rpart", }, + "set_body_appearance_rpart": { + "status": "replayable", + "op": "make_set_body_appearance_rpart", + }, "make_assembly_rassembly": { "status": "replayable", "op": "make_assembly_rassembly", @@ -608,6 +612,7 @@ CANONICAL_CORE_OP_SET: Tuple[str, ...] = ( "make_identity_placement_rplacement", "make_part_rpart", "make_assign_material_rpart", + "make_set_body_appearance_rpart", "make_assembly_rassembly", "reference_definition", "make_add_component_rassembly", @@ -3159,6 +3164,22 @@ def _execute_graph( _store_outputs(node, result) continue + if op_name == "make_set_body_appearance_rpart": + ctx.require_params(node.node_id, op_name, params, ("body_id",)) + part_outputs = _input_outputs(ctx, outputs, node, 0) + if part_outputs: + color = params.get("color") + result = ops.set_body_appearance_rpart( + cast(Part, part_outputs[0]), + str(params["body_id"]), + color=cast(Any, tuple(color)) if color is not None else None, + opacity=cast(Optional[float], params.get("opacity")), + name=cast(Optional[str], params.get("name")), + reset=bool(params.get("reset", False)), + ) + _store_outputs(node, result) + continue + if op_name == "make_assembly_rassembly": ctx.require_params( node.node_id, op_name, params, ("assembly_id",) diff --git a/src/simplecadapi/scene/compiler.py b/src/simplecadapi/scene/compiler.py index 743e529c..5dab4ab0 100644 --- a/src/simplecadapi/scene/compiler.py +++ b/src/simplecadapi/scene/compiler.py @@ -325,7 +325,7 @@ def _compile_part(root_id: str, part: Part, transform: Placement, source: SceneS definition_id = f"definition/{root_id}/part/{_encode(part.part_id)}" normalized = _normalized_part(part) if definition_id not in definitions: - appearance_id = _appearance(part.material, root_id, appearances) + appearance_id = _appearance(part.material, root_id, appearances, body=part.bodies[0]) definitions[definition_id] = {"definition_id": definition_id, "kind": "part", "name": part.name, "source": _product_definition_source(root_id, part, source), "sdk_metadata": _metadata(part)} renderables[definition_id] = _make_renderable(definition_id, part.body, options, appearances, appearance_id=appearance_id) products[definition_id] = normalized @@ -624,8 +624,11 @@ def _ocp_version() -> str: return str(occt.__version__) -def _appearance(material: Material | None, root_id: str, appearances: dict[str, dict[str, Any]]) -> str: - draft = {"alpha_mode": "opaque", "base_color": [*(material.color if material and material.color else (0.72, 0.75, 0.78)), 1], "double_sided": False, "edge_color": [0.08, 0.09, 0.1, 1], "metallic": 0, "name": material.name if material else None, "roughness": 0.55, "sdk_metadata": {}, "source": {"kind": "product_material", "root_id": root_id, "material_id": material.material_id} if material else None} +def _appearance(material: Material | None, root_id: str, appearances: dict[str, dict[str, Any]], *, body: Any = None) -> str: + # A body colour (set_body_appearance_rpart) overrides the material colour. Scene 1.0 is opaque only: a body + # opacity is not written here (the live preview and the package scene carry it). + color = body.color if body is not None and body.color is not None else (material.color if material and material.color else (0.72, 0.75, 0.78)) + draft = {"alpha_mode": "opaque", "base_color": [*color, 1], "double_sided": False, "edge_color": [0.08, 0.09, 0.1, 1], "metallic": 0, "name": material.name if material else None, "roughness": 0.55, "sdk_metadata": {}, "source": {"kind": "product_material", "root_id": root_id, "material_id": material.material_id} if material else None} appearance_id = "appearance/evaluated/" + hashlib.sha256(canonical_json_bytes(draft)).hexdigest() appearances.setdefault(appearance_id, {"appearance_id": appearance_id, **draft}) return appearance_id diff --git a/src/simplecadapi/scene/preview.py b/src/simplecadapi/scene/preview.py index a61e5315..dd16f3f5 100644 --- a/src/simplecadapi/scene/preview.py +++ b/src/simplecadapi/scene/preview.py @@ -36,6 +36,7 @@ import numpy as np from .._internal.mesh import DEFAULT_ANGULAR_TOLERANCE, DEFAULT_LINEAR_TOLERANCE, cached_mesh from simplecadapi._cpp import Assembly, Part, Solid +from ..product.bodies import body_display_color from ..product.placement import Placement, identity_placement from .compiler import ( _curve_geometry, @@ -85,6 +86,10 @@ class PreviewNode: definition_id: str display_name: str placement: Placement # CAD space, millimetres, relative to the product + color: tuple[float, float, float] | None = None + """The display colour (RGB in [0, 1]): the body's colour, else the material's; ``None`` is the viewer's default.""" + opacity: float | None = None + """The body's display opacity in [0, 1]; ``None`` is opaque.""" @dataclass @@ -279,6 +284,7 @@ def compile_preview( parts[preview.key] = preview solids.setdefault(preview.key, body) definitions.setdefault(preview.key, part.part_id) + only = part.bodies[0] nodes.append( PreviewNode( node_id="node/" + "/".join(path), @@ -286,6 +292,8 @@ def compile_preview( definition_id=part.part_id, display_name=name, placement=placement, + color=body_display_color(part, only), + opacity=only.opacity, ) ) return @@ -305,6 +313,8 @@ def compile_preview( definition_id=part.part_id, display_name=f"{name} / {item.name or item.body_id}", placement=placement, + color=body_display_color(part, item), + opacity=item.opacity, ) ) @@ -399,6 +409,9 @@ def encode_preview(scene: PreviewScene, omit: Collection[str] = ()) -> bytes: "y_axis": list(node.placement.y_axis), "z_axis": list(node.placement.z_axis), }, + # the display colour and opacity, only when known (a viewer draws its default otherwise) + **({"color": [float(c) for c in node.color]} if node.color is not None else {}), + **({"opacity": float(node.opacity)} if node.opacity is not None else {}), } for node in scene.nodes ], diff --git a/src/simplecadapi/scene/product_scene.py b/src/simplecadapi/scene/product_scene.py index 5ab79142..f4c02f52 100644 --- a/src/simplecadapi/scene/product_scene.py +++ b/src/simplecadapi/scene/product_scene.py @@ -602,6 +602,23 @@ def _node_id(path: tuple[str, ...]) -> str: return "node/" + "/".join(path) +def _appearance_properties(definition: PartDefinition, body_id: str | None) -> dict[str, Any]: + """``color`` / ``opacity`` of a body that has its own (``body_id`` None: the body of a one-body part), else ``{}``. + + A viewer draws a node with ``properties.color`` in that colour; without one, the material's (``material_id``). + """ + + for row in definition.appearance: + if body_id is None or row.body_id == body_id: + out: dict[str, Any] = {} + if row.color is not None: + out["color"] = list(row.color) + if row.opacity is not None: + out["opacity"] = row.opacity + return out + return {} + + def _build_nodes( root: Definition, definitions: Mapping[str, Definition], @@ -650,6 +667,8 @@ def _build_nodes( "properties": { "content_hash": definition.content_hash, "revision": definition.revision, + # a one-body part's body colour / opacity (set_body_appearance_rpart), when it has one + **(_appearance_properties(definition, None) if is_part and not definition.bodies else {}), }, } ) @@ -670,7 +689,7 @@ def _build_nodes( "geometry_asset_id": geometry_id, "entity_asset_id": entity_id, "material_id": part_node["material_id"], - "properties": {"body_id": body_id}, + "properties": {"body_id": body_id, **_appearance_properties(definition, body_id)}, } ) if isinstance(definition, AssemblyDefinition): diff --git a/src/simplecadapi/types.py b/src/simplecadapi/types.py index 1f381888..615f4624 100644 --- a/src/simplecadapi/types.py +++ b/src/simplecadapi/types.py @@ -13,6 +13,7 @@ the meaning from there. Each alias is the type a caller may pass (``Annotated`` - ``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}``. - ``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). A plain ``float | Expr`` is a number without a unit (a factor, a tolerance). """ @@ -35,6 +36,7 @@ Count = Annotated[int, "count"] Point2 = Annotated[Sequence[_Number], "point2"] Plane = Annotated[Union[Literal["XY", "XZ", "YZ"], Mapping[str, Sequence[_Number]]], "plane"] SketchProfile = Annotated[Union[int, str], "sketch_profile"] +Color = Annotated[Sequence[float], "color"] MEANINGS: dict[str, str] = { "Length": "length", @@ -46,7 +48,8 @@ MEANINGS: dict[str, str] = { "Point2": "point2", "Plane": "plane", "SketchProfile": "sketch_profile", + "Color": "color", } """The type names a signature may carry, and the meaning each stands for (what :mod:`simplecadapi.catalog` reads).""" -__all__ = ["Angle", "Count", "Direction3", "Length", "MEANINGS", "Plane", "Point2", "Point3", "SketchProfile", "Vector3"] +__all__ = ["Angle", "Color", "Count", "Direction3", "Length", "MEANINGS", "Plane", "Point2", "Point3", "SketchProfile", "Vector3"] diff --git a/test/test_body_appearance.py b/test/test_body_appearance.py new file mode 100644 index 00000000..093525b0 --- /dev/null +++ b/test/test_body_appearance.py @@ -0,0 +1,253 @@ +"""Body appearance: a display colour, opacity and name per body of a Part (``set_body_appearance_rpart``). + +The material colour is the default; a body colour overrides it for display. The appearance reaches the live preview, +the legacy scene compiler, the product package (part definition and package scene), STEP, the cell cache (pickle) +and graph replay. A Part whose bodies have no appearance is byte for byte what it was. +""" + +from __future__ import annotations + +import copy +import pickle +import re +import tempfile +import unittest +from pathlib import Path + +import simplecadapi as scad +from simplecadapi import catalog +from simplecadapi.artifacts import materialize_definition +from simplecadapi.artifacts.validation import validate_manifest +from simplecadapi.exporter.step import export_product_package_to_step +from simplecadapi.product.packages import build_product_package, encode_product_package, load_product_package +from simplecadapi.runtime import run_notebook +from simplecadapi.scene.preview import compile_preview, decode_preview_header, encode_preview + +from test_notebook_runtime import NotebookTestCase, cell, notebook_text + +RED = (0.9, 0.2, 0.1) +BLUE = (0.1, 0.3, 0.8) + + +def _case() -> scad.Part: + return scad.make_part_rpart( + part_id="case", + bodies={ + "base": scad.make_box_rsolid(20.0, 20.0, 10.0, tag_prefix="base"), + "lid": scad.make_box_rsolid(20.0, 20.0, 2.0, (40.0, 0.0, 0.0), tag_prefix="lid"), + }, + ) + + +def _plate() -> scad.Part: + return scad.make_part_rpart(part_id="plate", body=scad.make_box_rsolid(10.0, 10.0, 2.0)) + + +class TestOperation(unittest.TestCase): + def test_sets_colour_opacity_and_name_of_one_body(self) -> None: + case = _case() + painted = scad.set_body_appearance_rpart(case, "lid", color=RED, opacity=0.5, name="Lid") + lid = painted.get_body("lid") + self.assertEqual(lid.color, RED) + self.assertEqual(lid.opacity, 0.5) + self.assertEqual(lid.name, "Lid") + self.assertIsNone(painted.get_body("base").color) + self.assertIsNone(case.get_body("lid").color) # values are immutable + self.assertEqual(painted.body_ids(), ("base", "lid")) + self.assertEqual( + painted.to_dict()["bodies"][1], {"body_id": "lid", "name": "Lid", "color": list(RED), "opacity": 0.5} + ) + + def test_none_keeps_and_reset_clears(self) -> None: + painted = scad.set_body_appearance_rpart(_case(), "lid", color=RED, name="Lid") + again = scad.set_body_appearance_rpart(painted, "lid", opacity=0.25) + self.assertEqual((again.get_body("lid").color, again.get_body("lid").name), (RED, "Lid")) + cleared = scad.set_body_appearance_rpart(again, "lid", reset=True) + lid = cleared.get_body("lid") + self.assertEqual((lid.color, lid.opacity, lid.name), (None, None, None)) + self.assertEqual(cleared.to_dict()["bodies"][1], {"body_id": "lid", "name": None}) + + def test_one_body_part_uses_the_default_body(self) -> None: + plate = scad.set_body_appearance_rpart(_plate(), color=BLUE) + self.assertFalse(plate.multi_body) + self.assertEqual(plate.bodies[0].color, BLUE) + self.assertEqual(plate.to_dict()["bodies"], [{"body_id": "body", "name": None, "color": list(BLUE)}]) + self.assertNotIn("bodies", _plate().to_dict()) # a plain one-body part keeps its dict + + def test_material_is_kept_and_overridden_for_display_only(self) -> None: + steel = scad.make_material_rmaterial("steel", color=(0.5, 0.5, 0.5), density=7.85, density_unit="g/cm^3") + case = scad.set_body_appearance_rpart(scad.assign_material_rpart(_case(), steel), "lid", color=RED) + self.assertEqual(case.material.material_id, "steel") + mass = scad.measure_part_mass_rmassreport(case) + self.assertAlmostEqual(mass.body("lid").mass_kg, 800.0 * 7.85e-6, places=12) + colors = {node.node_id: node.color for node in compile_preview(case).nodes} + self.assertEqual(colors, {"node/case/body:base": (0.5, 0.5, 0.5), "node/case/body:lid": RED}) + + def test_errors(self) -> None: + for kwargs in ({"color": (1.5, 0, 0)}, {"color": (1, 0)}, {"opacity": 2.0}, {"name": " "}): + with self.subTest(kwargs=kwargs), self.assertRaises(scad.SimpleCADError): + scad.set_body_appearance_rpart(_case(), "lid", **kwargs) + with self.assertRaisesRegex(scad.SimpleCADError, "hinge"): + scad.set_body_appearance_rpart(_case(), "hinge", color=RED) + with self.assertRaises(scad.SimpleCADError): + scad.set_body_appearance_rpart("not a part", color=RED) + with self.assertRaises(Exception): + scad.Body("a", scad.make_box_rsolid(1, 1, 1), color=(2, 0, 0)) + + def test_catalog_types_every_parameter(self) -> None: + op = catalog.operation("set_body_appearance_rpart") + kinds = {p.name: p.kind for p in op.params} + self.assertEqual( + kinds, + {"part": "part", "body_id": "text", "color": "color", "opacity": "number", "name": "text", "reset": "bool"}, + ) + self.assertEqual(op.returns, "part") + self.assertEqual(catalog.operation("make_material_rmaterial").params[-1].kind, "color") + + +class TestCacheAndReplay(unittest.TestCase): + def test_pickle_and_deepcopy_keep_the_appearance(self) -> None: + case = scad.set_body_appearance_rpart(_case(), "lid", color=RED, opacity=0.5, name="Lid") + plate = scad.set_body_appearance_rpart(_plate(), color=BLUE, name="Plate") + for again in (pickle.loads(pickle.dumps(case)), copy.deepcopy(case)): + lid = again.get_body("lid") + self.assertEqual((lid.color, lid.opacity, lid.name), (RED, 0.5, "Lid")) + one = pickle.loads(pickle.dumps(plate)) + self.assertFalse(one.multi_body) + self.assertEqual((one.bodies[0].color, one.bodies[0].name), (BLUE, "Plate")) + plain = pickle.loads(pickle.dumps(_plate())) + self.assertIsNone(plain.bodies[0].color) + + def test_recorded_and_replayed(self) -> None: + with scad.GraphSession() as session: + case = scad.set_body_appearance_rpart(_case(), "lid", color=RED, opacity=0.5, name="Lid") + scad.set_body_appearance_rpart(case, "base", color=BLUE) + model = scad.export_model_json(session) + self.assertIn("make_set_body_appearance_rpart", model) + parts = [item for item in scad.replay_model_json(model) if isinstance(item, scad.Part)] + final = parts[-1] + self.assertEqual(final.get_body("base").color, BLUE) + lid = final.get_body("lid") + self.assertEqual((lid.color, lid.opacity, lid.name), (RED, 0.5, "Lid")) + + +class TestPreviewAndScene(unittest.TestCase): + def test_preview_header_carries_colour_and_opacity(self) -> None: + case = scad.set_body_appearance_rpart(_case(), "lid", color=RED, opacity=0.5, name="Lid") + nodes = {n["node_id"]: n for n in decode_preview_header(encode_preview(compile_preview(case)))["nodes"]} + self.assertEqual(nodes["node/case/body:lid"]["color"], list(RED)) + self.assertEqual(nodes["node/case/body:lid"]["opacity"], 0.5) + self.assertEqual(nodes["node/case/body:lid"]["display_name"], "case / Lid") + self.assertNotIn("color", nodes["node/case/body:base"]) + + def test_a_plain_preview_header_is_unchanged(self) -> None: + header = decode_preview_header(encode_preview(compile_preview(_plate()))) + self.assertNotIn("color", header["nodes"][0]) + self.assertNotIn("opacity", header["nodes"][0]) + + def test_legacy_scene_compiler_uses_the_body_colour(self) -> None: + from simplecadapi.scene import compiler + + plate = scad.set_body_appearance_rpart(_plate(), color=BLUE) + package = compiler.compile_scene(scene_id="plate", roots=[compiler.SceneRoot(root_id="plate", value=plate)]) + colors = [list(a["base_color"]) for a in package.manifest["appearances"]] + self.assertIn([*BLUE, 1], colors) + + +PAINTED = notebook_text( + cell( + """ + base = scad.make_box_rsolid(20.0, 20.0, 10.0, tag_prefix="base") + lid = scad.make_box_rsolid(20.0, 20.0, 2.0, (40.0, 0.0, 0.0), tag_prefix="lid") + """, + returns="base, lid", + ), + cell( + """ + case = scad.make_part_rpart(part_id=scad.notebook_id(), bodies={"base": base, "lid": lid}) + case = scad.set_body_appearance_rpart(case, "lid", color=(0.9, 0.2, 0.1), opacity=0.5, name="Lid") + """, + reads="base, lid", + returns="case", + ), + table='id = "case"', +) + +PLATE = notebook_text( + cell( + """ + plate = scad.make_part_rpart(part_id=scad.notebook_id(), body=scad.make_box_rsolid(5.0, 5.0, 1.0)) + plate = scad.set_body_appearance_rpart(plate, color=(0.1, 0.3, 0.8), name="Plate") + """, + returns="plate", + ), + table='id = "plate"', +) + +PLAIN = notebook_text( + cell("plate = scad.make_part_rpart(part_id=scad.notebook_id(), body=scad.make_box_rsolid(5.0, 5.0, 1.0))", returns="plate"), + table='id = "plain"', +) + + +class TestPackage(NotebookTestCase): + def test_multi_body_definition_round_trip(self) -> None: + path = self.write("case.py", PAINTED) + first = run_notebook(path) + second = run_notebook(path) + self.assertEqual(self.statuses(second)[-1], "cached") + # (the content hash of a cached multi-body run differs from the first run on this branch already: + # test_multi_body_part's cache test, known WIP of the stable-refs merge; the appearance is the same) + self.assertEqual(first.definition.to_dict()["appearance"], second.definition.to_dict()["appearance"]) + manifest = second.definition.to_dict() + self.assertEqual(manifest["profile"], "simplecad-part-definition-3") + self.assertEqual(manifest["appearance"], {"bodies": [{"body_id": "lid", "color": list(RED), "opacity": 0.5}]}) + self.assertEqual([row["name"] for row in manifest["solid_cache"]["bodies"]], [None, "Lid"]) + validate_manifest(manifest, "part_definition") + part = materialize_definition(load_product_package(encode_product_package(build_product_package(second.definition)))) + lid = part.get_body("lid") + self.assertEqual((lid.color, lid.opacity, lid.name), (RED, 0.5, "Lid")) + self.assertIsNone(part.get_body("base").color) + + def test_one_body_definition_keeps_profile_2_and_round_trips(self) -> None: + definition = run_notebook(self.write("plate.py", PLATE)).definition + manifest = definition.to_dict() + self.assertEqual(manifest["profile"], "simplecad-part-definition-2") + self.assertEqual(manifest["appearance"], {"bodies": [{"body_id": "body", "color": list(BLUE), "opacity": None, "name": "Plate"}]}) + validate_manifest(manifest, "part_definition") + part = materialize_definition(load_product_package(encode_product_package(build_product_package(definition)))) + self.assertFalse(part.multi_body) + self.assertEqual((part.bodies[0].color, part.bodies[0].name), (BLUE, "Plate")) + + def test_a_plain_definition_has_no_appearance_key(self) -> None: + definition = run_notebook(self.write("plain.py", PLAIN)).definition + self.assertNotIn("appearance", definition.to_dict()) + self.assertEqual(definition.appearance, ()) + + def test_package_scene_nodes_carry_the_colour(self) -> None: + from simplecadapi.scene.product_scene import compile_product_scene + + nodes = {n["node_id"]: n for n in compile_product_scene(run_notebook(self.write("case.py", PAINTED)).definition).manifest["nodes"]} + self.assertEqual(nodes["node/case/body:lid"]["properties"]["color"], list(RED)) + self.assertEqual(nodes["node/case/body:lid"]["properties"]["opacity"], 0.5) + self.assertNotIn("color", nodes["node/case/body:base"]["properties"]) + plate = compile_product_scene(run_notebook(self.write("plate.py", PLATE)).definition).manifest["nodes"] + self.assertEqual(plate[0]["properties"]["color"], list(BLUE)) + + def test_step_writes_the_body_colours_and_names(self) -> None: + for name, text, expected, label in (("case.py", PAINTED, RED, "Lid"), ("plate.py", PLATE, BLUE, None)): + data = encode_product_package(build_product_package(run_notebook(self.write(name, text)).definition)) + with tempfile.TemporaryDirectory() as directory: + path = Path(directory) / "out.step" + export_product_package_to_step(data, path) + step = path.read_text(encoding="utf-8", errors="replace") + rgb = [tuple(round(float(v), 3) for v in m) for m in re.findall(r"COLOUR_RGB\('[^']*',([\d.Ee+-]+),([\d.Ee+-]+),([\d.Ee+-]+)\)", step)] + # OCCT takes the colour as linear RGB (Quantity_TOC_RGB, as for a material colour) and STEP stores sRGB + srgb = tuple(round(c * 12.92 if c <= 0.0031308 else 1.055 * c ** (1 / 2.4) - 0.055, 3) for c in expected) + self.assertTrue(any(all(abs(a - b) < 2e-3 for a, b in zip(srgb, row)) for row in rgb), (name, rgb)) + if label: + self.assertIn(f"'{label}'", step) + + +if __name__ == "__main__": + unittest.main() diff --git a/test/test_serialization.py b/test/test_serialization.py index 971df0ac..d38ad103 100644 --- a/test/test_serialization.py +++ b/test/test_serialization.py @@ -332,6 +332,7 @@ class TestCoverageMatrix(unittest.TestCase): "make_identity_placement_rplacement", "make_part_rpart", "make_assign_material_rpart", + "make_set_body_appearance_rpart", "make_assembly_rassembly", "make_add_component_rassembly", "reference_definition",