diff --git a/docs/HLSD/mcp-server.md b/docs/HLSD/mcp-server.md index 4e0ed5ae87..9f79124276 100644 --- a/docs/HLSD/mcp-server.md +++ b/docs/HLSD/mcp-server.md @@ -85,8 +85,11 @@ They say to prefer typed tools over clicks and never retry a call that returned `get_settings`' meta and search for what a setting does, say how a gizmo opens and is driven (and that `gizmo_file` only stands in for a file picker inside one, since its name draws agents to it for any gizmo work), that the camera turns with `set_view` rather than a drag, and which indices are 0-based. -They also point to `api_describe` for the operations plugins offer, which `tools/list` never shows, so -nothing else tells an agent they exist. Clients that defer tools load only their names and the +They also point to `api_describe {query}` as the one search across every catalog an agent calls into: +the tools, the operations plugins offer (which `tools/list` never shows, so nothing else tells an agent +they exist), Speed Dial actions, settings, the Python API and the Design tab's methods. An agent rarely +knows which catalog answers "how do I add a brim", and each catalog has its own search with its own +arguments. Clients that defer tools load only their names and the instructions at first, so the instructions are how an agent without a skill learns which tool to load. @@ -397,8 +400,8 @@ the UI thread. | Scripts | `run_script` | run a script file or inline script, with results per step | | | `export_script` | write the session journal as a script that can be replayed; calls whose job is still running are left out and listed | | | `run_python` | run Python code against `orca.host`, calling tools through `orca.host.tools`; needs the Python setting (see Python scripts); cancellable | -| | `python_api` | search `orca.host` in the running build: names, signatures and documentation | -| API | `api_describe` | look up any registered tool or plugin operation: its schema by name, matches by words, or every name | +| | `python_api` | search the `orca` package in the running build: names, signatures and documentation, paged | +| API | `api_describe` | look up any registered tool or plugin operation by name, list every name, or search every catalog by words | | | `api_call` | call a registered tool or plugin operation by name; runs and is journaled as that tool's own call | | CAD | `cad_call` | a method of the Design tab: sketches, features, reads and measurements, feature and body edits, undo, commit to plate; `describe_tools` lists them (CAD builds, Design tab enabled) | @@ -2544,8 +2547,22 @@ agent's idle wait, and a `tools/mcp` driver run from the dialog against the same **Journal and replay.** `run_python` is journaled as one step holding its code, kept when the code failed partway; its tool calls are not journaled. In a JSON script a `run_python` step's `code` is never -substituted, and a step whose outcome is not `finished` fails. `python_api` searches the reference built -from the running build's `orca.host`. +substituted, and a step whose outcome is not `finished` fails. + +**The reference.** `python_api` serves the reference `python_api_reference()` builds from the running +build's `orca` package: `orca.host`, and the classes, events and pages plugins build on. It walks the +modules and lists each public class, function, method, property, named instance (such as +`orca.host.preset.process`) and constant (such as `orca.host.ui.PD_CAN_ABORT`) with its signature and +documentation. The signature lines pybind11 starts a docstring with become the signature, a class's are its +constructors, and an enum's values stay in its documentation rather than becoming entries, as they would +where a module exports them. The documentation is the bindings' own docstrings, a class's followed by what +its constructors say of their arguments; a constant can't carry one, so its documentation names the entries +whose documentation names it. The reference is only as good as the docstrings: a test requires every entry +to have documentation, every constructor that takes arguments to say what they are, and every parameter a +name (pybind11 names an unnamed one `arg0`). A query ranks the +entries as the settings search does (`query_words()`, `match_score()`); without one the whole package is +listed with each entry's first sentence. The reply says whether numpy is installed, which the mesh and +matrix arrays need and which the bundled Python lacks unless a file run's PEP 723 block installs it. ## Plugins and the tools @@ -2602,8 +2619,20 @@ offered again by a new load). The call's job is the caller's, so an operation al plugin unloads runs to its end; its own tool calls are refused from then on. **`api_describe` and `api_call`.** `api_describe` gives the schema of any registered tool or operation, -searches them by words (each match with its schema), or lists every name; for `cad_call` it points to -`describe_tools`, which lists the Design tab's methods. `api_call {tool, args}` is dispatched before it runs +or lists every name; for `cad_call` it points to `describe_tools`, which lists the Design tab's methods. +Its search by words is the one search across catalogs: the best five tools and operations that match (more +with `limit`), a tool with the first sentence of its description, since `tools/list` has its schema, and an +operation with its schema, which nothing else lists; and beside them the best five of each other catalog with +its total and how to use it: Speed Dial +actions, the settings being edited (`search_settings()`, as `get_settings` searches without a scope), the +Python reference and the Design tab's methods (noting when the Design tab is off). Every catalog is ranked +the same way (`query_words()`, `match_score()`): a query word matches where a word of the name or text +starts with it, CamelCase parts included, and entries matching more words, then more of them in the name, +come first. Scores of different catalogs don't compare, so each keeps its own list. Actions, settings +and the Design tab's methods are read on the UI thread: when it can't run the call (a native dialog holds +it, or it is busy) the search leaves those three out, and before the main window exists (the server starts +ahead of it) it leaves out the settings. The tools, operations and Python reference answer whatever the UI +thread is doing. `api_call {tool, args}` is dispatched before it runs (`resolve_api_call()`, in the protocol, in child calls and in the plugin caller): the target's arguments are normalized and validated, and the call runs as the target's own, with its guard, mode, budget and journal flag, so the journal records the target. diff --git a/src/slic3r/GUI/Mcp/McpService.cpp b/src/slic3r/GUI/Mcp/McpService.cpp index f782413e12..317764f80c 100644 --- a/src/slic3r/GUI/Mcp/McpService.cpp +++ b/src/slic3r/GUI/Mcp/McpService.cpp @@ -158,10 +158,11 @@ const char* kInstructions = "- export_script saves this session's calls as a replayable script; run_script replays one.\n" "- run_python runs Python against orca.host, the plugin API (python_api searches it), computing over meshes and " "settings and calling tools through orca.host.tools, once the person has allowed Python scripts in Preferences.\n" + "- Not sure what does something? api_describe {query} searches every catalog at once: the tools, the operations " + "plugins offer (plugin.., which the tool list does not show; api_call runs them), Speed Dial actions, " + "settings, the Python API and the Design tab's methods, each match with how to use it.\n" "API lane:\n" "- Typed tools: open_files, select_preset, set_settings, slice, export and the rest.\n" - "- Plugins may offer operations (plugin..) that the tool list does not show: api_describe lists and " - "searches them with their schemas, api_call runs them.\n" "- What a setting does, or which one controls an effect: get_settings with keys, or query with a few words; " "each setting's meta has its description and where (its settings page and group).\n" "- Objects, parts and plates are 0-based indices, as list_objects and list_plates give them; filament slots and " diff --git a/src/slic3r/GUI/Mcp/McpTools.hpp b/src/slic3r/GUI/Mcp/McpTools.hpp index 18ce19faa0..bcf9f3c81a 100644 --- a/src/slic3r/GUI/Mcp/McpTools.hpp +++ b/src/slic3r/GUI/Mcp/McpTools.hpp @@ -119,12 +119,49 @@ int arg_int(const nlohmann::json& args, const char* key, int fallback); double arg_double(const nlohmann::json& args, const char* key, double fallback); bool arg_bool(const nlohmann::json& args, const char* key, bool fallback); +// ---- search (McpToolsCommon.cpp) ------------------------------------------------------------- + +// The words of a search query: lower case, split at anything but a letter or a digit. "to" or "of" +// starts a word of most help texts, so words of fewer than three letters are left out when the query +// has longer ones. +std::vector query_words(const std::string& query); + +// How well an entry matches the words of query_words(): {words found in `name` or `text`, of them those +// found in `name`}, {0, 0} when none is. A word is found where a word of the text starts with it, so +// "retract" finds "retraction"; the text's words are split at underscores, dots and the like and also +// at a capital in a CamelCase name, so "mesh" finds TriangleMesh. +std::pair match_score(const std::vector& words, const std::string& name, const std::string& text); + +// The first sentence of `text` on one line, for a listing: up to the first full stop followed by a space +// or the end, "e.g." and "i.e." aside; the whole text when it has none. +std::string first_sentence(const std::string& text); + // A setting value from JSON in the serialized form set_deserialize accepts: "3", "0.2", "1"/"0" // for booleans, "a,b" for arrays. A list of strings (`key` names a coStrings option, such as // post_process) is quoted and separated by semicolons, as ConfigOptionStrings writes it, since its // entries may contain commas. Throws ToolFailure for values with no such form. std::string to_config_string(const nlohmann::json& value, const std::string& key = {}); +// ---- Python (McpToolsPython.cpp) ------------------------------------------------------------- + +// python_api's reference: every public module, class, function, method, property, named instance (such +// as orca.host.preset.process) and constant (such as orca.host.ui.PD_CAN_ABORT) of the orca package, in +// the order the package lists them, each {name, kind, signature, doc}. signature holds the signature lines +// pybind11 starts a docstring with (a class's are its constructors, joined with " | "), and doc the rest +// of the docstring: a class's own followed by what its constructors say, and for a constant, which has +// none, the entries whose doc names it. An enum's values are in its class's doc, not entries of their own. +// Takes the GIL; the caller keeps the interpreter running (a PythonRuntimeLease). Throws ToolFailure when +// the package can't be read. +nlohmann::json python_api_reference(); + +// The entries of python_api_reference() that `query` describes, best first: those matching more of its +// words (in the name, signature or doc), then those matching more of them in their name. +nlohmann::json rank_python_api(const nlohmann::json& reference, const std::string& query); + +// Whether numpy is installed in OrcaSlicer's Python, which the mesh and matrix arrays of orca.host need. +// Takes the GIL, as python_api_reference() does. +bool python_has_numpy(); + // ---- settings scopes (McpToolsConfig.cpp) ---------------------------------------------------- // The keys the object scope (or, with `is_part`, the volume scope) takes: those of `offered` @@ -160,6 +197,11 @@ nlohmann::json option_meta(const ConfigOptionDef& def); // the query has longer ones. std::vector rank_settings(const std::string& query, const std::vector& within, std::size_t limit); +// get_settings' search without a scope, for api_describe: the process, filament and printer settings being +// edited that `query` describes, best first, {total, items: [{key, scope, label, where}]} with at most +// `limit` items. UI thread. +nlohmann::json search_settings(const std::string& query, std::size_t limit); + // For a per-variant or per-extruder vector `key` of a preset's `config` that has more than one entry: // {"variants": [what each entry is for], "active": [the entry each extruder prints with, extruder 1 // first]}; a per-extruder key has no "active", since each extruder uses its own entry. `extruder_types` diff --git a/src/slic3r/GUI/Mcp/McpToolsApi.cpp b/src/slic3r/GUI/Mcp/McpToolsApi.cpp index 37530dc91e..2d0254cc50 100644 --- a/src/slic3r/GUI/Mcp/McpToolsApi.cpp +++ b/src/slic3r/GUI/Mcp/McpToolsApi.cpp @@ -1,22 +1,25 @@ // api_describe and api_call: a generic way to every registered tool and to the operations plugins offer -// (plugin..), which tools/list never shows. +// (plugin..), which tools/list never shows. api_describe's search also reaches the other +// catalogs an agent calls into: Speed Dial actions, settings, the Python API and the Design tab's methods. #include "McpService.hpp" #include "McpTools.hpp" #include "McpTypes.hpp" +#include "slic3r/GUI/ActionRegistry.hpp" +#include "slic3r/GUI/CAD/McpControl.hpp" +#include "slic3r/GUI/GUI_App.hpp" #include "slic3r/GUI/I18N.hpp" #include "slic3r/plugin/PluginManager.hpp" #include "slic3r/plugin/PluginOperations.hpp" +#include "slic3r/plugin/PythonInterpreter.hpp" #include #include -#include #include #include #include -#include #include #include #include @@ -27,10 +30,93 @@ using nlohmann::json; namespace { -std::string lower(std::string s) +// How many of each other catalog's matches api_describe shows beside the tools; its own search lists +// the rest. +constexpr std::size_t kCatalogHits = 5; + +using Scored = std::vector, json>>; + +// A catalog's best matches for api_describe: {total, items, use}, or null when nothing matched. +json catalog_hits(Scored scored, const std::string& use) { - std::transform(s.begin(), s.end(), s.begin(), [](unsigned char c) { return char(std::tolower(c)); }); - return s; + if (scored.empty()) + return nullptr; + std::stable_sort(scored.begin(), scored.end(), [](const auto& a, const auto& b) { return a.first > b.first; }); + json items = json::array(); + for (std::size_t i = 0; i < scored.size() && i < kCatalogHits; ++i) + items.push_back(std::move(scored[i].second)); + return {{"total", scored.size()}, {"items", std::move(items)}, {"use", use}}; +} + +// The Speed Dial actions, settings and Design tab methods matching `words` (of `query`), for +// api_describe. A catalog that can't be read yet (startup, before the main window) is left out. UI thread. +json ui_catalog_hits(const std::vector& words, const std::string& query) +{ + json out = json::object(); + if (ActionRegistry* actions = wxGetApp().m_action_registry.get()) { + ActionRegistry::Query all; + all.limit = 100000; + const json listed = actions->describe(all); + Scored scored; + for (const json& a : listed["actions"]) { + const std::pair score = match_score(words, a.value("id", "") + ' ' + a.value("title", ""), + a.value("group", "") + ' ' + a.value("description", "")); + if (score.first == 0) + continue; + json hit{{"id", a["id"]}, {"title", a["title"]}, {"description", a.value("description", "")}}; + if (a.contains("param")) + hit["param"] = a["param"]; + scored.emplace_back(score, std::move(hit)); + } + out["actions"] = catalog_hits(std::move(scored), "run_action {id, param}; list_actions {query} lists more"); + } + try { + json settings = search_settings(query, kCatalogHits); + if (settings["total"] != 0) { + settings["use"] = "get_settings {scope, keys} reads one with its description; set_settings {scope, values} changes it"; + out["settings"] = std::move(settings); + } + } catch (const ToolFailure&) { + } + const json methods = cad_describe_tools(json::object()); + Scored scored; + for (const json& row : methods["tools"]) { + const std::pair score = match_score(words, row.value("name", ""), row.value("summary", "")); + if (score.first > 0) + scored.emplace_back(score, json{{"name", row["name"]}, {"summary", row.value("summary", "")}}); + } + out["cad"] = catalog_hits(std::move(scored), + wxGetApp().is_enable_cad_feature() ? + "cad_call {method, params}; cad_call {method: \"describe_tools\", params: {method}} gives its params" : + "cad_call {method, params}, once the Design tab is on: a person enables it in Preferences and restarts " + "OrcaSlicer"); + return out; +} + +// The Python API entries matching `query`, for api_describe, or null when Python is not running or none +// matches. +json python_hits(const std::string& query) +{ + if (!PythonInterpreter::instance().is_initialized()) + return nullptr; + PythonRuntimeLease lease = PythonInterpreter::instance().acquire_runtime_lease(); + if (!lease) + return nullptr; + json ranked; + try { + ranked = rank_python_api(python_api_reference(), query); + } catch (const ToolFailure&) { + return nullptr; // python_api reports why + } + if (ranked.empty()) + return nullptr; + json items = json::array(); + for (std::size_t i = 0; i < ranked.size() && i < kCatalogHits; ++i) + items.push_back({{"name", ranked[i]["name"]}, {"kind", ranked[i]["kind"]}, {"signature", ranked[i]["signature"]}, + {"summary", first_sentence(ranked[i]["doc"].get())}}); + return {{"total", ranked.size()}, + {"items", std::move(items)}, + {"use", "run_python {code}; python_api {query} gives each entry's whole documentation"}}; } json describe_tool(const ToolDef& def) @@ -90,14 +176,18 @@ void register_api_tools(McpService& service) }); reg.add(inspect_tool( - "api_describe", L("Describe tools and plugin operations"), - "Look up any registered tool, and the operations plugins offer (plugin.., not in the tool list): " - "with tool, its description and input schema; with query, the best matches by name and description, each with " - "its schema; with neither, every name. Call them with api_call.", + "api_describe", L("Find tools, actions, settings and APIs"), + "Find what does something, in one search, or look up one tool. With query: the tools and the operations plugins " + "offer (plugin.., not in the tool list) that match, best first, a tool with its first sentence (its " + "schema is in the tool list, or here with tool) and an operation with its schema; and beside " + "them the best few matches of each other catalog, with its total and how to use it: actions (Speed Dial commands " + "for run_action), settings (get_settings / set_settings), python (the orca API for run_python) and cad (Design tab " + "methods for cad_call). With tool: that tool's or operation's description and input schema. With neither: every " + "tool and operation name. Call tools and operations with api_call.", object_schema({{"tool", prop("string", "A tool or operation name: its schema.")}, - {"query", prop("string", "A few words to search names and descriptions.")}, - {"limit", {{"type", "integer"}, {"minimum", 1}, {"maximum", 200}, {"description", "At most this many (default 20)."}}}}), - [&service](const json& args, ToolContext&) { + {"query", prop("string", "A few words saying what you want to do or find, e.g. \"brim\" or \"mesh normals\".")}, + {"limit", {{"type", "integer"}, {"minimum", 1}, {"maximum", 200}, {"description", "At most this many tools (default 5)."}}}}), + [&service](const json& args, ToolContext& ctx) { std::vector> all; for (const ToolDef& def : service.registry().tools()) all.emplace_back(std::shared_ptr(), &def); @@ -111,32 +201,43 @@ void register_api_tools(McpService& service) return ToolResult::ok(describe_tool(*def)); throw ToolFailure("Unknown tool: " + name, {{"did_you_mean", service.registry().similar(name)}}); } - const std::size_t limit = std::size_t(arg_int(args, "limit", 20)); - std::vector words; - { - std::istringstream in(lower(arg_string(args, "query"))); - for (std::string w; in >> w;) - words.push_back(w); - } - json items = json::array(); - if (words.empty()) { + const std::size_t limit = std::size_t(arg_int(args, "limit", int(kCatalogHits))); + const std::string query = arg_string(args, "query"); + const std::vector words = query_words(query); + json items = json::array(); + if (query.empty()) { for (const auto& def : all) items.push_back(def->name); return ToolResult::ok({{"total", items.size()}, {"names", std::move(items)}}); } - std::vector>> scored; + std::vector, std::shared_ptr>> scored; for (const auto& def : all) { - const std::string name = lower(def->name), text = lower(def->description); - int score = 0; - for (const std::string& w : words) - score += (name.find(w) != std::string::npos ? 3 : 0) + (text.find(w) != std::string::npos ? 1 : 0); - if (score > 0) + const std::pair score = match_score(words, def->name, def->description); + if (score.first > 0) scored.emplace_back(score, def); } std::stable_sort(scored.begin(), scored.end(), [](const auto& a, const auto& b) { return a.first > b.first; }); - for (std::size_t i = 0; i < scored.size() && i < limit; ++i) - items.push_back(describe_tool(*scored[i].second)); - return ToolResult::ok({{"total", scored.size()}, {"items", std::move(items)}}); + // A registered tool's schema is in tools/list already, so a match names it with its first sentence; an + // operation's is nowhere else, so it comes with the match. + for (std::size_t i = 0; i < scored.size() && i < limit; ++i) { + const ToolDef& def = *scored[i].second; + if (def.name.rfind("plugin.", 0) == 0) + items.push_back(describe_tool(def)); + else + items.push_back({{"name", def.name}, {"lane", lane_name(def.lane)}, {"summary", first_sentence(def.description)}}); + } + json out{{"total", scored.size()}, {"items", std::move(items)}}; + // The tools and operations answer without the UI thread: one held by a dialog or still starting + // leaves its catalogs out rather than failing the search. + try { + out.update(ctx.run_ui([&] { return ui_catalog_hits(words, query); })); + } catch (const ToolFailure&) { + } + out["python"] = python_hits(query); + for (const char* catalog : {"actions", "settings", "python", "cad"}) + if (out.contains(catalog) && out[catalog].is_null()) + out.erase(catalog); + return ToolResult::ok(std::move(out)); })); // Dispatched before it runs (resolve_api_call): the call runs as the target's own, with its guard, diff --git a/src/slic3r/GUI/Mcp/McpToolsCommon.cpp b/src/slic3r/GUI/Mcp/McpToolsCommon.cpp index 95915735bf..07a954e7f5 100644 --- a/src/slic3r/GUI/Mcp/McpToolsCommon.cpp +++ b/src/slic3r/GUI/Mcp/McpToolsCommon.cpp @@ -14,11 +14,13 @@ #include #include +#include #include #include #include #include #include +#include #include #include #include @@ -83,6 +85,49 @@ ToolDef mutate_tool(std::string name, std::string title, std::string description namespace { +// The words of `text` in lower case, split at anything but a letter or a digit. With `camel`, a word +// with a capital after a lower-case letter also counts as its parts: TriangleMesh as triangle and mesh. +std::vector text_words(const std::string& text, bool camel) +{ + std::vector words; + std::string word; + std::vector parts; // where each CamelCase part after the first starts in `word` + const auto flush = [&] { + if (word.empty()) + return; + std::size_t from = 0; + for (const std::size_t at : parts) { + words.push_back(word.substr(from, at - from)); + from = at; + } + if (!parts.empty()) + words.push_back(word.substr(from)); + words.push_back(std::exchange(word, {})); + parts.clear(); + }; + unsigned char previous = 0; + for (const char c : text) { + const auto u = static_cast(c); + if (!std::isalnum(u)) { + flush(); + previous = 0; + continue; + } + if (camel && std::isupper(u) && std::islower(previous)) + parts.push_back(word.size()); + word += char(std::tolower(u)); + previous = u; + } + flush(); + return words; +} + +// Whether a word of `words` starts with `w`. +bool has_word(const std::vector& words, const std::string& w) +{ + return std::any_of(words.begin(), words.end(), [&w](const std::string& word) { return word.compare(0, w.size(), w) == 0; }); +} + // Whether a 3D view is shown but can't draw yet. On Wayland a canvas gets its GL surface from the // map event GTK handles once the main loop runs again, after the closures queued with the change // that showed it, such as a tab switch. wxGLCanvas's IsShownOnScreen() needs that surface; the @@ -216,6 +261,40 @@ json page(const json& items, const json& args, std::size_t default_limit) return result; } +std::vector query_words(const std::string& query) +{ + std::vector words = text_words(query, false); + std::vector longer; + std::copy_if(words.begin(), words.end(), std::back_inserter(longer), [](const std::string& w) { return w.size() >= 3; }); + return longer.empty() ? words : longer; +} + +std::pair match_score(const std::vector& words, const std::string& name, const std::string& text) +{ + const std::vector in_name = text_words(name, true); + const std::vector in_text = text_words(text, true); + std::pair score; + for (const std::string& w : words) + if (has_word(in_name, w)) { + ++score.first; + ++score.second; + } else if (has_word(in_text, w)) + ++score.first; + return score; +} + +std::string first_sentence(const std::string& text) +{ + std::string line = text; + std::replace(line.begin(), line.end(), '\n', ' '); + for (std::size_t dot = line.find('.'); dot != std::string::npos; dot = line.find('.', dot + 1)) { + const bool abbreviation = dot >= 3 && (line.compare(dot - 3, 3, "e.g") == 0 || line.compare(dot - 3, 3, "i.e") == 0); + if (!abbreviation && (dot + 1 == line.size() || line[dot + 1] == ' ')) + return line.substr(0, dot + 1); + } + return line; +} + json poll_ui(ToolContext& ctx, const std::function& poll, std::chrono::milliseconds timeout, const std::string& what) { json v = poll_until(ctx, poll, timeout, std::chrono::milliseconds(200)); diff --git a/src/slic3r/GUI/Mcp/McpToolsConfig.cpp b/src/slic3r/GUI/Mcp/McpToolsConfig.cpp index 659c90f626..30ec732941 100644 --- a/src/slic3r/GUI/Mcp/McpToolsConfig.cpp +++ b/src/slic3r/GUI/Mcp/McpToolsConfig.cpp @@ -1033,26 +1033,7 @@ json option_meta(const ConfigOptionDef& def) std::vector rank_settings(const std::string& query, const std::vector& within, std::size_t limit) { - const auto words_of = [](const std::string& text) { - std::vector words; - std::string word; - for (const char c : lower(text) + ' ') { - if (std::isalnum(static_cast(c))) - word += c; - else if (!word.empty()) - words.push_back(std::exchange(word, {})); - } - return words; - }; - const auto has = [](const std::vector& words, const std::string& w) { - return std::any_of(words.begin(), words.end(), [&w](const std::string& word) { return word.compare(0, w.size(), w) == 0; }); - }; - // "to" or "of" starts a word of most help texts, so short words count only when the query has no longer one. - std::vector words = words_of(query); - std::vector longer; - std::copy_if(words.begin(), words.end(), std::back_inserter(longer), [](const std::string& w) { return w.size() >= 3; }); - if (!longer.empty()) - words = std::move(longer); + const std::vector words = query_words(query); // (query words matched, those matched in the key or label) per key. std::vector, std::string>> scored; std::set seen; // a scope's options can list a key twice @@ -1060,15 +1041,7 @@ std::vector rank_settings(const std::string& query, const std::vect const ConfigOptionDef* def = print_config_def.get(key); if (def == nullptr || !seen.insert(key).second) continue; - const std::vector name = words_of(key + ' ' + def->label + ' ' + def->full_label); - const std::vector tooltip = words_of(def->tooltip); - std::pair score; - for (const std::string& w : words) - if (has(name, w)) { - ++score.first; - ++score.second; - } else if (has(tooltip, w)) - ++score.first; + const std::pair score = match_score(words, key + ' ' + def->label + ' ' + def->full_label, def->tooltip); if (score.first > 0) scored.emplace_back(score, key); } @@ -1610,22 +1583,31 @@ std::string to_config_string(const json& v, const std::string& key) namespace { +// The scopes a search without one looks through: the process, filament and printer settings being edited, +// since a question about an effect rarely knows which tab answers it. +const char* const kSearchScopes[]{"process", "filament", "printer"}; + +// The keys of kSearchScopes, each once, with the scope that offers it first. UI thread. +std::vector search_scope_options(std::map& scope_of) +{ + std::vector options; + for (const char* scope : kSearchScopes) + for (const std::string& key : resolve_target(json{{"scope", scope}}, false).options) + if (scope_of.emplace(key, scope).second) + options.push_back(key); + return options; +} + // get_settings: the settings `args` asks for, read on the UI thread. json read_settings(const json& args) { - // A search with no scope looks through the process, filament and printer settings being edited, since a - // question about an effect rarely knows which tab answers it; each match names its scope. + // A search with no scope looks through kSearchScopes; each match names its scope. if (args.contains("query") && !args.contains("scope") && !args.contains("preset") && !args.contains("compare")) { - const char* const scopes[]{"process", "filament", "printer"}; - std::vector options; std::map scope_of; - for (const char* scope : scopes) - for (const std::string& key : resolve_target(json{{"scope", scope}}, false).options) - if (scope_of.emplace(key, scope).second) - options.push_back(key); - const std::vector ranked = rank_settings(arg_string(args, "query"), options, 200); - std::map found; - for (const char* scope : scopes) { + const std::vector options = search_scope_options(scope_of); + const std::vector ranked = rank_settings(arg_string(args, "query"), options, 200); + std::map found; + for (const char* scope : kSearchScopes) { json keys = json::array(); for (const std::string& key : ranked) if (scope_of[key] == scope) @@ -1760,6 +1742,31 @@ json read_settings(const json& args) } // namespace +json search_settings(const std::string& query, std::size_t limit) +{ + ui_plater(); // the presets and the settings pages exist once the main window does + std::map scope_of; + const std::vector options = search_scope_options(scope_of); + const std::vector ranked = rank_settings(query, options, options.size()); + const std::map types{{"process", Preset::TYPE_PRINT}, {"filament", Preset::TYPE_FILAMENT}, + {"printer", Preset::TYPE_PRINTER}}; + std::map> places; + json items = json::array(); + for (std::size_t i = 0; i < ranked.size() && i < limit; ++i) { + const std::string& key = ranked[i]; + const std::string& scope = scope_of[key]; + const ConfigOptionDef* def = print_config_def.get(key); + auto place = places.find(scope); + if (place == places.end()) + place = places.emplace(scope, setting_places(types.at(scope))).first; + json item{{"key", key}, {"scope", scope}, {"label", def->full_label.empty() ? def->label : def->full_label}}; + if (const auto where = place->second.find(key); where != place->second.end()) + item["where"] = where->second; + items.push_back(std::move(item)); + } + return {{"total", ranked.size()}, {"items", std::move(items)}}; +} + void register_config_tools(McpService& service) { ToolRegistry& reg = service.registry(); @@ -2030,6 +2037,7 @@ void register_config_tools(McpService& service) {"offset", {{"type", "integer"}, {"minimum", 0}}}}), [](const json& args, ToolContext& ctx) { return ToolResult::ok(ctx.run_ui([&] { + ui_plater(); // the presets and the settings pages exist once the main window does return read_settings(args); })); })); diff --git a/src/slic3r/GUI/Mcp/McpToolsPython.cpp b/src/slic3r/GUI/Mcp/McpToolsPython.cpp index 9b41abb1f5..ad131139f0 100644 --- a/src/slic3r/GUI/Mcp/McpToolsPython.cpp +++ b/src/slic3r/GUI/Mcp/McpToolsPython.cpp @@ -1,4 +1,5 @@ -// run_python and python_api: Python scripts against orca.host, the plugin API, and its reference. +// run_python and python_api: Python scripts against orca.host, the plugin API, and the orca package's +// reference. #include "McpService.hpp" #include "McpTools.hpp" @@ -17,9 +18,12 @@ #include #include +#include #include +#include #include #include +#include namespace Slic3r { namespace GUI { namespace Mcp { @@ -46,30 +50,60 @@ private: ToolContext& m_ctx; }; -// The reference python_api searches: every function, class and method under orca.host with its -// signature and documentation, from the running build's bindings. +// python_api_reference()'s walk over the orca package. constexpr const char* kReferenceSource = R"PY( -import inspect, types +import inspect, re, types -def _first_line(doc): - return doc.strip().splitlines()[0] if doc and doc.strip() else "" +# A signature line pybind11 starts a docstring with: "name(...) -> T", numbered after "Overloaded function.", +# and without a name for a property's getter. +_SIGNATURE = re.compile(r"^(?:\d+\. )?(\w*)\(.*\)(?: -> .+)?$") +_SELF = re.compile(r"\bself: [\w.]+") +# The types of a module's constants, such as orca.host.ui.PD_CAN_ABORT. +_CONSTANTS = (bool, int, float, str) + +def _split(names, doc): + """The signature lines of a docstring whose function is called one of names, and the rest of it.""" + signatures, text = [], [] + for line in (doc or "").splitlines(): + stripped = line.strip() + match = _SIGNATURE.match(stripped) + if match and match.group(1) in names: + signatures.append(_SELF.sub("self", re.sub(r"^\d+\. ", "", stripped))) + elif stripped != "Overloaded function.": + text.append(line) + # An overloaded function's first line, name(*args, **kwargs), stands for the numbered overloads after it. + if len(signatures) > 1: + signatures = [s for s in signatures if not s.endswith("(*args, **kwargs)")] + return signatures, "\n".join(text).strip() def _entry(name, obj, kind): - doc = inspect.getdoc(obj) or "" - try: - signature = name.rsplit(".", 1)[-1] + str(inspect.signature(obj)) - except (TypeError, ValueError): - # pybind11 functions start their docstring with the signature. - signature = _first_line(doc) - if signature and "(" in signature: - doc = doc[len(signature):].strip() - else: - signature = name.rsplit(".", 1)[-1] - return {"name": name, "kind": kind, "signature": signature, "doc": doc} + short = name.rsplit(".", 1)[-1] + if kind == "class": + # A class's own docstring, not one inherited from a base, then what its constructors say of their + # arguments; the constructors' signatures are the class's. + init = vars(obj).get("__init__") + signatures, made = _split(("__init__",), init.__doc__ if init is not None else None) + signatures = [short + s[len("__init__"):].replace("(self, ", "(").replace("(self)", "()").replace(" -> None", "") + for s in signatures] + doc = inspect.cleandoc(obj.__doc__ or "") + if made and made != doc: + doc = (doc + "\n\n" + made).strip() + return {"name": name, "kind": kind, "signature": " | ".join(signatures) or short, "doc": doc} + if kind == "property": + getter = obj.fget.__doc__ if obj.fget is not None else "" + returns = re.match(r"^\w*\(.*\) -> (.+)$", (getter or "").strip().split("\n")[0]) + _, doc = _split((short, ""), inspect.getdoc(obj)) + return {"name": name, "kind": kind, "signature": short + (": " + returns.group(1) if returns else ""), "doc": doc} + signatures, doc = _split((short, ""), inspect.getdoc(obj)) + if not signatures: + try: + signatures = [short + str(inspect.signature(obj))] + except (TypeError, ValueError): + signatures = [short] + return {"name": name, "kind": kind, "signature": " | ".join(signatures), "doc": doc} -def reference(host): - out = [] - seen = set() +def reference(package): + out, seen, constants = [], set(), [] def walk(module, prefix): if id(module) in seen: return @@ -78,42 +112,90 @@ def reference(host): for name, value in sorted(vars(module).items()): if name.startswith("_"): continue + full = prefix + name if isinstance(value, types.ModuleType): - if value.__name__.startswith(host.__name__): - walk(value, prefix + name + ".") + if value.__name__.startswith(package.__name__): + walk(value, full + ".") elif inspect.isclass(value): - out.append(_entry(prefix + name, value, "class")) + out.append(_entry(full, value, "class")) + # An enum lists its values in its docstring; name and value are every enum's. + values = getattr(value, "__members__", None) for member, attr in sorted(vars(value).items()): - if member.startswith("_"): + if member.startswith("_") or (values is not None and (member in values or member in ("name", "value"))): continue kind = "property" if isinstance(attr, property) else "method" if callable(attr) else None if kind: - out.append(_entry(prefix + name + "." + member, attr, kind)) + out.append(_entry(full + "." + member, attr, kind)) elif callable(value): - out.append(_entry(prefix + name, value, "function")) - walk(host, "orca.host.") + out.append(_entry(full, value, "function")) + elif isinstance(value, _CONSTANTS): + constants.append(len(out)) + out.append({"name": full, "kind": "constant", "signature": name + " = " + repr(value), "doc": ""}) + elif type(value).__module__.startswith(package.__name__) and not hasattr(type(value), "__members__"): + # An instance the package offers by name, such as orca.host.preset.process; enum values + # exported into a module are their enum's. + kind_of = type(value) + out.append({"name": full, "kind": "attribute", "signature": name + ": " + kind_of.__module__ + "." + kind_of.__name__, + "doc": inspect.cleandoc(kind_of.__doc__ or "")}) + walk(package, package.__name__ + ".") + # A constant has no docstring of its own: the documentation of what takes it says what it means. + for i in constants: + word = re.compile(r"\b" + re.escape(out[i]["name"].rsplit(".", 1)[-1]) + r"\b") + users = [e["name"] for e in out if e["kind"] != "constant" and word.search(e["doc"])] + if users: + out[i]["doc"] = "See " + ", ".join(users) + "." return out - -def search(host, query, limit): - entries = reference(host) - words = [w for w in query.lower().replace(".", " ").replace("_", " ").split() if w] - if not words: - return len(entries), [{"name": e["name"], "kind": e["kind"], "signature": e["signature"]} for e in entries[:limit]] - scored = [] - for e in entries: - name = e["name"].lower().replace("_", " ").replace(".", " ") - doc = e["doc"].lower() - hits = sum(1 for w in words if w in name or w in doc) - if hits == 0: - continue - in_name = sum(1 for w in words if w in name) - scored.append((-hits, -in_name, e["name"], e)) - scored.sort(key=lambda t: t[:3]) - return len(scored), [t[3] for t in scored[:limit]] )PY"; } // namespace +json python_api_reference() +{ + py::gil_scoped_acquire gil; + try { + py::dict scope; + py::exec(kReferenceSource, scope); + json entries = json::array(); + for (const auto item : scope["reference"](py::module_::import("orca")).cast()) { + json entry = json::object(); + for (const auto field : item.cast()) + entry[field.first.cast()] = field.second.cast(); + entries.push_back(std::move(entry)); + } + return entries; + } catch (py::error_already_set& e) { + throw ToolFailure(std::string("Cannot read the Python API: ") + e.what()); + } +} + +json rank_python_api(const json& reference, const std::string& query) +{ + const std::vector words = query_words(query); + std::vector, std::size_t>> scored; + for (std::size_t i = 0; i < reference.size(); ++i) { + const json& e = reference[i]; + const std::pair score = match_score(words, e["name"].get(), + e["signature"].get() + '\n' + e["doc"].get()); + if (score.first > 0) + scored.emplace_back(score, i); + } + std::stable_sort(scored.begin(), scored.end(), [](const auto& a, const auto& b) { return a.first > b.first; }); + json out = json::array(); + for (const auto& [score, i] : scored) + out.push_back(reference[i]); + return out; +} + +bool python_has_numpy() +{ + py::gil_scoped_acquire gil; + try { + return !py::module_::import("importlib.util").attr("find_spec")("numpy").is_none(); + } catch (py::error_already_set&) { + return false; + } +} + void register_python_tools(McpService& service) { ToolRegistry& reg = service.registry(); @@ -121,9 +203,11 @@ void register_python_tools(McpService& service) ToolDef run = mutate_tool( "run_python", L("Run Python code"), "Run Python code inside OrcaSlicer as its main program (__name__ == \"__main__\") against orca.host, the whole plugin " - "API (python_api searches it): read objects, meshes (numpy) and settings, compute, use orca.host.ui and the preset " + "API (python_api searches it): read objects, meshes and settings, compute, use orca.host.ui and the preset " "API, and call these same tools, with their guards and undo, through orca.host.tools.call(name, args), from the code " - "and from the threads and pool tasks it starts while the run lasts. The run ends once its code and the non-daemon " + "and from the threads and pool tasks it starts while the run lasts. Mesh and matrix arrays need numpy, which " + "python_api says is installed or not; a file run's PEP 723 block can install it. The code runs on a worker " + "thread, where calls documented as UI thread only raise RuntimeError. The run ends once its code and the non-daemon " "threads and pool tasks it started are done; its windows close with it. `args` holds the args you pass; set `result` " "to a JSON value to return it; print() output comes back as output. Returns {status: finished | raised | cancelled | " "timed_out, result, output, traceback?, message?}; a script that raised changed what it changed before. Python runs " @@ -196,33 +280,33 @@ void register_python_tools(McpService& service) reg.add(inspect_tool( "python_api", L("Search the Python API"), - "Search orca.host, the plugin API run_python scripts use, in the running build: modules, classes, functions, methods " - "and properties with their signatures and documentation, best match first. Without query, lists the names.", + "Search orca, the Python API of run_python scripts and plugins, in the running build: orca.host (the project's " + "model and meshes, presets and their editors, slicing data, orca.host.ui windows and dialogs, orca.host.tools " + "calling these tools) and the classes, events and pages plugins build on. Each entry has its kind, signature (a " + "class's constructors) and documentation. A query ranks them, best match first; without one, the whole package is " + "listed with each entry's first sentence. Page with offset. numpy says whether numpy is installed, which mesh and " + "matrix arrays need.", object_schema({{"query", prop("string", "A few words, such as \"mesh normals\" or \"preset value\".")}, - {"limit", {{"type", "integer"}, {"minimum", 1}, {"maximum", 200}, {"description", "At most this many (default 20)."}}}}), + {"limit", {{"type", "integer"}, {"minimum", 1}, {"maximum", 200}, {"description", "At most this many (default 20)."}}}, + {"offset", {{"type", "integer"}, {"minimum", 0}}}}), [](const json& args, ToolContext&) { if (!PythonInterpreter::instance().is_initialized()) throw ToolFailure("Python is not available in this OrcaSlicer"); PythonRuntimeLease lease = PythonInterpreter::instance().acquire_runtime_lease(); if (!lease) throw ToolFailure("Python is shutting down"); - py::gil_scoped_acquire gil; - try { - py::dict scope; - py::exec(kReferenceSource, scope); - py::object host = py::module_::import("orca").attr("host"); - py::tuple found = scope["search"](host, arg_string(args, "query"), arg_int(args, "limit", 20)); - json items = json::array(); - for (const auto item : found[1].cast()) { - json entry = json::object(); - for (const auto field : item.cast()) - entry[field.first.cast()] = field.second.cast(); - items.push_back(std::move(entry)); - } - return ToolResult::ok({{"total", found[0].cast()}, {"items", std::move(items)}}); - } catch (py::error_already_set& e) { - throw ToolFailure(std::string("Cannot read the Python API: ") + e.what()); - } + const json reference = python_api_reference(); + const std::string query = arg_string(args, "query"); + json items = json::array(); + if (query.empty()) { + for (const json& e : reference) + items.push_back({{"name", e["name"]}, {"kind", e["kind"]}, {"signature", e["signature"]}, + {"summary", first_sentence(e["doc"].get())}}); + } else + items = rank_python_api(reference, query); + json out = page(items, args, 20); + out["numpy"] = python_has_numpy(); + return ToolResult::ok(std::move(out)); })); } diff --git a/src/slic3r/plugin/PythonPluginBridge.cpp b/src/slic3r/plugin/PythonPluginBridge.cpp index cd23bc9335..3c63f30846 100644 --- a/src/slic3r/plugin/PythonPluginBridge.cpp +++ b/src/slic3r/plugin/PythonPluginBridge.cpp @@ -432,95 +432,197 @@ void bind_python_api(pybind11::module_& m) .value("Unknown", PluginCapabilityType::Unknown) .export_values(); - py::enum_(m, "PluginResult", "Execution summary code") + py::enum_(m, "PluginResult", + "Status of an ExecutionResult. What the host does with each value depends on the\n" + "method that returns it; see the execute() method of each capability base.") .value("Success", PluginResult::Success) .value("Skipped", PluginResult::Skipped) .value("RecoverableError", PluginResult::RecoverableError) .value("FatalError", PluginResult::FatalError) .export_values(); - py::enum_(m, "LifecycleEvent", "Application lifecycle moment passed to on_lifecycle_event") - .value("NewProject", LifecycleEvent::NewProject) - .value("ProjectOpened", LifecycleEvent::ProjectOpened) - .value("ProjectBeforeSave", LifecycleEvent::ProjectBeforeSave) - .value("ProjectAfterSave", LifecycleEvent::ProjectAfterSave) - .value("ProjectClosed", LifecycleEvent::ProjectClosed) - .value("ProjectDirtyChanged", LifecycleEvent::ProjectDirtyChanged) - .value("SliceStarted", LifecycleEvent::SliceStarted) - .value("SliceGeometryFinished", LifecycleEvent::SliceGeometryFinished) - .value("GCodeExportStarted", LifecycleEvent::GCodeExportStarted) - .value("GCodeExportFinished", LifecycleEvent::GCodeExportFinished) - .value("SlicingJobComplete", LifecycleEvent::SlicingJobComplete) - .value("ObjectAdded", LifecycleEvent::ObjectAdded) - .value("ObjectDeleted", LifecycleEvent::ObjectDeleted) - .value("ObjectTransformed", LifecycleEvent::ObjectTransformed) - .value("ObjectChanged", LifecycleEvent::ObjectChanged) - .value("ObjectRenamed", LifecycleEvent::ObjectRenamed) - .value("PlateCreated", LifecycleEvent::PlateCreated) - .value("PlateDeleted", LifecycleEvent::PlateDeleted) - .value("PlateSelected", LifecycleEvent::PlateSelected) - .value("PlateRenamed", LifecycleEvent::PlateRenamed) - .value("PresetSelected", LifecycleEvent::PresetSelected) - .value("PresetSaved", LifecycleEvent::PresetSaved) - .value("PrintStateChanged", LifecycleEvent::PrintStateChanged) - .value("DeviceOnline", LifecycleEvent::DeviceOnline) - .value("DeviceOffline", LifecycleEvent::DeviceOffline) - .value("DeviceDiscovered", LifecycleEvent::DeviceDiscovered) - .value("DeviceSelected", LifecycleEvent::DeviceSelected) - .value("UploadStarted", LifecycleEvent::UploadStarted) - .value("UploadFinished", LifecycleEvent::UploadFinished) - .value("PrintJobStarted", LifecycleEvent::PrintJobStarted) - .value("PrintJobFinished", LifecycleEvent::PrintJobFinished) - .value("SendJobStarted", LifecycleEvent::SendJobStarted) - .value("SendJobFinished", LifecycleEvent::SendJobFinished) + py::enum_(m, "LifecycleEvent", + "Application lifecycle moment passed to on_lifecycle_event(). The LifecycleEventContext\n" + "fields describe which events fill them.") + .value("NewProject", LifecycleEvent::NewProject, + "A new project is being started. It fires before the current project is reset, so a\n" + "ProjectClosed event for that project, when it had a file or objects, follows it.") + .value("ProjectOpened", LifecycleEvent::ProjectOpened, "A project was opened; name is its file path.") + .value("ProjectBeforeSave", LifecycleEvent::ProjectBeforeSave, + "The project is about to be saved; name is the target file path.") + .value("ProjectAfterSave", LifecycleEvent::ProjectAfterSave, "The project was saved; name is its file path.") + .value("ProjectClosed", LifecycleEvent::ProjectClosed, + "The current project, when it had a file or objects, was closed or reset; name is its file path\n" + "without the extension, or empty if it was never saved.") + .value("ProjectDirtyChanged", LifecycleEvent::ProjectDirtyChanged, + "The project gained or lost unsaved changes; see dirty and source.") + .value("SliceStarted", LifecycleEvent::SliceStarted, + "Slicing started, on the slicing thread; id and name identify the model.") + .value("SliceGeometryFinished", LifecycleEvent::SliceGeometryFinished, + "The slicing steps finished, before G-code export, on the slicing thread; id and name identify the\n" + "model.") + .value("GCodeExportStarted", LifecycleEvent::GCodeExportStarted, + "G-code export started, on the slicing thread; msg is the output path.") + .value("GCodeExportFinished", LifecycleEvent::GCodeExportFinished, + "G-code export ended; code is Ok or Error, and msg is the output path, followed by the error on\n" + "failure.") + .value("SlicingJobComplete", LifecycleEvent::SlicingJobComplete, + "The background slicing job ended, on the UI thread; code is Ok, Warn when cancelled, or Error with\n" + "the error in msg.") + .value("ObjectAdded", LifecycleEvent::ObjectAdded, "An object was added; name is its name.") + .value("ObjectDeleted", LifecycleEvent::ObjectDeleted, "An object was deleted; name is its name.") + .value("ObjectTransformed", LifecycleEvent::ObjectTransformed, + "Objects were moved, rotated, scaled, arranged or auto-oriented; msg says which, and name is the\n" + "object's name when exactly one object was moved, rotated or scaled.") + .value("ObjectChanged", LifecycleEvent::ObjectChanged, + "An object's geometry changed; name, id and, when known, index identify it.") + .value("ObjectRenamed", LifecycleEvent::ObjectRenamed, + "An object or one of its parts was renamed; name, previous_name, id, index and source (\"object\" or\n" + "\"volume\") describe it.") + .value("PlateCreated", LifecycleEvent::PlateCreated, "A plate was added; name and index identify it.") + .value("PlateDeleted", LifecycleEvent::PlateDeleted, "A plate was deleted; name and index identify it.") + .value("PlateSelected", LifecycleEvent::PlateSelected, + "Another plate became the current plate; name and index identify it.") + .value("PlateRenamed", LifecycleEvent::PlateRenamed, + "A plate was renamed; name, previous_name and index describe it.") + .value("PresetSelected", LifecycleEvent::PresetSelected, + "A preset was selected; name is the preset name and msg its type: \"print\", \"filament\",\n" + "\"printer\", \"sla_print\" or \"sla_material\".") + .value("PresetSaved", LifecycleEvent::PresetSaved, + "A preset was saved; name is the preset name and msg is \"new\" or \"overwrite\".") + .value("PrintStateChanged", LifecycleEvent::PrintStateChanged, + "A printer's print status changed; name is the device id and msg the new status.") + .value("DeviceOnline", LifecycleEvent::DeviceOnline, "A printer came online; name is its device id.") + .value("DeviceOffline", LifecycleEvent::DeviceOffline, "A printer went offline; name is its device id.") + .value("DeviceDiscovered", LifecycleEvent::DeviceDiscovered, + "A printer not known before was discovered on the network; name is its device id.") + .value("DeviceSelected", LifecycleEvent::DeviceSelected, + "The user selected a printer; name is its device id, or empty when the selection was cleared.") + .value("UploadStarted", LifecycleEvent::UploadStarted, + "An upload to a print host such as OctoPrint started; name is the uploaded file's name.") + .value("UploadFinished", LifecycleEvent::UploadFinished, + "A print host upload ended; code is Ok or Error, with the error in msg.") + .value("PrintJobStarted", LifecycleEvent::PrintJobStarted, + "Sending a print job to a printer started; name is the project name, device_id the printer and\n" + "source the sender.") + .value("PrintJobFinished", LifecycleEvent::PrintJobFinished, + "Sending a print job ended; code is Ok, Warn when cancelled, or Error, and msg is \"\", \"cancelled\",\n" + "\"failed\" or \"exception\".") + .value("SendJobStarted", LifecycleEvent::SendJobStarted, + "Sending a file to a printer's storage started; name is the project name and device_id the printer.") + .value("SendJobFinished", LifecycleEvent::SendJobFinished, + "Sending a file to a printer's storage ended; code and msg as for PrintJobFinished.") .export_values(); py::enum_(m, "LifecycleEvtCode", "Outcome code accompanying a LifecycleEventContext") - .value("Ok", LifecycleEvtCode::Ok) - .value("Error", LifecycleEvtCode::Error) - .value("Warn", LifecycleEvtCode::Warn) + .value("Ok", LifecycleEvtCode::Ok, "The event happened, or the operation it reports succeeded.") + .value("Error", LifecycleEvtCode::Error, "The operation failed; msg holds the detail.") + .value("Warn", LifecycleEvtCode::Warn, "The operation was cancelled.") .export_values(); - py::class_(m, "LifecycleEventContext", "Payload accompanying a LifecycleEvent") + py::class_(m, "LifecycleEventContext", + "Payload accompanying a LifecycleEvent. Each field says which events fill it; a\n" + "field the event does not use is empty, -1 or False.") .def(py::init<>()) - .def_readonly("name", &LifecycleEventContext::name) - .def_readonly("code", &LifecycleEventContext::code) - .def_readonly("msg", &LifecycleEventContext::msg) - .def_readonly("id", &LifecycleEventContext::id) - .def_readonly("previous_name", &LifecycleEventContext::previous_name) - .def_readonly("device_id", &LifecycleEventContext::device_id) - .def_readonly("job_id", &LifecycleEventContext::job_id) - .def_readonly("source", &LifecycleEventContext::source) - .def_readonly("index", &LifecycleEventContext::index) - .def_readonly("dirty", &LifecycleEventContext::dirty); + .def_readonly("name", &LifecycleEventContext::name, + "The event's subject: a file path for Project* events (see ProjectClosed), the model name for\n" + "SliceStarted, SliceGeometryFinished, GCodeExport* and SlicingJobComplete, the object, plate or\n" + "preset name for Object*, Plate* and Preset* events, the device id for PrintStateChanged and\n" + "Device* events, the uploaded file name for Upload* events, and the project name for PrintJob*\n" + "and SendJob* events. Empty for NewProject and ProjectDirtyChanged.") + .def_readonly("code", &LifecycleEventContext::code, + "The LifecycleEvtCode. Only GCodeExportFinished, SlicingJobComplete, UploadFinished,\n" + "PrintJobFinished and SendJobFinished report anything but Ok: Error on failure, Warn when\n" + "cancelled.") + .def_readonly("msg", &LifecycleEventContext::msg, + "Detail text: the output path for GCodeExport* events, followed by the error on failure;\n" + "the error or \"cancelled\" for SlicingJobComplete; the error for UploadFinished; \"\",\n" + "\"cancelled\", \"failed\" or \"exception\" for PrintJobFinished and SendJobFinished; \"moved\",\n" + "\"rotated\", \"scaled\", \"arranged\" or \"auto_oriented\" for ObjectTransformed; the preset\n" + "type for PresetSelected; \"new\" or \"overwrite\" for PresetSaved; the new status for\n" + "PrintStateChanged; \"online\" or \"offline\" for DeviceOnline and DeviceOffline. Error text\n" + "is for people, not for parsing.") + .def_readonly("id", &LifecycleEventContext::id, + "A numeric id as a decimal string: the model's id for SliceStarted, SliceGeometryFinished,\n" + "GCodeExport* and SlicingJobComplete, the object's or part's id for ObjectChanged and\n" + "ObjectRenamed.") + .def_readonly("previous_name", &LifecycleEventContext::previous_name, + "The old name for ObjectRenamed and PlateRenamed.") + .def_readonly("device_id", &LifecycleEventContext::device_id, + "The target printer's device id for PrintJob* and SendJob* events. PrintStateChanged and\n" + "Device* events carry the device id in name instead.") + .def_readonly("job_id", &LifecycleEventContext::job_id, + "The task id for PrintJob* events sent through the multi-printer task queue (source\n" + "\"task_manager\").") + .def_readonly("source", &LifecycleEventContext::source, + "Where the event came from: \"object\" or \"volume\" for ObjectRenamed, \"geometry\" for\n" + "ObjectChanged, \"print_job\" or \"task_manager\" for PrintJob* events, \"send_job\" for\n" + "SendJob* events, and for ProjectDirtyChanged the change that flipped the state: \"plater\",\n" + "\"presets\", \"undo_redo\", \"save\" or \"batch\".") + .def_readonly("index", &LifecycleEventContext::index, + "A 0-based index: the plate for Plate* events, the object for ObjectChanged (when known) and\n" + "object renames, and the part within its object for part renames.") + .def_readonly("dirty", &LifecycleEventContext::dirty, + "For ProjectDirtyChanged, True when the project now has unsaved changes."); - py::class_(m, "PluginContext", "Context shared with plugin entry points") + py::class_(m, "PluginContext", + "Holds the OrcaSlicer version. No OrcaSlicer call passes one to a plugin; slicing steps\n" + "read the version from SlicingPipelineContext.orca_version.") .def(py::init<>()) - .def_readwrite("orca_version", &PluginContext::orca_version); + .def_readwrite("orca_version", &PluginContext::orca_version, "The OrcaSlicer version string."); - py::class_(m, "ExecutionResult", "Structured execution outcome") - .def(py::init<>()) - .def(py::init()) - .def_readwrite("status", &ExecutionResult::status) - .def_readwrite("message", &ExecutionResult::message) - .def_readwrite("data", &ExecutionResult::data) - .def_static("success", &ExecutionResult::success, py::arg("message") = std::string(), py::arg("data") = std::string()) - .def_static("skipped", &ExecutionResult::skipped, py::arg("message") = std::string()) - .def_static("failure", &ExecutionResult::failure, py::arg("status"), py::arg("message"), py::arg("data") = std::string()); + py::class_(m, "ExecutionResult", + "Outcome a capability's execute() returns: a PluginResult status, a message for the\n" + "user or the log, and optional data. Build one with success(), skipped() or failure().") + .def(py::init<>(), "A Success result with no message or data.") + .def(py::init(), py::arg("status"), py::arg("message"), + py::arg("data"), "A result with the given status, message and data.") + .def_readwrite("status", &ExecutionResult::status, "The PluginResult status.") + .def_readwrite("message", &ExecutionResult::message, + "Text shown to the user or logged, depending on the capability; may be empty.") + .def_readwrite("data", &ExecutionResult::data, + "Extra result text for the caller, such as a JSON string. The Plugins dialog logs it; the host\n" + "does not otherwise read it.") + .def_static("success", &ExecutionResult::success, py::arg("message") = std::string(), + py::arg("data") = std::string(), "Return a Success result with an optional message and data.") + .def_static("skipped", &ExecutionResult::skipped, py::arg("message") = std::string(), + "Return a Skipped result, for a run that had nothing to do, with an optional message.") + .def_static("failure", &ExecutionResult::failure, py::arg("status"), py::arg("message"), + py::arg("data") = std::string(), + "Return a failed result: status is PluginResult.RecoverableError or PluginResult.FatalError,\n" + "message says what went wrong, and data is optional."); // Config lives at the capability level, not as a global orca.* function: the host reads the // owning (plugin_key, capability) straight off the instance the call arrived on, so a // capability can only ever address its own config and never has to name itself. // Registered on the base, so every capability type (script/gcode/printer-agent) inherits it. - py::class_>(m, "PythonPluginBase") + py::class_>( + m, "PythonPluginBase", + "Base of every capability class, holding what all capabilities share: the required get_name(), the\n" + "on_load(), on_unload() and on_lifecycle_event() hooks, and the capability's config. Subclass one of\n" + "the typed bases rather than this class: orca.script.ScriptPluginCapabilityBase,\n" + "orca.pages.PagesPluginCapabilityBase, orca.printer_agent.PrinterAgentBase,\n" + "orca.slicing.SlicingPipelineCapabilityBase or orca.resource_texture.ResourceTexturePluginCapabilityBase.") .def(py::init<>()) - .def("get_name", &PluginCapabilityInterface::get_name) - .def("get_type", &PluginCapabilityInterface::get_type) - .def("on_load", &PluginCapabilityInterface::on_load) - .def("on_unload", &PluginCapabilityInterface::on_unload) - .def("on_lifecycle_event", &PluginCapabilityInterface::on_lifecycle_event, - "Override to react to an application lifecycle moment (LifecycleEvent) and its\n" - "LifecycleEventContext payload. Available on every capability type.") + .def("get_name", &PluginCapabilityInterface::get_name, + "Required. Return this capability's name. The host reads it once when the plugin loads, shows it\n" + "in the UI and uses it to refer to the capability in presets and configs, so it must stay the same.\n" + "It must not contain ';' and must be unique among loaded capabilities of the same type.") + .def("get_type", &PluginCapabilityInterface::get_type, + "Return this capability's PluginType. Each typed capability base already returns its own type, and\n" + "the host reads it once when the plugin loads.") + .def("on_load", &PluginCapabilityInterface::on_load, + "Called once when the plugin loads, after all of its capabilities have been created. Raising an\n" + "exception fails the plugin load. The default does nothing.") + .def("on_unload", &PluginCapabilityInterface::on_unload, + "Called once when the plugin unloads (disabled, removed, reloaded or at exit), and after its own\n" + "on_load() raised. Exceptions are logged and ignored. The default does nothing.") + .def("on_lifecycle_event", &PluginCapabilityInterface::on_lifecycle_event, py::arg("event"), py::arg("ctx"), + "Called for every application lifecycle moment, on every loaded and enabled capability whatever\n" + "its type. event is a LifecycleEvent and ctx the LifecycleEventContext describing it. It runs on\n" + "the thread that raised the event, a background thread for slicing, export, upload and print-job\n" + "events. The return value is ignored, and exceptions are logged and ignored. The default does\n" + "nothing.") .def("has_config_ui", &PluginCapabilityInterface::has_config_ui, "Override to return True to replace the host's default JSON editor with your own HTML\n" "UI, returned by get_config_ui(). Every capability is configurable and appears in the\n" @@ -569,11 +671,17 @@ void bind_python_api(pybind11::module_& m) "The plugin key, capability name and version are supplied by the host. Returns False if\n" "the string is not valid JSON, or if the config file could not be written."); - // Expose the package marker base as orca.base. @orca.plugin later verifies that the - // decorated class derives from this exact pybind-registered C++ type. - py::class_(m, "base") + // @orca.plugin verifies that the decorated class derives from this exact pybind-registered C++ type. + py::class_( + m, "base", + "Base of a plugin's package class. Subclass it once per plugin, decorate the subclass with\n" + "@orca.plugin, and override register_capabilities().") .def(py::init<>()) - .def("register_capabilities", &PyPluginPackage::register_capabilities); + .def("register_capabilities", &PyPluginPackage::register_capabilities, + "Called once while OrcaSlicer loads the plugin, after its module is imported. Call\n" + "orca.register_capability() for each capability class, and orca.request_permissions() and\n" + "orca.register_operation() as needed. Raising an exception fails the plugin load. The default\n" + "registers nothing."); BOOST_LOG_TRIVIAL(debug) << "Registering embedded Python plugin type bindings"; @@ -607,7 +715,13 @@ void bind_python_api(pybind11::module_& m) g_pending_capabilities[g_active_plugin_key].push_back(std::move(plugin_cls)); BOOST_LOG_TRIVIAL(debug) << "Registered Python plugin capability class for key " << g_active_plugin_key; }, - R"pbdoc(Register a PluginCapability subclass while OrcaSlicer loads your module.)pbdoc"); + py::arg("capability_class"), + R"pbdoc(Register a capability class while OrcaSlicer loads your module, normally from register_capabilities(). + +Pass the class, not an instance: OrcaSlicer creates one instance with no arguments after +register_capabilities() returns. The class must derive from a capability base such as +orca.script.ScriptPluginCapabilityBase. Raises ValueError outside plugin loading or for a class that is +not a capability.)pbdoc"); m.def( "register_operation", @@ -765,7 +879,11 @@ instance is created. Denying the request aborts the plugin load.)pbdoc"); slot = cls; } return cls; // decorator returns the class unchanged - }, R"pbdoc(Mark the single plugin package class (the orca.base subclass) for this file.)pbdoc"); + }, py::arg("cls"), + R"pbdoc(Decorator marking the plugin's package class, its orca.base subclass, and returning it unchanged. + +Use it on exactly one class per plugin. Raises ValueError outside plugin loading, on something that is +not a class, on a class that does not derive from orca.base, or on a second package class.)pbdoc"); } diff --git a/src/slic3r/plugin/host/PluginHostApp.cpp b/src/slic3r/plugin/host/PluginHostApp.cpp index b7fb1cdad6..b6e3441cd9 100644 --- a/src/slic3r/plugin/host/PluginHostApp.cpp +++ b/src/slic3r/plugin/host/PluginHostApp.cpp @@ -156,35 +156,55 @@ py::object selected_printer() // app and only reachable once the GUI is up (the accessors throw before that). void host_bindings::register_app(py::module_& host) { - py::class_>(host, "Plater") - .def("model", static_cast(&GUI::Plater::model), py::return_value_policy::reference_internal) - .def("is_project_dirty", &GUI::Plater::is_project_dirty) - .def("is_presets_dirty", &GUI::Plater::is_presets_dirty) - .def("inside_snapshot_capture", &GUI::Plater::inside_snapshot_capture) - // Path the project was last opened from or saved to; empty while it has never been saved. + py::class_>(host, "Plater", + "The app's project editor: the live project's Model and its saved state. Get it with orca.host.plater().") + .def("model", static_cast(&GUI::Plater::model), + py::return_value_policy::reference_internal, + "The live project's Model, the same one orca.host.model() returns.") + .def("is_project_dirty", &GUI::Plater::is_project_dirty, + "True when the project has unsaved changes: to its objects and plates, its project settings or its " + "presets (see is_presets_dirty()).") + .def("is_presets_dirty", &GUI::Plater::is_presets_dirty, + "True when any preset has unsaved edits or, for a project opened from or saved to a file, when the " + "printer, process, filament presets or filament colours differ from the ones it was opened or saved with.") + .def("inside_snapshot_capture", &GUI::Plater::inside_snapshot_capture, + "True while the app is inside an edit grouped into a single undo step, during which it takes no further " + "undo snapshots.") .def("project_path", [](GUI::Plater& plater) { require_main_thread("project_path"); return GUI::into_u8(plater.get_project_filename(".3mf")); - }) + }, "Path of the project's .3mf file, where it was last opened from or saved to; empty while it has never been " + "saved. UI thread only: from a worker thread, where run_python scripts run, it raises RuntimeError.") .def("export_3mf_copy", &export_3mf_copy, py::arg("path"), "Write the current project, unsaved changes included, to path as a 3MF copy. The project's " - "file name and saved state are not changed, and the signed-in account is not written as the designer."); + "file name and saved state are not changed, and the signed-in account is not written as the designer. " + "The path must end in .3mf (ValueError otherwise), and writing it goes through the same permission check " + "as open(path, \"w\"). Raises RuntimeError while the 3D view is not ready yet. UI thread only: from a " + "worker thread, where run_python scripts run, it raises RuntimeError."); - host.def("plater", ¤t_plater, py::return_value_policy::reference); + host.def("plater", ¤t_plater, py::return_value_policy::reference, + "The app's Plater, which holds the live project. Raises RuntimeError before the app's main window is up."); host.def("model", []() -> Model& { return current_plater()->model(); - }, py::return_value_policy::reference); - host.def("preset_bundle", ¤t_preset_bundle, py::return_value_policy::reference); + }, py::return_value_policy::reference, + "The live project's Model: what the 3D editor shows, owned by the app and changed as the person or tools edit " + "it. The objects, volumes and instances it hands out are references into it, so fetch them again after the " + "project changes rather than keeping them. Raises RuntimeError before the app's main window is up."); + host.def("preset_bundle", ¤t_preset_bundle, py::return_value_policy::reference, + "The app's live PresetBundle: every loaded printer, process and filament preset and the ones selected for " + "the project. Raises RuntimeError while the app is still loading its presets at startup."); host.def("app_info", &app_info, "The running app: version, build, mode, language, app_config_version (the version that wrote the app config " "before this run, empty when there was none), stealth_mode, is_signed_in (Orca Cloud), is_bambu_signed_in (Bambu Cloud), network_plugin_version (empty " - "when the Bambu network plugin is not loaded) and network_plugin_error (empty unless it failed to load)."); + "when the Bambu network plugin is not loaded) and network_plugin_error (empty unless it failed to load). " + "UI thread only: from a worker thread, where run_python scripts run, it raises RuntimeError."); host.def("gl_info", &gl_info, "OpenGL vendor, renderer, version, glsl_version and core_profile of the 3D view; None before it has been created."); host.def("selected_printer", &selected_printer, "Agent, model_id, connection ('lan' or 'cloud'), online, connected and firmware of the printer selected in the " "device list; model_id and firmware are empty for non-Bambu agents. None when none is selected. Print hosts " - "configured in the printer preset (OctoPrint and the like) are not in the device list."); + "configured in the printer preset (OctoPrint and the like) are not in the device list. UI thread only: from " + "a worker thread, where run_python scripts run, it raises RuntimeError."); } } // namespace Slic3r diff --git a/src/slic3r/plugin/host/PluginHostGeometry.cpp b/src/slic3r/plugin/host/PluginHostGeometry.cpp index c45105d480..28a207e723 100644 --- a/src/slic3r/plugin/host/PluginHostGeometry.cpp +++ b/src/slic3r/plugin/host/PluginHostGeometry.cpp @@ -77,52 +77,92 @@ void host_bindings::register_geometry(py::module_& host) // instead — see the lifetime rule in PluginHostSlicing.cpp. // ------------------------------------------------------------------ - // Axis-aligned bounding box, returned by value (a copy) so its lifetime is - // independent of the model object it was computed from. Coordinates are in mm. - py::class_(host, "BoundingBox", "Axis-aligned bounding box in millimetres") - .def_property_readonly("defined", [](const BoundingBoxf3& bb) { return bb.defined; }) - .def_property_readonly("min", [](const BoundingBoxf3& bb) { return vec3_to_tuple(bb.min); }) - .def_property_readonly("max", [](const BoundingBoxf3& bb) { return vec3_to_tuple(bb.max); }) - .def_property_readonly("size", [](const BoundingBoxf3& bb) { return vec3_to_tuple(bb.size()); }) - .def_property_readonly("center", [](const BoundingBoxf3& bb) { return vec3_to_tuple(bb.center()); }) - .def_property_readonly("radius", [](const BoundingBoxf3& bb) { return bb.radius(); }); + py::class_(host, "BoundingBox", + "Axis-aligned 3D bounding box in mm. It is a copy, independent of what it was computed from. Check defined " + "before using the other fields.") + .def_property_readonly("defined", [](const BoundingBoxf3& bb) { return bb.defined; }, + "False for an empty box, such as that of an object without model parts, or one with no extent along " + "some axis, such as that of a flat mesh; min and max then mean nothing.") + .def_property_readonly("min", [](const BoundingBoxf3& bb) { return vec3_to_tuple(bb.min); }, + "Minimum corner (x, y, z), in mm.") + .def_property_readonly("max", [](const BoundingBoxf3& bb) { return vec3_to_tuple(bb.max); }, + "Maximum corner (x, y, z), in mm.") + .def_property_readonly("size", [](const BoundingBoxf3& bb) { return vec3_to_tuple(bb.size()); }, + "Extent (dx, dy, dz), max minus min, in mm.") + .def_property_readonly("center", [](const BoundingBoxf3& bb) { return vec3_to_tuple(bb.center()); }, + "Center (x, y, z), the midpoint of min and max, in mm.") + .def_property_readonly("radius", [](const BoundingBoxf3& bb) { return bb.radius(); }, + "Half the length of the box's diagonal, in mm: the radius of the sphere around center that holds the box."); // Point: a constructible value type (default holder, so Python-owned instances // are freed). Returned-by-reference from Polygon.points, it aliases the buffer; // x()/y() are Eigen lvalues, so the properties are read/write. p+q / p-q go // through Eigen expression templates, wrapped back into a Point. - py::class_(host, "Point") - .def(py::init([](coord_t x, coord_t y) { return Point(x, y); }), py::arg("x"), py::arg("y")) + py::class_(host, "Point", + "2D point in scaled integer coordinates, the unit of all orca.host 2D geometry: mm = value * SCALING_FACTOR, " + "which is 1e-6 (1 unit = 1 nm), or 1e-5 when a side of the printer's bed is longer than 2147 mm. " + "orca.slicing.unscale(value) converts a coordinate to mm with the factor in use, and " + "round(mm / orca.slicing.unscale(1)) converts back. A Point read from Polygon.points is a live reference into " + "that polygon.") + .def(py::init([](coord_t x, coord_t y) { return Point(x, y); }), py::arg("x"), py::arg("y"), + "Point at (x, y), in scaled integer coordinates.") .def_property("x", [](const Point& p) { return p.x(); }, - [](Point& p, coord_t v) { p.x() = v; }) + [](Point& p, coord_t v) { p.x() = v; }, + "X coordinate in scaled units; assigning it edits the polygon this Point belongs to, if any.") .def_property("y", [](const Point& p) { return p.y(); }, - [](Point& p, coord_t v) { p.y() = v; }) - .def("__add__", [](const Point& a, const Point& b) { return Point(a + b); }, py::is_operator()) - .def("__sub__", [](const Point& a, const Point& b) { return Point(a - b); }, py::is_operator()) - .def("__mul__", [](const Point& a, double s) { return Point(a.x() * s, a.y() * s); }, py::is_operator()) + [](Point& p, coord_t v) { p.y() = v; }, + "Y coordinate in scaled units; assigning it edits the polygon this Point belongs to, if any.") + .def("__add__", [](const Point& a, const Point& b) { return Point(a + b); }, py::is_operator(), + "Component-wise sum, as a new Point.") + .def("__sub__", [](const Point& a, const Point& b) { return Point(a - b); }, py::is_operator(), + "Component-wise difference, as a new Point.") + .def("__mul__", [](const Point& a, double s) { return Point(a.x() * s, a.y() * s); }, py::is_operator(), + "Both coordinates multiplied by a float and rounded to integers, as a new Point.") .def("__repr__", [](const Point& p) { return "orca.host.Point(" + std::to_string(p.x()) + ", " + std::to_string(p.y()) + ")"; - }); + }, "orca.host.Point(x, y) with the scaled coordinates."); - py::class_(host, "Polygon") - .def(py::init<>()) - .def("size", [](const Polygon& p) { return p.points.size(); }) - .def("is_valid", [](const Polygon& p) { return p.is_valid(); }) - .def("is_counter_clockwise", [](const Polygon& p) { return p.is_counter_clockwise(); }) - .def("is_clockwise", [](const Polygon& p) { return p.is_clockwise(); }) + py::class_(host, "Polygon", + "Closed 2D polygon whose last vertex joins back to the first, in scaled integer coordinates (see Point). " + "Outer contours run counter-clockwise and holes clockwise. Plugins can construct and own one; a Polygon " + "reached from an ExPolygon or the slicing graph is a live reference into it.") + .def(py::init<>(), "Empty polygon; add vertices with append() or set_points().") + .def("size", [](const Polygon& p) { return p.points.size(); }, "Number of vertices.") + .def("is_valid", [](const Polygon& p) { return p.is_valid(); }, + "True when the polygon has at least 3 vertices; self-intersections are not checked.") + .def("is_counter_clockwise", [](const Polygon& p) { return p.is_counter_clockwise(); }, + "True when the signed area is 0 or more: counter-clockwise winding, as outer contours have.") + .def("is_clockwise", [](const Polygon& p) { return p.is_clockwise(); }, + "True when the signed area is negative: clockwise winding, as holes have.") .def("make_counter_clockwise", [](Polygon& p) { return p.make_counter_clockwise(); }, "Reorient to CCW in place. Returns True if it reversed the winding.") - .def("make_clockwise", [](Polygon& p) { return p.make_clockwise(); }) - .def("area", [](const Polygon& p) { return p.area(); }) - .def("centroid", [](const Polygon& p) { return p.centroid(); }) - .def("contains", [](const Polygon& p, const Point& pt) { return p.contains(pt); }, py::arg("point")) - .def("translate", [](Polygon& p, double x, double y) { p.translate(x, y); }, py::arg("x"), py::arg("y")) - .def("rotate", [](Polygon& p, double angle) { p.rotate(angle); }, py::arg("angle")) + .def("make_clockwise", [](Polygon& p) { return p.make_clockwise(); }, + "Reorient to CW in place. Returns True if it reversed the winding.") + .def("area", [](const Polygon& p) { return p.area(); }, + "Signed area in scaled units squared, positive when counter-clockwise and negative when clockwise; " + "multiply by orca.slicing.unscale(1) ** 2 for mm^2.") + .def("centroid", [](const Polygon& p) { return p.centroid(); }, + "Centre of mass of the enclosed area, as a Point in scaled coordinates. Meaningless for a polygon with " + "fewer than 3 vertices or no area.") + .def("contains", [](const Polygon& p, const Point& pt) { return p.contains(pt); }, py::arg("point"), + "True when point lies inside the polygon or on its boundary, whichever its winding.") + .def("translate", [](Polygon& p, double x, double y) { p.translate(x, y); }, py::arg("x"), py::arg("y"), + "Move every vertex by (x, y) scaled units, in place; x and y are truncated to integers.") + .def("rotate", [](Polygon& p, double angle) { p.rotate(angle); }, py::arg("angle"), + "Rotate in place by angle radians, counter-clockwise, about the origin (0, 0); vertices are rounded to " + "integers.") .def("rotate", [](Polygon& p, double angle, const Point& c) { p.rotate(angle, c); }, - py::arg("angle"), py::arg("center")) - .def("douglas_peucker", [](Polygon& p, double tol) { p.douglas_peucker(tol); }, py::arg("tolerance")) + py::arg("angle"), py::arg("center"), + "Rotate in place by angle radians, counter-clockwise, about the Point center; vertices are rounded to " + "integers.") + .def("douglas_peucker", [](Polygon& p, double tol) { p.douglas_peucker(tol); }, py::arg("tolerance"), + "Simplify in place with the Douglas-Peucker algorithm, dropping vertices within tolerance scaled units " + "of the simplified outline. A small polygon can end up with fewer than 3 vertices, so check is_valid() " + "afterwards. The polygon must not be empty.") .def("simplify", [](const Polygon& p, double tol) { return p.simplify(tol); }, py::arg("tolerance"), - "Return simplified geometry as a list of Polygon (may split into several).") + "Return simplified geometry as a list of Polygon (may split into several): Douglas-Peucker with " + "tolerance in scaled units, then cleaned into simple polygons. Expects a non-empty counter-clockwise " + "polygon.") .def("offset", [](const Polygon& p, coord_t delta) { return offset(p, (float) delta); }, py::arg("delta"), "Clipper offset by `delta` scaled units (negative shrinks). Returns [Polygon].") // --- Point-object idiom: references into the buffer (in-place element edit). --- @@ -157,7 +197,10 @@ void host_bindings::register_geometry(py::module_& host) // their own geometry, not just navigate the live slicing graph. contour/holes accessors // still use reference_internal, so refs into a graph-owned ExPolygon stay non-owning views // tied to that owner's lifetime, same as Polygon/Surface. - py::class_(host, "ExPolygon") + py::class_(host, "ExPolygon", + "Polygon with holes: a counter-clockwise outer contour and clockwise hole Polygons, in scaled integer " + "coordinates (see Point). Plugins can construct and own one; an ExPolygon reached from the slicing graph is a " + "live reference into it.") .def(py::init([](py::handle contour, py::handle holes) { // Accept bound Polygons or (N,2) ndarrays for both contour and each hole. ExPolygon ex; @@ -180,7 +223,8 @@ void host_bindings::register_geometry(py::module_& host) [](ExPolygon& e) -> Polygon& { return e.contour; }, [](ExPolygon& e, py::handle v) { e.contour = as_polygon(v, "ExPolygon.contour"); }, py::return_value_policy::reference_internal, - "Outer contour (CCW). Read returns a live Polygon ref; assign a Polygon/ndarray to replace it.") + "Outer contour (CCW). Read returns a live Polygon ref; assign a Polygon/ndarray to replace it. An " + "assigned contour keeps its winding, so pass it counter-clockwise.") .def_property_readonly("holes", [](py::object self) { ExPolygon& e = self.cast(); py::list out; @@ -199,18 +243,36 @@ void host_bindings::register_geometry(py::module_& host) } e.holes = std::move(tmp.holes); }, py::arg("holes"), "Replace all holes. Invalidates prior hole refs (C++ vector semantics).") - .def("translate", [](ExPolygon& e, double x, double y) { e.translate(x, y); }, py::arg("x"), py::arg("y")) - .def("rotate", [](ExPolygon& e, double a) { e.rotate(a); }, py::arg("angle")) + .def("translate", [](ExPolygon& e, double x, double y) { e.translate(x, y); }, py::arg("x"), py::arg("y"), + "Move the contour and holes by (x, y) scaled units, in place; x and y are truncated to integers.") + .def("rotate", [](ExPolygon& e, double a) { e.rotate(a); }, py::arg("angle"), + "Rotate the contour and holes in place by angle radians, counter-clockwise, about the origin (0, 0); " + "vertices are rounded to integers.") .def("rotate", [](ExPolygon& e, double a, const Point& c) { e.rotate(a, c); }, - py::arg("angle"), py::arg("center")) - .def("scale", [](ExPolygon& e, double f) { e.scale(f); }, py::arg("factor")) - .def("douglas_peucker", [](ExPolygon& e, double t) { e.douglas_peucker(t); }, py::arg("tolerance")) - .def("area", [](const ExPolygon& e) { return e.area(); }) - .def("is_valid", [](const ExPolygon& e) { return e.is_valid(); }) - .def("contains", [](const ExPolygon& e, const Point& p) { return e.contains(p); }, py::arg("point")) - .def("num_contours", [](const ExPolygon& e) { return e.num_contours(); }) + py::arg("angle"), py::arg("center"), + "Rotate the contour and holes in place by angle radians, counter-clockwise, about the Point center; " + "vertices are rounded to integers.") + .def("scale", [](ExPolygon& e, double f) { e.scale(f); }, py::arg("factor"), + "Multiply every coordinate by factor in place, which scales about the origin (0, 0); results are " + "truncated to integers.") + .def("douglas_peucker", [](ExPolygon& e, double t) { e.douglas_peucker(t); }, py::arg("tolerance"), + "Simplify the contour and each hole in place with the Douglas-Peucker algorithm, tolerance in scaled " + "units. A small ring can end up with fewer than 3 vertices, so check is_valid() afterwards. The contour " + "and holes must not be empty.") + .def("area", [](const ExPolygon& e) { return e.area(); }, + "Area of the contour minus its holes, in scaled units squared (multiply by orca.slicing.unscale(1) ** 2 " + "for mm^2). Assumes the normal winding: contour counter-clockwise, holes clockwise.") + .def("is_valid", [](const ExPolygon& e) { return e.is_valid(); }, + "True when the contour has at least 3 vertices and runs counter-clockwise and every hole has at least 3 " + "vertices and runs clockwise.") + .def("contains", [](const ExPolygon& e, const Point& p) { return e.contains(p); }, py::arg("point"), + "True when point lies inside the contour and outside every hole; a point on the contour or on a hole's " + "boundary counts as inside.") + .def("num_contours", [](const ExPolygon& e) { return e.num_contours(); }, + "Number of rings: 1 for the contour plus one per hole.") .def("simplify", [](const ExPolygon& e, double t) { return e.simplify(t); }, py::arg("tolerance"), - "Return simplified geometry as [ExPolygon].") + "Return simplified geometry as [ExPolygon]: Douglas-Peucker on each ring with tolerance in scaled units, " + "then merged back into simple shapes.") .def("offset", [](const ExPolygon& e, coord_t delta) { return offset_ex(e, (float) delta); }, py::arg("delta"), "Clipper offset by `delta` scaled units (negative shrinks). Returns [ExPolygon].") .def("union_ex", [](const ExPolygon& a, const ExPolygon& b) { diff --git a/src/slic3r/plugin/host/PluginHostMesh.cpp b/src/slic3r/plugin/host/PluginHostMesh.cpp index f03a329a4a..0427dd9648 100644 --- a/src/slic3r/plugin/host/PluginHostMesh.cpp +++ b/src/slic3r/plugin/host/PluginHostMesh.cpp @@ -47,11 +47,14 @@ void host_bindings::register_mesh(py::module_& host) // ModelVolume::set_mesh — never mutate a mesh obtained from the graph. py::class_>(host, "TriangleMesh", "Immutable snapshot of a ModelVolume's mesh in local (untransformed) coordinates, mm.") - .def("vertex_count", [](const TriangleMesh& mesh) { return mesh.its.vertices.size(); }) - .def("triangle_count", [](const TriangleMesh& mesh) { return mesh.its.indices.size(); }) - .def("facets_count", [](const TriangleMesh& mesh) { return mesh.its.indices.size(); }) - .def("is_empty", [](const TriangleMesh& mesh) { return mesh.its.indices.empty(); }) - // Read-only, zero-copy (N, 3) float32 view of vertex positions. Requires numpy. + .def("vertex_count", [](const TriangleMesh& mesh) { return mesh.its.vertices.size(); }, + "Number of vertices; vertex(index) takes 0 to vertex_count() - 1.") + .def("triangle_count", [](const TriangleMesh& mesh) { return mesh.its.indices.size(); }, + "Number of triangles; triangle(index) takes 0 to triangle_count() - 1.") + .def("facets_count", [](const TriangleMesh& mesh) { return mesh.its.indices.size(); }, + "Number of triangles, the same as triangle_count().") + .def("is_empty", [](const TriangleMesh& mesh) { return mesh.its.indices.empty(); }, + "True when the mesh has no triangles.") .def("vertices", [](py::object self) { const TriangleMesh& mesh = self.cast(); return with_numpy([&] { @@ -61,7 +64,6 @@ void host_bindings::register_mesh(py::module_& host) static_cast(vertices.size()))); }); }, "Read-only zero-copy (N, 3) float32 ndarray of vertex positions (local mm). Requires numpy.") - // Read-only, zero-copy (M, 3) int32 view of triangle vertex indices. Requires numpy. .def("triangles", [](py::object self) { const TriangleMesh& mesh = self.cast(); return with_numpy([&] { @@ -70,8 +72,8 @@ void host_bindings::register_mesh(py::module_& host) self, indices.empty() ? nullptr : indices.front().data(), static_cast(indices.size()))); }); - }, "Read-only zero-copy (M, 3) int32 ndarray of triangle vertex indices. Requires numpy.") - // One normalized normal per triangle as an (M, 3) float32 copy. Requires numpy. + }, "Read-only zero-copy (M, 3) int32 ndarray of triangle vertex indices (0-based rows of vertices()). " + "Requires numpy.") .def("face_normals", [](const TriangleMesh& mesh) { return with_numpy([&] { std::vector normals = its_face_normals(mesh.its); @@ -87,24 +89,31 @@ void host_bindings::register_mesh(py::module_& host) return py::object(std::move(array)); }); }, "Per-triangle normalized normals as an (M, 3) float32 ndarray (copy). Requires numpy.") - // numpy-free element access, bounds-checked. .def("vertex", [](const TriangleMesh& mesh, size_t index) { const std::vector& vertices = mesh.its.vertices; if (index >= vertices.size()) throw py::index_error("vertex index out of range"); const stl_vertex& vertex = vertices[index]; return py::make_tuple(vertex.x(), vertex.y(), vertex.z()); - }) + }, py::arg("index"), + "Vertex at index, 0-based, as an (x, y, z) tuple of floats in local mm; raises IndexError when out of " + "range. Needs no numpy; vertices() returns them all at once.") .def("triangle", [](const TriangleMesh& mesh, size_t index) { const std::vector& indices = mesh.its.indices; if (index >= indices.size()) throw py::index_error("triangle index out of range"); const stl_triangle_vertex_indices& triangle = indices[index]; return py::make_tuple(triangle[0], triangle[1], triangle[2]); - }) - .def("volume", [](const TriangleMesh& mesh) { return mesh.stats().volume; }) - .def("bounding_box", [](const TriangleMesh& mesh) { return bbox_from_stats(mesh.stats()); }) - .def("is_manifold", [](const TriangleMesh& mesh) { return mesh.stats().manifold(); }); + }, py::arg("index"), + "Triangle at index, 0-based, as a tuple (i0, i1, i2) of 0-based vertex indices, ordered so the right-hand " + "rule gives its normal; raises IndexError when out of range. Needs no numpy; triangles() returns them all.") + .def("volume", [](const TriangleMesh& mesh) { return mesh.stats().volume; }, + "Volume in mm^3 that the mesh encloses; -1 when it was never computed. Meaningful only for a closed " + "mesh (see is_manifold()).") + .def("bounding_box", [](const TriangleMesh& mesh) { return bbox_from_stats(mesh.stats()); }, + "Bounding box of the mesh's vertices in its local frame, in mm.") + .def("is_manifold", [](const TriangleMesh& mesh) { return mesh.stats().manifold(); }, + "True when the mesh has no open edges, that is, it is closed."); } } // namespace Slic3r diff --git a/src/slic3r/plugin/host/PluginHostModel.cpp b/src/slic3r/plugin/host/PluginHostModel.cpp index 8d9be8dd3d..99759ccf36 100644 --- a/src/slic3r/plugin/host/PluginHostModel.cpp +++ b/src/slic3r/plugin/host/PluginHostModel.cpp @@ -30,51 +30,84 @@ namespace Slic3r { // by the app (the live Plater model) or by a Print's model snapshot. void host_bindings::register_model(py::module_& host) { - py::enum_(host, "ModelVolumeType") - .value("Invalid", ModelVolumeType::INVALID) - .value("ModelPart", ModelVolumeType::MODEL_PART) - .value("NegativeVolume", ModelVolumeType::NEGATIVE_VOLUME) - .value("ParameterModifier", ModelVolumeType::PARAMETER_MODIFIER) - .value("SupportBlocker", ModelVolumeType::SUPPORT_BLOCKER) - .value("SupportEnforcer", ModelVolumeType::SUPPORT_ENFORCER) - // Expose every seam mode returned by ModelVolume::type() to plugins. - .value("PreciseSeamCenter", ModelVolumeType::PRECISE_SEAM_CENTER) - .value("PreciseSeamLeft", ModelVolumeType::PRECISE_SEAM_LEFT) - .value("PreciseSeamRight", ModelVolumeType::PRECISE_SEAM_RIGHT) - .value("PreciseSeamEnforced", ModelVolumeType::PRECISE_SEAM_ENFORCED) - .value("PreciseSeamBlocked", ModelVolumeType::PRECISE_SEAM_BLOCKED) - .value("PreciseSeamNeutral", ModelVolumeType::PRECISE_SEAM_NEUTRAL); + // Shared by id() on every model class. + static constexpr const char* id_doc = + "Positive integer ID, unique within this app session. A Print's model snapshot gives the same object, " + "volume or instance the same ID, so it matches them to the live project."; - py::class_>(host, "ModelVolume") - .def("id", [](const ModelVolume& volume) { return volume.id().id; }) - .def_readonly("name", &ModelVolume::name) - .def("type", &ModelVolume::type) - .def("is_model_part", &ModelVolume::is_model_part) - .def("is_modifier", &ModelVolume::is_modifier) - .def("is_negative_volume", &ModelVolume::is_negative_volume) - .def("is_support_enforcer", &ModelVolume::is_support_enforcer) - .def("is_support_blocker", &ModelVolume::is_support_blocker) - .def("is_support_modifier", &ModelVolume::is_support_modifier) - // Let plugins identify seam helper geometry without relying on enum ordering. - .def("is_precise_seam", &ModelVolume::is_precise_seam) - .def("is_precise_seam_strong", &ModelVolume::is_precise_seam_strong) - .def("is_precise_seam_weak", &ModelVolume::is_precise_seam_weak) - // Extruder ID is 1-based for FFF, -1 for SLA or support volumes. - .def("extruder_id", &ModelVolume::extruder_id) - .def("offset", [](const ModelVolume& volume) { return vec3_to_tuple(volume.get_offset()); }) - .def("rotation", [](const ModelVolume& volume) { return vec3_to_tuple(volume.get_rotation()); }) - .def("scaling_factor", [](const ModelVolume& volume) { return vec3_to_tuple(volume.get_scaling_factor()); }) - .def("mirror", [](const ModelVolume& volume) { return vec3_to_tuple(volume.get_mirror()); }) - // 4x4 float64 affine matrix mapping this volume into its parent object frame. Requires numpy. + py::enum_(host, "ModelVolumeType", + "What a ModelVolume is: printed geometry, a settings or support modifier, or a precise seam helper. " + "ModelVolume.type() returns it; prefer the is_*() checks on ModelVolume to comparing values.") + .value("Invalid", ModelVolumeType::INVALID, "No valid type.") + .value("ModelPart", ModelVolumeType::MODEL_PART, "Printed geometry.") + .value("NegativeVolume", ModelVolumeType::NEGATIVE_VOLUME, "Subtracted from the object's model parts.") + .value("ParameterModifier", ModelVolumeType::PARAMETER_MODIFIER, + "Not printed; overrides settings where it overlaps the object's model parts.") + .value("SupportBlocker", ModelVolumeType::SUPPORT_BLOCKER, "Not printed; keeps support out where it overlaps.") + .value("SupportEnforcer", ModelVolumeType::SUPPORT_ENFORCER, "Not printed; forces support where it overlaps.") + .value("PreciseSeamCenter", ModelVolumeType::PRECISE_SEAM_CENTER, + "Strong precise seam helper: the seam goes at the middle of where it crosses the outer wall.") + .value("PreciseSeamLeft", ModelVolumeType::PRECISE_SEAM_LEFT, + "Strong precise seam helper: the seam goes at the first point where it crosses the outer wall.") + .value("PreciseSeamRight", ModelVolumeType::PRECISE_SEAM_RIGHT, + "Strong precise seam helper: the seam goes at the last point where it crosses the outer wall.") + .value("PreciseSeamEnforced", ModelVolumeType::PRECISE_SEAM_ENFORCED, + "Weak precise seam helper: marks the outer wall it crosses as a preferred seam area.") + .value("PreciseSeamBlocked", ModelVolumeType::PRECISE_SEAM_BLOCKED, + "Weak precise seam helper: keeps the seam off the outer wall it crosses.") + .value("PreciseSeamNeutral", ModelVolumeType::PRECISE_SEAM_NEUTRAL, + "Weak precise seam helper: resets the outer wall it crosses to neutral."); + + py::class_>(host, "ModelVolume", + "One volume of a ModelObject: a model part, a negative volume, a modifier, a support enforcer or blocker, or " + "a precise seam helper (see type()). Its mesh is in the volume's local frame and matrix() places it in the " + "object frame. A live reference into the project: fetch it again after the project changes.") + .def("id", [](const ModelVolume& volume) { return volume.id().id; }, id_doc) + .def_readonly("name", &ModelVolume::name, "Volume name, as the object list shows it.") + .def("type", &ModelVolume::type, "The volume's ModelVolumeType.") + .def("is_model_part", &ModelVolume::is_model_part, "True for a model part: printed geometry.") + .def("is_modifier", &ModelVolume::is_modifier, + "True for a settings modifier (ModelVolumeType.ParameterModifier) only, not for the other helper volumes.") + .def("is_negative_volume", &ModelVolume::is_negative_volume, + "True for a negative volume, which is subtracted from the object's model parts.") + .def("is_support_enforcer", &ModelVolume::is_support_enforcer, "True for a support enforcer.") + .def("is_support_blocker", &ModelVolume::is_support_blocker, "True for a support blocker.") + .def("is_support_modifier", &ModelVolume::is_support_modifier, "True for a support enforcer or blocker.") + .def("is_precise_seam", &ModelVolume::is_precise_seam, + "True for any of the six precise seam helper types. Use these checks rather than ranges of " + "ModelVolumeType values.") + .def("is_precise_seam_strong", &ModelVolume::is_precise_seam_strong, + "True for a strong precise seam helper (PreciseSeamCenter, PreciseSeamLeft or PreciseSeamRight), which " + "puts the seam at one point.") + .def("is_precise_seam_weak", &ModelVolume::is_precise_seam_weak, + "True for a weak precise seam helper (PreciseSeamEnforced, PreciseSeamBlocked or PreciseSeamNeutral), " + "which marks seam areas the way seam painting does.") + .def("extruder_id", &ModelVolume::extruder_id, + "1-based filament slot from the volume's own extruder setting, else the object's when the volume sets " + "none or 0, else 1. Returned for every volume type, including those that print nothing; multi-material " + "painting on the volume is not reflected.") + .def("offset", [](const ModelVolume& volume) { return vec3_to_tuple(volume.get_offset()); }, + "Position (x, y, z) of the volume in its object's frame, in mm.") + .def("rotation", [](const ModelVolume& volume) { return vec3_to_tuple(volume.get_rotation()); }, + "Rotation (rx, ry, rz) relative to the object frame, in radians, applied about X, then Y, then Z.") + .def("scaling_factor", [](const ModelVolume& volume) { return vec3_to_tuple(volume.get_scaling_factor()); }, + "Scale (sx, sy, sz) relative to the object frame as positive factors, 1.0 meaning unscaled; " + "mirror() reports mirroring.") + .def("mirror", [](const ModelVolume& volume) { return vec3_to_tuple(volume.get_mirror()); }, + "Mirroring (mx, my, mz) relative to the object frame: -1.0 on each axis the volume is mirrored along, " + "1.0 on the others.") .def("matrix", [](const ModelVolume& volume) { return mat4_to_numpy(volume.get_matrix()); }, - "Volume-to-object 4x4 float64 affine matrix (copy). Requires numpy.") - .def("facets_count", [](const ModelVolume& volume) { return volume.mesh().facets_count(); }) - // Raw (untransformed) mesh volume in mm^3; -1 if it was never computed. - .def("volume", [](const ModelVolume& volume) { return volume.mesh().stats().volume; }) - // Bounding box of the raw (untransformed) mesh, in the volume's local frame. - .def("bounding_box", [](const ModelVolume& volume) { return bbox_from_stats(volume.mesh().stats()); }) - .def("is_manifold", [](const ModelVolume& volume) { return volume.mesh().stats().manifold(); }) - // Full mesh geometry (vertices/triangles) as an immutable snapshot. + "Volume-to-object 4x4 float64 affine matrix (copy), in mm, applied to column vectors (x, y, z, 1). " + "Requires numpy.") + .def("facets_count", [](const ModelVolume& volume) { return volume.mesh().facets_count(); }, + "Number of triangles in the volume's mesh.") + .def("volume", [](const ModelVolume& volume) { return volume.mesh().stats().volume; }, + "Volume in mm^3 that the volume's mesh encloses in its local frame, with no volume or instance scaling " + "applied; -1 when it was never computed. Meaningful only for a closed mesh (see is_manifold()).") + .def("bounding_box", [](const ModelVolume& volume) { return bbox_from_stats(volume.mesh().stats()); }, + "Bounding box of the volume's mesh in its local frame (volume transform not applied), in mm.") + .def("is_manifold", [](const ModelVolume& volume) { return volume.mesh().stats().manifold(); }, + "True when the volume's mesh has no open edges, that is, it is closed.") .def("mesh", [](const ModelVolume& volume) { // The volume stores its mesh as shared_ptr (a // copy-on-write snapshot); the const_pointer_cast only serves the @@ -82,150 +115,212 @@ void host_bindings::register_model(py::module_& host) // read-only methods (see the immutability rule in PluginHostMesh.cpp). return std::const_pointer_cast(volume.get_mesh_shared_ptr()); }, "Return the volume's TriangleMesh (local coordinates) for vertex/triangle access.") - .def("mesh_errors_count", [](const ModelVolume& volume) { return volume.get_repaired_errors_count(); }) - .def("is_fdm_support_painted", &ModelVolume::is_fdm_support_painted) - .def("is_seam_painted", &ModelVolume::is_seam_painted) - .def("is_mm_painted", &ModelVolume::is_mm_painted) - .def("is_fuzzy_skin_painted", &ModelVolume::is_fuzzy_skin_painted) - .def("config_keys", [](const ModelVolume& volume) { return volume.config.keys(); }) + .def("mesh_errors_count", [](const ModelVolume& volume) { return volume.get_repaired_errors_count(); }, + "Number of mesh errors recorded as repaired with the volume's mesh, for example in the 3MF it was " + "loaded from: degenerate, removed and reversed facets and fixed and backwards edges, summed. 0 when " + "none were recorded. Defects still present are not counted; see is_manifold().") + .def("is_fdm_support_painted", &ModelVolume::is_fdm_support_painted, + "True when the volume has support enforcer or blocker painting.") + .def("is_seam_painted", &ModelVolume::is_seam_painted, "True when the volume has seam painting.") + .def("is_mm_painted", &ModelVolume::is_mm_painted, "True when the volume has multi-material (colour) painting.") + .def("is_fuzzy_skin_painted", &ModelVolume::is_fuzzy_skin_painted, + "True when the volume has fuzzy skin painting.") + .def("config_keys", [](const ModelVolume& volume) { return volume.config.keys(); }, + "Keys of the settings this volume overrides (its part or modifier settings); settings it inherits are " + "not listed.") .def("config_value", [](const ModelVolume& volume, const std::string& key) { return config_value_or_none(volume.config.get(), key); - }); + }, py::arg("key"), + "This volume's override of setting key, serialized as in a config file, or None when the volume does not " + "override it."); - py::class_>(host, "ModelInstance") - .def("id", [](const ModelInstance& instance) { return instance.id().id; }) - .def_readonly("printable", &ModelInstance::printable) - // True only if the object is printable, this instance is printable and it - // currently sits fully inside the print volume (set during slicing). - .def("is_printable", &ModelInstance::is_printable) - .def("offset", [](const ModelInstance& instance) { return vec3_to_tuple(instance.get_offset()); }) - .def("rotation", [](const ModelInstance& instance) { return vec3_to_tuple(instance.get_rotation()); }) - .def("scaling_factor", [](const ModelInstance& instance) { return vec3_to_tuple(instance.get_scaling_factor()); }) - .def("mirror", [](const ModelInstance& instance) { return vec3_to_tuple(instance.get_mirror()); }) - // 4x4 float64 affine matrix mapping the object into world space. Requires numpy. - // World vertices = instance.matrix() @ volume.matrix() applied to mesh vertices. + py::class_>(host, "ModelInstance", + "One placement of a ModelObject: its object-to-world transform and its printable flag. Plates share one " + "world space side by side, so world positions include the offset of the instance's plate. A live reference " + "into the project: fetch it again after the project changes.") + .def("id", [](const ModelInstance& instance) { return instance.id().id; }, id_doc) + .def_readonly("printable", &ModelInstance::printable, + "Whether this instance is printable, as the object list's Printable toggle sets it; an instance " + "that is not printable is not sliced.") + .def("is_printable", &ModelInstance::is_printable, + "True when this instance gets sliced: the object and this instance are printable, and the app's last " + "print-volume check, made against the current plate, found it fully inside the printable volume.") + .def("offset", [](const ModelInstance& instance) { return vec3_to_tuple(instance.get_offset()); }, + "Position (x, y, z) of the object's origin in world coordinates, in mm.") + .def("rotation", [](const ModelInstance& instance) { return vec3_to_tuple(instance.get_rotation()); }, + "Rotation (rx, ry, rz) in radians, applied about X, then Y, then Z.") + .def("scaling_factor", + [](const ModelInstance& instance) { return vec3_to_tuple(instance.get_scaling_factor()); }, + "Scale (sx, sy, sz) as positive factors, 1.0 meaning unscaled; mirror() reports mirroring.") + .def("mirror", [](const ModelInstance& instance) { return vec3_to_tuple(instance.get_mirror()); }, + "Mirroring (mx, my, mz): -1.0 on each axis the instance is mirrored along, 1.0 on the others.") .def("matrix", [](const ModelInstance& instance) { return mat4_to_numpy(instance.get_matrix()); }, - "Object-to-world 4x4 float64 affine matrix (copy). Requires numpy.") - .def("is_left_handed", &ModelInstance::is_left_handed) - // Assemble-view placement. Each instance carries a second transform used only by - // the Assemble view, set from stored 3mf assemble data or derived from the regular - // transform. Until then (is_assemble_initialized() false) it is identity. - .def("is_assemble_initialized", [](ModelInstance& instance) { return instance.is_assemble_initialized(); }) + "Object-to-world 4x4 float64 affine matrix (copy), in mm, applied to column vectors (x, y, z, 1). World " + "vertices are instance.matrix() @ volume.matrix() applied to a volume's mesh vertices. Requires numpy.") + .def("is_left_handed", &ModelInstance::is_left_handed, + "True when the transform mirrors the object (negative determinant), which reverses triangle winding.") + .def("is_assemble_initialized", [](ModelInstance& instance) { return instance.is_assemble_initialized(); }, + "True once the instance has its own Assemble-view transform, set from the project's assemble data or " + "derived from the regular transform. Until then the assemble_*() values describe the identity transform.") .def("assemble_offset", [](const ModelInstance& instance) { return vec3_to_tuple(instance.get_assemble_transformation().get_offset()); - }) + }, "Position (x, y, z) of the object in the Assemble view, in mm.") .def("assemble_rotation", [](const ModelInstance& instance) { return vec3_to_tuple(instance.get_assemble_transformation().get_rotation()); - }) - // 4x4 float64 affine matrix placing the object in the Assemble view. Requires numpy. + }, "Rotation (rx, ry, rz) in the Assemble view, in radians, applied about X, then Y, then Z.") .def("assemble_matrix", [](const ModelInstance& instance) { return mat4_to_numpy(instance.get_assemble_transformation().get_matrix()); - }, "Assemble-view 4x4 float64 affine matrix (copy). Requires numpy.") - // Offset from the instance origin to its position within the source assembly, - // recorded at import time (e.g. from a STEP assembly). + }, "Assemble-view 4x4 float64 affine matrix (copy), in mm, applied to column vectors (x, y, z, 1). " + "Requires numpy.") .def("offset_to_assembly", [](const ModelInstance& instance) { return vec3_to_tuple(instance.get_offset_to_assembly()); - }) - // World-space bounding box of this instance. + }, "Offset (x, y, z) in mm of this object within the assembly it came from, which the Assemble view uses to " + "explode the assembly. Set when a multi-part object is split into objects and kept in the project 3MF; " + "(0, 0, 0) otherwise.") .def("bounding_box", [](ModelInstance& instance) { const ModelObject* object = instance.get_object(); if (object == nullptr) return BoundingBoxf3(); return object->instance_bounding_box(instance); - }); + }, "World-space bounding box of this instance's model parts, in mm, fitted to the transformed meshes. " + "Modifiers and other helper volumes are left out."); - py::class_>(host, "ModelObject") - .def("id", [](const ModelObject& object) { return object.id().id; }) - .def_readonly("name", &ModelObject::name) - .def_readonly("module_name", &ModelObject::module_name) - .def_readonly("input_file", &ModelObject::input_file) - // Import-time flag only: the GUI's printable toggle writes the per-instance - // ModelInstance::printable and never updates this field, so derive an - // object's effective state from its instances. - .def_readonly("printable", &ModelObject::printable) + py::class_>(host, "ModelObject", + "An object of the project: its volumes (parts, modifiers and other helpers) in the object frame, its " + "instances placing it in the world, and its per-object settings. A live reference into the project: fetch it " + "again after the project changes, since deleting the object frees it.") + .def("id", [](const ModelObject& object) { return object.id().id; }, id_doc) + .def_readonly("name", &ModelObject::name, "Object name, as the object list shows it.") + .def_readonly("module_name", &ModelObject::module_name, + "Assembly module name from the project 3MF's object metadata; empty unless the file set one.") + .def_readonly("input_file", &ModelObject::input_file, + "Path of the file the object was loaded from (a model file or the project 3MF); empty for an " + "object created in the app.") + .def_readonly("printable", &ModelObject::printable, + "Object-level printable flag. The object list's Printable toggle sets ModelInstance.printable " + "instead and leaves this unchanged, so read the instances (printable, is_printable()) for the " + "effective state.") .def("instance_count", [](const ModelObject& object) { return object.instances.size(); - }) + }, "Number of instances (copies) of the object; instance(index) takes 0 to instance_count() - 1.") .def("volume_count", [](const ModelObject& object) { return object.volumes.size(); - }) + }, "Number of volumes of every type; volume(index) takes 0 to volume_count() - 1. parts_count() counts the " + "model parts only.") .def("instances", [](ModelObject& object) { py::list instances; for (ModelInstance* instance : object.instances) instances.append(py::cast(instance, py::return_value_policy::reference)); return instances; - }) + }, "All instances as a list of ModelInstance, in index order.") .def("instance", [](ModelObject& object, size_t index) -> ModelInstance* { if (index >= object.instances.size()) throw py::index_error("instance index out of range"); return object.instances[index]; - }, py::return_value_policy::reference_internal) + }, py::return_value_policy::reference_internal, py::arg("index"), + "The instance at index, 0-based; raises IndexError when out of range.") .def("volumes", [](ModelObject& object) { py::list volumes; for (ModelVolume* volume : object.volumes) volumes.append(py::cast(volume, py::return_value_policy::reference)); return volumes; - }) + }, "All volumes of every type as a list of ModelVolume, in index order.") .def("volume", [](ModelObject& object, size_t index) -> ModelVolume* { if (index >= object.volumes.size()) throw py::index_error("volume index out of range"); return object.volumes[index]; - }, py::return_value_policy::reference_internal) - // World-space bounding box over all instances of this object. - .def("bounding_box", [](const ModelObject& object) { return object.bounding_box_exact(); }) - // Bounding box of the object's raw (untransformed) part meshes — its intrinsic size. - .def("raw_mesh_bounding_box", [](const ModelObject& object) { return object.raw_mesh_bounding_box(); }) - .def("min_z", &ModelObject::min_z) - .def("max_z", &ModelObject::max_z) - .def("facets_count", [](const ModelObject& object) { return object.facets_count(); }) - .def("parts_count", [](const ModelObject& object) { return object.parts_count(); }) - .def("materials_count", [](const ModelObject& object) { return object.materials_count(); }) - .def("mesh_errors_count", [](const ModelObject& object) { return object.get_repaired_errors_count(); }) - .def("is_multiparts", &ModelObject::is_multiparts) - .def("is_cut", &ModelObject::is_cut) - .def("has_custom_layering", &ModelObject::has_custom_layering) - .def("is_fdm_support_painted", &ModelObject::is_fdm_support_painted) - .def("is_seam_painted", &ModelObject::is_seam_painted) - .def("is_mm_painted", &ModelObject::is_mm_painted) - .def("is_fuzzy_skin_painted", &ModelObject::is_fuzzy_skin_painted) + }, py::return_value_policy::reference_internal, py::arg("index"), + "The volume at index, 0-based, counting volumes of every type; raises IndexError when out of range.") + .def("bounding_box", [](const ModelObject& object) { return object.bounding_box_exact(); }, + "World-space bounding box of the object's model parts over all its instances, in mm, fitted to the " + "transformed meshes. Modifiers and other helper volumes are left out.") + .def("raw_mesh_bounding_box", [](const ModelObject& object) { return object.raw_mesh_bounding_box(); }, + "Bounding box of the object's model parts in the object frame, in mm: volume transforms applied, " + "instance transform not. Modifiers and other helper volumes are left out.") + .def("min_z", &ModelObject::min_z, + "Lowest world Z of the object's model parts, in mm, from the first instance's transform; all instances " + "of an object share their Z range.") + .def("max_z", &ModelObject::max_z, + "Highest world Z of the object's model parts, in mm, from the first instance's transform; all instances " + "of an object share their Z range.") + .def("facets_count", [](const ModelObject& object) { return object.facets_count(); }, + "Total number of triangles in the object's model parts.") + .def("parts_count", [](const ModelObject& object) { return object.parts_count(); }, + "Number of model parts (printed volumes); modifiers and other helper volumes are not counted.") + .def("materials_count", [](const ModelObject& object) { return object.materials_count(); }, + "Number of distinct material IDs among the volumes, where volumes without one share the empty ID, so " + "usually 1. These are materials an imported AMF file defines, not filaments; see " + "ModelVolume.extruder_id().") + .def("mesh_errors_count", [](const ModelObject& object) { return object.get_repaired_errors_count(); }, + "Sum of ModelVolume.mesh_errors_count() over all the object's volumes: mesh errors recorded as " + "repaired, not defects still present.") + .def("is_multiparts", &ModelObject::is_multiparts, + "True when the object has more than one volume of any type, so a part with a modifier counts.") + .def("is_cut", &ModelObject::is_cut, + "True when the object is a piece of a Cut that is still linked to the other pieces of that cut.") + .def("has_custom_layering", &ModelObject::has_custom_layering, + "True when the object has layer height ranges or a variable layer height profile; the profile may still " + "match the default layering.") + .def("is_fdm_support_painted", &ModelObject::is_fdm_support_painted, + "True when any of the object's volumes has support enforcer or blocker painting.") + .def("is_seam_painted", &ModelObject::is_seam_painted, + "True when any of the object's volumes has seam painting.") + .def("is_mm_painted", &ModelObject::is_mm_painted, + "True when any of the object's volumes has multi-material (colour) painting.") + .def("is_fuzzy_skin_painted", &ModelObject::is_fuzzy_skin_painted, + "True when any of the object's volumes has fuzzy skin painting.") .def("config_keys", [](const ModelObject& object) { return object.config.keys(); - }) + }, "Keys of the settings this object overrides (its per-object settings); settings it inherits from the " + "presets are not listed.") .def("config_value", [](const ModelObject& object, const std::string& key) { return config_value_or_none(object.config.get(), key); - }); + }, py::arg("key"), + "This object's override of setting key, serialized as in a config file, or None when the object does not " + "override it."); - py::class_>(host, "Model") - .def("id", [](const Model& model) { return model.id().id; }) + py::class_>(host, "Model", + "A project's scene: its objects, each with its volumes and instances, across all plates. orca.host.model() " + "is the live project; a Print's model() is the snapshot that Print slices.") + .def("id", [](const Model& model) { return model.id().id; }, id_doc) .def("object_count", [](const Model& model) { return model.objects.size(); - }) + }, "Number of objects in the project; object(index) takes 0 to object_count() - 1.") .def("object", [](Model& model, size_t index) -> ModelObject* { if (index >= model.objects.size()) throw py::index_error("model object index out of range"); return model.objects[index]; - }, py::return_value_policy::reference_internal) + }, py::return_value_policy::reference_internal, py::arg("index"), + "The object at index, 0-based in object-list order; raises IndexError when out of range.") .def("objects", [](Model& model) { py::list objects; for (ModelObject* object : model.objects) objects.append(py::cast(object, py::return_value_policy::reference)); return objects; - }) - // World-space bounding box of the whole model. bounding_box() is exact; - // bounding_box_approx() is faster and cached. - .def("bounding_box", [](const Model& model) { return model.bounding_box_exact(); }) - .def("bounding_box_approx", [](const Model& model) { return model.bounding_box_approx(); }) - .def("max_z", &Model::max_z) - .def("material_count", [](const Model& model) { return model.materials.size(); }) - .def("is_fdm_support_painted", &Model::is_fdm_support_painted) - .def("is_seam_painted", &Model::is_seam_painted) - .def("is_mm_painted", &Model::is_mm_painted) - .def("is_fuzzy_skin_painted", &Model::is_fuzzy_skin_painted) - .def("current_plate_index", [](const Model& model) { return model.curr_plate_index; }) + }, "All objects as a list of ModelObject, in index order.") + .def("bounding_box", [](const Model& model) { return model.bounding_box_exact(); }, + "World-space bounding box of every instance's model parts on all plates, in mm, fitted to the " + "transformed meshes.") + .def("bounding_box_approx", [](const Model& model) { return model.bounding_box_approx(); }, + "Quicker, looser bounding_box(): it transforms each object's part box rather than its meshes, so it can " + "be larger for rotated objects.") + .def("max_z", &Model::max_z, "Highest world Z of any object's model parts, in mm; 0.0 for an empty project.") + .def("material_count", [](const Model& model) { return model.materials.size(); }, + "Number of materials that imported AMF files defined in the model; 0 for most projects. Not the " + "filament count.") + .def("is_fdm_support_painted", &Model::is_fdm_support_painted, + "True when any object has support enforcer or blocker painting.") + .def("is_seam_painted", &Model::is_seam_painted, "True when any object has seam painting.") + .def("is_mm_painted", &Model::is_mm_painted, "True when any object has multi-material (colour) painting.") + .def("is_fuzzy_skin_painted", &Model::is_fuzzy_skin_painted, "True when any object has fuzzy skin painting.") + .def("current_plate_index", [](const Model& model) { return model.curr_plate_index; }, + "0-based index of the selected plate.") .def("designer", [](const Model& model) { return model.design_info ? model.design_info->Designer : std::string(); - }) - .def("design_id", [](const Model& model) { return model.stl_design_id; }); + }, "Designer name from the metadata of the project 3MF the project was loaded from; empty when it has none.") + .def("design_id", [](const Model& model) { return model.stl_design_id; }, + "Design ID of an online model the loaded files came from, read from 3MF metadata or a binary STL " + "header; empty when they carry none."); } } // namespace Slic3r diff --git a/src/slic3r/plugin/host/PluginHostPresets.cpp b/src/slic3r/plugin/host/PluginHostPresets.cpp index d79f7b428e..5e5771b0ec 100644 --- a/src/slic3r/plugin/host/PluginHostPresets.cpp +++ b/src/slic3r/plugin/host/PluginHostPresets.cpp @@ -577,7 +577,14 @@ std::vector list_bundle_ids() void host_bindings::register_presets(py::module_& host) { - auto preset = host.def_submodule("preset", "Preset operations"); + auto preset = host.def_submodule("preset", + "Preset editing. orca.host.preset.process, orca.host.preset.printer and " + "orca.host.preset.filament are the PresetEditor instances that change the " + "edited process, printer and filament presets: update(key, value) for one " + "setting, begin_update() for a batch. Each accepts only settings of its own " + "category, so a printer setting passed to process is rejected rather than " + "written. bundles reloads local preset bundles. To read presets and settings, " + "use orca.host.preset_bundle()."); auto bundles = preset.def_submodule("bundles", "Local preset bundle operations"); bundles.def("reload_local", &reload_local_bundle, py::arg("bundle_id"), "Reload one local preset bundle from the active user's _local directory."); @@ -585,34 +592,45 @@ void host_bindings::register_presets(py::module_& host) "IDs of local preset bundles in the active user's _local directory that reload_local() accepts, " "including bundles added after startup."); - py::enum_(host, "PresetType") - .value("Invalid", Preset::TYPE_INVALID) - .value("Print", Preset::TYPE_PRINT) - .value("SlaPrint", Preset::TYPE_SLA_PRINT) - .value("Filament", Preset::TYPE_FILAMENT) - .value("SlaMaterial", Preset::TYPE_SLA_MATERIAL) - .value("Printer", Preset::TYPE_PRINTER) - .value("PhysicalPrinter", Preset::TYPE_PHYSICAL_PRINTER) - .value("Plate", Preset::TYPE_PLATE) - .value("Model", Preset::TYPE_MODEL); + py::enum_(host, "PresetType", + "Kind of preset: the type of a Preset, and the category a PresetEditor, PresetTransaction " + "or PresetUpdateResult targets.") + .value("Invalid", Preset::TYPE_INVALID, "No preset type (an unset value).") + .value("Print", Preset::TYPE_PRINT, + "Process preset, the print settings the GUI calls \"process\" (PresetBundle.prints).") + .value("SlaPrint", Preset::TYPE_SLA_PRINT, "SLA print preset; not used by OrcaSlicer's FFF printers.") + .value("Filament", Preset::TYPE_FILAMENT, "Filament preset (PresetBundle.filaments).") + .value("SlaMaterial", Preset::TYPE_SLA_MATERIAL, "SLA resin preset; not used by OrcaSlicer's FFF printers.") + .value("Printer", Preset::TYPE_PRINTER, "Printer (machine) preset (PresetBundle.printers).") + .value("PhysicalPrinter", Preset::TYPE_PHYSICAL_PRINTER, + "A physical printer's connection settings; no Preset has this type.") + .value("Plate", Preset::TYPE_PLATE, + "Per-plate settings of the project; no PresetBundle collection holds this type.") + .value("Model", Preset::TYPE_MODEL, + "Per-object and per-part settings of the project; no PresetBundle collection holds this type."); py::class_(preset, "PresetUpdateResult", - "Outcome of one committed preset transaction. target_name is the preset that was " - "edited; selection_changed says whether begin_update() switched the active preset; " - "for filament, slot_number is the 1-based target slot, slot_assignment_changed " - "says whether selecting the requested preset reassigned that slot, and shared_slots " - "lists every 1-based slot whose assigned preset is the edited (shared) one. keys " - "lists the settings applied, in order, and dirty says whether the edited preset " - "now differs from its saved state.") - .def_readonly("type", &PresetUpdateResult::type) - .def_readonly("target_name", &PresetUpdateResult::target_name) - .def_readonly("selection_changed", &PresetUpdateResult::selection_changed) - .def_readonly("slot_number", &PresetUpdateResult::slot_number) - .def_readonly("slot_assignment_changed", &PresetUpdateResult::slot_assignment_changed) - .def_readonly("shared_slots", &PresetUpdateResult::shared_slots) - .def_readonly("keys", &PresetUpdateResult::keys) - .def_readonly("dirty", &PresetUpdateResult::dirty) - .def_property_readonly("category", [](const PresetUpdateResult& result) { return preset_tab_name(result.type); }) + "Outcome of one committed preset transaction, returned by " + "PresetTransaction.commit(). Filament slot numbers are 1-based.") + .def_readonly("type", &PresetUpdateResult::type, "PresetType of the edited preset: Print, Printer or Filament.") + .def_readonly("target_name", &PresetUpdateResult::target_name, "Internal name of the preset that was edited.") + .def_readonly("selection_changed", &PresetUpdateResult::selection_changed, + "True when begin_update() switched the edited preset to reach the target; False when the target " + "was already being edited.") + .def_readonly("slot_number", &PresetUpdateResult::slot_number, + "1-based filament slot the transaction targeted; -1 for process and printer.") + .def_readonly("slot_assignment_changed", &PresetUpdateResult::slot_assignment_changed, + "True when begin_update() assigned the requested preset to the filament slot in place of its " + "previous one; always False for process and printer.") + .def_readonly("shared_slots", &PresetUpdateResult::shared_slots, + "1-based filament slots whose assigned preset is the edited one, all of which the edit affects; " + "empty for process and printer.") + .def_readonly("keys", &PresetUpdateResult::keys, "Setting keys that were applied, in staging order.") + .def_readonly("dirty", &PresetUpdateResult::dirty, + "True when the edited preset now differs from its saved state and still needs saving.") + .def_property_readonly( + "category", [](const PresetUpdateResult& result) { return preset_tab_name(result.type); }, + "Category of the edited preset: \"process\", \"printer\" or \"filament\".") .def("__repr__", [](const PresetUpdateResult& result) { return std::string(""; @@ -626,20 +644,29 @@ void host_bindings::register_presets(py::module_& host) "while the UI thread stays responsive; set() and commit() run synchronously on the " "same worker. Nothing is saved to disk: the edited preset stays dirty until the user " "saves it.") - .def_readonly("type", &PresetTransaction::type) - .def_readonly("target_name", &PresetTransaction::target_name) - .def_readonly("selection_changed", &PresetTransaction::selection_changed) - .def_property_readonly("slot_number", [](const PresetTransaction& transaction) { - return transaction.filament ? transaction.slot_number : -1; - }) - .def_property_readonly("category", [](const PresetTransaction& transaction) { return preset_tab_name(transaction.type); }) - .def_property_readonly("staged_keys", [](const PresetTransaction& transaction) { - std::vector keys; - keys.reserve(transaction.staged.size()); - for (const auto& entry : transaction.staged) - keys.push_back(entry.first); - return keys; - }) + .def_readonly("type", &PresetTransaction::type, "PresetType of the target preset: Print, Printer or Filament.") + .def_readonly("target_name", &PresetTransaction::target_name, + "Internal name of the preset this transaction edits.") + .def_readonly("selection_changed", &PresetTransaction::selection_changed, + "True when begin_update() switched the edited preset to reach the target; False when the target " + "was already being edited.") + .def_property_readonly( + "slot_number", + [](const PresetTransaction& transaction) { return transaction.filament ? transaction.slot_number : -1; }, + "1-based filament slot this transaction was created for; -1 for process and printer.") + .def_property_readonly( + "category", [](const PresetTransaction& transaction) { return preset_tab_name(transaction.type); }, + "Category of the target preset: \"process\", \"printer\" or \"filament\".") + .def_property_readonly( + "staged_keys", + [](const PresetTransaction& transaction) { + std::vector keys; + keys.reserve(transaction.staged.size()); + for (const auto& entry : transaction.staged) + keys.push_back(entry.first); + return keys; + }, + "Setting keys staged with set() so far, in staging order, as a new list.") .def("set", &PresetTransaction::set, py::arg("key"), py::arg("value"), "Stage one setting change. key must be a setting of the target preset category and value its " "serialized string form; staging validates neither, so commit() is where an invalid key or value " @@ -655,7 +682,9 @@ void host_bindings::register_presets(py::module_& host) "Handle to a category of currently edited preset. It is not a snapshot: it always " "resolves the preset the matching tab edits now, so it stays usable across preset " "switches. update() edits the preset in place; the change is not saved to disk.") - .def_readonly("type", &PresetEditor::type) + .def_readonly("type", &PresetEditor::type, + "PresetType this editor edits: Print for orca.host.preset.process, Printer for " + "orca.host.preset.printer, Filament for orca.host.preset.filament.") .def( "begin_update", [](const PresetEditor& editor, const std::string& preset_name) { @@ -727,100 +756,196 @@ void host_bindings::register_presets(py::module_& host) "(the slot's current assignment is kept), then set(key, value) and commit(); like " "begin_update() this call blocks the background Script worker."); - // The three preset categories edited by the main tabs. `process` is the print/process preset, - // `printer` the machine preset and `filament` the currently edited filament preset (its - // 3-argument form addresses a 1-based filament slot); each only accepts its own settings, so a - // printer setting passed to `process` is rejected instead of written silently. preset.attr("process") = py::cast(PresetEditor{Preset::TYPE_PRINT}); preset.attr("printer") = py::cast(PresetEditor{Preset::TYPE_PRINTER}); preset.attr("filament") = py::cast(PresetEditor{Preset::TYPE_FILAMENT}); - py::class_>(host, "Preset") - .def_readonly("type", &Preset::type) - .def_readonly("name", &Preset::name) - .def_readonly("alias", &Preset::alias) - .def_readonly("file", &Preset::file) - .def_readonly("is_default", &Preset::is_default) - .def_readonly("is_external", &Preset::is_external) - .def_readonly("is_system", &Preset::is_system) - .def_readonly("is_visible", &Preset::is_visible) - .def_readonly("is_dirty", &Preset::is_dirty) - .def_readonly("is_compatible", &Preset::is_compatible) - .def_readonly("is_project_embedded", &Preset::is_project_embedded) - .def_readonly("bundle_id", &Preset::bundle_id) - .def("is_user", &Preset::is_user) - .def("is_from_bundle", &Preset::is_from_bundle) - .def("label", &Preset::label, py::arg("no_alias") = false) - .def("config_keys", [](const Preset& preset) { return preset.config.keys(); }) - .def("config_value", [](const Preset& preset, const std::string& key) { - return config_value_or_none(preset.config, key); - }); + py::class_>( + host, "Preset", + "One named set of process, filament or printer settings. Get presets from orca.host.preset_bundle(): its " + "prints, filaments and printers collections, or the current_*_preset() shortcuts. A Preset is a live " + "reference into the app's preset store, not a copy: it reflects later edits, and adding or deleting presets " + "(saving a new preset, loading a project, reloading a bundle) invalidates it, so look presets up again " + "instead of keeping them. Read a setting with config_value(key); change one through orca.host.preset.process, " + ".printer or .filament (PresetEditor), never through this object.") + .def_readonly("type", &Preset::type, "PresetType of this preset: Print (process), Filament or Printer.") + .def_readonly("name", &Preset::name, + "Internal name, unique within its collection. find_preset(), " + "PresetEditor.begin_update(preset_name) and the filament slot assignments use it. A preset " + "from an imported bundle is named \"_local//\" or " + "\"_subscribed//\".") + .def_readonly("alias", &Preset::alias, + "Logical name without the printer suffix, such as \"Generic PLA\" for \"Generic PLA @BBL X1C\"; " + "label() shows it in place of name. Empty when the preset has none. find_preset() does not " + "match it.") + .def_readonly("file", &Preset::file, + "Path of the file this preset was loaded from or is saved to; empty for the built-in default " + "preset.") + .def_readonly("is_default", &Preset::is_default, + "True for the built-in default preset at index 0 of each collection (\"Default Setting\", " + "\"Default Filament\" or \"Default Printer\"), which holds every setting's default value.") + .def_readonly("is_external", &Preset::is_external, + "True for a preset loaded from a file outside OrcaSlicer's preset folders, such as a config " + "file or the settings stored in a G-code or 3MF project.") + .def_readonly("is_system", &Preset::is_system, + "True for a read-only system preset from a vendor profile; changes to it can only be saved as a " + "new user preset.") + .def_readonly("is_visible", &Preset::is_visible, + "Whether the preset selectors offer it: False for a system printer whose model or variant, or a " + "system filament, is not enabled in the printer and filament selection. The default preset is " + "visible only when nothing else is available.") + .def_readonly("is_dirty", &Preset::is_dirty, + "True when the preset has unsaved changes. Only the selected preset and its edited copy " + "(PresetCollection.edited_preset()) can be dirty.") + .def_readonly("is_compatible", &Preset::is_compatible, + "Whether it suits the selected printer (its compatible_printers or " + "compatible_printers_condition) and, for a filament, the edited process (compatible_prints). The " + "selectors hide incompatible presets. Always True for printer presets.") + .def_readonly("is_project_embedded", &Preset::is_project_embedded, + "True for a preset stored in the loaded 3MF project rather than in the user's preset folder.") + .def_readonly("bundle_id", &Preset::bundle_id, + "ID of the imported preset bundle this preset came from (an Orca Cloud UUID, or a name and " + "timestamp for an external bundle); empty when it is not from a bundle.") + .def("is_user", &Preset::is_user, + "True for a user preset: not the default preset, not a system preset, not embedded in the project and " + "not from a bundle.") + .def("is_from_bundle", &Preset::is_from_bundle, + "True when the preset came from an imported preset bundle, that is when bundle_id is set.") + .def("label", &Preset::label, py::arg("no_alias") = false, + "Display label: alias, or name when there is no alias or no_alias is True, prefixed with the GUI's " + "unsaved-changes marker (\"* \" in English) when is_dirty. Look presets up by name, not by label.") + .def( + "config_keys", [](const Preset& preset) { return preset.config.keys(); }, + "Names of every setting in this preset. A preset holds its complete config, so a user preset also lists " + "the settings it inherits unchanged from its parent.") + .def( + "config_value", + [](const Preset& preset, const std::string& key) { return config_value_or_none(preset.config, key); }, + py::arg("key"), + "Serialized value of one setting, in the string form PresetTransaction.set() and PresetEditor.update() " + "take: numbers as text, booleans \"1\"/\"0\", enums by name, percentages with \"%\", vector options " + "comma-separated (string lists ';'-separated, quoted where needed). None when the preset has no such " + "setting."); - py::class_>(host, "PresetCollection") - .def("size", &PresetCollection::size) - .def("get_selected_preset", [](PresetCollection& collection) -> Preset& { - return collection.get_selected_preset(); - }, py::return_value_policy::reference_internal) - .def("selected_preset", [](PresetCollection& collection) -> Preset& { - return collection.get_selected_preset(); - }, py::return_value_policy::reference_internal) - .def("get_selected_preset_name", &PresetCollection::get_selected_preset_name) - .def("selected_preset_name", &PresetCollection::get_selected_preset_name) - .def("get_edited_preset", [](PresetCollection& collection) -> Preset& { - return collection.get_edited_preset(); - }, py::return_value_policy::reference_internal) - .def("edited_preset", [](PresetCollection& collection) -> Preset& { - return collection.get_edited_preset(); - }, py::return_value_policy::reference_internal) - .def("preset", [](PresetCollection& collection, size_t index) -> Preset& { - if (index >= collection.size()) - throw py::index_error("preset index out of range"); - return collection.preset(index); - }, py::return_value_policy::reference_internal) - .def("find_preset", [](PresetCollection& collection, const std::string& name) -> Preset* { - return collection.find_preset(name); - }, py::return_value_policy::reference_internal) - .def("preset_names", [](const PresetCollection& collection) { - std::vector names; - names.reserve(collection.get_presets().size()); - for (const Preset& preset : collection.get_presets()) - names.push_back(preset.name); - return names; - }); + py::class_>( + host, "PresetCollection", + "All presets of one type: the prints (process), filaments or printers collection of " + "orca.host.preset_bundle(). Index 0 is the built-in default preset; hidden and incompatible presets are " + "included. Items are live Preset references (see Preset). Read a setting with Preset.config_value(key); to " + "change one, use orca.host.preset.process, .filament or .printer (PresetEditor), which edit the currently " + "edited preset the way the settings tab does.") + .def("size", &PresetCollection::size, + "Number of presets, including the default preset at index 0; preset(index) accepts 0 to size() - 1.") + .def( + "get_selected_preset", + [](PresetCollection& collection) -> Preset& { return collection.get_selected_preset(); }, + py::return_value_policy::reference_internal, + "The selected preset as last saved, without unsaved changes; edited_preset() has the values in effect. " + "Same as selected_preset().") + .def( + "selected_preset", [](PresetCollection& collection) -> Preset& { return collection.get_selected_preset(); }, + py::return_value_policy::reference_internal, + "The selected preset as last saved, without unsaved changes; edited_preset() has the values in effect.") + .def("get_selected_preset_name", &PresetCollection::get_selected_preset_name, + "Internal name of the selected preset, or \"\" when none is selected. Same as selected_preset_name().") + .def("selected_preset_name", &PresetCollection::get_selected_preset_name, + "Internal name of the selected preset, or \"\" when none is selected.") + .def( + "get_edited_preset", [](PresetCollection& collection) -> Preset& { return collection.get_edited_preset(); }, + py::return_value_policy::reference_internal, + "The selected preset including its unsaved changes. Same as edited_preset().") + .def( + "edited_preset", [](PresetCollection& collection) -> Preset& { return collection.get_edited_preset(); }, + py::return_value_policy::reference_internal, + "The selected preset including its unsaved changes: the values the settings tab shows. The object follows " + "the collection's selection, so once another preset is selected it describes that one. For filaments it is " + "the preset the Filament tab shows; PresetBundle.current_filament_presets() gives every slot's preset.") + .def( + "preset", + [](PresetCollection& collection, size_t index) -> Preset& { + if (index >= collection.size()) + throw py::index_error("preset index out of range"); + return collection.preset(index); + }, + py::arg("index"), py::return_value_policy::reference_internal, + "The preset at a 0-based index, 0 being the built-in default preset; at the selected index it is the " + "edited copy with unsaved changes. Raises IndexError when index >= size().") + .def( + "find_preset", + [](PresetCollection& collection, const std::string& name) -> Preset* { + return collection.find_preset(name); + }, + py::arg("name"), py::return_value_policy::reference_internal, + "The preset with this internal name (a renamed system preset is also found by a former name), or None. " + "For the selected preset it is the edited copy with unsaved changes. Aliases and display labels do not " + "match.") + .def( + "preset_names", + [](const PresetCollection& collection) { + std::vector names; + names.reserve(collection.get_presets().size()); + for (const Preset& preset : collection.get_presets()) + names.push_back(preset.name); + return names; + }, + "Internal names of all presets in index order, so preset_names()[i] is preset(i).name; the default preset " + "comes first."); - py::class_>(host, "PresetBundle") - .def_property_readonly("prints", [](PresetBundle& bundle) -> PresetCollection& { - return bundle.prints; - }, py::return_value_policy::reference_internal) - .def_property_readonly("printers", &printer_presets, py::return_value_policy::reference_internal) - .def_property_readonly("filaments", [](PresetBundle& bundle) -> PresetCollection& { - return bundle.filaments; - }, py::return_value_policy::reference_internal) - .def_property_readonly("sla_prints", [](PresetBundle& bundle) -> PresetCollection& { - return bundle.sla_prints; - }, py::return_value_policy::reference_internal) - .def_property_readonly("sla_materials", [](PresetBundle& bundle) -> PresetCollection& { - return bundle.sla_materials; - }, py::return_value_policy::reference_internal) - .def("current_process_preset", [](PresetBundle& bundle) -> Preset& { - return bundle.prints.get_edited_preset(); - }, py::return_value_policy::reference_internal) - .def("current_print_preset", [](PresetBundle& bundle) -> Preset& { - return bundle.prints.get_edited_preset(); - }, py::return_value_policy::reference_internal) - .def("current_printer_preset", [](PresetBundle& bundle) -> Preset& { - return bundle.printers.get_edited_preset(); - }, py::return_value_policy::reference_internal) - .def("current_filament_preset_names", [](PresetBundle& bundle) { - return bundle.filament_presets; - }) - .def("current_filament_presets", ¤t_filament_presets) - .def("full_config_keys", [](const PresetBundle& bundle) { - return bundle.full_config().keys(); - }) - .def("full_config_value", [](const PresetBundle& bundle, const std::string& key) { - return config_value_or_none(bundle.full_config(), key); - }); + py::class_>( + host, "PresetBundle", + "All loaded presets and the current selection; orca.host.preset_bundle() returns the app's live bundle. " + "prints, filaments and printers are the PresetCollections; current_process_preset(), current_printer_preset() " + "and current_filament_presets() are the presets in effect, and full_config_value(key) reads the merged " + "settings slicing would use. It only reads: to change a setting use orca.host.preset.process, .filament or " + ".printer (PresetEditor.update(key, value) or begin_update()), which apply it through the settings tab.") + .def_property_readonly( + "prints", [](PresetBundle& bundle) -> PresetCollection& { return bundle.prints; }, + py::return_value_policy::reference_internal, "PresetCollection of process (print settings) presets.") + .def_property_readonly("printers", &printer_presets, py::return_value_policy::reference_internal, + "PresetCollection of printer presets.") + .def_property_readonly( + "filaments", [](PresetBundle& bundle) -> PresetCollection& { return bundle.filaments; }, + py::return_value_policy::reference_internal, + "PresetCollection of filament presets; current_filament_presets() says which one each slot uses.") + .def_property_readonly( + "sla_prints", [](PresetBundle& bundle) -> PresetCollection& { return bundle.sla_prints; }, + py::return_value_policy::reference_internal, + "PresetCollection of SLA print presets; not used by OrcaSlicer's FFF printers.") + .def_property_readonly( + "sla_materials", [](PresetBundle& bundle) -> PresetCollection& { return bundle.sla_materials; }, + py::return_value_policy::reference_internal, + "PresetCollection of SLA resin presets; not used by OrcaSlicer's FFF printers.") + .def( + "current_process_preset", [](PresetBundle& bundle) -> Preset& { return bundle.prints.get_edited_preset(); }, + py::return_value_policy::reference_internal, + "The edited process preset, with its unsaved changes; same as prints.edited_preset().") + .def( + "current_print_preset", [](PresetBundle& bundle) -> Preset& { return bundle.prints.get_edited_preset(); }, + py::return_value_policy::reference_internal, "Same as current_process_preset().") + .def( + "current_printer_preset", + [](PresetBundle& bundle) -> Preset& { return bundle.printers.get_edited_preset(); }, + py::return_value_policy::reference_internal, + "The edited printer preset, with its unsaved changes; same as printers.edited_preset().") + .def( + "current_filament_preset_names", [](PresetBundle& bundle) { return bundle.filament_presets; }, + "Preset name stored for each filament slot, as a new list where index i is slot i + 1.") + .def("current_filament_presets", ¤t_filament_presets, + "The preset assigned to each filament slot, as a list where index i is slot i + 1, with None for a slot " + "whose name matches no preset. A slot assigned the edited filament preset gives the edited copy with " + "unsaved changes.") + .def( + "full_config_keys", [](const PresetBundle& bundle) { return bundle.full_config().keys(); }, + "Names of every setting in the merged config full_config_value() reads.") + .def( + "full_config_value", + [](const PresetBundle& bundle, const std::string& key) { + return config_value_or_none(bundle.full_config(), key); + }, + py::arg("key"), + "Serialized value of one setting from the merged config slicing would use: the edited process and printer " + "presets, each filament slot's preset and the project settings. Per-filament settings hold one value per " + "slot, in slot order. None when key is not a setting. Each call rebuilds the merged config."); } } // namespace Slic3r diff --git a/src/slic3r/plugin/host/PluginHostSlicing.cpp b/src/slic3r/plugin/host/PluginHostSlicing.cpp index 85bc227281..0d082af9df 100644 --- a/src/slic3r/plugin/host/PluginHostSlicing.cpp +++ b/src/slic3r/plugin/host/PluginHostSlicing.cpp @@ -93,61 +93,109 @@ void host_bindings::register_slicing(py::module_& host) // not stash references or arrays across execute() calls; copy what you need. // ------------------------------------------------------------------ - py::enum_(host, "SurfaceType") - .value("stTop", stTop) - .value("stBottom", stBottom) - .value("stBottomBridge", stBottomBridge) - .value("stInternalAfterExternalBridge", stInternalAfterExternalBridge) - .value("stInternal", stInternal) - .value("stInternalSolid", stInternalSolid) - .value("stInternalBridge", stInternalBridge) - .value("stSecondInternalBridge", stSecondInternalBridge) - .value("stInternalVoid", stInternalVoid) - .value("stPerimeter", stPerimeter) - .value("stCount", stCount) + py::enum_(host, "SurfaceType", + "Classification of a Surface, which decides how the slicer prints its area. The values are " + "also exported into orca.host (orca.host.stTop and so on).") + .value("stTop", stTop, "Top surface, visible from above; printed as top solid infill.") + .value("stBottom", stBottom, + "Bottom surface, visible from below and resting on the bed or on support; printed with normal flow.") + .value("stBottomBridge", stBottomBridge, "Bottom surface over air, printed as a bridge with bridging flow.") + .value("stInternalAfterExternalBridge", stInternalAfterExternalBridge, + "Second bridge layer, printed above a bottom bridge.") + .value("stInternal", stInternal, "Sparse infill.") + .value("stInternalSolid", stInternalSolid, + "Solid infill inside the object, below top surfaces or making up the vertical shell thickness.") + .value("stInternalBridge", stInternalBridge, "First solid layer over sparse infill, printed with bridging flow.") + .value("stSecondInternalBridge", stSecondInternalBridge, + "Second solid layer over sparse infill, printed with bridging flow.") + .value("stInternalVoid", stInternalVoid, + "Internal area left without infill on this layer: sparse infill limited to where it supports surfaces " + "above, or combined into a thicker infill layer above.") + .value("stPerimeter", stPerimeter, "Area covered by walls.") + .value("stCount", stCount, "Number of surface types; not a surface type itself.") .export_values(); // Surface: default holder (Python-owned instances are freed), so plugins can construct // their own Surface(surface_type, expolygon) — not just navigate the live slicing graph. // expolygon is a reference_internal property, same idiom as the Polygon/ExPolygon // accessors in PluginHostGeometry.cpp. - py::class_(host, "Surface") + py::class_(host, "Surface", + "One typed area of a layer: an ExPolygon with a SurfaceType and fill hints. A Surface read from " + "LayerRegion.slices or fill_surfaces is a live reference into the slicing graph: valid only " + "while the slicing hook (execute(ctx)) runs, and invalidated by set(), append() or clear() on " + "its collection. A Surface you construct is your own; SurfaceCollection.set() copies it.") .def(py::init([](SurfaceType t, const ExPolygon& e) { return Surface(t, e); }), - py::arg("surface_type"), py::arg("expolygon")) - .def(py::init([](SurfaceType t) { return Surface(t); }), py::arg("surface_type")) + py::arg("surface_type"), py::arg("expolygon"), + "A new surface of surface_type covering a copy of expolygon; thickness and bridge_angle start at -1 " + "(unset) and extra_perimeters at 0.") + .def(py::init([](SurfaceType t) { return Surface(t); }), py::arg("surface_type"), + "A new surface of surface_type with no geometry; assign expolygon before using it.") .def_readwrite("surface_type", &Surface::surface_type, "This surface's SurfaceType. Assigning reclassifies it in place (geometry unchanged).") - .def_readwrite("thickness", &Surface::thickness) - .def_readwrite("bridge_angle", &Surface::bridge_angle) - .def_readwrite("extra_perimeters", &Surface::extra_perimeters) + .def_readwrite("thickness", &Surface::thickness, + "Height in mm of the infill printed for this surface; -1 (unset) means the layer height. The slicer sets " + "it where infill is combined over several layers.") + .def_readwrite("bridge_angle", &Surface::bridge_angle, + "Infill direction in radians, counter-clockwise from +X, used for this surface instead of the region's " + "infill angle when 0 or more; negative (-1 by default) means not set. The slicer sets it on bridges.") + .def_readwrite("extra_perimeters", &Surface::extra_perimeters, + "Walls added to the region's wall_loops for this surface; 0 by default. It takes effect on " + "LayerRegion.slices before walls are generated (Step.posSlice).") .def_property("expolygon", [](Surface& s) -> ExPolygon& { return s.expolygon; }, [](Surface& s, const ExPolygon& e) { s.expolygon = e; }, py::return_value_policy::reference_internal, "This surface's geometry. Read returns a live ExPolygon ref; assign to replace it.") - .def("area", [](const Surface& s) { return s.area(); }) - .def("is_top", [](const Surface& s) { return s.is_top(); }) - .def("is_bottom", [](const Surface& s) { return s.is_bottom(); }) - .def("is_bridge", [](const Surface& s) { return s.is_bridge(); }) - .def("is_internal", [](const Surface& s) { return s.is_internal(); }) - .def("is_external", [](const Surface& s) { return s.is_external(); }) - .def("is_solid", [](const Surface& s) { return s.is_solid(); }); + .def( + "area", [](const Surface& s) { return s.area(); }, + "Area of expolygon (contour minus holes) in scaled units squared; multiply by " + "orca.slicing.unscale(1) ** 2 for mm^2.") + .def( + "is_top", [](const Surface& s) { return s.is_top(); }, "True for stTop.") + .def( + "is_bottom", [](const Surface& s) { return s.is_bottom(); }, "True for stBottom and stBottomBridge.") + .def( + "is_bridge", [](const Surface& s) { return s.is_bridge(); }, + "True for stBottomBridge and stInternalBridge; False for the other bridge types.") + .def( + "is_internal", [](const Surface& s) { return s.is_internal(); }, + "True for every type that is_external() is not, stPerimeter and stInternalVoid included.") + .def( + "is_external", [](const Surface& s) { return s.is_external(); }, + "True for top and bottom surfaces: stTop, stBottom and stBottomBridge.") + .def( + "is_solid", [](const Surface& s) { return s.is_solid(); }, + "True for stTop, stBottom, stBottomBridge, stInternalSolid and stInternalBridge."); // SurfaceCollection: kept on py::nodelete — it is only ever a reference into the live // slicing graph (LayerRegion::slices/fill_surfaces), never constructed by a plugin. - py::class_>(host, "SurfaceCollection") - .def("size", [](const SurfaceCollection& c) { return c.surfaces.size(); }) - .def("empty", [](const SurfaceCollection& c) { return c.empty(); }) - .def("clear", [](SurfaceCollection& c) { c.clear(); }) - .def("has", [](const SurfaceCollection& c, SurfaceType t) { return c.has(t); }, py::arg("surface_type")) - .def("set_type", [](SurfaceCollection& c, SurfaceType t) { c.set_type(t); }, py::arg("surface_type")) + py::class_>( + host, "SurfaceCollection", + "The typed surfaces of one LayerRegion (its slices or fill_surfaces): a live reference into the slicing graph, " + "valid only while the slicing hook (execute(ctx)) runs. set(), append() and clear() invalidate Surface " + "references obtained from it earlier.") + .def( + "size", [](const SurfaceCollection& c) { return c.surfaces.size(); }, "Number of surfaces.") + .def( + "empty", [](const SurfaceCollection& c) { return c.empty(); }, "True when the collection holds no surfaces.") + .def( + "clear", [](SurfaceCollection& c) { c.clear(); }, + "Remove every surface. Invalidates Surface references obtained from this collection.") + .def( + "has", [](const SurfaceCollection& c, SurfaceType t) { return c.has(t); }, py::arg("surface_type"), + "True when any surface has surface_type.") + .def( + "set_type", [](SurfaceCollection& c, SurfaceType t) { c.set_type(t); }, py::arg("surface_type"), + "Retag every surface as surface_type in place; geometry is unchanged and Surface references stay valid.") .def("set", [](SurfaceCollection& c, const std::vector& src, SurfaceType t) { c.set(src, t); }, py::arg("expolygons"), py::arg("surface_type"), "Replace all surfaces from a list of ExPolygon, all tagged `surface_type`.") .def("set", [](SurfaceCollection& c, const std::vector& src) { c.set(src); }, py::arg("surfaces"), "Replace all surfaces from a list of Surface (types preserved per surface).") .def("append", [](SurfaceCollection& c, const std::vector& src, SurfaceType t) { c.append(src, t); }, - py::arg("expolygons"), py::arg("surface_type")) + py::arg("expolygons"), py::arg("surface_type"), + "Add one surface per ExPolygon (copied), each tagged surface_type, after the existing surfaces. " + "Invalidates Surface references obtained from this collection.") .def("filter_by_type", [](py::object self, SurfaceType t) { SurfaceCollection& c = self.cast(); py::list out; @@ -176,12 +224,20 @@ void host_bindings::register_slicing(py::module_& host) // `.entities` child surfaces as a bare ExtrusionEntity (only .role is available). // flatten_paths() (a dynamic_cast walk) still yields proper ExtrusionPath leaves and // is the robust way to extract toolpaths. - py::class_>(host, "ExtrusionEntity") + py::class_>( + host, "ExtrusionEntity", + "Base of the read-only extrusion tree in LayerRegion.perimeters and .fills. Each node comes as its concrete " + "class (ExtrusionEntityCollection, ExtrusionLoop, ExtrusionMultiPath or ExtrusionPath); a node of a class not " + "bound here comes as a bare ExtrusionEntity with only role. A live reference into the slicing graph, valid " + "only while the slicing hook (execute(ctx)) runs.") .def_property_readonly("role", [](const ExtrusionEntity& e) { return ExtrusionEntity::role_to_string(e.role()); }, "Extrusion role as a human-readable string (e.g. \"Outer wall\", \"Sparse infill\")."); - py::class_>(host, "ExtrusionPath") + py::class_>( + host, "ExtrusionPath", + "One extrusion along a polyline with a single role, width, height and flow: the leaf of the extrusion tree. " + "Read-only, and valid only while the slicing hook runs.") .def("points", [](py::object self) { const ExtrusionPath& p = self.cast(); const Points3& pts = p.polyline.points; @@ -189,13 +245,20 @@ void host_bindings::register_slicing(py::module_& host) return py::object(make_readonly_rows( self, pts.empty() ? nullptr : pts.front().data(), (py::ssize_t) pts.size())); }); - }, "Path vertices as a read-only int64 (N,3) numpy view in scaled coords " - "(the polyline is natively 3D on this branch). Requires numpy.") - .def_readonly("width", &ExtrusionPath::width) - .def_readonly("height", &ExtrusionPath::height) - .def_readonly("mm3_per_mm", &ExtrusionPath::mm3_per_mm); + }, "Path vertices as a read-only int64 (N,3) numpy view of x, y, z in scaled coordinates; multiply by " + "orca.slicing.unscale(1) for mm. Requires numpy.") + .def_readonly("width", &ExtrusionPath::width, + "Extrusion width in mm; for a bridge, the diameter of the bridge thread. -1 when unset.") + .def_readonly("height", &ExtrusionPath::height, + "Extrusion height in mm: the layer height, or for a bridge the thread diameter. -1 when unset.") + .def_readonly("mm3_per_mm", &ExtrusionPath::mm3_per_mm, + "Volume of plastic extruded per mm of path, in mm^3 per mm; the G-code generator derives the E amount " + "from it. -1 when unset."); - py::class_>(host, "ExtrusionLoop") + py::class_>( + host, "ExtrusionLoop", + "A closed extrusion, such as one wall loop, made of consecutive ExtrusionPaths whose role, width or flow can " + "change along the loop (at an overhang, for example). Read-only, and valid only while the slicing hook runs.") .def_property_readonly("paths", [](py::object self) { ExtrusionLoop& l = self.cast(); py::list out; @@ -204,7 +267,10 @@ void host_bindings::register_slicing(py::module_& host) return out; }, "The loop's constituent paths as [ExtrusionPath]."); - py::class_>(host, "ExtrusionMultiPath") + py::class_>( + host, "ExtrusionMultiPath", + "An open, continuous extrusion made of consecutive ExtrusionPaths whose role, width or flow can change along " + "it. Read-only, and valid only while the slicing hook runs.") .def_property_readonly("paths", [](py::object self) { ExtrusionMultiPath& m = self.cast(); py::list out; @@ -214,8 +280,14 @@ void host_bindings::register_slicing(py::module_& host) }, "The multipath's constituent paths as [ExtrusionPath]."); py::class_>(host, "ExtrusionEntityCollection") - .def("size", [](const ExtrusionEntityCollection& c) { return c.entities.size(); }) + std::unique_ptr>( + host, "ExtrusionEntityCollection", + "An ordered group of extrusion entities: paths, loops, multipaths or nested collections. LayerRegion.perimeters " + "and .fills are collections of collections. role is \"Multiple\" when the children's roles differ. Read-only, " + "and valid only while the slicing hook runs.") + .def( + "size", [](const ExtrusionEntityCollection& c) { return c.entities.size(); }, + "Number of direct children (entities), not of leaf paths.") .def_property_readonly("entities", [](py::object self) { ExtrusionEntityCollection& c = self.cast(); py::list out; @@ -238,14 +310,25 @@ void host_bindings::register_slicing(py::module_& host) }, "Every leaf ExtrusionPath under this tree (collections recursed into, " "loops/multipaths decomposed)."); - py::class_>(host, "PrintRegion") - .def("config_keys", [](const PrintRegion& r) { return r.config().keys(); }) + py::class_>( + host, "PrintRegion", + "Resolved settings shared by the parts of an object that print alike: walls, infill and the other per-region " + "settings. Parts and modifiers with different settings form separate regions. From LayerRegion.region(); " + "valid only while the slicing hook (execute(ctx)) runs.") + .def( + "config_keys", [](const PrintRegion& r) { return r.config().keys(); }, + "Names of this region's settings (the per-region options such as walls and infill); read one with " + "config_value(key).") .def("config_value", [](const PrintRegion& r, const std::string& key) { return config_value_or_none(r.config(), key); }, py::arg("key"), "Serialized value of this region's resolved config option, or None if absent."); - auto layer_region = py::class_>(host, "LayerRegion"); + auto layer_region = py::class_>( + host, "LayerRegion", + "The part of one Layer printed with one PrintRegion's settings: its sliced surfaces (slices), the surfaces " + "prepared for infill (fill_surfaces) and the walls (perimeters) and infill (fills) generated for them. From " + "Layer.regions(); a live reference valid only while the slicing hook (execute(ctx)) runs."); layer_region .def_readonly("slices", &LayerRegion::slices, "Sliced, typed surfaces (SurfaceCollection). Edit in place, or replace with " @@ -271,11 +354,19 @@ void host_bindings::register_slicing(py::module_& host) }, py::arg("key"), "Serialized value of this region's resolved config option, or None if absent."); - auto layer = py::class_>(host, "Layer"); + auto layer = py::class_>( + host, "Layer", + "One layer of a PrintObject: its heights in mm, merged islands (lslices) and per-region data (regions()). From " + "PrintObject.layers() or support_layers(); a live reference valid only while the slicing hook (execute(ctx)) " + "runs."); layer - .def_readonly("print_z", &Layer::print_z) - .def_readonly("slice_z", &Layer::slice_z) - .def_readonly("height", &Layer::height) + .def_readonly("print_z", &Layer::print_z, + "Z of the top of this layer in mm, measured from the bed with any raft below the object included; the " + "layer's bottom is print_z - height.") + .def_readonly("slice_z", &Layer::slice_z, + "Z in mm at which the object was cut to make this layer, measured from the object's bottom without the " + "raft: normally the middle of the layer, lower when Z anti-aliasing (zaa_enabled) is on.") + .def_readonly("height", &Layer::height, "Thickness of this layer in mm.") .def_property_readonly("upper_layer", [](Layer& l) -> py::object { if (l.upper_layer == nullptr) return py::none(); return py::cast(l.upper_layer, py::return_value_policy::reference); @@ -305,7 +396,12 @@ void host_bindings::register_slicing(py::module_& host) }, "Merged per-layer islands as [ExPolygon] refs (in-place editable). Derived from the " "region slices; call make_slices() to re-derive after edits. Invalidated by make_slices()."); - py::class_>(host, "PrintObject") + py::class_>( + host, "PrintObject", + "One object as sliced: its layers, support layers, transformation and resolved per-object settings. An object " + "identical to another (same mesh and settings) is a PrintObject of its own that may hold the other's Layer " + "objects rather than slicing its own. From Print.objects() or ctx.object; a live reference valid only while " + "the slicing hook (execute(ctx)) runs.") .def("id", [](const PrintObject& o) { return o.id().id; }, "Stable numeric object id (ObjectBase::id()).") .def("layers", [](py::object self) { @@ -336,13 +432,19 @@ void host_bindings::register_slicing(py::module_& host) "sliced polygons live in this same frame, so its midpoint is the footprint center.") .def("trafo", [](const PrintObject& o) { return mat4_to_numpy(o.trafo()); }, "Object-to-print 4x4 float64 affine matrix (copy). Requires numpy.") - .def("config_keys", [](const PrintObject& o) { return o.config().keys(); }) + .def( + "config_keys", [](const PrintObject& o) { return o.config().keys(); }, + "Names of the per-object settings this object resolves (such as layer height and supports); read one with " + "config_value(key).") .def("config_value", [](const PrintObject& o, const std::string& key) { return config_value_or_none(o.config(), key); }, py::arg("key"), "Serialized value of a resolved per-object config option, or None if absent."); - py::class_>(host, "Print") + py::class_>( + host, "Print", + "The plate being sliced: its objects and the resolved full config. Reached as ctx.print in a slicing pipeline " + "hook (orca.slicing); a live reference valid only while that hook runs.") .def("objects", [](py::object self) { Print& p = self.cast(); py::list out; @@ -355,7 +457,10 @@ void host_bindings::register_slicing(py::module_& host) "The Print's own Model snapshot (worker-thread stable). Inside slicing " "hooks use THIS — never orca.host.model(), which is the live GUI model " "owned by another thread.") - .def("config_keys", [](const Print& p) { return p.full_print_config().keys(); }) + .def( + "config_keys", [](const Print& p) { return p.full_print_config().keys(); }, + "Names of every setting in this slice's resolved full config (process, printer and per-filament " + "settings); read one with config_value(key).") .def("config_value", [](const Print& p, const std::string& key) { return config_value_or_none(p.full_print_config(), key); }, py::arg("key"), diff --git a/src/slic3r/plugin/host/PluginHostUi.cpp b/src/slic3r/plugin/host/PluginHostUi.cpp index 7415e635dd..606b2cff89 100644 --- a/src/slic3r/plugin/host/PluginHostUi.cpp +++ b/src/slic3r/plugin/host/PluginHostUi.cpp @@ -778,7 +778,10 @@ void PluginHostUi::RegisterBindings(pybind11::module_& host) ui.attr("WINDOW_MODAL") = py::int_(WINDOW_MODAL); py::class_(ui, "UiWindow", "Handle to a plugin HTML window or modal dialog created by create_window().") - .def_property_readonly("id", [](const UiWindowHandle& h) { return h.id; }) + .def_property_readonly( + "id", [](const UiWindowHandle& h) { return h.id; }, + "Positive integer identifying this window, unique among plugin UI handles for the app's lifetime and " + "never reused; two handles with equal ids refer to the same window.") .def( "post", [](const UiWindowHandle& h, py::object data) { handle_post(h.id, std::move(data)); }, py::arg("data"), "Send a payload to the page (delivered to window.orca.onMessage handlers).") @@ -796,7 +799,10 @@ void PluginHostUi::RegisterBindings(pybind11::module_& host) "is called when the page submits; offload heavy work to a thread and push results back with window.post()."); py::class_(ui, "UiDockPanel", "Handle to a dockable plugin HTML panel created by create_dock_panel().") - .def_property_readonly("id", [](const UiDockPanelHandle& h) { return h.id; }) + .def_property_readonly( + "id", [](const UiDockPanelHandle& h) { return h.id; }, + "Positive integer identifying this panel, unique among plugin UI handles for the app's lifetime and " + "never reused; two handles with equal ids refer to the same panel.") .def( "post", [](const UiDockPanelHandle& h, py::object data) { handle_post(h.id, std::move(data)); }, py::arg("data"), "Send a payload to the page (delivered to window.orca.onMessage handlers).") @@ -822,8 +828,12 @@ void PluginHostUi::RegisterBindings(pybind11::module_& host) py::class_(ui, "ProgressDialog", "Handle to a native progress dialog.") .def(py::init(&new_progress_dialog), py::arg("title"), py::arg("message"), py::arg("maximum") = 100, - py::arg("style") = wxPD_APP_MODAL | wxPD_AUTO_HIDE) - .def_property_readonly("id", [](const UiProgressHandle& h) { return h.id; }) + py::arg("style") = wxPD_APP_MODAL | wxPD_AUTO_HIDE, + "Open a native progress dialog, as create_progress_dialog() does, with the same arguments.") + .def_property_readonly( + "id", [](const UiProgressHandle& h) { return h.id; }, + "Positive integer identifying this progress dialog, unique among plugin UI handles for the app's lifetime " + "and never reused; two handles with equal ids refer to the same dialog.") .def( "pulse", [](const UiProgressHandle& h, const std::string& message) { return progress_pulse(h.id, message); }, py::arg("message") = "", "Pulse the dialog gauge; returns False if the dialog is closed or cancelled.") @@ -855,7 +865,14 @@ void PluginHostUi::RegisterBindings(pybind11::module_& host) ui.def("create_progress_dialog", &ui_create_progress_dialog, py::arg("title"), py::arg("message"), py::arg("maximum") = 100, py::arg("style") = wxPD_APP_MODAL | wxPD_AUTO_HIDE, - "Create a native progress dialog and return a ProgressDialog handle."); + "Create a native progress dialog and return a ProgressDialog handle. maximum is the value update() reaches " + "when the work is done (100 when 0 or less). style combines these flags with |: PD_APP_MODAL disables every " + "other OrcaSlicer window while the dialog shows, not only the one it belongs to (on macOS, only that one " + "either way); PD_AUTO_HIDE hides the dialog once update() reaches maximum, where without it that update() " + "shows \"Done.\" and returns only once the person closes the dialog; PD_CAN_ABORT adds a Cancel button, " + "after which update() and pulse() return False; PD_ELAPSED_TIME, PD_ESTIMATED_TIME and PD_REMAINING_TIME " + "show those times; PD_CAN_SKIP has no effect, as the dialog has no Skip button. The default is " + "PD_APP_MODAL | PD_AUTO_HIDE."); py::enum_(ui, "NotificationLevel") .value("ProgressBarNotificationLevel", GUI::NotificationManager::NotificationLevel::ProgressBarNotificationLevel) diff --git a/src/slic3r/plugin/pluginTypes/pages/PagesPluginCapability.cpp b/src/slic3r/plugin/pluginTypes/pages/PagesPluginCapability.cpp index a9f47cb271..6ada951482 100644 --- a/src/slic3r/plugin/pluginTypes/pages/PagesPluginCapability.cpp +++ b/src/slic3r/plugin/pluginTypes/pages/PagesPluginCapability.cpp @@ -27,12 +27,23 @@ void PagesPluginCapability::RegisterBindings(pybind11::module_& module) auto pages = module.def_submodule("pages", "Plugin page API"); py::class_>(pages, "PagesPluginCapabilityBase") + std::shared_ptr>( + pages, "PagesPluginCapabilityBase", + "Base for a page capability: a tab in OrcaSlicer's main window, labelled with get_name(), that shows\n" + "the HTML get_ui() returns. The page sends data to the plugin with window.orca.postMessage(data), which\n" + "calls on_message(), and receives what post_message() sends through window.orca.onMessage(callback).") .def(py::init<>()) - .def("get_type", &PagesPluginCapability::get_type) - .def("get_ui", &PagesPluginCapability::get_ui) - .def("get_icon", &PagesPluginCapability::get_icon) - .def("on_message", &PagesPluginCapability::on_message) + .def("get_type", &PagesPluginCapability::get_type, "Return PluginType.Pages.") + .def("get_ui", &PagesPluginCapability::get_ui, + "Required. Return the page as an HTML document string. Called when the tab is first shown and again\n" + "whenever the page reloads.") + .def("get_icon", &PagesPluginCapability::get_icon, + "Return the tab icon: an absolute path to an .svg or .png file, or the name of an image bundled with\n" + "OrcaSlicer. Called once when the tab is created. The default returns \"\", for no icon.") + .def("on_message", &PagesPluginCapability::on_message, py::arg("data"), + "Called on the UI thread when the page calls window.orca.postMessage(data). Receives data decoded\n" + "from JSON: a dict, list, str, number, bool or None. The return value is ignored; answer with\n" + "post_message(). The default does nothing.") .def( "post_message", [](PagesPluginCapability& capability, py::object data) { diff --git a/src/slic3r/plugin/pluginTypes/printerAgent/PrinterAgentPluginCapability.cpp b/src/slic3r/plugin/pluginTypes/printerAgent/PrinterAgentPluginCapability.cpp index eac19199bf..b6a5db1edc 100644 --- a/src/slic3r/plugin/pluginTypes/printerAgent/PrinterAgentPluginCapability.cpp +++ b/src/slic3r/plugin/pluginTypes/printerAgent/PrinterAgentPluginCapability.cpp @@ -22,133 +22,320 @@ void PrinterAgentPluginCapability::RegisterBindings(pybind11::module_& module) { auto printer_agent_module = module.def_submodule("printer_agent", "Printer Agent API"); - py::enum_(printer_agent_module, "FilamentSyncMode") - .value("None_", FilamentSyncMode::none) - .value("Subscription", FilamentSyncMode::subscription) - .value("Pull", FilamentSyncMode::pull) + py::enum_(printer_agent_module, "FilamentSyncMode", + "How the host gets a printer's filament (AMS) data; returned by\n" + "PrinterAgentBase.get_filament_sync_mode().") + .value("None_", FilamentSyncMode::none, "The agent provides no filament data.") + .value("Subscription", FilamentSyncMode::subscription, + "The printer's status messages carry the filament data as it changes.") + .value("Pull", FilamentSyncMode::pull, "The host calls fetch_filament_info() whenever it needs the data.") .export_values(); - py::enum_(printer_agent_module, "CameraStreamMode") - .value("None_", CameraStreamMode::none) - .value("HTTP", CameraStreamMode::http) - .value("HTTPS", CameraStreamMode::https) - .value("HTTP_SNAPSHOT", CameraStreamMode::http_snapshot) - .value("RTSP", CameraStreamMode::rtsp) + py::enum_(printer_agent_module, "CameraStreamMode", + "How the host shows a printer's camera; returned by\n" + "PrinterAgentBase.get_camera_stream_mode(). Every mode but None_ plays the URL from\n" + "get_camera_url().") + .value("None_", CameraStreamMode::none, "The printer has no camera view.") + .value("HTTP", CameraStreamMode::http, "An http:// video stream.") + .value("HTTPS", CameraStreamMode::https, "An https:// video stream.") + .value("HTTP_SNAPSHOT", CameraStreamMode::http_snapshot, "An HTTP endpoint that returns one image per request.") + .value("RTSP", CameraStreamMode::rtsp, "An rtsp:// stream on the LAN.") .export_values(); - py::class_(printer_agent_module, "AgentInfo") + py::class_(printer_agent_module, "AgentInfo", + "Identity of a printer agent, returned by PrinterAgentBase.get_agent_info().") .def(py::init<>()) .def(py::init([](std::string id, std::string name, std::string version, std::string description) { return AgentInfo{std::move(id), std::move(name), std::move(version), std::move(description)}; }), - py::arg("id"), py::arg("name"), py::arg("version"), py::arg("description")) - .def_readwrite("id", &AgentInfo::id) - .def_readwrite("name", &AgentInfo::name) - .def_readwrite("version", &AgentInfo::version) - .def_readwrite("description", &AgentInfo::description); + py::arg("id"), py::arg("name"), py::arg("version"), py::arg("description"), + "An AgentInfo with these fields, each as its property describes; AgentInfo() leaves them all empty.") + .def_readwrite("id", &AgentInfo::id, + "Agent id, e.g. \"moonraker\". Printer presets select their agent by this id, so it must be\n" + "non-empty and must not change; a capability whose id another agent already uses is disabled.") + .def_readwrite("name", &AgentInfo::name, "Name shown to the user, e.g. \"Moonraker\".") + .def_readwrite("version", &AgentInfo::version, "Agent version string, e.g. \"1.0.0\".") + .def_readwrite("description", &AgentInfo::description, "Short description of the agent."); - py::class_(printer_agent_module, "DetectResult") + py::class_(printer_agent_module, "DetectResult", + "What PrinterAgentBase.bind_detect() reports about a printer found at an IP address.") .def(py::init<>()) - .def_readwrite("result_msg", &detectResult::result_msg) - .def_readwrite("command", &detectResult::command) - .def_readwrite("dev_id", &detectResult::dev_id) - .def_readwrite("model_id", &detectResult::model_id) - .def_readwrite("dev_name", &detectResult::dev_name) - .def_readwrite("version", &detectResult::version) - .def_readwrite("bind_state", &detectResult::bind_state) - .def_readwrite("connect_type", &detectResult::connect_type); + .def_readwrite("result_msg", &detectResult::result_msg, "Detail text. The host does not read it.") + .def_readwrite("command", &detectResult::command, "The host does not read it.") + .def_readwrite("dev_id", &detectResult::dev_id, "The printer's device id (serial number).") + .def_readwrite("model_id", &detectResult::model_id, + "The printer's model id, stored as the device's printer type.") + .def_readwrite("dev_name", &detectResult::dev_name, "The printer's display name.") + .def_readwrite("version", &detectResult::version, "The printer's firmware version.") + .def_readwrite("bind_state", &detectResult::bind_state, + "\"free\" when the printer can be added, \"occupied\" when it is bound to another account (the\n" + "host then refuses it).") + .def_readwrite("connect_type", &detectResult::connect_type, + "\"lan\" for a printer in LAN-only mode, \"cloud\" for one in cloud mode (the host then asks\n" + "the user to switch it to LAN only)."); - py::class_(printer_agent_module, "PrintParams") + py::class_(printer_agent_module, "PrintParams", + "A print or send job, passed to the PrinterAgentBase start_* methods. A send job sets\n" + "fewer fields than a print job; the print options hold no meaningful value there.") .def(py::init<>()) - .def_readwrite("dev_id", &PrintParams::dev_id) - .def_readwrite("task_name", &PrintParams::task_name) - .def_readwrite("project_name", &PrintParams::project_name) - .def_readwrite("preset_name", &PrintParams::preset_name) - .def_readwrite("filename", &PrintParams::filename) - .def_readwrite("config_filename", &PrintParams::config_filename) - .def_readwrite("plate_index", &PrintParams::plate_index) - .def_readwrite("ftp_folder", &PrintParams::ftp_folder) - .def_readwrite("ftp_file", &PrintParams::ftp_file) - .def_readwrite("ftp_file_md5", &PrintParams::ftp_file_md5) - .def_readwrite("nozzle_mapping", &PrintParams::nozzle_mapping) - .def_readwrite("ams_mapping", &PrintParams::ams_mapping) - .def_readwrite("ams_mapping2", &PrintParams::ams_mapping2) - .def_readwrite("ams_mapping_info", &PrintParams::ams_mapping_info) - .def_readwrite("nozzles_info", &PrintParams::nozzles_info) - .def_readwrite("connection_type", &PrintParams::connection_type) - .def_readwrite("comments", &PrintParams::comments) - .def_readwrite("origin_profile_id", &PrintParams::origin_profile_id) - .def_readwrite("stl_design_id", &PrintParams::stl_design_id) - .def_readwrite("origin_model_id", &PrintParams::origin_model_id) - .def_readwrite("print_type", &PrintParams::print_type) - .def_readwrite("dst_file", &PrintParams::dst_file) - .def_readwrite("dev_name", &PrintParams::dev_name) - .def_readwrite("dev_ip", &PrintParams::dev_ip) - .def_readwrite("use_ssl_for_ftp", &PrintParams::use_ssl_for_ftp) - .def_readwrite("use_ssl_for_mqtt", &PrintParams::use_ssl_for_mqtt) - .def_readwrite("username", &PrintParams::username) - .def_readwrite("password", &PrintParams::password) - .def_readwrite("task_bed_leveling", &PrintParams::task_bed_leveling) - .def_readwrite("task_flow_cali", &PrintParams::task_flow_cali) - .def_readwrite("task_vibration_cali", &PrintParams::task_vibration_cali) - .def_readwrite("task_layer_inspect", &PrintParams::task_layer_inspect) - .def_readwrite("task_record_timelapse", &PrintParams::task_record_timelapse) - .def_readwrite("task_use_ams", &PrintParams::task_use_ams) - .def_readwrite("task_bed_type", &PrintParams::task_bed_type) - .def_readwrite("extra_options", &PrintParams::extra_options) - .def_readwrite("auto_bed_leveling", &PrintParams::auto_bed_leveling) - .def_readwrite("auto_flow_cali", &PrintParams::auto_flow_cali) - .def_readwrite("auto_offset_cali", &PrintParams::auto_offset_cali) - .def_readwrite("task_ext_change_assist", &PrintParams::task_ext_change_assist) - .def_readwrite("try_emmc_print", &PrintParams::try_emmc_print); + .def_readwrite("dev_id", &PrintParams::dev_id, "Device id of the target printer.") + .def_readwrite("task_name", &PrintParams::task_name, "Task name. The host leaves it empty.") + .def_readwrite("project_name", &PrintParams::project_name, + "Job name for the printer: the project or model name for a print, \".gcode.3mf\"\n" + "for a send, and \"verify_job\" for the connection check (see start_send_gcode_to_sdcard()).") + .def_readwrite("preset_name", &PrintParams::preset_name, + "Name of the print profile for the job record, or \"_plate_\" when none is known.") + .def_readwrite("filename", &PrintParams::filename, + "Local path of the file to send: a .3mf holding the sliced plate's G-code, or a small\n" + "temporary file for the connection check.") + .def_readwrite("config_filename", &PrintParams::config_filename, + "Local path of a .3mf holding only the project's configuration.") + .def_readwrite("plate_index", &PrintParams::plate_index, + "1-based number of the plate to print, whose G-code is inside filename.") + .def_readwrite("ftp_folder", &PrintParams::ftp_folder, + "Folder on the printer's storage to upload into, from the printer model's profile; empty when\n" + "the model defines none.") + .def_readwrite("ftp_file", &PrintParams::ftp_file, "The host leaves it empty.") + .def_readwrite("ftp_file_md5", &PrintParams::ftp_file_md5, "The host leaves it empty.") + .def_readwrite("nozzle_mapping", &PrintParams::nozzle_mapping, + "JSON nozzle mapping for printers with several nozzles; empty otherwise.") + .def_readwrite("ams_mapping", &PrintParams::ams_mapping, + "JSON array with one entry per project filament: the printer tray index it prints from, or -1\n" + "when it has none or uses an external spool.") + .def_readwrite("ams_mapping2", &PrintParams::ams_mapping2, + "JSON array with one {\"ams_id\": int, \"slot_id\": int} object per project filament; both are\n" + "255 when the filament is not mapped.") + .def_readwrite("ams_mapping_info", &PrintParams::ams_mapping_info, + "JSON array with one object per project filament, holding ams (tray index or -1),\n" + "sourceColor, targetColor, filamentId, filamentType and nozzleId.") + .def_readwrite("nozzles_info", &PrintParams::nozzles_info, + "JSON array describing the printer's nozzles; filled only for two-nozzle printers.") + .def_readwrite("connection_type", &PrintParams::connection_type, + "\"lan\" for a printer in LAN-only mode, \"cloud\" otherwise.") + .def_readwrite("comments", &PrintParams::comments, + "Note the host sets on the cloud print path saying why a LAN send was not used or failed,\n" + "e.g. \"no_ip\", \"low_version\", \"no_sdcard\", \"no_password\", \"upload_failed\" or\n" + "\"failed()\".") + .def_readwrite("origin_profile_id", &PrintParams::origin_profile_id, + "Designer profile id from the project's 3MF metadata, or 0.") + .def_readwrite("stl_design_id", &PrintParams::stl_design_id, + "Online model library design id of the project's model, or 0.") + .def_readwrite("origin_model_id", &PrintParams::origin_model_id, + "Designer model id from the project's 3MF metadata, or empty.") + .def_readwrite("print_type", &PrintParams::print_type, + "\"from_normal\" for a sliced project, \"from_sdcard_view\" for a file already on the\n" + "printer's storage.") + .def_readwrite("dst_file", &PrintParams::dst_file, + "Path of the file on the printer's storage when print_type is \"from_sdcard_view\".") + .def_readwrite("dev_name", &PrintParams::dev_name, + "Printer display name. Set only for jobs sent to several printers at once.") + .def_readwrite("dev_ip", &PrintParams::dev_ip, "IP address of the printer.") + .def_readwrite("use_ssl_for_ftp", &PrintParams::use_ssl_for_ftp, "Whether the file upload should use TLS.") + .def_readwrite("use_ssl_for_mqtt", &PrintParams::use_ssl_for_mqtt, + "Whether the printer's LAN message connection should use TLS.") + .def_readwrite("username", &PrintParams::username, + "LAN user name. The host takes it from the agent's default LAN user name, which is empty for a\n" + "plugin agent.") + .def_readwrite("password", &PrintParams::password, "The access code stored for the printer.") + .def_readwrite("task_bed_leveling", &PrintParams::task_bed_leveling, "Level the bed before printing.") + .def_readwrite("task_flow_cali", &PrintParams::task_flow_cali, "Run flow dynamics calibration before printing.") + .def_readwrite("task_vibration_cali", &PrintParams::task_vibration_cali, + "Run vibration compensation calibration before printing.") + .def_readwrite("task_layer_inspect", &PrintParams::task_layer_inspect, "Inspect the first layer.") + .def_readwrite("task_record_timelapse", &PrintParams::task_record_timelapse, "Record a timelapse.") + .def_readwrite("task_use_ams", &PrintParams::task_use_ams, + "Feed filament from the AMS rather than an external spool.") + .def_readwrite("task_bed_type", &PrintParams::task_bed_type, + "Plate type: \"cool_plate\", \"textured_cool_plate\", \"eng_plate\", \"hot_plate\",\n" + "\"textured_plate\", \"supertack_plate\" or \"unknown\".") + .def_readwrite("extra_options", &PrintParams::extra_options, "The host leaves it empty.") + .def_readwrite("auto_bed_leveling", &PrintParams::auto_bed_leveling, + "Bed leveling choice: 0 off, 1 on, 2 auto.") + .def_readwrite("auto_flow_cali", &PrintParams::auto_flow_cali, + "Flow dynamics calibration choice: 0 off, 1 on, 2 auto.") + .def_readwrite("auto_offset_cali", &PrintParams::auto_offset_cali, + "Nozzle offset calibration choice: 0 off, 1 on, 2 auto.") + .def_readwrite("task_ext_change_assist", &PrintParams::task_ext_change_assist, + "The user changes the external spool by hand for a multi-color print.") + .def_readwrite("try_emmc_print", &PrintParams::try_emmc_print, + "Send the job to the printer's internal (eMMC) storage rather than its SD card."); - py::class_(printer_agent_module, "PrinterConnectionParams") + py::class_(printer_agent_module, "PrinterConnectionParams", + "Where and how to reach a LAN printer; passed to\n" + "PrinterAgentBase.connect_printer().") .def(py::init<>()) - .def_readwrite("dev_id", &PrinterConnectionParams::dev_id) - .def_readwrite("host", &PrinterConnectionParams::host) - .def_readwrite("port", &PrinterConnectionParams::port) - .def_readwrite("username", &PrinterConnectionParams::username) - .def_readwrite("password", &PrinterConnectionParams::password) - .def_readwrite("use_ssl", &PrinterConnectionParams::use_ssl) - .def_readwrite("ca_file", &PrinterConnectionParams::ca_file); + .def_readwrite("dev_id", &PrinterConnectionParams::dev_id, "The printer's device id.") + .def_readwrite("host", &PrinterConnectionParams::host, + "Host name or IP address, without the http:// or https:// prefix.") + .def_readwrite("port", &PrinterConnectionParams::port, + "Port as a string, from the printer address or the preset's printhost_port; empty when unset.") + .def_readwrite("username", &PrinterConnectionParams::username, + "LAN user name: the agent's default LAN user name, which is empty for a plugin agent.") + .def_readwrite("password", &PrinterConnectionParams::password, + "The access code or API key stored for the printer.") + .def_readwrite("use_ssl", &PrinterConnectionParams::use_ssl, "True when the printer address starts with https.") + .def_readwrite("ca_file", &PrinterConnectionParams::ca_file, + "Path of a CA certificate file from the preset's printhost_cafile, or empty."); py::class_>( - printer_agent_module, "PrinterAgentBase") + printer_agent_module, "PrinterAgentBase", + "Base for a printer agent capability: the protocol OrcaSlicer uses to find printers, connect to them,\n" + "send them commands and start print jobs. A printer preset picks its agent by get_agent_info().id.\n" + "\n" + "Methods marked Required must be overridden: without one the host logs an error and gets the failure\n" + "value. Methods returning an int return 0 on success and a negative error code on failure. A command\n" + "the agent cannot translate returns -7010, one this printer lacks returns -7020, and the host shows a\n" + "dialog for both. An exception raised by any method is logged and the host gets -1, or False, \"\" or\n" + "the default value for other return types. In the command_* methods, sequence_id is the command id the\n" + "host tracks and lan_mode is True for a printer in LAN-only mode.\n" + "\n" + "The agent reports back through callables the host hands over with these methods, which the plugin\n" + "also implements by name, storing the callable (None clears it) and returning 0:\n" + "set_on_local_connect_fn(fn) with fn(status, dev_id, msg), status 0 connected, 1 failed, 2 lost;\n" + "set_on_local_message_fn(fn) and set_on_message_fn(fn) with fn(dev_id, json_msg) for messages from\n" + "LAN and cloud printers; set_on_user_message_fn(fn) with fn(dev_id, json_msg);\n" + "set_on_printer_connected_fn(fn) with fn(dev_id); set_on_subscribe_failure_fn(fn) with fn(dev_id);\n" + "set_on_ssdp_msg_fn(fn) with fn(device_json) for discovered printers (see start_discovery());\n" + "set_queue_on_main_fn(fn) with fn(callable), which runs callable on the UI thread; and\n" + "set_server_callback(fn) with fn(url, http_status).") .def(py::init<>()) - .def("get_type", &PrinterAgentPluginCapability::get_type) - .def("get_agent_info", &PrinterAgentPluginCapability::get_agent_info) - .def("connect_printer", &PrinterAgentPluginCapability::connect_printer) - .def("disconnect_printer", &PrinterAgentPluginCapability::disconnect_printer) - .def("send_message", &PrinterAgentPluginCapability::send_message) - .def("send_message_to_printer", &PrinterAgentPluginCapability::send_message_to_printer) - .def("command_ams_refresh_rfid", &PrinterAgentPluginCapability::command_ams_refresh_rfid) - .def("command_ams_calibrate", &PrinterAgentPluginCapability::command_ams_calibrate) - .def("command_ams_select_tray", &PrinterAgentPluginCapability::command_ams_select_tray) - .def("command_start_camera", &PrinterAgentPluginCapability::command_start_camera) - .def("command_xyz_abs", &PrinterAgentPluginCapability::command_xyz_abs) - .def("command_auto_leveling", &PrinterAgentPluginCapability::command_auto_leveling) - .def("command_go_home", &PrinterAgentPluginCapability::command_go_home) - .def("command_set_bed", &PrinterAgentPluginCapability::command_set_bed) - .def("command_set_nozzle", &PrinterAgentPluginCapability::command_set_nozzle) - .def("command_axis_control", &PrinterAgentPluginCapability::command_axis_control) - .def("start_discovery", &PrinterAgentPluginCapability::start_discovery) - .def("bind_detect", &PrinterAgentPluginCapability::bind_detect) - .def("get_user_selected_machine", &PrinterAgentPluginCapability::get_user_selected_machine) - .def("set_user_selected_machine", &PrinterAgentPluginCapability::set_user_selected_machine) - .def("start_send_gcode_to_sdcard", &PrinterAgentPluginCapability::start_send_gcode_to_sdcard) - .def("start_local_print", &PrinterAgentPluginCapability::start_local_print) - .def("get_filament_sync_mode", &PrinterAgentPluginCapability::get_filament_sync_mode) - .def("get_camera_stream_mode", &PrinterAgentPluginCapability::get_camera_stream_mode) - .def("fetch_filament_info", &PrinterAgentPluginCapability::fetch_filament_info) - .def("get_camera_url", &PrinterAgentPluginCapability::get_camera_url) - .def("check_cert", &PrinterAgentPluginCapability::check_cert) - .def("install_device_cert", &PrinterAgentPluginCapability::install_device_cert) - .def("ping_bind", &PrinterAgentPluginCapability::ping_bind) - .def("bind", &PrinterAgentPluginCapability::bind) - .def("unbind", &PrinterAgentPluginCapability::unbind) - .def("start_print", &PrinterAgentPluginCapability::start_print) - .def("start_local_print_with_record", &PrinterAgentPluginCapability::start_local_print_with_record) - .def("start_sdcard_print", &PrinterAgentPluginCapability::start_sdcard_print); + .def("get_type", &PrinterAgentPluginCapability::get_type, "Return PluginType.PrinterConnection.") + .def("get_agent_info", &PrinterAgentPluginCapability::get_agent_info, + "Required. Return the AgentInfo identifying this agent. The host reads it when it registers the\n" + "capability and whenever it checks which agent is active, so return the same values every time.") + .def("connect_printer", &PrinterAgentPluginCapability::connect_printer, py::arg("params"), + "Required. Called to connect to a LAN printer described by params, a PrinterConnectionParams. Start\n" + "connecting, in the background if it takes time, and report the outcome through the\n" + "set_on_local_connect_fn() callable. Return 0 when the attempt started, a negative code otherwise.") + .def("disconnect_printer", &PrinterAgentPluginCapability::disconnect_printer, + "Required. Close the connection connect_printer() opened. Called when the user switches printers or\n" + "agents and when OrcaSlicer closes, which waits at most 3 seconds for it. Return 0 on success.") + .def("send_message", &PrinterAgentPluginCapability::send_message, py::arg("dev_id"), py::arg("json_str"), + py::arg("qos"), py::arg("flag"), + "Required. Send a command to a printer that is not in LAN-only mode, through the cloud.\n" + "json_str is a Bambu-style JSON command such as\n" + "{\"print\": {\"command\": \"gcode_line\", \"param\": \"G28\\n\", \"sequence_id\": \"1\"}};\n" + "qos is the MQTT QoS level, 0 or 1; the host always passes flag=0. Return 0 when sent.") + .def("send_message_to_printer", &PrinterAgentPluginCapability::send_message_to_printer, py::arg("dev_id"), + py::arg("json_str"), py::arg("qos"), py::arg("flag"), + "Required. Send a command straight to a printer in LAN-only mode. The arguments and return value\n" + "are those of send_message().") + .def("command_ams_refresh_rfid", &PrinterAgentPluginCapability::command_ams_refresh_rfid, py::arg("dev_id"), + py::arg("ams_id"), py::arg("slot_id"), py::arg("sequence_id"), py::arg("lan_mode"), + "Ask the printer to re-read the RFID tag of slot slot_id in AMS unit ams_id. When ams_id is -1,\n" + "slot_id is a tray index counted across all units (unit * 4 + slot). The default returns -7010.") + .def("command_ams_calibrate", &PrinterAgentPluginCapability::command_ams_calibrate, py::arg("dev_id"), + py::arg("ams_id"), py::arg("sequence_id"), py::arg("lan_mode"), + "Ask the printer to calibrate AMS unit ams_id. The default returns -7010.") + .def("command_ams_select_tray", &PrinterAgentPluginCapability::command_ams_select_tray, py::arg("dev_id"), + py::arg("tray_id"), py::arg("sequence_id"), py::arg("lan_mode"), + "Ask the printer to load filament from a tray; tray_id is the tray index counted across all AMS units\n" + "(unit * 4 + slot), as a string. The default returns -7010.") + .def("command_start_camera", &PrinterAgentPluginCapability::command_start_camera, py::arg("dev_id"), + "Ask the printer to start its camera. The default returns -7010.") + .def("command_xyz_abs", &PrinterAgentPluginCapability::command_xyz_abs, py::arg("dev_id"), + py::arg("sequence_id"), py::arg("lan_mode"), + "Switch the printer to absolute positioning. The default sends G90 as a gcode_line command through\n" + "send_message_to_printer() when lan_mode is True, send_message() otherwise.") + .def("command_auto_leveling", &PrinterAgentPluginCapability::command_auto_leveling, py::arg("dev_id"), + py::arg("sequence_id"), py::arg("lan_mode"), + "Level the bed. The default sends G29 as a gcode_line command, as command_xyz_abs() does.") + .def("command_go_home", &PrinterAgentPluginCapability::command_go_home, py::arg("dev_id"), + py::arg("is_printing"), py::arg("supports_mqtt_homing"), py::arg("sequence_id"), py::arg("lan_mode"), + "Home the axes. is_printing is True while the printer prints. The default sends the\n" + "back_to_center command when supports_mqtt_homing is True, otherwise G28 (G28 X while printing).") + .def("command_set_bed", &PrinterAgentPluginCapability::command_set_bed, py::arg("dev_id"), py::arg("temp"), + py::arg("supports_mqtt_bed_ctrl"), py::arg("sequence_id"), py::arg("lan_mode"), + "Set the bed temperature to temp, in degrees Celsius. The default sends the set_bed_temp command when\n" + "supports_mqtt_bed_ctrl is True, otherwise M140.") + .def("command_set_nozzle", &PrinterAgentPluginCapability::command_set_nozzle, py::arg("dev_id"), + py::arg("temp"), py::arg("sequence_id"), py::arg("lan_mode"), + "Set the nozzle temperature to temp, in degrees Celsius. The default sends M104.") + .def("command_axis_control", &PrinterAgentPluginCapability::command_axis_control, py::arg("dev_id"), + py::arg("axis"), py::arg("unit"), py::arg("input_val"), py::arg("speed"), py::arg("is_core_xy"), + py::arg("supports_mqtt_axis_control"), py::arg("sequence_id"), py::arg("lan_mode"), + "Jog one axis. axis is \"X\", \"Y\", \"Z\" or \"E\"; the move is input_val * unit millimeters,\n" + "negative to go back; speed is the feed rate in mm/min; is_core_xy says whether the printer is\n" + "CoreXY. The default sends a relative G1 move (G0 after M83 for E), inverting Y and Z moves when\n" + "is_core_xy is False, and returns -1 for any other axis.") + .def("start_discovery", &PrinterAgentPluginCapability::start_discovery, py::arg("start"), py::arg("sending"), + "Required. Called with start=True when OrcaSlicer starts looking for printers and start=False when\n" + "it stops; the host always passes sending=False. Report each printer found by calling the\n" + "set_on_ssdp_msg_fn() callable with a JSON string holding dev_id, dev_name, dev_ip, dev_type,\n" + "dev_signal, connect_type and bind_state, plus optional sec_link, ssdp_version and connection_name.\n" + "Return True on success.") + .def("bind_detect", &PrinterAgentPluginCapability::bind_detect, py::arg("dev_ip"), py::arg("sec_link"), + py::arg("detect"), + "Required. Called when the user adds a printer by IP address dev_ip; the host passes\n" + "sec_link=\"secure\". Set the fields of detect, a DetectResult the host reads afterwards, in place.\n" + "Return 0 on success; on failure -1 tells the user the connection failed and -2 that the login\n" + "request could not be sent.") + .def("get_user_selected_machine", &PrinterAgentPluginCapability::get_user_selected_machine, + "Required. Return the device id last stored by set_user_selected_machine(), or \"\".") + .def("set_user_selected_machine", &PrinterAgentPluginCapability::set_user_selected_machine, py::arg("dev_id"), + "Required. Called with the device id of the printer the user selects, or \"\" to clear the\n" + "selection. Store it for get_user_selected_machine() and return 0.") + .def("start_send_gcode_to_sdcard", &PrinterAgentPluginCapability::start_send_gcode_to_sdcard, + py::arg("params"), py::arg("update_fn"), py::arg("cancel_fn"), py::arg("wait_fn"), + "Required. Upload params.filename to the printer's storage without starting it. Before a LAN\n" + "print or send, the host also calls it as a connection check, with project_name \"verify_job\", a\n" + "small temporary file and None for all three callables; return 0 when that upload works. See\n" + "start_print() for the callables and the return value.") + .def("start_local_print", &PrinterAgentPluginCapability::start_local_print, py::arg("params"), + py::arg("update_fn"), py::arg("cancel_fn"), + "Required. Upload the job to a printer in LAN-only mode and start it. params is a PrintParams; see\n" + "start_print() for the callables and the return value.") + .def("get_filament_sync_mode", &PrinterAgentPluginCapability::get_filament_sync_mode, + "Return the FilamentSyncMode saying how the host gets the printer's filament data. The default is\n" + "FilamentSyncMode.None_.") + .def("get_camera_stream_mode", &PrinterAgentPluginCapability::get_camera_stream_mode, + "Return the CameraStreamMode saying how the host shows the printer's camera. The default is\n" + "CameraStreamMode.None_.") + .def("fetch_filament_info", &PrinterAgentPluginCapability::fetch_filament_info, py::arg("dev_id"), + py::arg("sync_mode"), + "Called when get_filament_sync_mode() is Pull, before the host reads the printer's filament slots;\n" + "sync_mode is FilamentSyncMode.Pull. Refresh the data and return True, or False when none is\n" + "available. The default returns False.") + .def("get_camera_url", &PrinterAgentPluginCapability::get_camera_url, + "Return the camera URL of the connected printer, played as get_camera_stream_mode() says. The\n" + "default returns \"\".") + .def("check_cert", &PrinterAgentPluginCapability::check_cert, + "Return 0 when the user's certificate for the printer is valid. The host does not call it.") + .def("install_device_cert", &PrinterAgentPluginCapability::install_device_cert, py::arg("dev_id"), + py::arg("lan_only"), + "Called for the selected printer after it connects and again periodically, to install or refresh\n" + "its certificate for TLS; lan_only is True for a printer in LAN-only mode. Returns nothing. The\n" + "default does nothing.") + .def("ping_bind", &PrinterAgentPluginCapability::ping_bind, py::arg("ping_code"), + "Required. Called with the PIN code the user typed to bind a printer to the signed-in account.\n" + "Return 0 when it is accepted, a negative value otherwise.") + .def("bind", &PrinterAgentPluginCapability::bind, py::arg("dev_ip"), py::arg("dev_id"), py::arg("dev_model"), + py::arg("sec_link"), py::arg("timezone"), py::arg("improved"), py::arg("update_fn"), + "Required. Bind the printer to the signed-in account. dev_model is the model name shown to the\n" + "user, sec_link the value the printer announced at discovery, timezone the local offset such as\n" + "\"UTC+08:00\", and improved whether the user joined the user experience improvement program.\n" + "Report progress by calling update_fn(stage, code, msg), stage 0 to 5 from connecting to\n" + "finished, code 0 or a negative error code. Return 0 on success.") + .def("unbind", &PrinterAgentPluginCapability::unbind, py::arg("dev_id"), + "Required. Remove the printer from the signed-in account. Return 0 on success.") + .def("start_print", &PrinterAgentPluginCapability::start_print, py::arg("params"), py::arg("update_fn"), + py::arg("cancel_fn"), py::arg("wait_fn"), + "Required. Start a print through the cloud, for a printer that is not in LAN-only mode. params is a\n" + "PrintParams. Report progress by calling update_fn(stage, code, msg): stage 0 create, 1 upload,\n" + "2 waiting, 3 sending, 4 record, 5 wait for printer, 6 finished, 7 error; code is a percentage\n" + "during upload and record, or a negative error code. cancel_fn() returns True once the user\n" + "cancelled; return -18 then. wait_fn(stage, job_info_json) waits until the printer has taken the\n" + "job and returns True. Any callable may be None. Return 0 on success or a negative error code,\n" + "e.g. -14 file not found, -4020 LAN upload failed, -5010 upload to storage failed.") + .def("start_local_print_with_record", &PrinterAgentPluginCapability::start_local_print_with_record, + py::arg("params"), py::arg("update_fn"), py::arg("cancel_fn"), py::arg("wait_fn"), + "Required. Upload the job over the LAN to a printer that is not in LAN-only mode and start it, also\n" + "recording it with the cloud. After a negative result the host normally falls back to start_print().\n" + "See start_print() for the arguments and the return value.") + .def("start_sdcard_print", &PrinterAgentPluginCapability::start_sdcard_print, py::arg("params"), + py::arg("update_fn"), py::arg("cancel_fn"), + "Required. Print a file already on the printer's storage, named by params.dst_file. See\n" + "start_print() for the callables and the return value."); } } // namespace Slic3r diff --git a/src/slic3r/plugin/pluginTypes/resourceTexture/ResourceTexturePluginCapability.cpp b/src/slic3r/plugin/pluginTypes/resourceTexture/ResourceTexturePluginCapability.cpp index ce58708842..7050f54f00 100644 --- a/src/slic3r/plugin/pluginTypes/resourceTexture/ResourceTexturePluginCapability.cpp +++ b/src/slic3r/plugin/pluginTypes/resourceTexture/ResourceTexturePluginCapability.cpp @@ -22,11 +22,17 @@ void ResourceTexturePluginCapability::RegisterBindings(pybind11::module_& module py::class_>(resource_texture, - "ResourceTexturePluginCapabilityBase") + std::shared_ptr>( + resource_texture, "ResourceTexturePluginCapabilityBase", + "Base for a resource texture capability: a pack of height-map images offered in the texture picker of\n" + "the texture displacement tool, listed under the capability's name.") .def(py::init<>()) - .def("get_type", &ResourceTexturePluginCapability::get_type) - .def("get_texture_dir", &ResourceTexturePluginCapability::get_texture_dir); + .def("get_type", &ResourceTexturePluginCapability::get_type, "Return PluginType.ResourceTexture.") + .def("get_texture_dir", &ResourceTexturePluginCapability::get_texture_dir, + "Required. Return the path of the folder holding the pack's images. Called once when the plugin\n" + "loads. The folder must be inside the plugin's own folder; its .png, .jpg, .jpeg and .bmp files are\n" + "used, without subfolders and at most 64 of them. An empty string, a folder that fails these\n" + "checks or a raised exception leaves the pack without textures."); } } // namespace Slic3r diff --git a/src/slic3r/plugin/pluginTypes/script/ScriptPluginCapability.cpp b/src/slic3r/plugin/pluginTypes/script/ScriptPluginCapability.cpp index f9ff379cf8..b2e7596881 100644 --- a/src/slic3r/plugin/pluginTypes/script/ScriptPluginCapability.cpp +++ b/src/slic3r/plugin/pluginTypes/script/ScriptPluginCapability.cpp @@ -17,9 +17,16 @@ void ScriptPluginCapability::RegisterBindings(pybind11::module_& module) auto script = module.def_submodule("script", "Script Plugins API"); - py::class_>(script, "ScriptPluginCapabilityBase") + py::class_>( + script, "ScriptPluginCapabilityBase", + "Base for a script capability: an action the user runs from the Plugins dialog or the speed dial.") .def(py::init<>()) - .def("get_type", &ScriptPluginCapability::get_type) - .def("execute", &ScriptPluginCapability::execute); + .def("get_type", &ScriptPluginCapability::get_type, "Return PluginType.Script.") + .def("execute", &ScriptPluginCapability::execute, + "Required. Called with no arguments when the user runs the script, on a worker thread rather than\n" + "the UI thread; it may be an async def. Return an ExecutionResult: Success and Skipped show its\n" + "message, or a default text, to the user, and the Plugins dialog reports RecoverableError and\n" + "FatalError as errors with the message. A raised exception is reported as an error."); } } // namespace Slic3r diff --git a/src/slic3r/plugin/pluginTypes/slicingPipeline/SlicingPipelinePluginCapability.cpp b/src/slic3r/plugin/pluginTypes/slicingPipeline/SlicingPipelinePluginCapability.cpp index ed2a6aeecf..178164efdf 100644 --- a/src/slic3r/plugin/pluginTypes/slicingPipeline/SlicingPipelinePluginCapability.cpp +++ b/src/slic3r/plugin/pluginTypes/slicingPipeline/SlicingPipelinePluginCapability.cpp @@ -18,26 +18,36 @@ bool SlicingPipelineContext::cancelled() const { return print && print->canceled void SlicingPipelinePluginCapability::RegisterBindings(py::module_& module) { auto slicing = module.def_submodule("slicing", "Slicing pipeline API (research/experimental)."); - py::enum_(slicing, "Step") - .value("posSlice", SlicingPipelineStepPlugin::posSlice) - .value("posPerimeters", SlicingPipelineStepPlugin::posPerimeters) - .value("posEstimateCurledExtrusions", SlicingPipelineStepPlugin::posEstimateCurledExtrusions) - .value("posPrepareInfill", SlicingPipelineStepPlugin::posPrepareInfill) // after prepare_infill, before make_fills: editing fill_surfaces here CASCADES - .value("posInfill", SlicingPipelineStepPlugin::posInfill) // after make_fills: editing fill_surfaces here does NOT regenerate the fills - .value("posIroning", SlicingPipelineStepPlugin::posIroning) - .value("posContouring", SlicingPipelineStepPlugin::posContouring) - .value("posSupportMaterial", SlicingPipelineStepPlugin::posSupportMaterial) - .value("posDetectOverhangsForLift", SlicingPipelineStepPlugin::posDetectOverhangsForLift) - .value("posSimplifyPath", SlicingPipelineStepPlugin::posSimplifyPath) // covers all simplify sub-steps - .value("psWipeTower", SlicingPipelineStepPlugin::psWipeTower) - .value("psSkirtBrim", SlicingPipelineStepPlugin::psSkirtBrim) - // Post-process seam: fires in the GUI export path AFTER the classic post_process scripts, on the - // exported G-code file. Unlike every step above it is NOT fired by Print::process(): ctx.print and - // ctx.object are None; instead ctx.gcode_path / ctx.host / ctx.output_name are set and the plugin - // edits the file at ctx.gcode_path IN PLACE. May fire more than once per slice (file export and/or - // upload each fire once, on separate working copies) and its output is not reflected in the G-code - // preview (the viewer maps the pre-post-process file). ctx.config_value() still works. - .value("psGCodePostProcess", SlicingPipelineStepPlugin::psGCodePostProcess) + py::enum_( + slicing, "Step", + "Point in slicing at which execute(ctx) runs, given as ctx.step. The pos* steps run for each\n" + "PrintObject that recomputed that step in the current slice, with ctx.object set; an object whose\n" + "step is still valid from an earlier slice is not passed again. The ps* steps run once for the whole\n" + "print, with ctx.object None.") + .value("posSlice", SlicingPipelineStepPlugin::posSlice, "After the object is sliced into layers.") + .value("posPerimeters", SlicingPipelineStepPlugin::posPerimeters, "After the object's walls are generated.") + .value("posEstimateCurledExtrusions", SlicingPipelineStepPlugin::posEstimateCurledExtrusions, + "After curled extrusions are estimated.") + .value("posPrepareInfill", SlicingPipelineStepPlugin::posPrepareInfill, + "After the infill regions are prepared and before the fills are generated, so edits to\n" + "fill_surfaces here change the fills generated next.") + .value("posInfill", SlicingPipelineStepPlugin::posInfill, + "After the fills are generated; edits to fill_surfaces here do not regenerate them.") + .value("posIroning", SlicingPipelineStepPlugin::posIroning, "After ironing is generated.") + .value("posContouring", SlicingPipelineStepPlugin::posContouring, "After Z contouring.") + .value("posSupportMaterial", SlicingPipelineStepPlugin::posSupportMaterial, "After supports are generated.") + .value("posDetectOverhangsForLift", SlicingPipelineStepPlugin::posDetectOverhangsForLift, + "After overhangs are detected for Z lift.") + .value("posSimplifyPath", SlicingPipelineStepPlugin::posSimplifyPath, + "After the extrusion paths are simplified, covering all of its sub-steps.") + .value("psWipeTower", SlicingPipelineStepPlugin::psWipeTower, "After the wipe tower is generated.") + .value("psSkirtBrim", SlicingPipelineStepPlugin::psSkirtBrim, "After the skirt and brim are generated.") + .value("psGCodePostProcess", SlicingPipelineStepPlugin::psGCodePostProcess, + "After G-code export, following the post-processing scripts. ctx.print and ctx.object are None;\n" + "ctx.gcode_path, ctx.host and ctx.output_name are set, and the plugin edits the file at\n" + "ctx.gcode_path in place. It can run more than once per slice, once for each file export or upload,\n" + "each on its own working copy, and the G-code preview does not show its edits.\n" + "ctx.config_value() still works.") .export_values(); // The read-graph data model (Surface / ExPolygon / the extrusion tree / LayerRegion / @@ -50,9 +60,14 @@ void SlicingPipelinePluginCapability::RegisterBindings(py::module_& module) { slicing.def("unscale", [](coord_t v) { return unscale(v); }, py::arg("coord"), "Convert a scaled integer coordinate to millimeters (reads the live SCALING_FACTOR)."); - py::class_(slicing, "SlicingPipelineContext") - .def_readonly("orca_version", &SlicingPipelineContext::orca_version) - .def_readonly("step", &SlicingPipelineContext::step) + py::class_( + slicing, "SlicingPipelineContext", + "What execute(ctx) receives: the Step, and either the slicing graph (print, object) for the slicing\n" + "steps or the exported G-code file for Step.psGCodePostProcess. Valid only during that execute() call.") + .def_readonly("orca_version", &SlicingPipelineContext::orca_version, "The OrcaSlicer version string.") + .def_readonly("step", &SlicingPipelineContext::step, + "The Step this call is for. execute() runs at every step, so return early for the steps the\n" + "plugin does not handle.") .def_readonly("gcode_path", &SlicingPipelineContext::gcode_path, "Path to the working G-code file, set ONLY at Step.psGCodePostProcess. Edit it in " "place; empty at every other step.") @@ -86,16 +101,28 @@ void SlicingPipelinePluginCapability::RegisterBindings(py::module_& module) { return config_value_or_none(*ctx.full_config, key); return py::none(); }, py::arg("key"), - "serialized value of a resolved (full) print config option for this slice, or " - "None if absent. Shorthand for ctx.print.config_value(key).") - .def("cancelled", &SlicingPipelineContext::cancelled); + "Return the serialized value of a resolved (full) print config option for this slice, as a\n" + "string, or None if absent. At the slicing steps it is shorthand for ctx.print.config_value(key);\n" + "it also works at Step.psGCodePostProcess.") + .def("cancelled", &SlicingPipelineContext::cancelled, + "Return True once the user has cancelled this slice; a long step should check it and return early.\n" + "Always False at Step.psGCodePostProcess."); py::class_>(slicing, "SlicingPipelineCapabilityBase") + std::shared_ptr>( + slicing, "SlicingPipelineCapabilityBase", + "Base for a slicing pipeline capability: Python run at each Step of slicing and on the exported G-code,\n" + "to read and change the intermediate slicing data. It runs only for slices whose print settings select\n" + "it in the Slicing Pipeline Plugin option.") .def(py::init<>()) - .def("get_type", &SlicingPipelinePluginCapability::get_type) - .def("execute", &SlicingPipelinePluginCapability::execute); + .def("get_type", &SlicingPipelinePluginCapability::get_type, "Return PluginType.SlicingPipeline.") + .def("execute", &SlicingPipelinePluginCapability::execute, py::arg("ctx"), + "Required. Called at every Step with ctx, a SlicingPipelineContext, on the slicing thread; it must be\n" + "a plain def, not async def, and must not call orca.host.ui. Return an ExecutionResult. At the\n" + "slicing steps FatalError, like a raised exception, stops the slice with its message as the error,\n" + "and the other statuses let slicing continue. At Step.psGCodePostProcess RecoverableError and\n" + "FatalError, like a raised exception, fail the export. A non-empty message is logged."); } } // namespace Slic3r diff --git a/tests/slic3rutils/test_mcp_tools.cpp b/tests/slic3rutils/test_mcp_tools.cpp index 0204777320..4fc3a514ec 100644 --- a/tests/slic3rutils/test_mcp_tools.cpp +++ b/tests/slic3rutils/test_mcp_tools.cpp @@ -13,6 +13,8 @@ #include +#include "python_test_support.hpp" + #include "slic3r/GUI/Mcp/McpTools.hpp" #include "slic3r/GUI/Mcp/McpTypes.hpp" #include "slic3r/GUI/Mcp/McpJournal.hpp" @@ -24,7 +26,9 @@ #include +#include #include +#include #include using namespace Slic3r::GUI::Mcp; @@ -58,6 +62,73 @@ TEST_CASE("setting values serialize the way their options read them back", "[Mcp CHECK_THROWS_AS(to_config_string(json::object()), ToolFailure); } +TEST_CASE("a search matches query words at the start of a text's words, CamelCase parts included", "[Mcp]") +{ + // Short words drop out once the query has a longer one. + CHECK(query_words("Add a Brim to it") == std::vector{"add", "brim"}); + CHECK(query_words("z") == std::vector{"z"}); + + const std::vector words = query_words("mesh normals"); + // "mesh" starts the second part of TriangleMesh and "normals" a word of the name: both in the name. + CHECK(match_score(words, "orca.host.TriangleMesh.face_normals", "Per-triangle normals.") == std::pair{2, 2}); + // A word only the text has counts, but not as a name match. + CHECK(match_score(words, "orca.host.ModelVolume.mesh", "Face normals are not cached.") == std::pair{2, 1}); + CHECK(match_score(words, "orca.host.Model", "The project's objects.") == std::pair{0, 0}); + // A word is matched at the start of a word, never inside one. + CHECK(match_score(query_words("range"), "arrange", "") == std::pair{0, 0}); + CHECK(match_score(query_words("retract"), "retraction_length", "") == std::pair{1, 1}); +} + +TEST_CASE("a listing summary is a documentation's first sentence on one line", "[Mcp]") +{ + CHECK(first_sentence("Return the mesh.\nIt is a copy.") == "Return the mesh."); + CHECK(first_sentence("A box, e.g. the bed's. More.") == "A box, e.g. the bed's."); + CHECK(first_sentence("Version 2.5 of the\nformat") == "Version 2.5 of the format"); + CHECK(first_sentence("") == ""); +} + +TEST_CASE("python_api's reference covers the orca package with constructors and named instances", "[Mcp][Python]") +{ + (void) import_orca_module(); + const json reference = python_api_reference(); + std::map by_name; + for (const json& entry : reference) + by_name[entry["name"].get()] = entry; + + // The plugin classes and pages beside orca.host. + CHECK(by_name.count("orca.pages") == 1); + CHECK(by_name.count("orca.script.ScriptPluginCapabilityBase") == 1); + // A class's signature is its constructors, and its documentation goes on with what they say. + REQUIRE(by_name.count("orca.host.Point") == 1); + CHECK(by_name["orca.host.Point"]["signature"].get().rfind("Point(x: ", 0) == 0); + REQUIRE(by_name.count("orca.host.ExPolygon") == 1); + CHECK(by_name["orca.host.ExPolygon"]["doc"].get().find("Orientation is normalized") != std::string::npos); + // A constant, which has no docstring, points at the documentation that says what it means. + REQUIRE(by_name.count("orca.host.ui.PD_CAN_ABORT") == 1); + const json& abort = by_name["orca.host.ui.PD_CAN_ABORT"]; + CHECK(abort["kind"] == "constant"); + CHECK(abort["signature"].get().rfind("PD_CAN_ABORT = ", 0) == 0); + CHECK(abort["doc"].get().find("orca.host.ui.create_progress_dialog") != std::string::npos); + // An instance a module offers by name. + REQUIRE(by_name.count("orca.host.preset.process") == 1); + CHECK(by_name["orca.host.preset.process"]["kind"] == "attribute"); + // An enum's values are in its documentation, also where a module exports them. + CHECK(by_name.count("orca.host.PresetType.Print") == 0); + CHECK(by_name.count("orca.Analysis") == 0); + // pybind11's signature lines are the signature, not documentation. + REQUIRE(by_name.count("orca.host.TriangleMesh.face_normals") == 1); + const json& normals = by_name["orca.host.TriangleMesh.face_normals"]; + CHECK(normals["signature"].get().rfind("face_normals(self)", 0) == 0); + CHECK(normals["doc"].get().find("face_normals(") == std::string::npos); + // An overloaded method's signature is its overloads, not pybind11's name(*args, **kwargs) before them. + REQUIRE(by_name.count("orca.host.preset.PresetEditor.begin_update") == 1); + const std::string overloads = by_name["orca.host.preset.PresetEditor.begin_update"]["signature"]; + CHECK(overloads.find("*args") == std::string::npos); + CHECK(overloads.find("slot_number") != std::string::npos); + + CHECK(rank_python_api(reference, "mesh normals")[0]["name"] == "orca.host.TriangleMesh.face_normals"); +} + TEST_CASE("every tool of the catalog has the lane the concept gives it", "[Mcp]") { for (const char* name : {"get_state", "wait", "cancel", "get_log", "run_script", "export_script", "dialog_respond", diff --git a/tests/slic3rutils/test_plugin_host_api.cpp b/tests/slic3rutils/test_plugin_host_api.cpp index 14b1d69aca..4a3c94b435 100644 --- a/tests/slic3rutils/test_plugin_host_api.cpp +++ b/tests/slic3rutils/test_plugin_host_api.cpp @@ -43,6 +43,10 @@ #include #include +#include +#include + +#include #include #include #include @@ -632,3 +636,40 @@ TEST_CASE("Plugin host API exposes TriangleMesh geometry to Python", "[PluginHos REQUIRE_THAT(instance_matrix.attr("__getitem__")(py::make_tuple(0, 3)).cast(), WithinAbs(5.0, 1e-6)); REQUIRE_THAT(instance_matrix.attr("__getitem__")(py::make_tuple(1, 3)).cast(), WithinAbs(6.0, 1e-6)); } + +TEST_CASE("every public member of the orca package has documentation and named parameters", "[PluginHost][Python]") +{ + // python_api serves this documentation to agents writing scripts and plugins: a member without it, or + // with a parameter pybind11 names argN, is one they can only guess at. A constant's documentation is + // the documentation that names it, and a class's goes on with what its constructors say; an enum's + // constructor takes one of the values its documentation lists. + const py::module_ orca = import_orca_module(); + const py::object cleandoc = py::module_::import("inspect").attr("cleandoc"); + const std::regex positional(R"(\barg\d+\b)"); + const std::regex takes_arguments(R"(\w\((?!\)))"); + std::vector undocumented; + std::vector unnamed; + std::vector constructors; + for (const nlohmann::json& entry : Slic3r::GUI::Mcp::python_api_reference()) { + const std::string name = entry["name"].get(); + const std::string signature = entry["signature"].get(); + const std::string doc = entry["doc"].get(); + if (doc.empty()) + undocumented.push_back(name); + if (std::regex_search(signature, positional)) + unnamed.push_back(name); + if (entry["kind"] == "class" && std::regex_search(signature, takes_arguments)) { + py::object cls = orca; + for (std::size_t from = name.find('.') + 1, dot = 0; dot != std::string::npos; from = dot + 1) { + dot = name.find('.', from); + cls = cls.attr(name.substr(from, dot - from).c_str()); + } + const py::object own = cls.attr("__doc__"); + if (!py::hasattr(cls, "__members__") && doc == cleandoc(own.is_none() ? py::str("") : own).cast()) + constructors.push_back(name); + } + } + CHECK(undocumented == std::vector{}); + CHECK(unnamed == std::vector{}); + CHECK(constructors == std::vector{}); +} diff --git a/tools/mcp/test_plugin_tools.py b/tools/mcp/test_plugin_tools.py index f4a34d6aa1..e1ea1b3e80 100644 --- a/tools/mcp/test_plugin_tools.py +++ b/tools/mcp/test_plugin_tools.py @@ -26,15 +26,11 @@ PLUGIN = "mcp_tools_fixture" CAPABILITIES = ["MCP tools fixture call", "MCP tools fixture thread", "MCP tools fixture rule", "MCP tools fixture export", "MCP tools fixture handle"] BROKEN = "mcp_tools_broken" -# A script that finds the fixture's handle among the loaded modules and tries one of its methods. +# A script that finds the fixture's progress dialog among the loaded modules and moves its gauge. GRAB_HANDLE = """ import sys handle = next(m.HANDLE for m in list(sys.modules.values()) if getattr(m, "HANDLE", None) is not None) -try: - handle.update(5) - result = "allowed" -except RuntimeError as e: - result = str(e) +result = handle.update(5) """ RULE = "MCP tools fixture never shown" # the match of the auto-answer rule the fixture's "rule" script sets PORT = 13692 @@ -157,6 +153,27 @@ def main(): exported = run_script(orca, plugin_dir, "export", CAPABILITIES[3]) check("a plugin is refused export_script", exported.get("ok") is False and "agent's session" in exported.get("error", ""), exported) + # api_describe's one search: an operation with its schema, a tool with its summary (its schema is in + # tools/list), and beside them the other catalogs' best matches. + found = orca.call("api_describe", query="fixture measure") + operation = next((i for i in found["items"] if i["name"] == f"plugin.{PLUGIN}.measure"), {}) + check("api_describe's search finds the plugin's operation with its schema", "input_schema" in operation, found) + found = orca.call("api_describe", query="slice plate") + tool = next((i for i in found["items"] if i["name"] == "slice"), {}) + check("api_describe's search names a tool with its summary", tool.get("summary") and "input_schema" not in tool, found) + found = orca.call("api_describe", query="brim width") + check("api_describe's search finds settings", any(s["key"] == "brim_width" for s in found.get("settings", {}).get("items", [])), + found) + found = orca.call("api_describe", query="arrange") + check("api_describe's search finds Speed Dial actions", any("arrange" in a["id"] for a in found.get("actions", {}).get("items", [])), + found) + found = orca.call("api_describe", query="mesh normals") + check("api_describe's search finds the Python API", found.get("python", {}).get("items", [{}])[0].get("name") == + "orca.host.TriangleMesh.face_normals", found) + found = orca.call("api_describe", query="extrude") + check("api_describe's search finds the Design tab's methods", found.get("cad", {}).get("items"), found) + found = orca.call("api_describe", query="?") + check("a query with no words to search for matches nothing", found.get("total") == 0 and "names" not in found, found) journal = orca.call("export_script")["script"]["steps"] check("a plugin's calls are not in the agent's journal", not any(s["tool"] == "dialog_auto_answer" for s in journal), journal) @@ -165,7 +182,7 @@ def main(): held = run_script(orca, plugin_dir, "handle", CAPABILITIES[4]) check("the plugin opens a progress dialog and keeps its handle", held.get("ok") is True, held) grab = orca.await_job(orca.call("run_python", code=GRAB_HANDLE)) - check("a script that finds a plugin's handle is refused its methods", "is for plugins" in str(grab.get("result")), grab) + check("a script that finds a plugin's handle can use its methods", grab.get("result") is True, grab) # --- The plugin unloads, as a person unticks it in the Plugins dialog. --- rules = lambda: json.dumps(orca.call("get_state").get("auto_answer_rules")) diff --git a/tools/mcp/tests/plugins/mcp_tools_fixture/mcp_tools_fixture.py b/tools/mcp/tests/plugins/mcp_tools_fixture/mcp_tools_fixture.py index 111efaace0..40cd398630 100644 --- a/tools/mcp/tests/plugins/mcp_tools_fixture/mcp_tools_fixture.py +++ b/tools/mcp/tests/plugins/mcp_tools_fixture/mcp_tools_fixture.py @@ -15,7 +15,7 @@ Each script writes what happened to out_.json in the plugin's storage fold permission unless ORCA_MCP_TOOLS_FIXTURE_ASK is 0. "call" calls get_state, "thread" calls it from a thread the script starts, "rule" registers an auto-answer rule, "export" asks for export_script, which a plugin is refused, and "handle" opens a progress dialog and keeps its handle in -HANDLE, for a script to be refused its methods. The plugin also offers the operation "measure", which +HANDLE, for a script to find and use. The plugin also offers the operation "measure", which doubles its argument a. """ import json @@ -87,7 +87,7 @@ class ExportScript(orca.script.ScriptPluginCapabilityBase): return record("export", lambda: orca.host.tools.call("export_script")) -# A handle only the plugin's own calls may use; a script that finds it here is refused its methods. +# The progress dialog the "handle" script opens; a script that finds it here uses it as the plugin can. HANDLE = None